From 2eeed94e513f468ab83c3066eafa58712a346d92 Mon Sep 17 00:00:00 2001 From: denstu473 <63150090+denstu473@users.noreply.github.com> Date: Sun, 18 Oct 2026 21:58:06 +0200 Subject: [PATCH 01/52] test(atn): add native parser matrix and contract fixtures --- .github/workflows/atn.yml | 166 ++++++++++++ .github/workflows/ci.yml | 5 +- ATTRIBUTION.md | 6 + crates/psd/fuzz/fuzz_targets/atn.rs | 12 +- crates/psd/tests/atn_contract.rs | 239 ++++++++++++++++++ crates/psd/tests/common/atn_roundtrip.rs | 71 ++++++ crates/psd/tests/fixtures/atn/README.md | 19 ++ crates/psd/tests/fixtures/atn/descriptors.atn | Bin 0 -> 859 bytes crates/psd/tests/fixtures/atn/empty.atn | Bin 0 -> 13 bytes crates/psd/tests/fixtures/atn/float-bits.atn | Bin 0 -> 428 bytes crates/psd/tests/fixtures/atn/metadata.atn | Bin 0 -> 214 bytes docs/atn-testing.md | 97 +++++++ docs/development.md | 3 + 13 files changed, 609 insertions(+), 9 deletions(-) create mode 100644 .github/workflows/atn.yml create mode 100644 crates/psd/tests/atn_contract.rs create mode 100644 crates/psd/tests/common/atn_roundtrip.rs create mode 100644 crates/psd/tests/fixtures/atn/README.md create mode 100644 crates/psd/tests/fixtures/atn/descriptors.atn create mode 100644 crates/psd/tests/fixtures/atn/empty.atn create mode 100644 crates/psd/tests/fixtures/atn/float-bits.atn create mode 100644 crates/psd/tests/fixtures/atn/metadata.atn create mode 100644 docs/atn-testing.md diff --git a/.github/workflows/atn.yml b/.github/workflows/atn.yml new file mode 100644 index 00000000000..1895598e282 --- /dev/null +++ b/.github/workflows/atn.yml @@ -0,0 +1,166 @@ +name: ATN + +on: + push: + branches: [main] + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + merge_group: + schedule: + - cron: "17 4 * * *" + workflow_dispatch: + inputs: + fuzz_seconds: + description: "Seconds of ATN parser fuzzing" + type: choice + options: ["60", "300", "600"] + default: "60" + +permissions: + contents: read + +concurrency: + group: atn-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + CARGO_TERM_COLOR: always + RUST_BACKTRACE: 1 + CARGO_PROFILE_DEV_DEBUG: "0" + CARGO_PROFILE_RELEASE_DEBUG: "0" + # Keep optimized arithmetic behavior without paying for release LTO in a parser test job. + CARGO_PROFILE_RELEASE_LTO: "false" + CARGO_PROFILE_RELEASE_CODEGEN_UNITS: "16" + +jobs: + parser: + name: ATN parser (${{ matrix.target }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 20 + strategy: + fail-fast: false + # These small CPU-only jobs can share the macOS pool with release builds. + max-parallel: 3 + matrix: + include: + - { os: ubuntu-24.04, target: x86_64-unknown-linux-gnu, arch: X64 } + - { os: ubuntu-24.04-arm, target: aarch64-unknown-linux-gnu, arch: ARM64 } + - { os: windows-2025, target: x86_64-pc-windows-msvc, arch: X64 } + - { os: windows-11-arm, target: aarch64-pc-windows-msvc, arch: ARM64 } + - { os: macos-15-intel, target: x86_64-apple-darwin, arch: X64 } + - { os: macos-15, target: aarch64-apple-darwin, arch: ARM64 } + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@stable + with: + targets: ${{ matrix.target }} + - uses: Swatinem/rust-cache@v2 + with: + key: atn-parser-${{ matrix.target }} + save-if: ${{ github.ref == 'refs/heads/main' }} + cache-on-failure: true + - name: Record native execution environment + env: + EXPECTED_ARCH: ${{ matrix.arch }} + TEST_TARGET: ${{ matrix.target }} + run: | + mkdir -p atn-results + # A successful cross-compilation must never stand in for native execution. + test "$RUNNER_ARCH" = "$EXPECTED_ARCH" + { + git rev-parse HEAD + printf 'runner=%s arch=%s target=%s\n' "$RUNNER_OS" "$RUNNER_ARCH" "$TEST_TARGET" + printf 'image=%s version=%s\n' "${ImageOS:-unknown}" "${ImageVersion:-unknown}" + rustc -vV + cargo -V + } | tee atn-results/environment.txt + - name: Parser unit tests + env: + TEST_TARGET: ${{ matrix.target }} + run: | + set -o pipefail + cargo test --locked -p photocraft-psd --target "$TEST_TARGET" --lib atn::tests:: -- --nocapture 2>&1 | tee atn-results/unit.log + - name: Parser contract tests (debug) + env: + TEST_TARGET: ${{ matrix.target }} + run: | + set -o pipefail + cargo test --locked -p photocraft-psd --target "$TEST_TARGET" --test atn_contract -- --nocapture 2>&1 | tee atn-results/debug.log + - name: Parser contract tests (release) + env: + TEST_TARGET: ${{ matrix.target }} + run: | + set -o pipefail + cargo test --locked --release -p photocraft-psd --target "$TEST_TARGET" --test atn_contract -- --nocapture 2>&1 | tee atn-results/release.log + - name: Upload parser evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: atn-parser-${{ matrix.target }} + path: atn-results/ + if-no-files-found: error + retention-days: 14 + + parser-gate: + name: ATN parser gate + needs: parser + if: always() + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Require every native parser leg + env: + PARSER_RESULT: ${{ needs.parser.result }} + run: test "$PARSER_RESULT" = success + + fuzz: + name: ATN parser fuzz + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@nightly + - uses: Swatinem/rust-cache@v2 + with: + key: atn-fuzz + workspaces: crates/psd/fuzz + save-if: ${{ github.ref == 'refs/heads/main' }} + cache-on-failure: true + - name: Install cargo-fuzz + run: cargo install cargo-fuzz --locked + - name: Seed parser fuzzing with the contract fixtures + run: | + mkdir -p crates/psd/fuzz/corpus/atn atn-results + cp crates/psd/tests/fixtures/atn/*.atn crates/psd/fuzz/corpus/atn/ + { + git rev-parse HEAD + rustc -vV + cargo fuzz --version + sha256sum crates/psd/tests/fixtures/atn/*.atn + } | tee atn-results/fuzz-environment.txt + - name: Fuzz ATN parsing and writing + working-directory: crates/psd + env: + FUZZ_SECONDS: ${{ inputs.fuzz_seconds || '60' }} + run: | + set -o pipefail + cargo fuzz run atn -- -max_total_time="$FUZZ_SECONDS" -max_len=65536 -rss_limit_mb=512 -timeout=5 2>&1 | tee ../../atn-results/fuzz.log + - name: Upload fuzz evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: atn-fuzz-evidence + path: | + atn-results/ + crates/psd/fuzz/artifacts/atn/ + crates/psd/fuzz/corpus/atn/ + if-no-files-found: warn + retention-days: 14 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ba8243353d2..b92a4aae47b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,7 +38,7 @@ jobs: # Which OSes the test job runs on. main, manual runs and PRs labelled `full-ci` get Linux and # Windows. Other PRs get Linux, plus Windows when they touch code whose behaviour differs by # platform: the app shell, UI, text and fonts, GPU, pen input, build scripts or the lockfile. - # macOS is tested only by release.yml. + # Full-workspace macOS tests run in release.yml; atn.yml has a small native parser matrix. platforms: timeout-minutes: 10 name: select platforms @@ -56,7 +56,7 @@ jobs: BASE: ${{ github.event.pull_request.base.sha }} FULL: ${{ contains(github.event.pull_request.labels.*.name, 'full-ci') }} run: | - # No macOS on PRs or main: the org's 5 macOS slots are kept for release builds, and + # No full-workspace macOS leg on PRs or main: the org's 5 slots serve release builds, and # release.yml builds and tests macOS (a failing release is fixed and rebuilt). # Windows tests run as two legs in parallel: the unit tests and the integration tests. As # one job they took ~28 min on the Windows runner; the legs take ~13 and ~15. Splitting @@ -399,6 +399,7 @@ jobs: target: - { crate: psd, name: parse } - { crate: psd, name: descriptor } + - { crate: psd, name: atn } - { crate: psd, name: image_source_data } - { crate: psd, name: grd } - { crate: psd, name: ase } diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index cbbbe069a52..2d2d831fd64 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -118,4 +118,10 @@ next to the files: | `corpus/pngsuite/` | PngSuite | Willem van Schaik | | Public domain | | `corpus/pixls/` (11 files) | Real camera raws, one per decode path: Canon PowerShot SX50 HS (CR2 and its DNG conversion), Nikon D3 uncompressed NEF and Z6 paired 12/14-bit lossy and packed NEFs, Sony DSC-RX0 cRAW ARW, Panasonic DC-G9 high-res RW2, Olympus E-1 GRBG ORF, plus the E-5 packed ORF as the documented known-unsupported case. Per file (each CC0, per its database entry): [IMG_4059.CR2](https://raw.pixls.us/data/Canon/PowerShot%20SX50%20HS/IMG_4059.CR2), [CRW_4061.DNG](https://raw.pixls.us/data/Canon/PowerShot%20SX50%20HS/CRW_4061.DNG), [JD1_8203.NEF](https://raw.pixls.us/data/Nikon/D3/JD1_8203.NEF), [DSC00009.ARW](https://raw.pixls.us/data/Sony/DSC-RX0/DSC00009.ARW), [P1000475.RW2](https://raw.pixls.us/data/Panasonic/DC-G9/P1000475.RW2), [E_1__C106743_gredos.ORF](https://raw.pixls.us/data/Olympus/E-1/E_1__C106743_gredos.ORF), [_7061961_copy.ORF](https://raw.pixls.us/data/Olympus/E-5/_7061961_copy.ORF), [DSC_0750.NEF](https://raw.pixls.us/data/Nikon/Z%206/DSC_0750.NEF), [DSC_0751.NEF](https://raw.pixls.us/data/Nikon/Z%206/DSC_0751.NEF), [DSC_0753.NEF](https://raw.pixls.us/data/Nikon/Z%206/DSC_0753.NEF), [DSC_0754.NEF](https://raw.pixls.us/data/Nikon/Z%206/DSC_0754.NEF) | The photographers of the pixls.us raw samples database | [raw.pixls.us](https://raw.pixls.us) `data/`, fetched per [xtask/src/corpus_pins.rs](xtask/src/corpus_pins.rs) | CC0 / public domain, per file as linked | +## Synthetic parser test fixtures + +| Path | Title | Author | Source | License | +|---|---|---|---|---| +| `crates/psd/tests/fixtures/atn/*.atn` | Independently encoded ATN version-16 parser fixtures | PhotoCraft contributors | Original synthetic test data; wire layout documented in `crates/psd/src/atn.rs`; provenance in the adjacent README | MIT OR Apache-2.0 | + Files copied into `corpus/` by hand (tiff, exr, raw) must be MIT, BSD or CC0. diff --git a/crates/psd/fuzz/fuzz_targets/atn.rs b/crates/psd/fuzz/fuzz_targets/atn.rs index 3bb1777c8a3..7d719a0b809 100644 --- a/crates/psd/fuzz/fuzz_targets/atn.rs +++ b/crates/psd/fuzz/fuzz_targets/atn.rs @@ -1,14 +1,12 @@ //! Fuzz the `.atn` actions parser: any input must return `Ok` or `Err`, never panic, and -//! anything that parses must survive a write and parse back equal. +//! anything that parses must survive writing, reparsing and stable canonical writing. #![no_main] use libfuzzer_sys::fuzz_target; -use photocraft_psd::atn; + +#[path = "../../tests/common/atn_roundtrip.rs"] +mod atn_roundtrip; fuzz_target!(|data: &[u8]| { - if let Ok(f) = atn::parse(data) { - let bytes = atn::write(&f).expect("a parsed set is writable"); - let again = atn::parse(&bytes).expect("a written set parses"); - assert_eq!(again.actions, f.actions); - } + atn_roundtrip::check(data); }); diff --git a/crates/psd/tests/atn_contract.rs b/crates/psd/tests/atn_contract.rs new file mode 100644 index 00000000000..55d7a6623de --- /dev/null +++ b/crates/psd/tests/atn_contract.rs @@ -0,0 +1,239 @@ +//! Portable public-API contract, executed natively in debug and release by ATN CI. +use photocraft_psd::PsdError; +use photocraft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; +use photocraft_psd::descriptor::{Class, Descriptor, Id, MAX_DEPTH, ObjectArray, ReferenceItem, UnicodeString, Value}; + +#[path = "common/atn_roundtrip.rs"] +mod atn_roundtrip; + +const FIXTURES: &[(&str, &[u8])] = &[ + ("empty", include_bytes!("fixtures/atn/empty.atn")), + ("metadata", include_bytes!("fixtures/atn/metadata.atn")), + ("descriptors", include_bytes!("fixtures/atn/descriptors.atn")), + ("float bits", include_bytes!("fixtures/atn/float-bits.atn")), +]; + +fn file_with(desc: Descriptor) -> AtnFile { + AtnFile { + actions: vec![AtnAction { + items: vec![AtnItem { event: AtnEvent::Code(*b"test"), descriptor: Some(desc), ..Default::default() }], + ..Default::default() + }], + ..Default::default() + } +} + +fn class(id: &str) -> Class { + Class { name: UnicodeString::default(), class_id: Id::new(id) } +} + +#[test] +fn independent_wire_fixtures_parse_and_write_byte_exactly() { + for (name, bytes) in FIXTURES { + let parsed = atn::parse(bytes).unwrap(); + assert!(parsed.warnings.is_empty(), "{name}"); + assert_eq!(atn::write(&parsed).unwrap(), *bytes, "{name}"); + atn_roundtrip::check(bytes); + } + assert_eq!(atn::write(&AtnFile::default()).unwrap(), FIXTURES[0].1); + assert_eq!(&FIXTURES[0].1[..4], &[0, 0, 0, 16], "the wire version is big-endian on every host"); +} + +#[test] +fn unicode_metadata_unknown_events_and_dialog_flags_are_preserved() { + let file = atn::parse(FIXTURES[1].1).unwrap(); + assert_eq!(file.name.0, vec![0x0053, 0x0065, 0x0074, 0x0020, 0xd83d, 0xde80, 0xd800, 0]); + assert!(file.expanded); + assert_eq!(file.actions.len(), 2); + let action = &file.actions[0]; + assert_eq!(action.name, UnicodeString::new_nul("Action Ω")); + assert_eq!((action.function_key, action.shift, action.command, action.color, action.expanded), (12, true, true, 7, true)); + let blur = &action.items[0]; + assert_eq!((blur.expanded, blur.enabled, blur.with_dialog, blur.dialog_options), (true, true, true, 2)); + assert_eq!(blur.event, AtnEvent::Code(*b"GsnB")); + assert_eq!(blur.descriptor, Some(Descriptor::new("null").with("Rds ", Value::UnitFloat { unit: *b"#Pxl", value: 2.5 }))); + let future = &action.items[1]; + assert_eq!(future.event, AtnEvent::Name("syntheticFutureEvent".into())); + assert_eq!((future.expanded, future.enabled, future.with_dialog, future.dialog_options), (false, false, true, 255)); + assert_eq!(future.dictionary, "Future event"); + assert!(future.descriptor.is_none()); + assert_eq!(file.actions[1].name, UnicodeString::new_nul("Empty")); + assert!(file.actions[1].items.is_empty()); +} + +#[test] +fn every_descriptor_variant_and_reference_form_is_retained() { + let expected = Descriptor::new("syntheticRoot") + .with( + "reference", + Value::Reference(vec![ + ReferenceItem::Property { class: class("Lyr "), key: Id::new("Nm ") }, + ReferenceItem::Class(class("Dcmn")), + ReferenceItem::Enumerated { class: class("Lyr "), type_id: Id::new("Ordn"), value: Id::new("Trgt") }, + ReferenceItem::Offset { class: class("Lyr "), offset: -3 }, + ReferenceItem::Identifier { class: class("Lyr "), id: 0x1234_5678 }, + ReferenceItem::Index { class: class("Lyr "), index: 4 }, + ReferenceItem::Name { class: class("Lyr "), name: UnicodeString::new_nul("Layer Ω") }, + ]), + ) + .with("nested", Value::Descriptor(Descriptor::new("child").with("flag", Value::Boolean(true)))) + .with("global", Value::GlobalObject(Descriptor::new("global"))) + .with("list", Value::List(vec![Value::Boolean(false), Value::Double(-3.5), Value::Text(UnicodeString::new("Ω"))])) + .with("double", Value::Double(1.25)) + .with("unit", Value::UnitFloat { unit: *b"#Prc", value: 37.5 }) + .with("units", Value::UnitFloats { unit: *b"#Pxl", values: vec![1.25, -0.0, -2.5] }) + .with("text", Value::Text(UnicodeString(vec![0x0054, 0x0065, 0x0078, 0x0074, 0x0020, 0xd83d, 0xde80, 0xdfff, 0]))) + .with("enum", Value::Enumerated { type_id: Id::new("Ordn"), value: Id::new("syntheticValue") }) + .with("integer", Value::Integer(i32::MIN)) + .with("large", Value::LargeInteger(0x0123_4567_89ab_cdef)) + .with("boolean", Value::Boolean(true)) + .with("class", Value::Class(class("Lyr "))) + .with("globalClass", Value::GlobalClass(class("Dcmn"))) + .with("alias", Value::Alias(vec![0, 255, 1, 128])) + .with("path", Value::Path(b"C:\\synthetic\\image.psd\0".to_vec())) + .with("raw", Value::RawData(vec![0, 127, 128, 255])) + .with( + "objectArray", + Value::ObjectArray(ObjectArray { + prefix: 16, + body: Descriptor::new("rationalPoint").with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: vec![1.0, 2.0] }), + }), + ); + let file = atn::parse(FIXTURES[2].1).unwrap(); + assert_eq!(file.actions[0].items[0].descriptor, Some(expected)); +} + +#[test] +fn nan_payloads_signed_zero_and_infinities_survive_without_false_fuzz_failures() { + let file = atn::parse(FIXTURES[3].1).unwrap(); + let descriptor = file.actions[0].items[0].descriptor.as_ref().unwrap(); + for (key, bits) in [ + ("nan", 0x7ff8_0000_0000_1234), + ("negativeZero", 0x8000_0000_0000_0000), + ("positiveInfinity", 0x7ff0_0000_0000_0000), + ("negativeInfinity", 0xfff0_0000_0000_0000), + ] { + let Some(Value::Double(value)) = descriptor.get(key) else { panic!("missing {key}") }; + assert_eq!(value.to_bits(), bits, "{key}"); + } + // Ordinary AST PartialEq fails for NaN, despite this valid byte-exact round trip. + assert_ne!(file.actions.clone(), file.actions); + atn_roundtrip::check(FIXTURES[3].1); +} + +#[test] +fn every_truncated_fixture_is_refused() { + for (name, bytes) in FIXTURES { + for end in 0..bytes.len() { + assert!(atn::parse(&bytes[..end]).is_err(), "{name}: cut at {end}/{}", bytes.len()); + } + } +} + +#[test] +fn trailing_bytes_only_add_a_diagnostic() { + for (name, bytes) in FIXTURES { + let mut input = bytes.to_vec(); + input.extend_from_slice(b"extra"); + let mut parsed = atn::parse(&input).unwrap(); + assert_eq!(parsed.warnings, ["5 trailing bytes ignored"], "{name}"); + parsed.warnings.clear(); + assert_eq!(atn::write(&parsed).unwrap(), *bytes, "{name}"); + atn_roundtrip::check(&input); + } +} + +#[test] +fn unsupported_versions_and_invalid_item_tags_are_refused() { + for version in [0_u32, 12, 15, 17, u32::MAX] { + let mut input = FIXTURES[0].1.to_vec(); + input[..4].copy_from_slice(&version.to_be_bytes()); + assert!(matches!(atn::parse(&input), Err(PsdError::Unsupported(_)))); + } + let file = file_with(Descriptor::new("null")); + let valid = atn::write(&file).unwrap(); + // The empty set/action names put the first step at offset 28. + for kind in [*b"bad!", *b"LONG", [0; 4]] { + let mut input = valid.clone(); + input[32..36].copy_from_slice(&kind); + assert!(matches!(atn::parse(&input), Err(PsdError::Invalid(_)))); + } + for flag in [-2_i32, 1, i32::MAX] { + let mut input = valid.clone(); + input[44..48].copy_from_slice(&flag.to_be_bytes()); + assert!(matches!(atn::parse(&input), Err(PsdError::Invalid(_)))); + } +} + +#[test] +fn declared_action_and_step_limits_are_enforced() { + let mut actions = FIXTURES[0].1.to_vec(); + let count = (atn::MAX_ACTIONS + 1) as u32; + actions[9..13].copy_from_slice(&count.to_be_bytes()); + actions.resize(13 + count as usize * 15, 0); + assert!(matches!(atn::parse(&actions), Err(PsdError::LimitExceeded("too many actions in one set")))); + + let mut steps = atn::write(&AtnFile { actions: vec![AtnAction::default()], ..Default::default() }).unwrap(); + let count = (atn::MAX_ITEMS + 1) as u32; + steps[24..28].copy_from_slice(&count.to_be_bytes()); + steps.resize(28 + count as usize * 20, 0); + assert!(matches!(atn::parse(&steps), Err(PsdError::LimitExceeded("too many steps in one action")))); + + let mut short = FIXTURES[0].1.to_vec(); + short[9..13].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(matches!(atn::parse(&short), Err(PsdError::UnexpectedEof { .. }))); +} + +#[test] +fn nested_descriptors_obey_the_parser_depth_limit() { + let mut desc = Descriptor::new("leaf").with("flag", Value::Boolean(true)); + for _ in 0..2 { + desc = Descriptor::new("node").with("next", Value::Descriptor(desc)); + } + let shallow = atn::write(&file_with(desc.clone())).unwrap(); + atn_roundtrip::check(&shallow); + assert!(atn::parse(&shallow).is_ok()); + for _ in 0..MAX_DEPTH + 2 { + desc = Descriptor::new("node").with("next", Value::Descriptor(desc)); + } + let deep = atn::write(&file_with(desc)).unwrap(); + assert!(matches!(atn::parse(&deep), Err(PsdError::LimitExceeded(_)))); +} + +#[test] +fn generated_metadata_and_float_patterns_round_trip() { + let mut seed = 0x9e37_79b9_7f4a_7c15_u64; + for index in 0..256_u16 { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let mut file = file_with(Descriptor::new("generated").with("value", Value::Double(f64::from_bits(seed)))); + file.name = UnicodeString(vec![index, 0xd800 | index, 0, 0xffff]); + file.expanded = index & 1 != 0; + let action = &mut file.actions[0]; + action.function_key = index; + action.shift = index & 2 != 0; + action.command = index & 4 != 0; + action.color = index; + action.expanded = index & 8 != 0; + action.name = UnicodeString(vec![0xdc00 | index, index]); + let item = &mut action.items[0]; + item.expanded = index & 16 != 0; + item.enabled = index & 32 != 0; + item.with_dialog = index & 64 != 0; + item.dialog_options = index as u8; + atn_roundtrip::check(&atn::write(&file).unwrap()); + } +} + +#[test] +fn actual_fuzz_invariant_handles_deterministic_seed_mutations() { + for (_, bytes) in FIXTURES { + for index in 0..128 { + let mut mutated = bytes.to_vec(); + let at = index * 47 % mutated.len(); + mutated[at] ^= (index as u8).wrapping_mul(13).wrapping_add(1); + atn_roundtrip::check(&mutated); + } + } +} diff --git a/crates/psd/tests/common/atn_roundtrip.rs b/crates/psd/tests/common/atn_roundtrip.rs new file mode 100644 index 00000000000..8b71754b561 --- /dev/null +++ b/crates/psd/tests/common/atn_roundtrip.rs @@ -0,0 +1,71 @@ +//! Shared invariant for the parser contract suite and the actual cargo-fuzz target. +use photocraft_psd::atn::{self, AtnFile}; +use photocraft_psd::descriptor::{Descriptor, Value}; + +fn scalar(value: &mut f64, bits: &mut Vec) { + bits.push(value.to_bits()); + // AST equality must remain meaningful when a valid descriptor contains NaN. + if value.is_nan() { + *value = 0.0; + } +} + +fn descriptor(desc: &mut Descriptor, bits: &mut Vec) { + for (_, item) in &mut desc.items { + value(item, bits); + } +} + +fn value(item: &mut Value, bits: &mut Vec) { + match item { + Value::Double(v) | Value::UnitFloat { value: v, .. } => scalar(v, bits), + Value::UnitFloats { values, .. } => { + for v in values { + scalar(v, bits); + } + } + Value::Descriptor(d) | Value::GlobalObject(d) => descriptor(d, bits), + Value::ObjectArray(array) => descriptor(&mut array.body, bits), + Value::List(items) => { + for item in items { + value(item, bits); + } + } + Value::Reference(_) + | Value::Text(_) + | Value::Enumerated { .. } + | Value::Integer(_) + | Value::LargeInteger(_) + | Value::Boolean(_) + | Value::Class(_) + | Value::GlobalClass(_) + | Value::Alias(_) + | Value::Path(_) + | Value::RawData(_) => {} + } +} + +fn floats(file: &mut AtnFile) -> Vec { + let mut bits = Vec::new(); + for action in &mut file.actions { + for item in &mut action.items { + if let Some(d) = &mut item.descriptor { + descriptor(d, &mut bits); + } + } + } + bits +} + +pub fn check(data: &[u8]) { + if let Ok(mut original) = atn::parse(data) { + let encoded = atn::write(&original).expect("a parsed set is writable"); + let mut again = atn::parse(&encoded).expect("a written set parses"); + assert_eq!(atn::write(&again).expect("a reparsed set is writable"), encoded); + assert_eq!(floats(&mut original), floats(&mut again), "every floating-point bit pattern survives"); + // Trailing-input diagnostics are not serialized into an action set. + original.warnings.clear(); + again.warnings.clear(); + assert_eq!(again, original, "set metadata, action metadata and every descriptor value survive"); + } +} diff --git a/crates/psd/tests/fixtures/atn/README.md b/crates/psd/tests/fixtures/atn/README.md new file mode 100644 index 00000000000..e26382f1ea3 --- /dev/null +++ b/crates/psd/tests/fixtures/atn/README.md @@ -0,0 +1,19 @@ +# Synthetic ATN parser fixtures + +These four tiny files were independently encoded field by field from the version-16 layout +documented in `src/atn.rs`, without calling PhotoCraft's writer. They are original test data, +licensed MIT OR Apache-2.0 under the repository's licenses. They contain no user artwork, +Photoshop program code or proprietary assets. They are not Photoshop-authored interoperability +oracles. + +| File | Bytes | Purpose | SHA-256 | +|---|---:|---|---| +| `empty.atn` | 13 | Empty set and explicit big-endian version | `6fd936f91296a13b0e7456a38b139a100fd17407d1c582d4502ce76413d01539` | +| `metadata.atn` | 214 | UTF-16 surrogate pairs/unpaired units, action order, function key, modifiers, panel flags, disabled step, unknown string event, dialog options | `cec2ff5a25e003aa29e790ea6b110f06ba848f0afd7901f3f8ad4740f782ede2` | +| `descriptors.atn` | 859 | Every descriptor value variant and every reference form currently represented by the parser | `6c76502822c1f36c8060a71adb227c4540663518785bbab1b70951dac0ef58ad` | +| `float-bits.atn` | 428 | NaN payload, negative zero, infinities, and floats inside lists, objects and arrays | `0aa6278a569c777f249b305e889896132c2a87e44a24cb1a55d1d3fc0928fd0c` | + +`tests/atn_contract.rs` checks the independently encoded bytes and expected public structures. +The ATN fuzz job copies the same files into its seed corpus. A fixture change should explain +the changed wire fields and update this table; do not regenerate expectations merely to make a +failing parser pass. diff --git a/crates/psd/tests/fixtures/atn/descriptors.atn b/crates/psd/tests/fixtures/atn/descriptors.atn new file mode 100644 index 0000000000000000000000000000000000000000..26b1bdd361babd5886fa5b910a41cbba94245c67 GIT binary patch literal 859 zcmY*Y!EVz)5FHacp(;gHFL1P!J10&^s4Zy99@x~p-oLu zIcz1DtjW1s60ABD28 zZYD?EV~2|%(~D&NXhVDHgXY6sW+bvb{_V?YTd2ZaDtF$WnDpe;x+NmU?WH=G{mD`i z+G&ewpRx|yTmXkl=RdXwQ|fjJ4&rYwzt=zf98oPwez?Z#{dhasnUD)su2(3BIU1=| zUUMcuB!$T_)nyg*hxw;3Uw;zV<4#eiR;4JF!dkvLO$`}8+Wn1u1ExvCK}+*ZAU_ha z5S9$f7s7o|b3!HDeB$OYxlaZ!uC}MVDoT;#v&!!h&&e*xYb#x(!{ literal 0 HcmV?d00001 diff --git a/crates/psd/tests/fixtures/atn/empty.atn b/crates/psd/tests/fixtures/atn/empty.atn new file mode 100644 index 0000000000000000000000000000000000000000..dbcd73d1960acb305ebb3f59856a5b13e1c1f265 GIT binary patch literal 13 NcmZQzU=Uz{0RRB401*HH literal 0 HcmV?d00001 diff --git a/crates/psd/tests/fixtures/atn/float-bits.atn b/crates/psd/tests/fixtures/atn/float-bits.atn new file mode 100644 index 0000000000000000000000000000000000000000..0f272adea8052e66dc94016aba18757b1d53925e GIT binary patch literal 428 zcmY*W%}&EG3{HnSegsm*6Cmvsc!6;!AR)Dvap0D;S(nMOQIbx;g*`GyZo}>xD3nqh;xGJTt`r5O&dq$k0Uzq~ncoF&x;&;PbVhcMLLc#_I$%w$z)?Z;80R zQ`(uJ1}r=GYo(w zfEkWZu#nB>^J>@-JRW=@Fl9E!4jIP [out dir]` fills From 9333e5aad0f10ca78bebedbf1351006c3228ae8e Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Mon, 19 Oct 2026 07:25:28 +0200 Subject: [PATCH 02/52] Prefer an installed pattern ID over a colliding name in ATN import Fixes #7288 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/atn_cmds.rs | 25 +++++++++++++----- crates/engine/src/atn_cmds/tests.rs | 36 ++++++++++++++++++++++++++ crates/engine/src/pattern_cmds.rs | 10 +++++-- crates/engine/src/pattern_fill_cmds.rs | 4 +-- 4 files changed, 64 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs index 9e8eb6cb7ca..1570c7dc712 100644 --- a/crates/engine/src/atn_cmds.rs +++ b/crates/engine/src/atn_cmds.rs @@ -950,14 +950,23 @@ fn adjustment_steps(a: &Adjustment, prefix: &str, type_desc: Option<&Descriptor> } /// 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> { 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()); @@ -974,8 +983,10 @@ fn pattern_params(t: &Descriptor) -> Option> { /// The `patternLayer` descriptor for [`pattern_params`]' params. fn pattern_desc(p: &Value) -> Option { 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)); diff --git a/crates/engine/src/atn_cmds/tests.rs b/crates/engine/src/atn_cmds/tests.rs index 26865d40609..5c1f7ae9821 100644 --- a/crates/engine/src/atn_cmds/tests.rs +++ b/crates/engine/src/atn_cmds/tests.rs @@ -1387,3 +1387,39 @@ fn function_keys_keep_shift_and_command() { } assert_eq!(super::function_key_name(7, false, false), "F7"); } + +/// 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 = v.as_array().unwrap().iter().map(|c| c.as_f64().unwrap()).collect(); + assert_eq!(got, want, "{action}"); + } +} diff --git a/crates/engine/src/pattern_cmds.rs b/crates/engine/src/pattern_cmds.rs index 0cb9052ceb1..56e7cc316a0 100644 --- a/crates/engine/src/pattern_cmds.rs +++ b/crates/engine/src/pattern_cmds.rs @@ -127,7 +127,13 @@ pub fn resolve(s: &Session, key: &str) -> Option { pub(crate) fn resolve_param(s: &Session, cmd: &str, p: &Value) -> Result { let key = p.get("pattern").and_then(Value::as_str).unwrap_or(""); - resolve(s, key).ok_or_else(|| bad(cmd, format!("no pattern \"{key}\" (see pattern.list)"))) + resolve_or_named(s, key, p).ok_or_else(|| bad(cmd, format!("no pattern \"{key}\" (see pattern.list)"))) +} + +/// [`resolve`]s `key`, else the optional `patternName` of `p`: an imported action's pattern +/// recorded with both an id and a name, whose id may not be installed here. +pub(crate) fn resolve_or_named(s: &Session, key: &str, p: &Value) -> Option { + resolve(s, key).or_else(|| p.get("patternName").and_then(Value::as_str).filter(|n| !n.is_empty()).and_then(|n| resolve(s, n))) } /// Copies `pat` into the document's patterns unless it is already there (by id). @@ -433,7 +439,7 @@ pub fn specs() -> Vec { 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? (used when `pattern` is not found),"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, diff --git a/crates/engine/src/pattern_fill_cmds.rs b/crates/engine/src/pattern_fill_cmds.rs index b9d75e6cb50..6ab51ac747d 100644 --- a/crates/engine/src/pattern_fill_cmds.rs +++ b/crates/engine/src/pattern_fill_cmds.rs @@ -37,7 +37,7 @@ fn edited(s: &Session, base: &Fill, p: &Value) -> Result<(Fill, Option) 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).ok_or_else(|| bad(format!("no pattern \"{key}\" (see pattern.list)")))?); } if let Some(v) = num("scale", SCALE_RANGE)? { scale = v / 100.0; @@ -137,7 +137,7 @@ pub fn specs() -> Vec { 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? (used when `pattern` is not found),"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, From 17f5c041d8419e9e65819680fc74c6a4821cebda Mon Sep 17 00:00:00 2001 From: Finn Newick Date: Thu, 22 Oct 2026 22:50:19 +0100 Subject: [PATCH 03/52] feat(actions): import recorded Camera Raw Filter steps as filter.cameraRaw `Adobe Camera Raw Filter` steps in .atn files imported as actions.photoshopStep placeholders, so many retouching actions stopped at them. They now import as filter.cameraRaw, with the Basic, tone curve, point curve, colour mixer, colour grading, detail, grain and vignette settings, using the descriptor keys of 62 recorded steps and the verified PSD Smart Filter mapping. Steps that use settings the command lacks (Calibration, non-Custom white balance, active neutral-only controls) stay Photoshop steps rather than replaying a different look. Export stays refused: the written step's version keys are unverified. Part of #6745 Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/atn_cmds.rs | 107 ++++++++++++++++++++++++++++ crates/engine/src/atn_cmds/tests.rs | 83 +++++++++++++++++++++ 2 files changed, 190 insertions(+) diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs index f166c239b3a..d2b143a2596 100644 --- a/crates/engine/src/atn_cmds.rs +++ b/crates/engine/src/atn_cmds.rs @@ -3037,6 +3037,110 @@ macro_rules! adjustment_event { const RIPPLE_SIZE: &[(&str, &str)] = &[("Sml", "small"), ("Mdm", "medium"), ("Lrg", "large")]; +/// Camera Raw Filter's scalar sliders. Every one is an integer in recorded steps except `Ex12` +/// and `ShpR` (doubles); the layout is from 62 recorded steps in 14 sets (#6745) and matches the +/// verified PSD Smart Filter mapping (`photocraft-io`'s `camera_raw_map.rs`). +const CAMERA_RAW: &[F] = &[ + F("Temp", "temperature", Kind::Long), + F("Tint", "tint", Kind::Long), + F("Ex12", "exposure", Kind::Dbl), + F("Cr12", "contrast", Kind::Long), + F("Hi12", "highlights", Kind::Long), + F("Sh12", "shadows", Kind::Long), + F("Wh12", "whites", Kind::Long), + F("Bk12", "blacks", Kind::Long), + F("CrTx", "texture", Kind::Long), + F("Cl12", "clarity", Kind::Long), + F("Dhze", "dehaze", Kind::Long), + F("Vibr", "vibrance", Kind::Long), + F("Strt", "saturation", Kind::Long), + F("PC_H", "curveHighlights", Kind::Long), + F("PC_L", "curveLights", Kind::Long), + F("PC_D", "curveDarks", Kind::Long), + F("PC_S", "curveShadows", Kind::Long), + F("CgBl", "gradeBlending", Kind::Long), + F("STB ", "gradeBalance", Kind::Long), + F("Shrp", "sharpenAmount", Kind::Long), + F("ShpR", "sharpenRadius", Kind::Dbl), + F("ShpD", "sharpenDetail", Kind::Long), + F("ShpM", "sharpenMasking", Kind::Long), + F("LNR ", "noiseLuminance", Kind::Long), + F("LNRD", "noiseLuminanceDetail", Kind::Long), + F("CNR ", "noiseColor", Kind::Long), + F("CNRD", "noiseColorDetail", Kind::Long), + F("GRNA", "grainAmount", Kind::Long), + F("GRNS", "grainSize", Kind::Long), + F("GRNF", "grainRoughness", Kind::Long), + F("PCVA", "vignetteAmount", Kind::Long), + F("PCVM", "vignetteMidpoint", Kind::Long), + F("PCVR", "vignetteRoundness", Kind::Long), + F("PCVF", "vignetteFeather", Kind::Long), + F("PCVH", "vignetteHighlights", Kind::Long), +]; + +/// A recorded Camera Raw Filter step (`Adobe Camera Raw Filter`) as `filter.cameraRaw` (#6745). +/// Settings the command has no counterpart for refuse the step rather than replaying a different +/// look: the Calibration panel, a white balance other than Custom, and the controls the PSD +/// mapping keeps only at their neutral values. Version metadata and a full settings snapshot's +/// lens and geometry keys are ignored, as other events ignore keys they don't map. +fn camera_raw_from(d: &Descriptor) -> Mapped { + const CALIBRATION: &[&str] = &["RHue", "RSat", "GHue", "GSat", "BHue", "BSat", "BlkB"]; + const NEUTRAL_ONLY: &[(&str, f64)] = + &[("LNRC", 0.0), ("CNRS", 50.0), ("MDis", 0.0), ("VigA", 0.0), ("VigM", 50.0), ("crfs", 100.0), ("TMMs", 0.0), ("PGTM", 0.0), ("RGBt", 0.0)]; + let active = |k: &str, neutral: f64| d.get(k).is_some() && get_num(d, k) != Some(neutral); + let custom_wb = d.get("WBal").is_none() || get_enum(d, "WBal").as_deref() == Some("Cst"); + if !custom_wb || CALIBRATION.iter().any(|k| active(k, 0.0)) || NEUTRAL_ONLY.iter().any(|(k, n)| active(k, *n)) { + return Mapped::Unsupported { harmless: false }; + } + let Some(mut m) = fields_from(d, CAMERA_RAW) else { return Mapped::Unsupported { harmless: false } }; + let nums = |keys: &[&str]| -> Option> { + let v: Vec> = keys.iter().map(|k| get_num(d, k)).collect(); + // Absent members keep the command's defaults only when the whole group is absent. + if v.iter().all(Option::is_none) { None } else { Some(v.into_iter().map(|n| Value::from(n.unwrap_or(0.0))).collect()) } + }; + if let (Some(a), Some(b), Some(c)) = (get_num(d, "PC_1"), get_num(d, "PC_2"), get_num(d, "PC_3")) { + m.insert("curveSplits".into(), json!([a, b, c])); + } + for (prefix, param) in [("HA_", "hslHue"), ("SA_", "hslSat"), ("LA_", "hslLum")] { + let keys: Vec = ["R", "O", "Y", "G", "A", "B", "P", "M"].iter().map(|c| format!("{prefix}{c}")).collect(); + if let Some(v) = nums(&keys.iter().map(String::as_str).collect::>()) { + m.insert(param.into(), Value::Array(v)); + } + } + for (keys, param) in [ + (["STSH", "STSS", "CgSL"], "gradeShadows"), + (["CgMH", "CgMS", "CgML"], "gradeMidtones"), + (["STHH", "STHS", "CgHL"], "gradeHighlights"), + (["CgGH", "CgGS", "CgGL"], "gradeGlobal"), + ] { + if let Some(v) = nums(&keys) { + m.insert(param.into(), json!({"hue": v[0], "sat": v[1], "lum": v[2]})); + } + } + match get_num(d, "PCVS") { + None => {} + Some(n) => match [(1.0, "highlightPriority"), (2.0, "colorPriority"), (3.0, "paintOverlay")].iter().find(|(k, _)| *k == n) { + Some((_, style)) => { + m.insert("vignetteStyle".into(), json!(style)); + } + None => return Mapped::Unsupported { harmless: false }, + }, + } + // Point curves: flat `[in0, out0, in1, out1, …]` lists on 0..255, as the command's pairs. + for (key, param) in [("Crv ", "pointCurve"), ("CrvR", "pointCurveRed"), ("CrvG", "pointCurveGreen"), ("CrvB", "pointCurveBlue")] { + let Some(list) = get_list(d, key) else { continue }; + let Some(flat) = list.iter().map(num).collect::>>() else { return Mapped::Unsupported { harmless: false } }; + if flat.len() % 2 != 0 { + return Mapped::Unsupported { harmless: false }; + } + let identity = flat == [0.0, 0.0, 255.0, 255.0]; + if !identity { + m.insert(param.into(), Value::Array(flat.as_chunks::<2>().0.iter().map(|[a, b]| json!([a, b])).collect())); + } + } + step(crate::lens_cmds::RAW, Value::Object(m)) +} + /// Whether a Select and Mask step carries Refine Edge Brush strokes, which no descriptor holds. fn has_refine_strokes(p: &Value) -> bool { p.get("refineStrokes").is_some_and(|v| !v.is_null() && v.as_array().is_none_or(|a| !a.is_empty())) @@ -3328,6 +3432,9 @@ const EVENTS: &[Event] = &[ ev!("Rple", "ripple", "Ripple", "filter.distort.ripple", &[F("Amnt", "amount", Kind::ExactLong), F("RplS", "size", Kind::Enum("RplS", RIPPLE_SIZE))]), ev!("Crst", "crystallize", "Crystallize", "filter.pixelate.crystallize", &[F("ClSz", "cellSize", Kind::ExactLong)]), Event { code: "GEfc", name: "filterGallery", label: "Filter Gallery", ids: GALLERY_IDS, from: gallery_from, to: gallery_to }, + // Import only: what Photoshop needs in a written step (process version, the full settings + // set) is unverified, so Save Actions still refuses `filter.cameraRaw`. + Event { code: "", name: "Adobe Camera Raw Filter", label: "Camera Raw Filter", ids: &[], from: camera_raw_from, to: |_, _| None }, // Adjustments (Image › Adjustments). Event { code: "", diff --git a/crates/engine/src/atn_cmds/tests.rs b/crates/engine/src/atn_cmds/tests.rs index d83d69e6246..b5f163eb2a6 100644 --- a/crates/engine/src/atn_cmds/tests.rs +++ b/crates/engine/src/atn_cmds/tests.rs @@ -2685,3 +2685,86 @@ fn hue_saturation_uses_photoshops_hue_key() { normalise(&mut p); assert_eq!(p["hue"], json!(30), "{p}"); } + +/// #6745: a recorded Camera Raw Filter step (`Adobe Camera Raw Filter`, the layout of 62 real +/// recordings) imports as `filter.cameraRaw` with its sliders, colour mixer, grading wheels, +/// vignette style and point curves, and plays. One that uses the Calibration panel (or noise +/// settings the command lacks) stays a Photoshop step rather than replaying a different look. +#[test] +fn camera_raw_filter_steps_import_as_filter_camera_raw() { + let int = |v: i32| D::Integer(v); + let mut d = desc("null") + .with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))) + .with("PrVe", int(184_549_376)) + .with("WBal", enm("WBal", "Cst ")) + .with("Temp", int(12)) + .with("Tint", int(-4)) + .with("Ex12", D::Double(0.35)) + .with("Cr12", int(10)) + .with("Hi12", int(-30)) + .with("Sh12", int(25)) + .with("Cl12", int(8)) + .with("Vibr", int(15)) + .with("PC_1", int(20)) + .with("PC_2", int(50)) + .with("PC_3", int(80)) + .with("STSH", int(210)) + .with("STSS", int(12)) + .with("CgSL", int(0)) + .with("CgBl", int(60)) + .with("STB ", int(-10)) + .with("Shrp", int(40)) + .with("ShpR", D::Double(1.2)) + .with("LNR ", int(20)) + .with("LNRC", int(0)) + .with("CNR ", int(25)) + .with("CNRS", int(50)) + .with("PCVA", int(-20)) + .with("PCVS", int(2)) + .with("Crv ", D::List([0, 0, 64, 50, 255, 255].map(int).to_vec())) + .with("CrvR", D::List([0, 0, 255, 255].map(int).to_vec())); + for (k, v) in ["R", "O", "Y", "G", "A", "B", "P", "M"].iter().zip(1..) { + d = d.with(&format!("HA_{k}"), int(v)); + } + d = d.with("SA_O", int(-15)); + let calibrated = desc("null").with("Ex12", D::Double(0.2)).with("RHue", int(8)); + let smoothed = desc("null").with("CNR ", int(25)).with("CNRS", int(70)); + let auto_wb = desc("null").with("WBal", enm("WBal", "Atmt")).with("Temp", int(5)); + let items = vec![ + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(d)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(calibrated)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(smoothed)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(auto_wb)), + ]; + let file = AtnFile { + name: UnicodeString::new_nul("Looks"), + expanded: false, + actions: vec![AtnAction { name: UnicodeString::new_nul("Warm"), items, ..Default::default() }], + warnings: vec![], + }; + let imp = import(&atn::write(&file).unwrap()).unwrap(); + let steps = &imp.actions[0].steps; + let (id, p) = &steps[0]; + assert_eq!(id, "filter.cameraRaw"); + assert_eq!( + *p, + json!({ + "temperature": 12, "tint": -4, "exposure": 0.35, "contrast": 10, "highlights": -30, "shadows": 25, + "clarity": 8, "vibrance": 15, "curveSplits": [20, 50, 80], + "hslHue": [1, 2, 3, 4, 5, 6, 7, 8], "hslSat": [0, -15, 0, 0, 0, 0, 0, 0], + "gradeShadows": {"hue": 210, "sat": 12, "lum": 0}, "gradeBlending": 60, "gradeBalance": -10, + "sharpenAmount": 40, "sharpenRadius": 1.2, "noiseLuminance": 20, "noiseColor": 25, + "vignetteAmount": -20, "vignetteStyle": "colorPriority", "pointCurve": [[0, 0], [64, 50], [255, 255]] + }) + ); + for (k, (id, _)) in steps.iter().enumerate().skip(1) { + assert_eq!(id, PHOTOSHOP_STEP, "step {k}"); + } + assert_eq!(imp.unsupported.iter().map(|u| u.step).collect::>(), [1, 2, 3]); + // The imported step plays. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 12})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"color": "#808080"})).unwrap(); + s.execute(id, p.clone()).unwrap(); +} From 62665c2aff8adb915307dbadfbd0c60e17ac3002 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20Lu=C3=ADs=20da=20Silva?= Date: Thu, 22 Oct 2026 19:41:13 -0300 Subject: [PATCH 04/52] Refuse exporting an adjustment edit that names its layer to .atn The Set event Photoshop plays edits the current adjustment layer, so a layer.setAdjustment step that names another layer (or document) played back on whichever adjustment layer was active. Refuse it in strict export, as layer.fill.pattern.set already does; skipUnsupported skips it. Steps recorded on the selected layer carry no layer and still export. Fixes #8532 --- crates/engine/src/atn_cmds.rs | 5 +++++ crates/engine/src/atn_cmds/tests.rs | 5 ++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs index f166c239b3a..7f133f939b5 100644 --- a/crates/engine/src/atn_cmds.rs +++ b/crates/engine/src/atn_cmds.rs @@ -1659,6 +1659,11 @@ fn set_to(id: &str, p: &Value) -> Option { desc("null").with("null", target_ref("contentLayer")).with("T ", D::Descriptor(pattern_desc(p)?)) } "layer.setAdjustment" => { + // The event edits the current adjustment layer: a step that names its layer or + // document would play back on whichever one is active instead (#8532). + if p.get("layer").is_some() || p.get("document").is_some() { + return None; + } // The adjustment kind isn't in the params: Photoshop needs it, so only steps that // name one (`kind`) export. let a = adjustment_by_suffix(jstr(p, "kind")?)?; diff --git a/crates/engine/src/atn_cmds/tests.rs b/crates/engine/src/atn_cmds/tests.rs index d83d69e6246..f7c486ac708 100644 --- a/crates/engine/src/atn_cmds/tests.rs +++ b/crates/engine/src/atn_cmds/tests.rs @@ -356,7 +356,8 @@ fn a_selective_color_step_in_the_scalar_form_keeps_its_values() { /// A setting Photoshop's event has no field for is dropped by export, and the step then plays back /// as a different edit: Crystallize's `seed` (#7668), Radial Blur's centre, Minimum's and -/// Maximum's `preserve`. Such a step is refused, as one with no equivalent event already is. +/// Maximum's `preserve`. Such a step is refused, as one with no equivalent event already is. So is +/// an adjustment edit that names its layer: the event edits the active one (#8532). #[test] fn a_setting_the_event_cannot_hold_is_refused() { for (id, params) in [ @@ -364,6 +365,7 @@ fn a_setting_the_event_cannot_hold_is_refused() { ("filter.blur.radialBlur", json!({"amount": 10, "centerX": 0.25, "centerY": 0.5})), ("filter.other.minimum", json!({"radius": 4, "preserve": "roundness"})), ("filter.other.maximum", json!({"radius": 4, "preserve": "roundness"})), + ("layer.setAdjustment", json!({"kind": "exposure", "layer": "Target_existing", "exposure": -0.75, "offset": 0.035, "gamma": 1.37})), ] { let mut s = Session::new(); s.actions.list.push(Action::new("A", vec![(id.into(), params)])); @@ -388,6 +390,7 @@ fn settings_at_the_value_the_event_plays_still_export() { ("filter.blur.radialBlur", json!({"amount": 10})), ("filter.other.minimum", json!({"radius": 4, "preserve": "squareness"})), ("filter.other.maximum", json!({"radius": 4})), + ("layer.setAdjustment", json!({"kind": "exposure", "exposure": -0.75, "offset": 0.035, "gamma": 1.37})), // `preserve` reaches the filter through a comparison with the exact string "roundness", // so these play as squareness -- replay's own value -- and lose nothing by export (#7759 // review). From 82f7d8707222df43389c3f632b8f2d20d97d5694 Mon Sep 17 00:00:00 2001 From: Finn Newick Date: Thu, 22 Oct 2026 23:42:20 +0100 Subject: [PATCH 05/52] fix(actions): keep partial Camera Raw splits and odd curves as Photoshop steps A step with only some of PC_1..PC_3, or a point curve that isn't a list, now stays a Photoshop step instead of importing without that setting. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/atn_cmds.rs | 14 +++++++++++--- crates/engine/src/atn_cmds/tests.rs | 6 +++++- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs index d2b143a2596..b1f43bd81a9 100644 --- a/crates/engine/src/atn_cmds.rs +++ b/crates/engine/src/atn_cmds.rs @@ -3098,8 +3098,13 @@ fn camera_raw_from(d: &Descriptor) -> Mapped { // Absent members keep the command's defaults only when the whole group is absent. if v.iter().all(Option::is_none) { None } else { Some(v.into_iter().map(|n| Value::from(n.unwrap_or(0.0))).collect()) } }; - if let (Some(a), Some(b), Some(c)) = (get_num(d, "PC_1"), get_num(d, "PC_2"), get_num(d, "PC_3")) { - m.insert("curveSplits".into(), json!([a, b, c])); + // The splits are one setting: all three, or none (the defaults); a partial set can't replay. + match (get_num(d, "PC_1"), get_num(d, "PC_2"), get_num(d, "PC_3")) { + (Some(a), Some(b), Some(c)) => { + m.insert("curveSplits".into(), json!([a, b, c])); + } + _ if ["PC_1", "PC_2", "PC_3"].iter().any(|k| d.get(k).is_some()) => return Mapped::Unsupported { harmless: false }, + _ => {} } for (prefix, param) in [("HA_", "hslHue"), ("SA_", "hslSat"), ("LA_", "hslLum")] { let keys: Vec = ["R", "O", "Y", "G", "A", "B", "P", "M"].iter().map(|c| format!("{prefix}{c}")).collect(); @@ -3128,7 +3133,10 @@ fn camera_raw_from(d: &Descriptor) -> Mapped { } // Point curves: flat `[in0, out0, in1, out1, …]` lists on 0..255, as the command's pairs. for (key, param) in [("Crv ", "pointCurve"), ("CrvR", "pointCurveRed"), ("CrvG", "pointCurveGreen"), ("CrvB", "pointCurveBlue")] { - let Some(list) = get_list(d, key) else { continue }; + if d.get(key).is_none() { + continue; + } + let Some(list) = get_list(d, key) else { return Mapped::Unsupported { harmless: false } }; let Some(flat) = list.iter().map(num).collect::>>() else { return Mapped::Unsupported { harmless: false } }; if flat.len() % 2 != 0 { return Mapped::Unsupported { harmless: false }; diff --git a/crates/engine/src/atn_cmds/tests.rs b/crates/engine/src/atn_cmds/tests.rs index b5f163eb2a6..fe0f5a22e84 100644 --- a/crates/engine/src/atn_cmds/tests.rs +++ b/crates/engine/src/atn_cmds/tests.rs @@ -2730,11 +2730,15 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { let calibrated = desc("null").with("Ex12", D::Double(0.2)).with("RHue", int(8)); let smoothed = desc("null").with("CNR ", int(25)).with("CNRS", int(70)); let auto_wb = desc("null").with("WBal", enm("WBal", "Atmt")).with("Temp", int(5)); + let partial_splits = desc("null").with("PC_1", int(20)); + let odd_curve = desc("null").with("Crv ", int(3)); let items = vec![ item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(d)), item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(calibrated)), item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(smoothed)), item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(auto_wb)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(partial_splits)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(odd_curve)), ]; let file = AtnFile { name: UnicodeString::new_nul("Looks"), @@ -2760,7 +2764,7 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { for (k, (id, _)) in steps.iter().enumerate().skip(1) { assert_eq!(id, PHOTOSHOP_STEP, "step {k}"); } - assert_eq!(imp.unsupported.iter().map(|u| u.step).collect::>(), [1, 2, 3]); + assert_eq!(imp.unsupported.iter().map(|u| u.step).collect::>(), [1, 2, 3, 4, 5]); // The imported step plays. let mut s = Session::new(); s.execute("file.new", json!({"width": 16, "height": 12})).unwrap(); From 13ba4fcb6f8c8ec0bcfd9ad818737ff478d3fb77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20Lu=C3=ADs=20da=20Silva?= Date: Thu, 22 Oct 2026 23:21:52 -0300 Subject: [PATCH 06/52] Export an adjustment edit whose layer is null, like the target layer A null layer means the target layer, as layer_ref reads it, so the guard refuses only a layer that names one. --- crates/engine/src/atn_cmds.rs | 5 +++-- crates/engine/src/atn_cmds/tests.rs | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs index 7f133f939b5..79b7945fa21 100644 --- a/crates/engine/src/atn_cmds.rs +++ b/crates/engine/src/atn_cmds.rs @@ -1660,8 +1660,9 @@ fn set_to(id: &str, p: &Value) -> Option { } "layer.setAdjustment" => { // The event edits the current adjustment layer: a step that names its layer or - // document would play back on whichever one is active instead (#8532). - if p.get("layer").is_some() || p.get("document").is_some() { + // document would play back on whichever one is active instead (#8532). A null + // `layer` is the target layer, as in `layer_ref`. + if p.get("layer").is_some_and(|l| !l.is_null()) || p.get("document").is_some() { return None; } // The adjustment kind isn't in the params: Photoshop needs it, so only steps that diff --git a/crates/engine/src/atn_cmds/tests.rs b/crates/engine/src/atn_cmds/tests.rs index f7c486ac708..3f205d3edde 100644 --- a/crates/engine/src/atn_cmds/tests.rs +++ b/crates/engine/src/atn_cmds/tests.rs @@ -391,6 +391,7 @@ fn settings_at_the_value_the_event_plays_still_export() { ("filter.other.minimum", json!({"radius": 4, "preserve": "squareness"})), ("filter.other.maximum", json!({"radius": 4})), ("layer.setAdjustment", json!({"kind": "exposure", "exposure": -0.75, "offset": 0.035, "gamma": 1.37})), + ("layer.setAdjustment", json!({"kind": "exposure", "layer": null, "exposure": -0.75})), // `preserve` reaches the filter through a comparison with the exact string "roundness", // so these play as squareness -- replay's own value -- and lose nothing by export (#7759 // review). From 75a5f03e73c0c1ece3c7c037369a27ef4ab1e537 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20Lu=C3=ADs=20da=20Silva?= Date: Thu, 22 Oct 2026 23:42:55 -0300 Subject: [PATCH 07/52] Export an adjustment edit whose document is null, like its layer A null document is the active one, as the command reads it; only a step that names a layer or document is refused. --- crates/engine/src/atn_cmds.rs | 4 ++-- crates/engine/src/atn_cmds/tests.rs | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs index 79b7945fa21..1577544d23c 100644 --- a/crates/engine/src/atn_cmds.rs +++ b/crates/engine/src/atn_cmds.rs @@ -1661,8 +1661,8 @@ fn set_to(id: &str, p: &Value) -> Option { "layer.setAdjustment" => { // The event edits the current adjustment layer: a step that names its layer or // document would play back on whichever one is active instead (#8532). A null - // `layer` is the target layer, as in `layer_ref`. - if p.get("layer").is_some_and(|l| !l.is_null()) || p.get("document").is_some() { + // `layer` or `document` is the target one, as the command reads it. + if ["layer", "document"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { return None; } // The adjustment kind isn't in the params: Photoshop needs it, so only steps that diff --git a/crates/engine/src/atn_cmds/tests.rs b/crates/engine/src/atn_cmds/tests.rs index 3f205d3edde..fcbeaa2800b 100644 --- a/crates/engine/src/atn_cmds/tests.rs +++ b/crates/engine/src/atn_cmds/tests.rs @@ -366,6 +366,7 @@ fn a_setting_the_event_cannot_hold_is_refused() { ("filter.other.minimum", json!({"radius": 4, "preserve": "roundness"})), ("filter.other.maximum", json!({"radius": 4, "preserve": "roundness"})), ("layer.setAdjustment", json!({"kind": "exposure", "layer": "Target_existing", "exposure": -0.75, "offset": 0.035, "gamma": 1.37})), + ("layer.setAdjustment", json!({"kind": "exposure", "document": 2, "exposure": -0.75})), ] { let mut s = Session::new(); s.actions.list.push(Action::new("A", vec![(id.into(), params)])); @@ -392,6 +393,7 @@ fn settings_at_the_value_the_event_plays_still_export() { ("filter.other.maximum", json!({"radius": 4})), ("layer.setAdjustment", json!({"kind": "exposure", "exposure": -0.75, "offset": 0.035, "gamma": 1.37})), ("layer.setAdjustment", json!({"kind": "exposure", "layer": null, "exposure": -0.75})), + ("layer.setAdjustment", json!({"kind": "exposure", "document": null, "exposure": -0.75})), // `preserve` reaches the filter through a comparison with the exact string "roundness", // so these play as squareness -- replay's own value -- and lose nothing by export (#7759 // review). From e6a3a4d511fe2a33188ec9e3549d6d676bea1936 Mon Sep 17 00:00:00 2001 From: John Turnbach Date: Fri, 23 Oct 2026 09:59:42 -0400 Subject: [PATCH 08/52] fix(atn): import Photoshop's string class for Vibrance adjustment Sets Photoshop's Properties panel records an edit of an existing Vibrance layer with the class string id `vibrance`, not the `Vbrn` code the adjustment table knows, so the whole Set imported as an unsupported Photoshop step and stopped playback. Map the string class to the same adjustment. Fixes #8534 --- crates/engine/src/atn_cmds.rs | 8 +++++++- crates/engine/src/atn_cmds/tests.rs | 24 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs index f166c239b3a..97ab83e3fd2 100644 --- a/crates/engine/src/atn_cmds.rs +++ b/crates/engine/src/atn_cmds.rs @@ -898,8 +898,14 @@ const ADJUSTMENTS: &[Adjustment] = &[ Adjustment { class: "GdMp", suffix: "gradientMap", from: gradient_map_from, to: gradient_map_to }, ]; +/// Classes Photoshop records by string id for an adjustment the table knows by its code: the +/// Properties panel writes an existing Vibrance layer's edit as class `vibrance` (#8534). +const ADJUSTMENT_CLASS_NAMES: &[(&str, &str)] = &[("vibrance", "Vbrn")]; + fn adjustment_by_class(c: &str) -> Option<&'static Adjustment> { - ADJUSTMENTS.iter().find(|a| a.class.trim_end() == c.trim_end()) + let c = c.trim_end(); + let c = ADJUSTMENT_CLASS_NAMES.iter().find(|(name, _)| *name == c).map_or(c, |(_, code)| code); + ADJUSTMENTS.iter().find(|a| a.class.trim_end() == c) } const PHOTO_FILTER_FIELDS: &[F] = &[F("Clr ", "color", Kind::Color), F("Dnst", "density", Kind::Long), F("PrsL", "preserveLuminosity", Kind::Bool)]; diff --git a/crates/engine/src/atn_cmds/tests.rs b/crates/engine/src/atn_cmds/tests.rs index d83d69e6246..c8b366bf219 100644 --- a/crates/engine/src/atn_cmds/tests.rs +++ b/crates/engine/src/atn_cmds/tests.rs @@ -2364,6 +2364,30 @@ fn adjustment_layer_reset_still_resets() { assert_eq!(steps[1].1, json!({"midtones": [10, 0, 0], "kind": "colorBalance"})); } +/// Photoshop's Properties panel records an edit of an existing Vibrance layer with the string +/// class `vibrance`, not the `Vbrn` code: both import as the same `layer.setAdjustment` (#8534). +#[test] +fn adjustment_layer_set_accepts_the_vibrance_string_class() { + let set = |class: &str| { + let t = desc(class).with("temperature", long(0.0)).with("tint", long(0.0)).with("vibrance", long(28.0)).with("Strt", long(-7.0)); + desc("null").with("null", target_ref("AdjL")).with("T ", D::Descriptor(t)) + }; + let file = AtnFile { + name: UnicodeString::new_nul("Vibrance"), + expanded: false, + actions: vec![AtnAction { + name: UnicodeString::new_nul("A"), + items: vec![item("set", "Set", Some(set("vibrance"))), item("set", "Set", Some(set("Vbrn")))], + ..Default::default() + }], + warnings: vec![], + }; + let action = import(&atn::write(&file).unwrap()).unwrap().actions.remove(0); + assert_eq!(action.steps[0].0, "layer.setAdjustment", "{:?}", action.steps); + assert_eq!(action.steps[0].1, json!({"vibrance": 28, "saturation": -7, "kind": "vibrance"})); + assert_eq!(action.steps[0], action.steps[1]); +} + /// A Free Transform recorded against an unlinked mask or an alpha channel must not export as a /// layer transform that moves the layer's pixels on replay (#7195). #[test] From d5f561190bd7d0ce74e9fc29b2e9667651879400 Mon Sep 17 00:00:00 2001 From: John Turnbach Date: Fri, 23 Oct 2026 09:59:42 -0400 Subject: [PATCH 09/52] docs(atn): document adjustment_by_class --- crates/engine/src/atn_cmds.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs index 97ab83e3fd2..f24595634e9 100644 --- a/crates/engine/src/atn_cmds.rs +++ b/crates/engine/src/atn_cmds.rs @@ -902,6 +902,9 @@ const ADJUSTMENTS: &[Adjustment] = &[ /// Properties panel writes an existing Vibrance layer's edit as class `vibrance` (#8534). const ADJUSTMENT_CLASS_NAMES: &[(&str, &str)] = &[("vibrance", "Vbrn")]; +/// The adjustment for a recorded descriptor class: its four-character code (`Vbrn`, trailing +/// spaces ignored) or a string id Photoshop uses for it instead (`vibrance`, see +/// [`ADJUSTMENT_CLASS_NAMES`]). `None` for a class that is not an adjustment this table knows. fn adjustment_by_class(c: &str) -> Option<&'static Adjustment> { let c = c.trim_end(); let c = ADJUSTMENT_CLASS_NAMES.iter().find(|(name, _)| *name == c).map_or(c, |(_, code)| code); From bbe7659ac3b4741ddb6dc935b1d78b11462e498e Mon Sep 17 00:00:00 2001 From: Finn Newick Date: Fri, 23 Oct 2026 15:05:23 +0100 Subject: [PATCH 10/52] fix(actions): refuse unreadable Camera Raw values, bad splits and curves A recorded Camera Raw Filter step now stays a Photoshop step when a value it records is not a number, when its curve splits are outside 0..=100 or out of order, or when a point curve is one that filter.cameraRaw refuses (validate_curve), instead of replaying a different look or failing on playback. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/atn_cmds.rs | 19 ++++++++++++++++--- crates/engine/src/atn_cmds/tests.rs | 17 ++++++++++++++++- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs index 9abbf7b922e..431adcdf789 100644 --- a/crates/engine/src/atn_cmds.rs +++ b/crates/engine/src/atn_cmds.rs @@ -3092,17 +3092,27 @@ fn camera_raw_from(d: &Descriptor) -> Mapped { if !custom_wb || CALIBRATION.iter().any(|k| active(k, 0.0)) || NEUTRAL_ONLY.iter().any(|(k, n)| active(k, *n)) { return Mapped::Unsupported { harmless: false }; } + // A value that is recorded but isn't a number can't replay: `fields_from` and `nums` would + // drop it (or read it as 0) and play a different look. + let unreadable = |k: &str| d.get(k).is_some() && get_num(d, k).is_none(); + let grouped = ["HA_", "SA_", "LA_"].iter().flat_map(|p| ["R", "O", "Y", "G", "A", "B", "P", "M"].map(|c| format!("{p}{c}"))); + let grades = ["STSH", "STSS", "CgSL", "CgMH", "CgMS", "CgML", "STHH", "STHS", "CgHL", "CgGH", "CgGS", "CgGL", "PC_1", "PC_2", "PC_3", "PCVS"]; + if CAMERA_RAW.iter().any(|F(k, ..)| unreadable(k)) || grouped.into_iter().any(|k| unreadable(&k)) || grades.iter().any(|k| unreadable(k)) { + return Mapped::Unsupported { harmless: false }; + } let Some(mut m) = fields_from(d, CAMERA_RAW) else { return Mapped::Unsupported { harmless: false } }; let nums = |keys: &[&str]| -> Option> { let v: Vec> = keys.iter().map(|k| get_num(d, k)).collect(); // Absent members keep the command's defaults only when the whole group is absent. if v.iter().all(Option::is_none) { None } else { Some(v.into_iter().map(|n| Value::from(n.unwrap_or(0.0))).collect()) } }; - // The splits are one setting: all three, or none (the defaults); a partial set can't replay. + // The splits are one setting: all three, or none (the defaults); a partial set can't replay, + // nor can splits outside 0..=100 or out of order, which would build a different curve. match (get_num(d, "PC_1"), get_num(d, "PC_2"), get_num(d, "PC_3")) { - (Some(a), Some(b), Some(c)) => { + (Some(a), Some(b), Some(c)) if (0.0..=100.0).contains(&a) && a < b && b < c && c <= 100.0 => { m.insert("curveSplits".into(), json!([a, b, c])); } + (Some(_), Some(_), Some(_)) => return Mapped::Unsupported { harmless: false }, _ if ["PC_1", "PC_2", "PC_3"].iter().any(|k| d.get(k).is_some()) => return Mapped::Unsupported { harmless: false }, _ => {} } @@ -3138,7 +3148,10 @@ fn camera_raw_from(d: &Descriptor) -> Mapped { } let Some(list) = get_list(d, key) else { return Mapped::Unsupported { harmless: false } }; let Some(flat) = list.iter().map(num).collect::>>() else { return Mapped::Unsupported { harmless: false } }; - if flat.len() % 2 != 0 { + // Odd lengths, and curves `filter.cameraRaw` refuses (one point, out of range, inputs not + // increasing), stay Photoshop steps rather than failing on playback. + let points: Vec<[f32; 2]> = flat.as_chunks::<2>().0.iter().map(|[a, b]| [*a as f32, *b as f32]).collect(); + if flat.len() % 2 != 0 || photocraft_algo::camera_raw::validate_curve(&points).is_err() { return Mapped::Unsupported { harmless: false }; } let identity = flat == [0.0, 0.0, 255.0, 255.0]; diff --git a/crates/engine/src/atn_cmds/tests.rs b/crates/engine/src/atn_cmds/tests.rs index a47bdc48b8b..95d39375db5 100644 --- a/crates/engine/src/atn_cmds/tests.rs +++ b/crates/engine/src/atn_cmds/tests.rs @@ -2749,6 +2749,14 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { let auto_wb = desc("null").with("WBal", enm("WBal", "Atmt")).with("Temp", int(5)); let partial_splits = desc("null").with("PC_1", int(20)); let odd_curve = desc("null").with("Crv ", int(3)); + // Review of #8714: values that would replay differently, or fail to play, stay Photoshop steps. + let reversed_splits = desc("null").with("PC_1", int(80)).with("PC_2", int(50)).with("PC_3", int(20)); + let split_past_100 = desc("null").with("PC_1", int(20)).with("PC_2", int(50)).with("PC_3", int(120)); + let one_point_curve = desc("null").with("Crv ", D::List([0, 0].map(int).to_vec())); + let unordered_curve = desc("null").with("CrvG", D::List([0, 0, 128, 90, 64, 50, 255, 255].map(int).to_vec())); + let text_contrast = desc("null").with("Cr12", D::Text(UnicodeString::new_nul("ten"))); + let text_hue = desc("null").with("HA_R", D::Text(UnicodeString::new_nul("red"))); + let text_grade = desc("null").with("STSH", D::Text(UnicodeString::new_nul("blue"))); let items = vec![ item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(d)), item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(calibrated)), @@ -2756,6 +2764,13 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(auto_wb)), item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(partial_splits)), item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(odd_curve)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(reversed_splits)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(split_past_100)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(one_point_curve)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(unordered_curve)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(text_contrast)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(text_hue)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(text_grade)), ]; let file = AtnFile { name: UnicodeString::new_nul("Looks"), @@ -2781,7 +2796,7 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { for (k, (id, _)) in steps.iter().enumerate().skip(1) { assert_eq!(id, PHOTOSHOP_STEP, "step {k}"); } - assert_eq!(imp.unsupported.iter().map(|u| u.step).collect::>(), [1, 2, 3, 4, 5]); + assert_eq!(imp.unsupported.iter().map(|u| u.step).collect::>(), (1..=12).collect::>()); // The imported step plays. let mut s = Session::new(); s.execute("file.new", json!({"width": 16, "height": 12})).unwrap(); From ee5d5560148ccef13ccc7fee2a47ba360b61c8c9 Mon Sep 17 00:00:00 2001 From: Finn Newick Date: Fri, 23 Oct 2026 15:25:06 +0100 Subject: [PATCH 11/52] fix(actions): keep out-of-range Camera Raw values as Photoshop steps A recorded Camera Raw Filter value outside its slider's range (exposure past +/-5, negative sharpening, ...) was imported and then clamped on playback. It now leaves the step as a Photoshop step, using the PSD mapping's ranges. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/atn_cmds.rs | 25 ++++++++++++++++++++++--- crates/engine/src/atn_cmds/tests.rs | 6 +++++- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs index 431adcdf789..ac3b5a50da2 100644 --- a/crates/engine/src/atn_cmds.rs +++ b/crates/engine/src/atn_cmds.rs @@ -3078,6 +3078,20 @@ const CAMERA_RAW: &[F] = &[ F("PCVH", "vignetteHighlights", Kind::Long), ]; +/// The range a Camera Raw Filter descriptor key's value can take, as `filter.cameraRaw` and the +/// PSD Smart Filter mapping (`photocraft-io`'s `camera_raw_map.rs`) accept it. +fn camera_raw_range(key: &str) -> std::ops::RangeInclusive { + match key { + "Ex12" => -5.0..=5.0, + "ShpR" => 0.5..=3.0, + "Shrp" => 0.0..=150.0, + "STSH" | "STHH" | "CgMH" | "CgGH" => 0.0..=360.0, + "PC_1" | "PC_2" | "PC_3" | "ShpD" | "ShpM" | "LNR " | "LNRD" | "CNR " | "CNRD" | "STSS" | "STHS" | "CgMS" | "CgGS" | "CgBl" | "GRNA" | "GRNS" + | "GRNF" | "PCVM" | "PCVF" | "PCVH" => 0.0..=100.0, + _ => -100.0..=100.0, + } +} + /// A recorded Camera Raw Filter step (`Adobe Camera Raw Filter`) as `filter.cameraRaw` (#6745). /// Settings the command has no counterpart for refuse the step rather than replaying a different /// look: the Calibration panel, a white balance other than Custom, and the controls the PSD @@ -3092,9 +3106,14 @@ fn camera_raw_from(d: &Descriptor) -> Mapped { if !custom_wb || CALIBRATION.iter().any(|k| active(k, 0.0)) || NEUTRAL_ONLY.iter().any(|(k, n)| active(k, *n)) { return Mapped::Unsupported { harmless: false }; } - // A value that is recorded but isn't a number can't replay: `fields_from` and `nums` would - // drop it (or read it as 0) and play a different look. - let unreadable = |k: &str| d.get(k).is_some() && get_num(d, k).is_none(); + // A value that is recorded but isn't a number, or lies outside the slider's range, can't + // replay: `fields_from` and `nums` would drop it (or read it as 0), and playback would clamp + // it, so the step would play a different look. The ranges are the PSD mapping's. + let unreadable = |k: &str| match (d.get(k), get_num(d, k)) { + (None, _) => false, + (Some(_), None) => true, + (Some(_), Some(v)) => k != "PCVS" && !(v.is_finite() && camera_raw_range(k).contains(&v)), + }; let grouped = ["HA_", "SA_", "LA_"].iter().flat_map(|p| ["R", "O", "Y", "G", "A", "B", "P", "M"].map(|c| format!("{p}{c}"))); let grades = ["STSH", "STSS", "CgSL", "CgMH", "CgMS", "CgML", "STHH", "STHS", "CgHL", "CgGH", "CgGS", "CgGL", "PC_1", "PC_2", "PC_3", "PCVS"]; if CAMERA_RAW.iter().any(|F(k, ..)| unreadable(k)) || grouped.into_iter().any(|k| unreadable(&k)) || grades.iter().any(|k| unreadable(k)) { diff --git a/crates/engine/src/atn_cmds/tests.rs b/crates/engine/src/atn_cmds/tests.rs index 95d39375db5..6f7e25121e3 100644 --- a/crates/engine/src/atn_cmds/tests.rs +++ b/crates/engine/src/atn_cmds/tests.rs @@ -2757,6 +2757,8 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { let text_contrast = desc("null").with("Cr12", D::Text(UnicodeString::new_nul("ten"))); let text_hue = desc("null").with("HA_R", D::Text(UnicodeString::new_nul("red"))); let text_grade = desc("null").with("STSH", D::Text(UnicodeString::new_nul("blue"))); + let exposure_past_5 = desc("null").with("Ex12", D::Double(6.0)); + let negative_sharpening = desc("null").with("Shrp", int(-10)); let items = vec![ item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(d)), item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(calibrated)), @@ -2771,6 +2773,8 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(text_contrast)), item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(text_hue)), item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(text_grade)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(exposure_past_5)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(negative_sharpening)), ]; let file = AtnFile { name: UnicodeString::new_nul("Looks"), @@ -2796,7 +2800,7 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { for (k, (id, _)) in steps.iter().enumerate().skip(1) { assert_eq!(id, PHOTOSHOP_STEP, "step {k}"); } - assert_eq!(imp.unsupported.iter().map(|u| u.step).collect::>(), (1..=12).collect::>()); + assert_eq!(imp.unsupported.iter().map(|u| u.step).collect::>(), (1..=14).collect::>()); // The imported step plays. let mut s = Session::new(); s.execute("file.new", json!({"width": 16, "height": 12})).unwrap(); From fe7f48fe2ee7ad5037105899d57d54cb325c84c0 Mon Sep 17 00:00:00 2001 From: Ben Huyck Date: Wed, 21 Oct 2026 11:46:12 +0000 Subject: [PATCH 12/52] PSD: guess the legacy code page of 8-bit names (#6743) --- Cargo.lock | 1 + Cargo.toml | 1 + crates/psd/Cargo.toml | 1 + crates/psd/src/codepage.rs | 461 +++++++++++++++++++++++++++++++++++++ crates/psd/src/lib.rs | 1 + 5 files changed, 465 insertions(+) create mode 100644 crates/psd/src/codepage.rs diff --git a/Cargo.lock b/Cargo.lock index 52a1b2aac64..ffc7f103ea4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5322,6 +5322,7 @@ dependencies = [ name = "photocraft-psd" version = "0.17.0" dependencies = [ + "encoding_rs", "flate2", "photocraft-psd", "proptest", diff --git a/Cargo.toml b/Cargo.toml index 144b7e4475e..c4816e637a0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -53,6 +53,7 @@ clap_mangen = { version = "0.3.3", features = ["env"] } arc-swap = "1" bytemuck = { version = "1", features = ["derive"] } flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] } +encoding_rs = { version = "0.8", default-features = false, features = ["alloc"] } image = { version = "0.25", default-features = false } # Baseline-JPEG decode of lossy DNG tiles (compression 34892), shared with zune-jpeg. zune-core = "0.5" diff --git a/crates/psd/Cargo.toml b/crates/psd/Cargo.toml index 12662f9bd3e..7ecce9ee673 100644 --- a/crates/psd/Cargo.toml +++ b/crates/psd/Cargo.toml @@ -20,6 +20,7 @@ testgen = [] [dependencies] thiserror = { workspace = true } flate2 = { workspace = true } +encoding_rs = { workspace = true } serde = { workspace = true, optional = true } [dev-dependencies] diff --git a/crates/psd/src/codepage.rs b/crates/psd/src/codepage.rs new file mode 100644 index 00000000000..3918cd1879d --- /dev/null +++ b/crates/psd/src/codepage.rs @@ -0,0 +1,461 @@ +//! Guessing the legacy code page of 8-bit names. +//! +//! Some formats store names as bytes in the writer's system ANSI code page: an `.atn` file's +//! event and dictionary names are CP936 (GBK) from Chinese Photoshop, CP932 (Shift_JIS) from +//! Japanese, Mac Roman from French Photoshop on a Mac, and so on. Nothing in the file says +//! which. When the file also stores some of those names as Unicode, [`match_known`] finds the +//! code page that turns the bytes into them. Otherwise [`guess`] infers one code page per file +//! from the names that are not valid UTF-8: +//! +//! 1. Candidates: Shift_JIS, GBK, Big5, EUC-KR, windows-1252, windows-1251, macintosh (Mac +//! Roman). A candidate that cannot decode every name without errors is dropped. +//! 2. Each survivor is scored by the share of non-ASCII bytes that fall in its common-text +//! ranges (GB2312 hanzi, JIS level-1 kanji and kana, Big5 level 1, KS X 1001 Hangul, +//! letters, and each page's punctuation). The highest share wins. +//! 3. A tie is broken by the script of a hint (text the file stores as UTF-16, so it decodes +//! fine): kana → Shift_JIS; Hangul → EUC-KR; Cyrillic → windows-1251; Han → GBK, then +//! Big5, then Shift_JIS; Latin letters → windows-1252, then Mac Roman. +//! 4. Still tied: windows-1252, flagged [`Guess::uncertain`]. +//! +//! Only the first [`GUESS_SAMPLE`] bytes of names are examined. + +use encoding_rs::{ + BIG5, DecoderResult, EUC_KR, Encoding, GBK, MACINTOSH, REPLACEMENT, SHIFT_JIS, UTF_8, UTF_16BE, UTF_16LE, WINDOWS_1251, WINDOWS_1252, X_USER_DEFINED, +}; + +use crate::error::{PsdError, Result}; + +/// At most this many bytes of legacy names are examined by [`guess`]. +pub(crate) const GUESS_SAMPLE: usize = 64 * 1024; +/// At most this many `(bytes, text)` pairs are examined by [`match_known`]. +pub(crate) const KNOWN_PAIRS: usize = 256; + +/// The code page [`guess`] settled on. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Guess { + /// The encoding to decode every legacy name with. + pub(crate) encoding: &'static Encoding, + /// Nothing told the candidates apart; `encoding` is the windows-1252 fallback. + pub(crate) uncertain: bool, +} + +/// Candidates in tie order (encoding_rs exposes encodings as statics, hence a function). +fn candidates() -> [&'static Encoding; 7] { + [SHIFT_JIS, GBK, BIG5, EUC_KR, WINDOWS_1252, WINDOWS_1251, MACINTOSH] +} + +/// The candidate that decodes the most of `pairs` (a name's bytes and the same name as Unicode) +/// exactly; ties go to the earlier candidate. `None` when it decodes none of them. Only the first +/// [`KNOWN_PAIRS`] pairs are examined. +pub(crate) fn match_known(pairs: &[(&[u8], &str)]) -> Option<&'static Encoding> { + let pairs = pairs.get(..KNOWN_PAIRS).unwrap_or(pairs); + let mut best = None; + let mut best_count = 0usize; + for enc in candidates() { + let count = pairs.iter().filter(|(bytes, text)| enc.decode_without_bom_handling_and_without_replacement(bytes).is_some_and(|d| d == *text)).count(); + if count > best_count { + best = Some(enc); + best_count = count; + } + } + best +} + +/// Guesses the one code page that `legacy` (names that are not valid UTF-8, in file order) were +/// written in. `hint` is text from the same file whose script points at the writer's locale. +pub(crate) fn guess(legacy: &[&[u8]], hint: &str) -> Guess { + let sample = sample(legacy); + if sample.is_empty() { + return Guess { encoding: UTF_8, uncertain: false }; + } + let mut best: Vec<&'static Encoding> = Vec::new(); + let mut best_score = (0u64, 1u64); + for enc in candidates() { + if !sample.iter().all(|(name, truncated)| decodes_cleanly(enc, name, *truncated)) { + continue; + } + let score = sample.iter().fold((0u64, 0u64), |(c, h), (name, _)| { + let (nc, nh) = score(enc, name); + (c.saturating_add(nc), h.saturating_add(nh)) + }); + let score = if score.1 == 0 { (0, 1) } else { score }; + // Compare common/high shares without division: a/b vs c/d ⇔ a·d vs c·b. + let lhs = u128::from(score.0) * u128::from(best_score.1); + let rhs = u128::from(best_score.0) * u128::from(score.1); + if best.is_empty() || lhs > rhs { + best = vec![enc]; + best_score = score; + } else if lhs == rhs { + best.push(enc); + } + } + match best.as_slice() { + [only] => Guess { encoding: only, uncertain: false }, + tied => match hinted(hint).iter().find(|enc| tied.contains(enc)) { + Some(enc) => Guess { encoding: enc, uncertain: false }, + None => Guess { encoding: WINDOWS_1252, uncertain: true }, + }, + } +} + +/// Decodes `bytes` with `enc`; invalid sequences become U+FFFD. +pub(crate) fn decode(bytes: &[u8], enc: &'static Encoding) -> String { + enc.decode_without_bom_handling(bytes).0.into_owned() +} + +/// Whether `name` decodes cleanly in the double-byte page `enc` and every non-ASCII byte of it is +/// common text there. A name in such a page can be valid UTF-8 by accident (GBK 去色 is +/// `C8 A5 C9 AB`, "ȥɫ"); real UTF-8 rarely passes, as its continuation bytes fall outside the +/// common ranges. Single-byte pages are never asked: their letters cover UTF-8's lead and +/// continuation bytes ("Weiß" is "Weiß" in windows-1252), and a legacy name there is valid UTF-8 +/// by accident only for unlikely pairs such as "é". +pub(crate) fn reads_as_common(name: &[u8], enc: &'static Encoding) -> bool { + if ![SHIFT_JIS, GBK, BIG5, EUC_KR].contains(&enc) { + return false; + } + let (common, high) = score(enc, name); + high > 0 && common == high && decodes_cleanly(enc, name, false) +} + +/// Resolves an encoding label (`shift_jis`, `gbk`, `big5`, `euc-kr`, `windows-1252`, `utf-8`…; +/// case and surrounding whitespace are ignored). Labels for encodings that cannot hold an 8-bit +/// name are rejected. +pub(crate) fn resolve_label(label: &str) -> Result<&'static Encoding> { + match Encoding::for_label(label.as_bytes()) { + Some(enc) if ![REPLACEMENT, UTF_16LE, UTF_16BE, X_USER_DEFINED].contains(&enc) => Ok(enc), + _ => Err(PsdError::Unsupported(format!("text encoding `{label}`: use a label such as shift_jis, gbk, big5, euc-kr, windows-1252 or utf-8"))), + } +} + +/// The names [`guess`] examines, each with whether it was cut short: names in order while they +/// fit in [`GUESS_SAMPLE`] bytes, and at least the first (truncated if it alone is longer). +fn sample<'a>(legacy: &[&'a [u8]]) -> Vec<(&'a [u8], bool)> { + let mut out = Vec::new(); + let mut total = 0usize; + for name in legacy { + let next = total.saturating_add(name.len()); + if next > GUESS_SAMPLE { + if out.is_empty() { + out.push((name.get(..GUESS_SAMPLE).unwrap_or(name), true)); + } + break; + } + out.push((*name, false)); + total = next; + } + out +} + +/// Whether `enc` decodes `bytes` without a single error. A `truncated` name may end inside a +/// character, which is not held against it. +fn decodes_cleanly(enc: &'static Encoding, bytes: &[u8], truncated: bool) -> bool { + let mut decoder = enc.new_decoder_without_bom_handling(); + // Every candidate decodes one byte to at most three UTF-8 bytes, so this is linear in + // `bytes` (a sampled name, or one name the file already holds). + let mut out = String::with_capacity(bytes.len().saturating_mul(3).saturating_add(16)); + let mut rest = bytes; + loop { + let (result, read) = decoder.decode_to_string_without_replacement(rest, &mut out, !truncated); + match result { + DecoderResult::InputEmpty => return true, + DecoderResult::Malformed(..) => return false, + DecoderResult::OutputFull => { + rest = rest.get(read..).unwrap_or_default(); + out.clear(); + } + } + } +} + +/// `(common, high)`: how many of a name's non-ASCII bytes `enc` reads as common text, and how +/// many non-ASCII bytes it has. +fn score(enc: &'static Encoding, name: &[u8]) -> (u64, u64) { + if enc == WINDOWS_1252 || enc == WINDOWS_1251 || enc == MACINTOSH { + // One byte is one character, and a non-ASCII byte is a non-ASCII character. Letters and + // typographic punctuation are common, as the double-byte pages' punctuation rows are. + let common = |ch: char| ch.is_alphabetic() || TYPOGRAPHIC.contains(&ch); + return decode(name, enc).chars().filter(|c| !c.is_ascii()).fold((0, 0), |(c, h), ch| (c + u64::from(common(ch)), h + 1)); + } + let (mut common, mut high) = (0u64, 0u64); + let mut i = 0usize; + while let Some(&lead) = name.get(i) { + if lead < 0x80 { + i += 1; + continue; + } + // Shift_JIS reads 0x80 and 0xA0–0xDF (half-width katakana, rare in real text) as one + // byte; elsewhere a lone non-ASCII byte is an error the decoder already rejected. + let single = if enc == SHIFT_JIS { lead == 0x80 || (0xA0..=0xDF).contains(&lead) || lead >= 0xFD } else { lead == 0x80 || lead == 0xFF }; + if single { + high += 1; + i += 1; + continue; + } + // A lead byte with nothing after it is where the sample was cut (the decoder rejects one + // at the real end of a name), so it is not scored. + let Some(&trail) = name.get(i + 1) else { break }; + // GB18030 four-byte sequences (second byte a digit) are never common text. + let len = if enc == GBK && trail.is_ascii_digit() { 4 } else { 2 }; + let len = len.min(name.len().saturating_sub(i)); + high += len as u64; + if len == 2 && is_common(enc, lead, trail) { + common += 2; + } + i += len; + } + (common, high) +} + +/// Quotes, dashes, ellipsis and bullet: windows-1252 and windows-1251 share them at 0x82–0x97; +/// Mac Roman has them too. +const TYPOGRAPHIC: [char; 10] = ['‘', '’', '‚', '“', '”', '„', '–', '—', '…', '•']; + +/// Whether the two-byte character `lead trail` is in `enc`'s common-text ranges. +fn is_common(enc: &'static Encoding, lead: u8, trail: u8) -> bool { + let both = u16::from_be_bytes([lead, trail]); + if enc == GBK { + // GB2312 hanzi, and the punctuation rows 0xA1 and 0xA3. + (0xA1..=0xFE).contains(&trail) && ((0xB0..=0xF7).contains(&lead) || lead == 0xA1 || lead == 0xA3) + } else if enc == BIG5 { + // Level-1 hanzi and punctuation. + (0xA4..=0xC6).contains(&lead) || lead == 0xA1 + } else if enc == SHIFT_JIS { + // Kana, level-1 kanji and punctuation. + (0x829F..=0x8396).contains(&both) || (0x889F..=0x9872).contains(&both) || (0x8140..=0x81FC).contains(&both) + } else if enc == EUC_KR { + // KS X 1001 Hangul and punctuation. + trail >= 0xA1 && ((0xB0..=0xC8).contains(&lead) || lead == 0xA1) + } else { + false + } +} + +/// The candidates the script of `hint` points at, strongest first. +fn hinted(hint: &str) -> Vec<&'static Encoding> { + let has = |lo: char, hi: char| hint.chars().any(|c| (lo..=hi).contains(&c) && c.is_alphabetic()); + if has('\u{3040}', '\u{30FF}') { + vec![SHIFT_JIS] + } else if has('\u{AC00}', '\u{D7A3}') { + vec![EUC_KR] + } else if has('\u{0400}', '\u{04FF}') { + vec![WINDOWS_1251] + } else if has('\u{4E00}', '\u{9FFF}') { + vec![GBK, BIG5, SHIFT_JIS] + } else if has('\u{00C0}', '\u{024F}') { + vec![WINDOWS_1252, MACINTOSH] + } else { + vec![] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const GBK_ISSUE: &[&[u8]] = &[b"\xbf\xc9\xd1\xa1\xd1\xd5\xc9\xab"]; // 可选颜色 (from #6743) + const SJIS_COMMENT: &[&[u8]] = &[ + b"\x91\x49\x91\xf0\x20\x3a", // 選択 : + b"\x90\xdd\x92\xe8\x20\x3a", // 設定 : + b"\x83\x52\x83\x73\x81\x5b", // コピー + b"\x95\xdb\x91\xb6", // 保存 + ]; + + fn encoded(enc: &'static Encoding, words: &[&str]) -> Vec> { + words.iter().map(|w| enc.encode(w).0.into_owned()).collect() + } + + fn guess_words(enc: &'static Encoding, words: &[&str], hint: &str) -> Guess { + let bytes = encoded(enc, words); + let refs: Vec<&[u8]> = bytes.iter().map(Vec::as_slice).collect(); + guess(&refs, hint) + } + + #[test] + fn issue_gbk_bytes_read_as_gbk() { + let g = guess(GBK_ISSUE, "调白"); + assert_eq!(g.encoding, GBK); + assert!(!g.uncertain); + assert_eq!(decode(GBK_ISSUE[0], g.encoding), "可选颜色"); + } + + #[test] + fn kanji_only_hint_still_reads_shift_jis() { + let g = guess(SJIS_COMMENT, "保存"); + assert_eq!(g.encoding, SHIFT_JIS); + assert_eq!(decode(SJIS_COMMENT[0], g.encoding), "選択 :"); + } + + #[test] + fn big5_reads_as_big5() { + assert_eq!(guess_words(BIG5, &["色彩範圍", "移動", "選取", "儲存"], "").encoding, BIG5); + } + + #[test] + fn hangul_hint_reads_euc_kr() { + let g = guess_words(EUC_KR, &["선택", "이동", "저장", "색상 범위"], "동작 1"); + assert_eq!(g.encoding, EUC_KR); + assert!(!g.uncertain); + } + + #[test] + fn cyrillic_hint_reads_1251() { + let g = guess_words(WINDOWS_1251, &["Выделить", "Переместить", "Сохранить"], "Набор 1"); + assert_eq!(g.encoding, WINDOWS_1251); + assert!(!g.uncertain); + } + + #[test] + fn latin_hint_reads_1252() { + let g = guess_words(WINDOWS_1252, &["Größe"], "Größe ändern"); + assert_eq!(g.encoding, WINDOWS_1252); + assert!(!g.uncertain); + } + + #[test] + fn tie_without_hint_is_1252_and_uncertain() { + let g = guess_words(WINDOWS_1252, &["Größe"], "Set 1"); + assert_eq!(g.encoding, WINDOWS_1252); + assert!(g.uncertain); + } + + #[test] + fn han_tie_prefers_gbk() { + // GBK 保存: GBK, Big5 and EUC-KR all read both characters as common text. + let names: &[&[u8]] = &[b"\xb1\xa3\xb4\xe6"]; + let g = guess(names, "动作"); + assert_eq!(g.encoding, GBK); + assert!(!g.uncertain); + assert_eq!(decode(names[0], g.encoding), "保存"); + assert_eq!(guess(names, "Set 1"), Guess { encoding: WINDOWS_1252, uncertain: true }); + } + + #[test] + fn typographic_punctuation_reads_as_1252() { + // ’ (0x92) then a letter is also a level-1 kanji pair in Shift_JIS. + let names: &[&[u8]] = &[b"Taille de l\x92image"]; + let g = guess(names, "Actions par défaut"); + assert_eq!(g.encoding, WINDOWS_1252); + assert!(!g.uncertain); + assert_eq!(decode(names[0], g.encoding), "Taille de l’image"); + assert_eq!(guess(names, "Set 1"), Guess { encoding: WINDOWS_1252, uncertain: true }); + } + + #[test] + fn utf8_lookalikes_read_as_common_text() { + // GBK 去色 and EUC-KR 칠 are also valid UTF-8 ("ȥɫ", "ĥ"). + assert!(reads_as_common(b"\xc8\xa5\xc9\xab", GBK)); + assert!(reads_as_common(b"\xc4\xa5", EUC_KR)); + // Real UTF-8 text does not: its continuation bytes fall outside the common ranges. + assert!(!reads_as_common("高斯模糊".as_bytes(), GBK)); + assert!(!reads_as_common("Gaussian Blur ✓".as_bytes(), GBK)); + assert!(!reads_as_common("Größe".as_bytes(), WINDOWS_1252)); + assert!(!reads_as_common(b"Blur", GBK), "ASCII has nothing to re-read"); + // Nor does UTF-8 in a single-byte page, though "Weiß" is à and Ÿ there and "Привет" is + // all Р, С and letters: accidental UTF-8 is a double-byte page's problem. + assert!(!reads_as_common("Weiß".as_bytes(), WINDOWS_1252)); + assert!(!reads_as_common("Привет".as_bytes(), WINDOWS_1251)); + assert!(!reads_as_common("Weiß".as_bytes(), MACINTOSH)); + } + + #[test] + fn latin_hint_reads_mac_roman_when_1252_does_not_fit() { + // Mac Roman "Arrière-plan": è is 0x8F, a control character in windows-1252. + let names: &[&[u8]] = &[b"Arri\x8fre-plan"]; + let g = guess(names, "Définir l’arrière-plan"); + assert_eq!(g.encoding, MACINTOSH); + assert!(!g.uncertain); + assert_eq!(decode(names[0], g.encoding), "Arrière-plan"); + } + + #[test] + fn known_names_pick_the_code_page() { + // Every step of the corpus/atn sets that has a non-ASCII panel name also stores it as + // Unicode (the descriptor's class name); here, Mac Roman "Définir". + let pairs: &[(&[u8], &str)] = &[(b"D\x8efinir", "Définir")]; + assert_eq!(match_known(pairs), Some(MACINTOSH)); + // GBK 保存 is a three-way tie for the statistics; the known name settles it. + assert_eq!(match_known(&[(b"\xb1\xa3\xb4\xe6", "保存")]), Some(GBK)); + } + + #[test] + fn most_matching_names_win() { + let pairs: &[(&[u8], &str)] = &[(b"\xb1\xa3\xb4\xe6", "保存"), (b"D\x8efinir", "Définir"), (b"Arri\x8fre-plan", "Arrière-plan")]; + assert_eq!(match_known(pairs), Some(MACINTOSH)); + } + + #[test] + fn known_name_ties_take_candidate_order() { + // Curly quotes are 0x93/0x94 in both windows-1252 and windows-1251. + assert_eq!(match_known(&[(b"\x93x\x94", "“x”")]), Some(WINDOWS_1252)); + } + + #[test] + fn known_names_that_match_nothing_decide_nothing() { + assert_eq!(match_known(&[(b"D\x8efinir", "Set")]), None); + assert_eq!(match_known(&[]), None); + // Past the cap, pairs are not examined. + let mut pairs = vec![(&b"D\x8efinir"[..], "x"); KNOWN_PAIRS]; + pairs.push((b"\xb1\xa3\xb4\xe6", "保存")); + assert_eq!(match_known(&pairs), None); + } + + #[test] + fn bytes_no_cjk_page_accepts_still_decode() { + // 0xFF is invalid in every double-byte candidate; windows-1251 (Ђ я Ђ) and Mac Roman + // (Ä ˇ Ä) read all three bytes as letters, windows-1252 only one (€ ÿ €). With nothing to + // break the tie, the fallback still decodes them. + let names: &[&[u8]] = &[b"\x80\xff\x80"]; + let g = guess(names, ""); + assert_eq!(g, Guess { encoding: WINDOWS_1252, uncertain: true }); + assert_eq!(decode(names[0], g.encoding), "€ÿ€"); + assert_eq!(guess(names, "Набор").encoding, WINDOWS_1251); + } + + #[test] + fn empty_or_utf8_input_is_utf8() { + let g = guess(&[], ""); + assert_eq!(g.encoding, UTF_8); + assert!(!g.uncertain); + } + + #[test] + fn mixed_code_pages_pick_one_and_never_fail() { + let names: &[&[u8]] = &[GBK_ISSUE[0], SJIS_COMMENT[0]]; + let g = guess(names, ""); + for name in names { + assert!(!decode(name, g.encoding).is_empty()); + } + } + + #[test] + fn huge_input_is_sampled() { + let names = vec![GBK_ISSUE[0]; 10_000]; + assert_eq!(guess(&names, "").encoding, GBK); + } + + #[test] + fn one_name_over_the_sample_cap_is_truncated_not_rejected() { + // "a" then 可 repeated past the cap, so the cut lands inside a two-byte character. + let mut name = b"a".to_vec(); + name.extend(b"\xbf\xc9".repeat(GUESS_SAMPLE / 2 + 1)); + assert_eq!(guess(&[&name], "可").encoding, GBK); + } + + #[test] + fn labels_resolve_and_reject() { + for ok in ["shift_jis", "gbk", "big5", "euc-kr", "windows-1252", "utf-8"] { + assert!(resolve_label(ok).is_ok(), "{ok}"); + } + for bad in ["nope", "replacement", "utf-16le", "x-user-defined", "", "iso-2022-kr"] { + let Err(e) = resolve_label(bad) else { panic!("{bad} should be rejected") }; + assert!(e.to_string().contains("shift_jis"), "{e}"); + } + } + + #[test] + fn labels_match_loosely() { + assert_eq!(resolve_label("Shift_JIS").ok(), Some(SHIFT_JIS)); + assert_eq!(resolve_label(" gbk ").ok(), Some(GBK)); + assert_eq!(resolve_label("gb2312").ok(), Some(GBK)); + } +} diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs index f5ffbed8b72..30509942163 100644 --- a/crates/psd/src/lib.rs +++ b/crates/psd/src/lib.rs @@ -48,6 +48,7 @@ pub mod asl; pub mod atn; pub mod blend; pub mod builder; +mod codepage; pub mod compression; pub mod descriptor; pub mod error; From d8244139bc8e61a5448b1f81d0c35e38ca2c31fb Mon Sep 17 00:00:00 2001 From: Ben Huyck Date: Thu, 22 Oct 2026 16:41:13 +0000 Subject: [PATCH 13/52] Actions: read .atn step names in the code page Photoshop wrote them in (#6743) --- crates/engine/src/cmd/atn_cmds/convert.rs | 2 +- crates/engine/src/cmd/atn_cmds/tests.rs | 13 + crates/psd/examples/atn_dump.rs | 7 +- crates/psd/src/atn.rs | 309 +++++++++++++++++++++- 4 files changed, 322 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/convert.rs b/crates/engine/src/cmd/atn_cmds/convert.rs index 78d65979bf0..79476cc5a7f 100644 --- a/crates/engine/src/cmd/atn_cmds/convert.rs +++ b/crates/engine/src/cmd/atn_cmds/convert.rs @@ -205,7 +205,7 @@ pub fn export( skip_unsupported: bool, ) -> std::result::Result<(Vec, Vec), String> { let mut skipped = Vec::new(); - let mut file = AtnFile { name: UnicodeString::new_nul(set), expanded: true, actions: Vec::new(), warnings: Vec::new() }; + let mut file = AtnFile { name: UnicodeString::new_nul(set), expanded: true, actions: Vec::new(), warnings: Vec::new(), ..Default::default() }; for a in actions { let mut out = AtnAction { name: UnicodeString::new_nul(&a.name), expanded: false, ..Default::default() }; if let Some((n, shift, command)) = function_keys.iter().find(|(n, _)| n == &a.name).and_then(|(_, key)| parse_function_key(key)) { diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 08286b53296..f58cfaef06c 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -45,6 +45,7 @@ fn layer_steps_with_string_id_blend_modes_import_with_their_mode() { ..Default::default() }], warnings: vec![], + ..Default::default() }; let imp = import(&atn::write(&file).unwrap()).unwrap(); assert!(imp.unsupported.is_empty(), "{:?}", imp.unsupported.iter().map(|u| &u.event).collect::>()); @@ -116,6 +117,7 @@ fn sample() -> AtnFile { AtnAction { name: UnicodeString::new_nul("Finish"), items: vec![item("Invs", "Inverse", None)], ..Default::default() }, ], warnings: Vec::new(), + ..Default::default() } } @@ -952,6 +954,7 @@ fn unsupported_shapes_become_photoshop_steps_not_errors() { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }], warnings: vec![], + ..Default::default() }; let imp = import(&atn::write(&file).unwrap()).unwrap(); let ids: Vec<&str> = imp.actions[0].steps.iter().map(|(id, _)| id.as_str()).collect(); @@ -975,6 +978,7 @@ fn save_preserves_the_kind_of_unsupported_atn_events() { ..Default::default() }], warnings: vec![], + ..Default::default() }; let mut session = Session::new(); session.execute("actions.load", json!({"data": b64(&atn::write(&source).unwrap())})).unwrap(); @@ -1050,6 +1054,7 @@ fn retouching_set_events_map_to_their_commands() { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }], warnings: vec![], + ..Default::default() }; let imp = import(&atn::write(&file).unwrap()).unwrap(); let steps = &imp.actions[0].steps; @@ -1342,6 +1347,7 @@ fn remaining_events_import_in_their_photoshop_shapes() { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }], warnings: vec![], + ..Default::default() }; let imp = import(&atn::write(&file).unwrap()).unwrap(); let steps = &imp.actions[0].steps; @@ -1430,6 +1436,7 @@ fn remaining_events_import_in_their_photoshop_shapes() { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }], warnings: vec![], + ..Default::default() }; let rest = import(&atn::write(&file).unwrap()).unwrap(); let rest_steps = &rest.actions[0].steps; @@ -1468,6 +1475,7 @@ fn remaining_events_import_in_their_photoshop_shapes() { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }], warnings: vec![], + ..Default::default() }; let more = import(&atn::write(&file).unwrap()).unwrap(); let more_steps = &more.actions[0].steps; @@ -1584,6 +1592,7 @@ fn set_of(name: &str, actions: Vec<(&str, Vec)>) -> String { expanded: false, actions: actions.into_iter().map(|(n, items)| AtnAction { name: UnicodeString::new_nul(n), items, ..Default::default() }).collect(), warnings: vec![], + ..Default::default() }; b64(&atn::write(&file).unwrap()) } @@ -2294,6 +2303,7 @@ fn fractional_translation_only_transform_keeps_offset_and_interpolation() { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items: vec![item("transform", "Transform", Some(d))], ..Default::default() }], warnings: vec![], + ..Default::default() }; let imp = import(&atn::write(&file).unwrap()).unwrap(); assert!(imp.unsupported.is_empty()); @@ -2706,6 +2716,7 @@ fn adjustment_layer_reset_still_resets() { ..Default::default() }], warnings: vec![], + ..Default::default() }; let steps = import(&atn::write(&file).unwrap()).unwrap().actions.remove(0).steps; assert_eq!(steps[0], ("layer.setAdjustment".to_string(), json!({}))); @@ -3057,6 +3068,7 @@ fn one_action(items: Vec) -> AtnFile { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }], warnings: vec![], + ..Default::default() } } @@ -3155,6 +3167,7 @@ fn long_names_are_clipped_instead_of_copied_into_every_diagnostic() { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul(&long), items: unknown(50), ..Default::default() }], warnings: vec![], + ..Default::default() }; let imp = import(&atn::write(&file).unwrap()).unwrap(); assert_eq!(imp.set.chars().count(), MAX_NAME_CHARS); diff --git a/crates/psd/examples/atn_dump.rs b/crates/psd/examples/atn_dump.rs index 04e268da947..bd341c7b006 100644 --- a/crates/psd/examples/atn_dump.rs +++ b/crates/psd/examples/atn_dump.rs @@ -56,9 +56,10 @@ fn main() { match atn::parse(&bytes) { Ok(f) => { println!( - "== {path}: set {:?}, {} actions{}", + "== {path}: set {:?}, {} actions{}{}", f.name.to_string_lossy(), f.actions.len(), + f.encoding.as_deref().map(|e| format!(", names in {e}")).unwrap_or_default(), if f.warnings.is_empty() { String::new() } else { format!(" ({})", f.warnings.join("; ")) } ); for a in &f.actions { @@ -66,8 +67,8 @@ fn main() { for item in &a.items { let flags = format!("{}{}", if item.enabled { "" } else { " off" }, if item.with_dialog { " dialog" } else { "" }); match &item.descriptor { - Some(d) => println!(" {:<22} {:<28}{flags} {}", item.event.id(), item.label(), keys(d)), - None => println!(" {:<22} {:<28}{flags}", item.event.id(), item.label()), + Some(d) => println!(" {:<22} {:<28}{flags} {}", item.event.id(), f.item_label(item), keys(d)), + None => println!(" {:<22} {:<28}{flags}", item.event.id(), f.item_label(item)), } } } diff --git a/crates/psd/src/atn.rs b/crates/psd/src/atn.rs index 6bb900d4351..ef620ad1f04 100644 --- a/crates/psd/src/atn.rs +++ b/crates/psd/src/atn.rs @@ -22,10 +22,19 @@ //! [`AtnItem::label`] gives a readable name. Photoshop 5-era files (version 12) use a //! different, undocumented layout and are rejected as unsupported. //! +//! Which legacy encoding is not recorded: Windows Photoshop uses the system code page (GBK in +//! Chinese, Shift_JIS in Japanese…), Mac Photoshop the Mac one. [`parse`] works it out once per +//! file into [`AtnFile::encoding`], first from steps that also store their name as Unicode (the +//! descriptor's class name), else by guessing from the bytes; [`parse_with_encoding`] takes it +//! from the caller. [`AtnFile::item_label`] reads names with it. The bytes themselves stay as +//! they are. +//! //! [`parse`] never panics: every count is bounds-checked against the bytes left, descriptor //! nesting is bounded, and allocations are capped. [`write`] produces the same layout, so -//! `parse(write(f)) == f`, and `write(parse(b)) == b` for files Photoshop wrote. +//! `parse(write(f)) == f` for files [`parse`] read, and `write(parse(b)) == b` for files Photoshop +//! wrote. +use crate::codepage; use crate::descriptor::{Descriptor, UnicodeString}; use crate::error::{PsdError, Result}; use crate::io::{Reader, WriteExt, decode_legacy_name}; @@ -50,6 +59,37 @@ pub struct AtnFile { /// Problems that did not stop the parse (trailing bytes…). #[cfg_attr(feature = "serde", serde(default))] pub warnings: Vec, + /// The encoding of the 8-bit names that are not ASCII or UTF-8 ("GBK", "Shift_JIS", + /// "macintosh"…): the one given to [`parse_with_encoding`], else the one that turns such + /// names into the Unicode class names stored with them, else a guess from the names shown + /// from their bytes alone. `None` when there are no such names, or nothing tells and no + /// name depends on it. [`write`] ignores it: names are written as stored. + #[cfg_attr(feature = "serde", serde(default))] + pub encoding: Option, +} + +impl AtnFile { + /// [`AtnItem::label`], with 8-bit names read in this file's [`encoding`](Self::encoding). + /// A name that is valid UTF-8 is read in that encoding only if it reads entirely as common + /// text there (GBK 去色 is also valid UTF-8, "ȥɫ"). + pub fn item_label(&self, item: &AtnItem) -> String { + let Some(enc) = self.encoding.as_deref().and_then(|label| codepage::resolve_label(label).ok()) else { return item.label() }; + let read = |bytes: &[u8]| match std::str::from_utf8(bytes) { + Ok(s) if s.is_ascii() || !codepage::reads_as_common(bytes, enc) => s.to_owned(), + _ => codepage::decode(bytes, enc), + }; + if let Some(class) = class_name(item) { + return class; + } + let dict = read(&item.dictionary); + if !dict.trim().is_empty() { + return dict; + } + match &item.event { + AtnEvent::Name(n) => read(n), + AtnEvent::Code(_) => item.event.id(), + } + } } /// One action of a set. @@ -116,8 +156,7 @@ impl AtnItem { /// A readable name for the step: the descriptor's class name when Photoshop stored one /// (Unicode, so a localised name survives), else [`Self::dictionary`], else the event id. pub fn label(&self) -> String { - let class = self.descriptor.as_ref().map(|d| d.name.to_string_lossy()).unwrap_or_default(); - if !class.trim().is_empty() { + if let Some(class) = class_name(self) { return class; } let dict = self.dictionary(); @@ -125,6 +164,12 @@ impl AtnItem { } } +/// The descriptor's class name, when Photoshop stored one: the step's name as Unicode. +fn class_name(item: &AtnItem) -> Option { + let class = item.descriptor.as_ref().map(|d| d.name.to_string_lossy())?; + (!class.trim().is_empty()).then_some(class) +} + /// A Photoshop event id: a four-character code (`GsnB`) or a string name (`trim`). #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -208,8 +253,25 @@ fn read_action(r: &mut Reader<'_>) -> Result { Ok(AtnAction { function_key, shift, command, color, name, expanded, items }) } -/// Parses an `.atn` file. +/// Parses an `.atn` file, working out the encoding of its 8-bit names (see the module docs). pub fn parse(data: &[u8]) -> Result { + parse_with_encoding(data, None) +} + +/// [`parse`], reading 8-bit names in `encoding` (a label such as `shift_jis`, `gbk`, `big5`, +/// `euc-kr`, `windows-1252`, `macintosh`) instead of working it out. An unknown label, or one +/// for an encoding that cannot hold an 8-bit name (UTF-16, `replacement`), is an error. +pub fn parse_with_encoding(data: &[u8], encoding: Option<&str>) -> Result { + let forced = encoding.map(codepage::resolve_label).transpose()?; + let mut f = parse_layout(data)?; + let mut warnings = Vec::new(); + let enc = forced.or_else(|| name_encoding(&f, &mut warnings)); + f.warnings.extend(warnings); + f.encoding = enc.map(|e| e.name().to_owned()); + Ok(f) +} + +fn parse_layout(data: &[u8]) -> Result { let mut r = Reader::new(data); let version = r.u32()?; if version != VERSION { @@ -231,7 +293,57 @@ pub fn parse(data: &[u8]) -> Result { if !r.is_empty() { warnings.push(format!("{} trailing bytes ignored", r.remaining())); } - Ok(AtnFile { name, expanded, actions, warnings }) + Ok(AtnFile { name, expanded, actions, warnings, encoding: None }) +} + +/// The encoding of `f`'s 8-bit names that are not ASCII or UTF-8, or `None` if no name shown +/// from them needs one; adds a warning when the guess is uncertain. +fn name_encoding(f: &AtnFile, warnings: &mut Vec) -> Option<&'static encoding_rs::Encoding> { + let items = || f.actions.iter().flat_map(|a| &a.items); + let legacy = |b: &[u8]| !b.is_ascii(); + // Steps that store their name as Unicode too: the encoding that turns one into the other. + let pairs: Vec<(&[u8], String)> = items() + .filter(|i| legacy(&i.dictionary)) + .filter_map(|i| class_name(i).filter(|c| std::str::from_utf8(&i.dictionary) != Ok(c.as_str())).map(|c| (i.dictionary.as_slice(), c))) + .take(codepage::KNOWN_PAIRS) + .collect(); + let pairs: Vec<(&[u8], &str)> = pairs.iter().map(|(b, c)| (*b, c.as_str())).collect(); + if let Some(enc) = codepage::match_known(&pairs) { + return Some(enc); + } + // Otherwise guess from the names shown from bytes alone. + let invalid = |b: &[u8]| std::str::from_utf8(b).is_err(); + let mut orphans: Vec<&[u8]> = Vec::new(); + for i in items() { + if class_name(i).is_none() && invalid(&i.dictionary) { + orphans.push(&i.dictionary); + } + if let AtnEvent::Name(n) = &i.event + && invalid(n) + { + orphans.push(n); + } + } + if orphans.is_empty() { + return None; + } + // The set, action and class names are UTF-16: their script points at the writer's locale. + let mut hint = f.name.to_string_lossy(); + for name in f.actions.iter().map(|a| a.name.to_string_lossy()).chain(items().filter_map(class_name)) { + if hint.len() > codepage::GUESS_SAMPLE { + break; + } + hint.push('\n'); + hint.push_str(&name); + } + let guess = codepage::guess(&orphans, &hint); + if guess.uncertain { + warnings.push(format!( + "step names aren't UTF-8 and their encoding couldn't be determined; read as {}; load with an explicit encoding to choose another", + guess.encoding.name() + )); + } + Some(guess.encoding) } fn write_item(out: &mut Vec, item: &AtnItem) -> Result<()> { @@ -336,6 +448,7 @@ mod tests { AtnAction { name: UnicodeString::new_nul("Empty"), ..Default::default() }, ], warnings: Vec::new(), + ..Default::default() } } @@ -390,6 +503,7 @@ mod tests { ..Default::default() }], warnings: Vec::new(), + ..Default::default() }; let mut expect = Vec::new(); expect.extend_from_slice(&[0, 0, 0, 16]); // version @@ -447,6 +561,191 @@ mod tests { assert!(matches!(parse(&bad_flag), Err(PsdError::Invalid(_)))); } + const GBK_SELECTIVE_COLOR: &[u8] = b"\xbf\xc9\xd1\xa1\xd1\xd5\xc9\xab"; // 可选颜色 (from #6743) + const GBK_DESATURATE: &[u8] = b"\xc8\xa5\xc9\xab"; // 去色: valid UTF-8 by accident ("ȥɫ") + const LABELS: [Option<&str>; 5] = [None, Some("shift_jis"), Some("gbk"), Some("utf-8"), Some("macintosh")]; + + /// A step stored with no descriptor, so nothing but its 8-bit names tells what it is called. + fn bare(event: AtnEvent, dictionary: &[u8]) -> AtnItem { + AtnItem { event, dictionary: dictionary.to_vec(), ..Default::default() } + } + + /// A step whose descriptor also stores its panel name as Unicode, as Photoshop does for most. + fn known(dictionary: &[u8], class: &str) -> AtnItem { + let descriptor = Descriptor { name: UnicodeString::new_nul(class), class_id: crate::descriptor::Id::new("setd"), items: Vec::new() }; + AtnItem { event: AtnEvent::name("set"), dictionary: dictionary.to_vec(), descriptor: Some(descriptor), ..Default::default() } + } + + fn one_action(set: &str, action: &str, items: Vec) -> Vec { + let f = AtnFile { + name: UnicodeString::new_nul(set), + actions: vec![AtnAction { name: UnicodeString::new_nul(action), items, ..Default::default() }], + ..Default::default() + }; + write(&f).unwrap() + } + + /// The issue's set: Chinese Photoshop's Selective Color step, named in GBK. + fn gbk_set() -> Vec { + one_action("相馆", "调白", vec![bare(AtnEvent::name("syntheticFill"), GBK_SELECTIVE_COLOR)]) + } + + fn labels(f: &AtnFile) -> Vec { + f.actions.iter().flat_map(|a| a.items.iter().map(|i| f.item_label(i))).collect() + } + + #[test] + fn gbk_step_names_read_as_gbk() { + let f = parse(&gbk_set()).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("GBK")); + assert_eq!(labels(&f), ["可选颜色"]); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + // The item itself, without the file's code page, reads as before. + assert_ne!(f.actions[0].items[0].label(), "可选颜色"); + } + + #[test] + fn legacy_names_are_kept_byte_for_byte() { + let bytes = gbk_set(); + let f = parse(&bytes).unwrap(); + assert_eq!(f.actions[0].items[0].dictionary, GBK_SELECTIVE_COLOR); + assert_eq!(write(&f).unwrap(), bytes); + assert_eq!(parse(&write(&f).unwrap()).unwrap(), f); + } + + #[test] + fn text_event_names_decode_too() { + let f = parse(&one_action("相馆", "调白", vec![bare(AtnEvent::Name(GBK_SELECTIVE_COLOR.to_vec()), b"")])).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("GBK")); + assert_eq!(labels(&f), ["可选颜色"]); + } + + #[test] + fn known_names_decide_the_code_page_of_the_rest() { + // French Photoshop on a Mac: "Définir" is stored as Mac Roman and as Unicode; the bare + // step's "Répéter" is only Mac Roman, which also reads as windows-1252 ("RŽpŽter"). + let items = vec![known(b"D\x8efinir", "Définir"), bare(AtnEvent::name("x"), b"R\x8ep\x8eter")]; + let f = parse(&one_action("Set 1", "Action 1", items)).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("macintosh")); + assert_eq!(labels(&f), ["Définir", "Répéter"]); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + } + + #[test] + fn class_names_hint_the_script() { + // GBK 保存 reads as common text in GBK, Big5 and EUC-KR alike; only the Chinese class + // name of another step (whose panel name is ASCII, so it settles nothing itself) says GBK. + let items = vec![known(b"Adjust", "调整"), bare(AtnEvent::name("x"), b"\xb1\xa3\xb4\xe6")]; + let f = parse(&one_action("Set 1", "Action 1", items)).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("GBK")); + assert_eq!(labels(&f), ["调整", "保存"]); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + } + + #[test] + fn known_names_alone_never_warn() { + // Nothing decodes to the Unicode name, but nothing is shown from the bytes either. + let f = parse(&one_action("Set 1", "Action 1", vec![known(b"\x80\xff\x80", "Something")])).unwrap(); + assert_eq!(f.encoding, None); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + assert_eq!(labels(&f), ["Something"]); + } + + #[test] + fn uncertain_guess_warns() { + let f = parse(&one_action("Set 1", "Action 1", vec![bare(AtnEvent::name("x"), b"\x80\xff\x80")])).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("windows-1252")); + assert_eq!(f.warnings.len(), 1, "{:?}", f.warnings); + assert!(f.warnings[0].contains("windows-1252"), "{:?}", f.warnings); + assert_eq!(labels(&f), ["€ÿ€"]); + } + + #[test] + fn utf8_files_have_no_encoding() { + let f = parse(&write(&set()).unwrap()).unwrap(); + assert_eq!(f.encoding, None); + let items: Vec<&AtnItem> = f.actions.iter().flat_map(|a| &a.items).collect(); + assert_eq!(labels(&f), items.iter().map(|i| i.label()).collect::>()); + let f = parse(&one_action("Set", "A", vec![bare(AtnEvent::name("x"), "高斯模糊 ✓".as_bytes())])).unwrap(); + assert_eq!((f.encoding.clone(), labels(&f)), (None, vec!["高斯模糊 ✓".to_string()])); + } + + #[test] + fn utf8_lookalike_names_decode_with_the_file() { + let items = vec![ + bare(AtnEvent::name("x"), GBK_SELECTIVE_COLOR), + bare(AtnEvent::name("y"), GBK_DESATURATE), + bare(AtnEvent::name("z"), "Gaussian Blur ✓".as_bytes()), + ]; + let f = parse(&one_action("相馆", "调白", items)).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("GBK")); + assert_eq!(labels(&f), ["可选颜色", "去色", "Gaussian Blur ✓"]); + } + + #[test] + fn utf8_names_stay_in_single_byte_files() { + // windows-1252 "Größe" beside a UTF-8 "Weiß"; windows-1251 "Уровни" beside a UTF-8 "Привет". + let latin = vec![bare(AtnEvent::name("x"), b"Gr\xf6\xdfe"), bare(AtnEvent::name("y"), "Weiß".as_bytes())]; + let f = parse(&one_action("Größe ändern", "Aktion", latin)).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("windows-1252")); + assert_eq!(labels(&f), ["Größe", "Weiß"]); + let cyrillic = vec![bare(AtnEvent::name("x"), b"\xd3\xf0\xee\xe2\xed\xe8"), bare(AtnEvent::name("y"), "Привет".as_bytes())]; + let f = parse(&one_action("Набор", "Операция", cyrillic)).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("windows-1251")); + assert_eq!(labels(&f), ["Уровни", "Привет"]); + // A forced single-byte encoding leaves UTF-8 names alone too. + let f = parse_with_encoding(&one_action("S", "A", vec![bare(AtnEvent::name("y"), "Weiß".as_bytes())]), Some("windows-1252")).unwrap(); + assert_eq!(labels(&f), ["Weiß"]); + } + + #[test] + fn forced_encoding_wins() { + let f = parse_with_encoding(&gbk_set(), Some("big5")).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("Big5")); + assert_ne!(labels(&f), ["可选颜色"]); + // A wrong override still loads, and saves the bytes it read. + let f = parse_with_encoding(&gbk_set(), Some("shift_jis")).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("Shift_JIS")); + assert_eq!(write(&f).unwrap(), gbk_set()); + // Forcing applies to all-UTF-8 files too. + assert_eq!(parse_with_encoding(&write(&set()).unwrap(), Some("gbk")).unwrap().encoding.as_deref(), Some("GBK")); + } + + #[test] + fn bad_labels_are_errors() { + for bad in ["nope", "replacement", "utf-16be", ""] { + assert!(matches!(parse_with_encoding(&gbk_set(), Some(bad)), Err(PsdError::Unsupported(_))), "{bad}"); + } + } + + #[test] + fn legacy_files_never_panic() { + let items = vec![known(b"D\x8efinir", "Définir"), bare(AtnEvent::Name(GBK_SELECTIVE_COLOR.to_vec()), GBK_DESATURATE)]; + let seed = one_action("相馆", "调白", items); + let check = |bytes: &[u8]| { + for label in LABELS { + if let Ok(f) = parse_with_encoding(bytes, label) { + let _ = labels(&f); + } + } + }; + for cut in 0..seed.len() { + check(&seed[..cut]); + } + let mut x: u32 = 0x85eb_ca6b; + for i in 0..500 { + let mut bytes = seed.clone(); + for _ in 0..(i % 5 + 1) { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + let at = (x as usize) % bytes.len(); + bytes[at] = (x >> 8) as u8; + } + check(&bytes); + } + } + #[test] fn garbage_never_panics() { let seed = write(&set()).unwrap(); From ef5b900141765237afb749d3049dff88ada5afa2 Mon Sep 17 00:00:00 2001 From: Ben Huyck Date: Thu, 22 Oct 2026 16:48:15 +0000 Subject: [PATCH 14/52] Actions: Load Actions takes an encoding and reports the one it used (#6743) --- crates/engine/src/cmd/atn_cmds.rs | 4 +- crates/engine/src/cmd/atn_cmds/convert.rs | 26 ++++++++---- crates/engine/src/cmd/atn_cmds/files.rs | 11 +++++- crates/engine/src/cmd/atn_cmds/tests.rs | 48 +++++++++++++++++++++++ 4 files changed, 77 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds.rs b/crates/engine/src/cmd/atn_cmds.rs index 7c717701bf8..0187681923a 100644 --- a/crates/engine/src/cmd/atn_cmds.rs +++ b/crates/engine/src/cmd/atn_cmds.rs @@ -39,7 +39,7 @@ mod tables; #[cfg(test)] use adjustments::{levels_from, selective_from}; -pub use convert::{Imported, Skipped, Unsupported, export, function_key_name, import, parse_function_key}; +pub use convert::{Imported, Skipped, Unsupported, export, function_key_name, import, import_with_encoding, parse_function_key}; #[cfg(test)] use convert::{MAX_NAME_CHARS, export_item, normalise}; #[cfg(test)] @@ -101,7 +101,7 @@ pub fn specs() -> Vec { label: "Load Actions…", menu: &[], shortcut: None, - params: r##"{"path":".atn file"?,"data":base64 bytes?,"set":name? (override the file's set name),"replace":bool=true (replace the actions of a set of the same name)} → {set, actions:[names], steps, unsupported:[{action, step, event, name}], functionKeys:[{action, key}], warnings}. Photoshop steps PhotoCraft cannot play become actions.photoshopStep steps (kept for Save Actions; they fail at playback with the step's name); tool selections and other steps with no document effect are imported switched off. Layer references by name replay in any document."##, + params: r##"{"path":".atn file"?,"data":base64 bytes?,"set":name? (override the file's set name),"replace":bool=true (replace the actions of a set of the same name),"encoding":"auto"|label="auto" (the encoding of 8-bit step names: shift_jis, gbk, big5, euc-kr, windows-1252, macintosh…; auto works it out)} → {set, actions:[names], steps, unsupported:[{action, step, event, name}], functionKeys:[{action, key}], warnings, encoding}. Photoshop steps PhotoCraft cannot play become actions.photoshopStep steps (kept for Save Actions; they fail at playback with the step's name); tool selections and other steps with no document effect are imported switched off. Layer references by name replay in any document."##, enabled: always, run: load, journal: false, diff --git a/crates/engine/src/cmd/atn_cmds/convert.rs b/crates/engine/src/cmd/atn_cmds/convert.rs index 79476cc5a7f..ccdbcf73480 100644 --- a/crates/engine/src/cmd/atn_cmds/convert.rs +++ b/crates/engine/src/cmd/atn_cmds/convert.rs @@ -23,15 +23,18 @@ pub struct Imported { pub function_keys: Vec<(String, String)>, pub unsupported: Vec, pub warnings: Vec, + /// The encoding the file's 8-bit step names were read in (`"GBK"`, `"Shift_JIS"`, + /// `"macintosh"`…); `None` when none needed one. + pub encoding: Option, } -fn photoshop_step(item: &AtnItem) -> (String, Value) { +fn photoshop_step(item: &AtnItem, label: String) -> (String, Value) { let descriptor = item.descriptor.as_ref().map(|d| photocraft_paint::tile::b64_encode(&d.to_bytes())); let event_kind = match &item.event { AtnEvent::Code(_) => "code", AtnEvent::Name(_) => "name", }; - (PHOTOSHOP_STEP.into(), json!({"event": item.event.id(), "eventKind": event_kind, "name": item.label(), "descriptor": descriptor})) + (PHOTOSHOP_STEP.into(), json!({"event": item.event.id(), "eventKind": event_kind, "name": label, "descriptor": descriptor})) } /// Integral floats become integers (`2.0` → `2`), as the commands' own docs and recordings @@ -61,7 +64,7 @@ pub(super) fn clip_name(s: &str) -> String { s.chars().take(MAX_NAME_CHARS).collect() } -fn convert_action(a: &AtnAction, set: &str, unsupported: &mut Vec) -> Action { +fn convert_action(file: &AtnFile, a: &AtnAction, set: &str, unsupported: &mut Vec) -> Action { let name = clip_name(&a.name.to_string_lossy()); let mut action = Action::new(name.clone(), Vec::new()); action.set = Some(clip_name(set)); @@ -74,8 +77,9 @@ fn convert_action(a: &AtnAction, set: &str, unsupported: &mut Vec) let (new_steps, enabled) = match mapped { Mapped::Steps(s) => (s, item.enabled), Mapped::Unsupported { harmless } => { - unsupported.push(Unsupported { action: name.clone(), step: i, event: item.event.id(), name: item.label() }); - (vec![photoshop_step(item)], item.enabled && !harmless) + let label = file.item_label(item); + unsupported.push(Unsupported { action: name.clone(), step: i, event: item.event.id(), name: label.clone() }); + (vec![photoshop_step(item, label)], item.enabled && !harmless) } }; for mut s in new_steps { @@ -96,12 +100,18 @@ fn convert_action(a: &AtnAction, set: &str, unsupported: &mut Vec) /// Convert a `.atn` file. Fails only when the file is unreadable: every step imports, as a /// command or as a kept Photoshop step. pub fn import(bytes: &[u8]) -> std::result::Result { - let file = atn::parse(bytes).map_err(|e| e.to_string())?; + import_with_encoding(bytes, None) +} + +/// [`import`], reading 8-bit step names in `encoding` (a label such as `"shift_jis"` or +/// `"gbk"`) instead of working it out. An unknown label fails. +pub fn import_with_encoding(bytes: &[u8], encoding: Option<&str>) -> std::result::Result { + let file = atn::parse_with_encoding(bytes, encoding).map_err(|e| e.to_string())?; let set = file.name.to_string_lossy(); let set = if set.trim().is_empty() { DEFAULT_SET.to_string() } else { clip_name(&set) }; - let mut out = Imported { set: set.clone(), warnings: file.warnings.clone(), ..Default::default() }; + let mut out = Imported { set: set.clone(), warnings: file.warnings.clone(), encoding: file.encoding.clone(), ..Default::default() }; for a in &file.actions { - let action = convert_action(a, &set, &mut out.unsupported); + let action = convert_action(&file, a, &set, &mut out.unsupported); if a.function_key > 0 { out.function_keys.push((action.name.clone(), function_key_name(a.function_key, a.shift, a.command))); } diff --git a/crates/engine/src/cmd/atn_cmds/files.rs b/crates/engine/src/cmd/atn_cmds/files.rs index be7bd451519..c22b673deb0 100644 --- a/crates/engine/src/cmd/atn_cmds/files.rs +++ b/crates/engine/src/cmd/atn_cmds/files.rs @@ -1,4 +1,4 @@ -use super::convert::{UniqueNames, export, import}; +use super::convert::{UniqueNames, export, import_with_encoding}; use super::{Action, DEFAULT_SET, EngineError, Result, Session, Value, bad, json}; pub(super) fn load(s: &mut Session, p: &Value) -> Result { @@ -6,8 +6,14 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result { if s.actions.recording.is_some() || s.actions.playing > 0 { return Err(bad(cmd, "stop recording or playing before loading actions")); } + let encoding = match p.get("encoding") { + None | Some(Value::Null) => None, + Some(Value::String(e)) if e == "auto" => None, + Some(Value::String(e)) if !e.is_empty() => Some(e.as_str()), + Some(_) => return Err(bad(cmd, "encoding must be \"auto\" or a label such as shift_jis, gbk, big5, euc-kr, windows-1252, macintosh")), + }; let (bytes, _) = crate::preset_import_cmds::file_bytes(p, cmd, ".atn file")?; - let mut imp = import(&bytes).map_err(|e| bad(cmd, e))?; + let mut imp = import_with_encoding(&bytes, encoding).map_err(|e| bad(cmd, e))?; match p.get("set") { None | Some(Value::Null) => {} Some(Value::String(n)) if !n.trim().is_empty() => { @@ -77,6 +83,7 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result { "unsupported": imp.unsupported, "functionKeys": keys.iter().map(|(n, k)| json!({"action": n, "key": k})).collect::>(), "warnings": imp.warnings, + "encoding": imp.encoding.as_deref().unwrap_or("UTF-8"), })) } diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index f58cfaef06c..4a41a12e0fa 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -3176,3 +3176,51 @@ 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 set from Chinese Photoshop: UTF-16 set and action names, a step name in GBK (可选颜色, +/// the bytes from #6743) on an event PhotoCraft has no command for, with no descriptor. +fn gbk_set() -> Vec { + let step = AtnItem { dictionary: b"\xbf\xc9\xd1\xa1\xd1\xd5\xc9\xab".to_vec(), ..item("syntheticFill", "", None) }; + let file = AtnFile { + name: UnicodeString::new_nul("相馆"), + actions: vec![AtnAction { name: UnicodeString::new_nul("调白"), items: vec![step], ..Default::default() }], + ..Default::default() + }; + atn::write(&file).unwrap() +} + +#[test] +fn load_decodes_legacy_step_names() { + let mut s = Session::new(); + let r = s.execute("actions.load", json!({"data": b64(&gbk_set())})).unwrap(); + assert_eq!(r["encoding"], "GBK", "{r}"); + assert_eq!(r["unsupported"][0]["name"], "可选颜色", "{r}"); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let played = s.execute("actions.play", json!({"action": "调白"})).unwrap(); + assert!(played["failed"]["error"].as_str().unwrap().contains("可选颜色"), "{played}"); +} + +#[test] +fn load_encoding_override() { + let mut s = Session::new(); + let r = s.execute("actions.load", json!({"data": b64(&gbk_set()), "encoding": "shift_jis"})).unwrap(); + assert_eq!(r["encoding"], "Shift_JIS", "{r}"); + let r = s.execute("actions.load", json!({"data": b64(&gbk_set()), "encoding": "auto"})).unwrap(); + assert_eq!(r["encoding"], "GBK", "{r}"); +} + +#[test] +fn load_reports_utf8() { + let mut s = Session::new(); + let r = s.execute("actions.load", json!({"data": b64(&atn::write(&sample()).unwrap())})).unwrap(); + assert_eq!(r["encoding"], "UTF-8", "{r}"); +} + +#[test] +fn load_rejects_bad_encodings() { + let mut s = Session::new(); + for bad in [json!(3), json!(""), json!("nope"), json!("replacement"), json!(["gbk"])] { + assert!(s.execute("actions.load", json!({"data": b64(&gbk_set()), "encoding": bad})).is_err(), "{bad}"); + } + assert!(s.actions.list.is_empty(), "nothing is loaded when the encoding is bad"); +} From c60cbcb99cc304549fcf1e668e78b21ff38d00d0 Mon Sep 17 00:00:00 2001 From: Ben Huyck Date: Wed, 21 Oct 2026 17:56:47 +0000 Subject: [PATCH 15/52] Contributors: credit regexer by GitHub profile name --- contributors/people.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 20f9f5b1435..518027a8aae 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -285,3 +285,6 @@ sync_github_name = true [people.dylanmtaylor] sync_github_name = true + +[people.regexer] +sync_github_name = true From da1b2e0070088dff289c0b4283dae4623a9143a2 Mon Sep 17 00:00:00 2001 From: marshiyar <57055687+marshiyar@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:12:26 -0700 Subject: [PATCH 16/52] fix(engine): refuse strict .atn export of a partial Levels edit (#8530) layer.setAdjustment changes only the settings it names, but the Levels descriptor writes each range whole and fills the end an edit did not name with 0 or 255. A recorded {"kind":"levels","inBlack":31} was exported as Inpt [31, 255] with nothing skipped, so replaying it also reset a retained Input White. This is the Levels half of #8701 (Color Balance and Hue/Saturation, #8531). levels_complete accepts a Levels edit only when, for the master curve and every channel object, inBlack/inWhite are both given or both absent, and likewise outBlack/outWhite. set_to uses it as the levels arm of the existing completeness check, so strict export refuses the step and a non-strict export lists it as skipped. Test partial_levels_edits_refuse_strict_export fails without the fix (the export succeeds with Inpt [31, 255]) and passes with it. Fixes #8530 --- crates/engine/src/cmd/atn_cmds/adjustments.rs | 10 +++++ crates/engine/src/cmd/atn_cmds/steps_make.rs | 7 +++- crates/engine/src/cmd/atn_cmds/tests.rs | 41 +++++++++++++++++++ 3 files changed, 56 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/adjustments.rs b/crates/engine/src/cmd/atn_cmds/adjustments.rs index 5da802b800a..44439bb3ec4 100644 --- a/crates/engine/src/cmd/atn_cmds/adjustments.rs +++ b/crates/engine/src/cmd/atn_cmds/adjustments.rs @@ -66,6 +66,16 @@ fn levels_entry(chan: Option<&str>, p: &Value) -> Descriptor { e } +/// Whether the Levels settings in `p` (the master curve and every channel object) name both ends +/// of each range they touch, or neither. `levels_entry` writes a whole `Inpt` or `Otpt` pair and +/// fills the end a partial edit left out with 0 or 255, so replaying `inBlack: 31` alone would +/// also reset a retained Input White (#8530). +pub(super) fn levels_complete(p: &Value) -> bool { + let pairs_whole = + |v: &Value| [("inBlack", "inWhite"), ("outBlack", "outWhite")].iter().all(|(low, high)| jnum(v, low).is_some() == jnum(v, high).is_some()); + pairs_whole(p) && CHANNELS.iter().filter_map(|(_, k)| p.get(*k).filter(|v| v.is_object())).all(pairs_whole) +} + pub(super) fn levels_to(p: &Value) -> Option { let mut entries = vec![D::Descriptor(levels_entry(None, p))]; for (_, k) in CHANNELS { diff --git a/crates/engine/src/cmd/atn_cmds/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs index 2fce72c36d4..c7617053fc8 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_make.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -1,4 +1,4 @@ -use super::adjustments::{HUE_RANGES, adjustment_by_class, adjustment_by_suffix, adjustment_steps}; +use super::adjustments::{HUE_RANGES, adjustment_by_class, adjustment_by_suffix, adjustment_steps, levels_complete}; use super::descriptors::{ PX, Target, ang, class, class_ref, code, color_desc, color_hex, desc, enm, get_bool, get_enum, get_list, get_num, get_obj, get_ref, get_text, jbool, jnum, jstr, layer_ref, layer_target, long, name_ref, pct, px, ref_class, target, target_ref, text, trimmed, @@ -762,7 +762,8 @@ pub(super) fn set_to(id: &str, p: &Value) -> Option { let kind = jstr(p, "kind")?; // `layer.setAdjustment` changes only the settings it names. Color Balance and // Hue/Saturation descriptors carry every setting, filling absent ones with defaults, - // so a partial edit would replay as one that also resets the rest (#8531). + // so a partial edit would replay as one that also resets the rest (#8531). Levels writes + // each range whole, so one end alone resets the other (#8530). // Present and of the shape the writer reads: anything else it would write as 0. let number = |p: &Value, k: &str| p.get(k).and_then(Value::as_f64).is_some_and(f64::is_finite); let numbers = |p: &Value, keys: &[&str]| keys.iter().all(|k| number(p, k)); @@ -784,6 +785,8 @@ pub(super) fn set_to(id: &str, p: &Value) -> Option { r.is_object() && numbers(r, &["hue", "saturation", "lightness"]) && bounds }) } + // Both ends of each range it names (#8530). + "levels" => levels_complete(p), _ => true, }; if !complete { diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 011e9aa5e51..8a41ea0347b 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -2278,6 +2278,47 @@ fn partial_color_balance_and_hue_saturation_edits_refuse_strict_export() { } } +/// Levels, like Color Balance and Hue/Saturation: the descriptor writes both ends of the Input and +/// of the Output range, filling the end an edit did not name with 0 or 255, so replaying +/// `inBlack: 31` alone would also reset a retained Input White (#8530). Strict export refuses it; +/// a pair given whole, or none of it, still exports and round-trips. +#[test] +fn partial_levels_edits_refuse_strict_export() { + let one = |p: Value| Action { name: "Probe".into(), steps: vec![("layer.setAdjustment".into(), p)], ..Default::default() }; + for p in [ + json!({"kind": "levels", "inBlack": 31}), + json!({"kind": "levels", "inWhite": 239}), + json!({"kind": "levels", "outBlack": 10}), + json!({"kind": "levels", "outWhite": 240}), + json!({"kind": "levels", "inBlack": 31, "inWhite": 239, "outWhite": 240}), + json!({"kind": "levels", "red": {"inBlack": 2}}), + json!({"kind": "levels", "inBlack": 1, "inWhite": 250, "blue": {"outBlack": 3}}), + // A value of the wrong shape is no value: the other end is then alone. + json!({"kind": "levels", "inBlack": 31, "inWhite": "239"}), + ] { + let err = export("Audit8", &[&one(p.clone())], &[], false).unwrap_err(); + assert!(err.contains("`layer.setAdjustment`"), "{p}: {err}"); + let (_, skipped) = export("Audit8", &[&one(p.clone())], &[], true).unwrap(); + assert_eq!(skipped, vec![Skipped { action: "Probe".into(), step: 0, id: "layer.setAdjustment".into() }], "{p}"); + } + for p in [ + json!({"kind": "levels", "inBlack": 31, "inWhite": 239}), + json!({"kind": "levels", "outBlack": 10, "outWhite": 240}), + json!({"kind": "levels", "inBlack": 31, "inWhite": 239, "outBlack": 10, "outWhite": 240, "gamma": 1.2}), + json!({"kind": "levels", "gamma": 0.8}), + json!({"kind": "levels", "inBlack": 1, "inWhite": 250, "red": {"inBlack": 2, "inWhite": 200}}), + ] { + let (bytes, skipped) = export("Audit8", &[&one(p.clone())], &[], false).unwrap_or_else(|e| panic!("{p}: {e}")); + assert!(skipped.is_empty(), "{p}"); + let steps = import(&bytes).unwrap().actions[0].steps.clone(); + let (id, back) = steps.first().unwrap(); + assert_eq!(id, "layer.setAdjustment"); + for k in ["inBlack", "inWhite", "outBlack", "outWhite"] { + assert_eq!(back.get(k), p.get(k), "{p}: {k} in {back}"); + } + } +} + /// Photoshop's Close has no document target: a Close of a specific document must not be /// exported as a plain Close, which would close the active document on playback. #[test] From e57d9d1cbe95eb528171fb0527102c3b206e1236 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Fri, 30 Oct 2026 22:58:26 -0600 Subject: [PATCH 17/52] ATN export: Stroke steps write the settings they leave at default (#8303) Photoshop opens the Stroke dialog for a Stroke descriptor without its blend mode, even with dialogs off, so an exported action stopped there. stroke_to now writes edit.stroke's defaults for location (center), opacity (100), mode (Normal) and preserveTransparency (false) when the step leaves them out, as Photoshop's own recorded Stroke carries them all. Fixes #8303 Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/atn_cmds/steps_layer.rs | 5 +++++ crates/engine/src/cmd/atn_cmds/tests.rs | 21 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/crates/engine/src/cmd/atn_cmds/steps_layer.rs b/crates/engine/src/cmd/atn_cmds/steps_layer.rs index c69595e566a..8cf5188a71c 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_layer.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_layer.rs @@ -499,6 +499,11 @@ pub(super) fn stroke_to(_: &str, p: &Value) -> Option { } let mut params = if p.is_null() { Map::new() } else { p.as_object()?.clone() }; params.insert("width".into(), Value::from(crate::extra_cmds::stroke_width(p))); + // Photoshop opens the Stroke dialog for a descriptor that leaves out a setting, even with + // dialogs off (#8303), so the command's defaults for the ones left out are written too. + for (key, default) in [("location", json!("center")), ("opacity", json!(100)), ("mode", json!("Normal")), ("preserveTransparency", json!(false))] { + params.entry(key).or_insert(default); + } fields_to(&Value::Object(params), STROKE, desc("null")) } diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 011e9aa5e51..44b73cc0705 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -836,6 +836,27 @@ fn bucket_keeps_an_explicit_color_through_atn() { } } +/// A Stroke step that leaves settings at their defaults still writes them (#8303): Photoshop +/// opens the Stroke dialog for a descriptor without its blend mode, even with dialogs off. +#[test] +fn stroke_writes_the_defaults_it_leaves_out() { + let exported = |params: Value| export_item("edit.stroke", ¶ms, "S").and_then(|item| item.descriptor).unwrap(); + let d = exported(json!({"width": 2, "location": "inside", "color": "#d03060", "opacity": 63})); + assert_eq!(get_enum(&d, "Md ").as_deref(), Some("Nrml"), "{d:?}"); + assert_eq!(get_enum(&d, "Lctn").as_deref(), Some("Insd"), "an explicit setting is kept"); + assert_eq!(get_num(&d, "Opct"), Some(63.0)); + let d = exported(json!({"width": 2})); + assert_eq!(get_enum(&d, "Lctn").as_deref(), Some("Cntr"), "{d:?}"); + assert_eq!(get_num(&d, "Opct"), Some(100.0)); + assert_eq!(get_enum(&d, "Md ").as_deref(), Some("Nrml")); + assert!(get_bool(&d, "PrsT") == Some(false), "{d:?}"); + // An explicit mode is kept, and the step imports back to the same stroke. + let p = json!({"width": 3, "location": "outside", "mode": "Multiply", "opacity": 40, "color": "#000000", "preserveTransparency": true}); + let d = exported(p.clone()); + let Mapped::Steps(steps) = (event_for(&AtnEvent::Code(*b"Strk")).unwrap().from)(&d) else { panic!("{d:?}") }; + assert_eq!(steps[0].1, json!({"width": 3.0, "location": "outside", "mode": "Multiply", "opacity": 40.0, "color": "#000000", "preserveTransparency": true})); +} + /// `image.adjustments.photoFilter` exported to .atn and imported back → its params, or None. fn photo_filter_round_trip(params: Value) -> Option { let item = export_item("image.adjustments.photoFilter", ¶ms, "S")?; From 02af2370b126bffb1e680364058e9ba0e11f4df5 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 31 Oct 2026 02:08:22 -0600 Subject: [PATCH 18/52] Actions panel: New Set makes an empty set, and New Action records into the selected set (#7535) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Photoshop's Actions panel has a folder button and a New Set… menu item that make an empty action set (default "Set 1"); New Action lands in the selected set. PhotoCraft showed sets from Load Actions but couldn't make one. - actions.newSet: an empty set (default "Set N"), kept for the session until it holds an action; actions.record takes a `set` for the new action. - Actions panel: the folder button and New Set… open a name dialog; empty sets show as folder rows; a click on a folder row selects it; New Action records into the selected action's set, else the selected set. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/actions_cmds.rs | 13 +++- crates/engine/src/cmd/actions_edit_cmds.rs | 65 +++++++++++++++- crates/ui-egui/src/dialogs.rs | 3 + crates/ui-egui/src/panels/actions.rs | 90 +++++++++++++++++++++- crates/ui-egui/src/panels/actions/tests.rs | 38 +++++++++ 5 files changed, 202 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index 8e8d532d5b9..21528c867a2 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -106,6 +106,10 @@ pub struct ActionState { /// Steps run by the current top-level script and everything it calls. #[serde(skip)] pub script_steps: u64, + /// Sets made with New Set (`actions.newSet`) that hold no action yet: the Actions panel shows + /// them as empty folders. A set is saved through its actions, so an empty one lasts the session. + #[serde(skip)] + pub sets: Vec, /// Bumped whenever `list` changes, so the preset store can skip unchanged writes. #[serde(skip)] pub rev: u64, @@ -366,7 +370,12 @@ fn record(s: &mut Session, p: &Value) -> Result { if s.actions.list.iter().any(|action| action.name == name) { return Err(bad("actions.record", "an action with this name already exists")); } - s.actions.list.push(Action::new(name, Vec::new())); + let set = match p.get("set") { + None | Some(Value::Null) => None, + Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()), + Some(_) => return Err(bad("actions.record", "\"set\" must be a set name or null")), + }; + s.actions.list.push(Action { set, ..Action::new(name, Vec::new()) }); s.actions.touch(); s.actions.list.len() - 1 }; @@ -766,7 +775,7 @@ pub fn specs() -> Vec { label: "Record Action", menu: &[], shortcut: None, - params: r##"{"name":str? (new action, default "Action N")} or {"action":name|index} (append) → {action, index}"##, + params: r##"{"name":str? (new action, default "Action N"),"set":name? (the set it goes in, as New Action records into the selected set)} or {"action":name|index} (append) → {action, index}"##, enabled: always, run: record, journal: false, diff --git a/crates/engine/src/cmd/actions_edit_cmds.rs b/crates/engine/src/cmd/actions_edit_cmds.rs index 1f9cce3431b..17d4ba729d0 100644 --- a/crates/engine/src/cmd/actions_edit_cmds.rs +++ b/crates/engine/src/cmd/actions_edit_cmds.rs @@ -1,6 +1,7 @@ //! Editing an action's steps and its set, as the Actions panel does beyond recording: //! `actions.insert` (Photoshop's Insert Stop… and Insert Menu Item…), `actions.dialog` (the -//! panel's dialog toggle column) and `actions.assignSet` (which set folder an action sits in). +//! panel's dialog toggle column), `actions.assignSet` (which set folder an action sits in) and +//! `actions.newSet` (New Set…, an empty set folder). //! //! All three refuse to run during playback, commit pending recorded steps first, and keep the //! per-step flag sets (`disabled`, `dialogs`) in step with the moved indices, like @@ -126,6 +127,38 @@ fn assign_set(s: &mut Session, p: &Value) -> Result { Ok(result) } +/// Every set name, in the Actions panel's order: the sets of the actions as they first appear, +/// then the empty ones New Set made. +pub fn set_names(s: &Session) -> Vec { + let mut names: Vec = Vec::new(); + for set in s.actions.list.iter().filter_map(|a| a.set.as_ref()).chain(&s.actions.sets) { + if !names.contains(set) { + names.push(set.clone()); + } + } + names +} + +/// New Set…: an empty set folder, named `name` or "Set N" (the first number no set has), that New +/// Action can record into. +fn new_set(s: &mut Session, p: &Value) -> Result { + let cmd = "actions.newSet"; + not_playing(s, cmd)?; + let names = set_names(s); + let name = match p.get("name") { + None | Some(Value::Null) => (1u32..).map(|n| format!("Set {n}")).find(|n| !names.contains(n)).ok_or_else(|| bad(cmd, "no free set name"))?, + Some(Value::String(n)) if !n.trim().is_empty() => n.trim().to_string(), + Some(Value::String(_)) => return Err(bad(cmd, "`name` is empty")), + Some(_) => return Err(bad(cmd, "`name` must be a string")), + }; + if names.contains(&name) { + return Err(bad(cmd, format!("a set named `{name}` already exists"))); + } + s.actions.sets.push(name.clone()); + s.actions.touch(); + Ok(json!({"set": name})) +} + /// The conditions of Photoshop's Insert Conditional, by their string ids. pub const CONDITIONS: &[&str] = &[ "always", @@ -285,6 +318,16 @@ pub fn specs() -> Vec { run: assign_set, journal: false, }, + CommandSpec { + id: "actions.newSet", + label: "New Set", + menu: &[], + shortcut: None, + params: r##"{"name":str? (default "Set N")} → {set}. An empty set folder in the Actions panel, as Photoshop's New Set… makes; New Action records into the selected set (actions.record's `set`). It is saved once it holds an action."##, + enabled: always, + run: new_set, + journal: false, + }, ] } @@ -412,6 +455,26 @@ mod tests { } } + #[test] + fn new_set_makes_an_empty_folder_that_new_actions_record_into() { + let mut s = session_with(&["select.all"]); + s.execute("actions.assignSet", json!({"action": "A", "set": "Set 1"})).unwrap(); + // Numbered past the sets the actions already have. + assert_eq!(s.execute("actions.newSet", json!({})).unwrap()["set"], "Set 2"); + assert_eq!(s.execute("actions.newSet", json!({"name": " Retouch "})).unwrap()["set"], "Retouch"); + assert_eq!(set_names(&s), ["Set 1", "Set 2", "Retouch"]); + assert!(s.execute("actions.newSet", json!({"name": "Set 1"})).is_err(), "a set an action is in"); + assert!(s.execute("actions.newSet", json!({"name": "Retouch"})).is_err(), "an empty set"); + assert!(s.execute("actions.newSet", json!({"name": " "})).is_err()); + // New Action into the empty set. + let r = s.execute("actions.record", json!({"set": "Retouch"})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let i = r["index"].as_u64().unwrap() as usize; + assert_eq!(s.actions.list[i].set.as_deref(), Some("Retouch")); + assert_eq!(set_names(&s), ["Set 1", "Retouch", "Set 2"], "Retouch now holds an action"); + assert!(s.execute("actions.record", json!({"set": 3})).is_err()); + } + #[test] fn assign_set_moves_an_action_between_folders() { let mut s = session_with(&["select.all"]); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 5f74f4afa71..e852de42fb9 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -295,6 +295,7 @@ fn command_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: _ if crate::disk_change_prompt::owns(fields) => crate::disk_change_prompt::body(ui, fields), _ if crate::replace_prompt::owns(fields) => crate::replace_prompt::body(ui, fields), _ if crate::actions::owns_insert_stop(fields) => crate::actions::insert_stop_body(ui, fields), + _ if crate::actions::owns_new_set(fields) => crate::actions::new_set_body(ui, fields), _ if crate::new_layer_ui::owns(fields) => crate::new_layer_ui::body(ui, fields), _ if crate::mask_trash_prompt::owns(fields) => crate::mask_trash_prompt::body(ui, fields), _ if crate::rasterize_prompt::owns(fields) => crate::rasterize_prompt::body(ui, fields), @@ -833,6 +834,7 @@ const ROUTES: &[fn(&Fields) -> bool] = &[ crate::delete_layer_prompt::owns, crate::disk_change_prompt::owns, crate::actions::owns_insert_stop, + crate::actions::owns_new_set, crate::new_layer_ui::owns, crate::new_group_ui::owns, crate::mask_trash_prompt::owns, @@ -989,6 +991,7 @@ fn confirm_command(app: &mut PhotocraftApp, d: Dialog) -> Result _ if crate::disk_change_prompt::owns(&d.fields) => crate::disk_change_prompt::confirm(app, &d.fields), _ if crate::replace_prompt::owns(&d.fields) => crate::replace_prompt::confirm(app), _ if crate::actions::owns_insert_stop(&d.fields) => crate::actions::insert_stop_confirm(app, &d.fields), + _ if crate::actions::owns_new_set(&d.fields) => crate::actions::new_set_confirm(app, &d.fields), _ if crate::new_layer_ui::owns(&d.fields) => crate::new_layer_ui::confirm(app, &d.fields), _ if crate::mask_trash_prompt::owns(&d.fields) => crate::mask_trash_prompt::confirm(app, &d.fields), _ if crate::rasterize_prompt::owns(&d.fields) => crate::rasterize_prompt::confirm(app, &d.fields), diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index c1ba436d226..8a183df9fdd 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -27,6 +27,10 @@ pub struct ActionsUi { /// Photoshop's Button Mode: each action is a coloured button, and a click plays it. #[serde(default)] pub button_mode: bool, + /// The set whose folder row was clicked last (or New Set made), while no action is selected: + /// New Action records into it, as Photoshop's does into the selected set (#7535). + #[serde(skip)] + pub selected_set: Option, #[serde(skip)] reveal_recording: Option<(usize, usize)>, /// The action whose name is being edited in place (double-click on its name). @@ -253,11 +257,23 @@ pub(crate) fn run_view(app: &mut PhotocraftApp, id: &str, params: Value) -> Resu Ok(Value::Null) } +/// The set New Action records into: the selected action's, else the selected set folder's. +fn new_action_set(app: &PhotocraftApp) -> Option { + match app.ui.actions.selected.and_then(|i| app.session.actions.list.get(i)) { + Some(action) => action.set.clone(), + None => app.ui.actions.selected_set.clone().filter(|set| photocraft_engine::actions_edit_cmds::set_names(&app.session).contains(set)), + } +} + fn begin_recording(app: &mut PhotocraftApp, append: bool) { if app.session.actions.recording.is_some() { return; } - let params = if append { app.ui.actions.selected.map_or(json!({}), |i| json!({"action": i})) } else { json!({}) }; + let params = if append { + app.ui.actions.selected.map_or(json!({}), |i| json!({"action": i})) + } else { + new_action_set(app).map_or(json!({}), |set| json!({"set": set})) + }; let Ok(v) = app.run("actions.record", params) else { return }; let Some(i) = v.get("index").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()) else { return }; app.ui.actions.selected = Some(i); @@ -449,6 +465,40 @@ fn save_dialog(app: &mut PhotocraftApp, set: Option) -> Result) -> bool { + fields.contains_key(NEW_SET) +} + +/// New Set…: name an empty set folder (Photoshop's default "Set N"). +fn new_set_dialog(app: &mut PhotocraftApp) -> Result { + let names = photocraft_engine::actions_edit_cmds::set_names(&app.session); + let name = (1u32..).map(|n| format!("Set {n}")).find(|n| !names.contains(n)).unwrap_or_default(); + let fields = json!({NEW_SET: true, "__command": "actions.newSet", "__label": "New Set", "name": name}); + let id = app.ui.open_dialog(crate::state::DialogKind::Command, fields.as_object().cloned().unwrap_or_default()); + Ok(json!({"dialog": id})) +} + +pub fn new_set_body(ui: &mut egui::Ui, fields: &mut serde_json::Map) { + ui.horizontal(|ui| { + let label = ui.label(tl!("Name:")); + let mut name = fields.get("name").and_then(Value::as_str).unwrap_or_default().to_string(); + ui.add(egui::TextEdit::singleline(&mut name).desired_width(220.0)).labelled_by(label.id); + fields.insert("name".into(), json!(name)); + }); +} + +/// Make the set and select it, so New Action records into it. +pub fn new_set_confirm(app: &mut PhotocraftApp, fields: &serde_json::Map) -> Result { + let r = app.run("actions.newSet", json!({"name": fields.get("name").cloned().unwrap_or(Value::Null)}))?; + app.ui.actions.selected_set = r["set"].as_str().map(str::to_string); + app.ui.actions.selected = None; + app.ui.actions.selected_step = None; + Ok(r) +} + pub fn owns_insert_stop(fields: &serde_json::Map) -> bool { fields.contains_key(INSERT_STOP) } @@ -640,6 +690,9 @@ pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if ui.add_enabled(!recording, egui::Button::new(tl!("New Action…"))).clicked() { act = Some("new"); } + if ui.button(tl!("New Set…")).clicked() { + act = Some("newSet"); + } if ui.add_enabled(any, egui::Button::new(tl!("Play"))).clicked() { act = Some("play"); } @@ -686,6 +739,7 @@ pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { Ok(Value::Null) } "load" => load_dialog(app), + "newSet" => new_set_dialog(app), "stop" => insert_stop_dialog(app), _ => save_dialog(app, None), }; @@ -837,10 +891,12 @@ struct SetHeaderResult { save: bool, } -fn draw_set_header(ui: &mut egui::Ui, set: &str, count: u64, collapsed: bool, tokens: &Tokens) -> SetHeaderResult { +fn draw_set_header(ui: &mut egui::Ui, set: &str, count: u64, collapsed: bool, selected: bool, tokens: &Tokens) -> SetHeaderResult { let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click()); response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, !collapsed, set)); - if response.hovered() { + if selected { + ui.painter().rect_filled(rect, 0.0, tokens.row_selected); + } else if response.hovered() { ui.painter().rect_filled(rect, 0.0, tokens.hover.gamma_multiply(0.5)); } let triangle = Rect::from_center_size(pos2(rect.left() + 12.0, rect.center().y), vec2(8.0, 8.0)); @@ -871,6 +927,20 @@ fn draw_set_header(ui: &mut egui::Ui, set: &str, count: u64, collapsed: bool, to SetHeaderResult { toggled, save } } +/// The sets New Set made that hold no action yet: empty folder rows after the rest. Returns the +/// set whose row was clicked. +fn draw_empty_sets(app: &PhotocraftApp, ui: &mut egui::Ui, rows: &[Row], t: &Tokens) -> Option { + let mut clicked = None; + for set in app.session.actions.sets.iter().filter(|set| !rows.iter().any(|r| r.set.as_ref() == Some(*set))) { + let selected = app.ui.actions.selected.is_none() && app.ui.actions.selected_set.as_ref() == Some(set); + let collapsed = app.ui.actions.collapsed_sets.contains(set); + if draw_set_header(ui, set, 0, collapsed, selected, t).toggled { + clicked = Some(set.clone()); + } + } + clicked +} + fn action_context_menu(app: &mut PhotocraftApp, response: &egui::Response, index: usize, name: &str, swatch: &str) { egui::Popup::context_menu(response).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { ui.label(tl!("Keyboard Shortcuts")); @@ -978,7 +1048,8 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { shown_set = Some(set); let collapsed = app.ui.actions.collapsed_sets.iter().any(|c| c == set); let count = rows.iter().filter(|r| r.set.as_deref() == Some(set)).count() as u64; - let result = draw_set_header(ui, set, count, collapsed, &t); + let selected = app.ui.actions.selected.is_none() && app.ui.actions.selected_set.as_deref() == Some(set); + let result = draw_set_header(ui, set, count, collapsed, selected, &t); if result.toggled { set_toggled = Some(set.to_string()); } @@ -1082,6 +1153,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { dialog_toggled = dialog_toggled.or(events.dialog_toggled); } } + set_toggled = set_toggled.take().or_else(|| draw_empty_sets(app, ui, &rows, &t)); }); if let Some((action, step)) = toggled { let _ = app.run("actions.toggle", json!({"action": action, "step": step})); @@ -1090,6 +1162,10 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let _ = app.run("actions.dialog", json!({"action": action, "step": step})); } if let Some(set) = set_toggled { + // A click on a set's folder row also selects the set, for New Action. + app.ui.actions.selected = None; + app.ui.actions.selected_step = None; + app.ui.actions.selected_set = Some(set.clone()); match app.ui.actions.collapsed_sets.iter().position(|c| *c == set) { Some(i) => { app.ui.actions.collapsed_sets.remove(i); @@ -1130,6 +1206,12 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if play.clicked() { play_idx = playback_selection(app); } + if crate::icons::button(ui, "folder", 24.0, false, tl!("Create new set")).clicked() + && let Err(e) = new_set_dialog(app) + { + app.ui.status = e; + app.ui.status_error = true; + } if crate::icons::button(ui, "plus", 24.0, false, tl!("Create new action")).clicked() && !recording_now { begin_recording(app, false); } diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index a2f76295138..11c9e36ec2c 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -655,6 +655,44 @@ fn set_folders_group_actions_and_collapse() { assert!(h.query_by_label("Sharpen").is_some()); } +/// #7535: the folder button (and the panel menu's New Set…) names an empty set, shown as a folder +/// row with no actions; New Action then records into it, as into any selected set. +#[test] +fn new_set_makes_an_empty_folder_that_new_action_records_into() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let mut retouch = Action::new("Sharpen", vec![]); + retouch.set = Some("Retouch".into()); + app.session.actions.list.push(retouch); + let mut h = Harness::builder().with_size(vec2(360.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(2); + h.get_by_label("Create new set").click(); + h.run_steps(2); + let id = h.state().ui.dialogs.last().map(|d| d.id).expect("the New Set dialog"); + let d = h.state_mut().ui.dialog_mut(id).unwrap(); + assert!(owns_new_set(&d.fields)); + assert_eq!(d.fields["name"], "Set 1"); + d.fields.insert("name".into(), json!("Web")); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + h.run_steps(2); + // An empty folder row, selected. + assert!(h.query_by_label("Web").is_some()); + assert_eq!(h.state().ui.actions.selected_set.as_deref(), Some("Web")); + h.get_by_label("Create new action").click(); + h.run_steps(2); + h.state_mut().run("actions.stop", json!({})).unwrap(); + let list = &h.state().session.actions.list; + assert_eq!((list[1].name.as_str(), list[1].set.as_deref()), ("Action 2", Some("Web"))); + // With an action selected, New Action records into that action's set. + h.state_mut().ui.actions.selected = Some(0); + h.run_steps(2); + h.get_by_label("Create new action").click(); + h.run_steps(2); + h.state_mut().run("actions.stop", json!({})).unwrap(); + assert_eq!(h.state().session.actions.list[2].set.as_deref(), Some("Retouch")); +} + #[test] fn moving_an_action_next_to_another_set_joins_it() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); From 6c247021317742c5a212e468c7b08eb8215ad349 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 31 Oct 2026 02:37:50 -0600 Subject: [PATCH 19/52] Actions panel: Record with a set selected makes a new action in it (CodeRabbit review on crates/ui-egui/src/panels/actions.rs:275) With a set's folder row selected and no action, Begin recording and Start Recording had nothing to append to and recorded a new action outside any set. They now record a new action into the selected set, as New Action does. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/actions.rs | 9 ++++--- crates/ui-egui/src/panels/actions/tests.rs | 30 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 8a183df9fdd..931b8f80b44 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -269,10 +269,11 @@ fn begin_recording(app: &mut PhotocraftApp, append: bool) { if app.session.actions.recording.is_some() { return; } - let params = if append { - app.ui.actions.selected.map_or(json!({}), |i| json!({"action": i})) - } else { - new_action_set(app).map_or(json!({}), |set| json!({"set": set})) + // Recording appends to the selected action; with none (a set folder selected, say) it makes a + // new action like New Action does, in the selected set. + let params = match app.ui.actions.selected { + Some(i) if append => json!({"action": i}), + _ => new_action_set(app).map_or(json!({}), |set| json!({"set": set})), }; let Ok(v) = app.run("actions.record", params) else { return }; let Some(i) = v.get("index").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()) else { return }; diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index 11c9e36ec2c..50c450e9081 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -693,6 +693,36 @@ fn new_set_makes_an_empty_folder_that_new_action_records_into() { assert_eq!(h.state().session.actions.list[2].set.as_deref(), Some("Retouch")); } +/// #7535: with a set's folder row selected and no action, Start Recording (like the Record button) +/// has no action to append to, so it records a new action into that set, as New Action does. +#[test] +fn start_recording_with_a_set_selected_records_a_new_action_into_it() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let mut retouch = Action::new("Sharpen", vec![]); + retouch.set = Some("Retouch".into()); + app.session.actions.list.push(retouch); + app.run("actions.newSet", json!({"name": "Web"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(360.0, 600.0)).build_ui_state( + |ui, app| { + panel_menu(app, ui); + panel(app, ui); + }, + app, + ); + h.run_steps(2); + h.get_by_label("Web").click(); + h.run_steps(2); + assert_eq!((h.state().ui.actions.selected, h.state().ui.actions.selected_set.as_deref()), (None, Some("Web"))); + h.get_by_label("Start Recording").click(); + h.run_steps(2); + h.state_mut().run("actions.stop", json!({})).unwrap(); + let list = &h.state().session.actions.list; + assert_eq!(list.len(), 2); + assert_eq!(list[1].set.as_deref(), Some("Web")); +} + #[test] fn moving_an_action_next_to_another_set_joins_it() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); From a4582df1d0381f26cfcdcd7c4bd2f48fed28d041 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 31 Oct 2026 02:38:35 -0600 Subject: [PATCH 20/52] =?UTF-8?q?Actions=20panel:=20Save=20Actions?= =?UTF-8?q?=E2=80=A6=20saves=20the=20selected=20set=20(CodeRabbit=20review?= =?UTF-8?q?=20on=20crates/ui-egui/src/panels/actions.rs:1168)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A click on a set's folder row clears the selected action, so Save Actions… fell back to the first action's set and could save another set. It now saves the selected set when no action is selected, and keeps the first action's set as the fallback when neither is selected. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/actions.rs | 8 +++--- crates/ui-egui/src/panels/actions/tests.rs | 30 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 931b8f80b44..eaf8f7357c5 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -428,10 +428,12 @@ fn load_dialog(app: &mut PhotocraftApp) -> Result { app.pick_file_bytes_filtered(&["atn"], |app, name, bytes| load_bytes(app, &name, &bytes)) } -/// Save Actions…: the selected action's set (every action of it), or every action when none -/// came from a set, as a `.atn` file Photoshop loads. +/// Save Actions…: the selected action's set (every action of it), else the selected set folder, +/// or every action when none came from a set, as a `.atn` file Photoshop loads. fn save_dialog(app: &mut PhotocraftApp, set: Option) -> Result { - let set = set.or_else(|| selected_action(app).and_then(|a| a.set.clone())); + let selected_set = app.ui.actions.selected.is_none().then(|| app.ui.actions.selected_set.clone()).flatten(); + let selected_set = selected_set.filter(|set| photocraft_engine::actions_edit_cmds::set_names(&app.session).contains(set)); + let set = set.or(selected_set).or_else(|| selected_action(app).and_then(|a| a.set.clone())); let params = match &set { Some(set) => json!({"set": set, "skipUnsupported": true}), None => json!({"skipUnsupported": true}), diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index 50c450e9081..8a9ec705f51 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -723,6 +723,36 @@ fn start_recording_with_a_set_selected_records_a_new_action_into_it() { assert_eq!(list[1].set.as_deref(), Some("Web")); } +/// Save Actions… after a click on set B's folder row saves set B, not the first action's set. +#[test] +fn save_actions_with_a_set_selected_saves_that_set() { + use egui_kittest::{Harness, kittest::Queryable}; + let (file_dialog, asked) = crate::file_dialog::fake(vec![None]); + let services = crate::Services { file_dialog: Some(file_dialog), ..Default::default() }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + for (name, set) in [("Sharpen", "Retouch"), ("Resize", "Web")] { + let mut action = Action::new(name, vec![("layer.new.layer".into(), json!({}))]); + action.set = Some(set.into()); + app.session.actions.list.push(action); + } + let mut h = Harness::builder().with_size(vec2(360.0, 600.0)).build_ui_state( + |ui, app| { + panel_menu(app, ui); + panel(app, ui); + }, + app, + ); + h.run_steps(2); + h.get_by_label("Web").click(); + h.run_steps(2); + assert_eq!((h.state().ui.actions.selected, h.state().ui.actions.selected_set.as_deref()), (None, Some("Web"))); + h.get_by_label("Save Actions…").click(); + h.run_steps(2); + h.state_mut().poll_file_dialog(&egui::Context::default(), None); + assert!(matches!(asked.borrow().as_slice(), [crate::file_dialog::FileDialogRequest::Save { suggested }] if suggested == "Web.atn"), "{:?}", asked.borrow()); +} + #[test] fn moving_an_action_next_to_another_set_joins_it() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); From fbb7a7d3f87d9871d42384f1f96aff0e7a6554c6 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 31 Oct 2026 03:17:22 -0600 Subject: [PATCH 21/52] Actions panel: recording into a collapsed set expands it (CodeRabbit review on crates/ui-egui/src/panels/actions.rs:276) A click on a set's folder row selects the set but also toggles it, so an expanded set ends up collapsed; New Action or Start Recording then made the action inside the collapsed set, hiding it and its recorded steps. begin_recording now expands the recorded action's set, as Photoshop shows the new action while it records. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/actions.rs | 4 +++ crates/ui-egui/src/panels/actions/tests.rs | 32 ++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index eaf8f7357c5..f95ceee635f 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -283,6 +283,10 @@ fn begin_recording(app: &mut PhotocraftApp, append: bool) { app.ui.actions.expanded.resize(i + 1, false); } app.ui.actions.expanded[i] = true; + // Its set too: a click that selected the set's folder row may have collapsed it. + if let Some(set) = app.session.actions.list.get(i).and_then(|a| a.set.as_ref()) { + app.ui.actions.collapsed_sets.retain(|c| c != set); + } } pub(crate) fn report_play(app: &mut PhotocraftApp, v: &Value) { diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index 8a9ec705f51..04b4f00dd2f 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -723,6 +723,38 @@ fn start_recording_with_a_set_selected_records_a_new_action_into_it() { assert_eq!(list[1].set.as_deref(), Some("Web")); } +/// A click on an expanded set's folder row selects it and collapses it; recording into it (New +/// Action or Start Recording) expands the set again, so the new action and its steps show. +#[test] +fn recording_into_a_collapsed_set_expands_it() { + use egui_kittest::{Harness, kittest::Queryable}; + for label in ["Create new action", "Start Recording"] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let mut retouch = Action::new("Sharpen", vec![]); + retouch.set = Some("Retouch".into()); + app.session.actions.list.push(retouch); + let mut h = Harness::builder().with_size(vec2(360.0, 600.0)).build_ui_state( + |ui, app| { + panel_menu(app, ui); + panel(app, ui); + }, + app, + ); + h.run_steps(2); + h.get_by_label("Retouch").click(); + h.run_steps(2); + assert_eq!(h.state().ui.actions.collapsed_sets, ["Retouch"], "{label}"); + assert!(h.query_by_label("Sharpen").is_none(), "{label}"); + h.get_by_label(label).click(); + h.run_steps(2); + assert!(h.state().ui.actions.collapsed_sets.is_empty(), "{label}"); + assert_eq!(h.state().ui.actions.selected, Some(1), "{label}"); + assert!(h.query_by_label("Action 2").is_some(), "{label}"); + h.state_mut().run("actions.stop", json!({})).unwrap(); + } +} + /// Save Actions… after a click on set B's folder row saves set B, not the first action's set. #[test] fn save_actions_with_a_set_selected_saves_that_set() { From c69ad0e86cb74dae0c148c4400bfe6f90ffa8137 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 31 Oct 2026 03:42:23 -0600 Subject: [PATCH 22/52] Actions: recording into an existing set keeps its exact name (CodeRabbit follow-up on actions_cmds.rs:373-378) Test: record_keeps_an_existing_sets_exact_name. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/actions_cmds.rs | 3 +++ crates/engine/src/cmd/actions_cmds/tests.rs | 15 +++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index 21528c867a2..f7662cdbcc5 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -372,6 +372,9 @@ fn record(s: &mut Session, p: &Value) -> Result { } let set = match p.get("set") { None | Some(Value::Null) => None, + // An existing set keeps its exact name (an older actions.json may pad it); a new one + // is trimmed. + Some(Value::String(n)) if s.actions.list.iter().any(|a| a.set.as_deref() == Some(n.as_str())) => Some(n.clone()), Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()), Some(_) => return Err(bad("actions.record", "\"set\" must be a set name or null")), }; diff --git a/crates/engine/src/cmd/actions_cmds/tests.rs b/crates/engine/src/cmd/actions_cmds/tests.rs index caddcaa8924..44366f423ef 100644 --- a/crates/engine/src/cmd/actions_cmds/tests.rs +++ b/crates/engine/src/cmd/actions_cmds/tests.rs @@ -1176,3 +1176,18 @@ fn arrange_that_cannot_move_is_a_noop_in_playback() { assert_eq!(played["ran"], 0, "{played}"); assert!(played["failed"].is_object(), "{played}"); } + +/// #10459 review: recording into an existing set keeps that set's exact name, even one with +/// surrounding spaces (from an older actions.json); a new set name is trimmed. +#[test] +fn record_keeps_an_existing_sets_exact_name() { + let mut s = Session::new(); + s.actions.list.push(Action { set: Some(" Web ".into()), ..Action::new("Old", Vec::new()) }); + s.execute("actions.record", json!({"name": "New", "set": " Web "})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let set_of = |s: &Session, n: &str| s.actions.list.iter().find(|a| a.name == n).and_then(|a| a.set.clone()); + assert_eq!(set_of(&s, "New").as_deref(), Some(" Web "), "the existing set"); + s.execute("actions.record", json!({"name": "Fresh", "set": " Print "})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(set_of(&s, "Fresh").as_deref(), Some("Print"), "a new set is trimmed"); +} From 841e74a18343faf86454574b6666ece64128c488 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 31 Oct 2026 18:30:49 +0100 Subject: [PATCH 23/52] Integration batch 11 (ATN): start of the batch, nothing merged yet Co-Authored-By: Claude Opus 5.5 From 6ef5813a123f46ae60d81b6664adbdb71bc09ea7 Mon Sep 17 00:00:00 2001 From: sn-o-w Date: Sat, 31 Oct 2026 17:56:24 +0200 Subject: [PATCH 24/52] Contributors: add myself (sn-o-w) --- contributors/people.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index cc378fd776d..9f96266cded 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -282,3 +282,7 @@ sync_github_name = true [people.dylanmtaylor] sync_github_name = true + +[people.sn-o-w] +real_name = "Cristian Silaghi" +sync_github_name = false From 1adef51797ae94e3f12f51da95e0fc64472e77c5 Mon Sep 17 00:00:00 2001 From: Ben Huyck Date: Wed, 21 Oct 2026 11:46:12 +0000 Subject: [PATCH 25/52] PSD: guess the legacy code page of 8-bit names (#6743) --- Cargo.lock | 1 + Cargo.toml | 1 + crates/psd/Cargo.toml | 1 + crates/psd/src/codepage.rs | 461 +++++++++++++++++++++++++++++++++++++ crates/psd/src/lib.rs | 1 + 5 files changed, 465 insertions(+) create mode 100644 crates/psd/src/codepage.rs diff --git a/Cargo.lock b/Cargo.lock index 5c882f28e9f..f163931a189 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5332,6 +5332,7 @@ dependencies = [ name = "photocraft-psd" version = "0.18.0" dependencies = [ + "encoding_rs", "flate2", "photocraft-psd", "proptest", diff --git a/Cargo.toml b/Cargo.toml index da26a96405a..b3d19ef9168 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -53,6 +53,7 @@ clap_mangen = { version = "0.3.3", features = ["env"] } arc-swap = "1" bytemuck = { version = "1", features = ["derive"] } flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] } +encoding_rs = { version = "0.8", default-features = false, features = ["alloc"] } image = { version = "0.25", default-features = false } # Baseline-JPEG decode of lossy DNG tiles (compression 34892), shared with zune-jpeg. zune-core = "0.5" diff --git a/crates/psd/Cargo.toml b/crates/psd/Cargo.toml index 12662f9bd3e..7ecce9ee673 100644 --- a/crates/psd/Cargo.toml +++ b/crates/psd/Cargo.toml @@ -20,6 +20,7 @@ testgen = [] [dependencies] thiserror = { workspace = true } flate2 = { workspace = true } +encoding_rs = { workspace = true } serde = { workspace = true, optional = true } [dev-dependencies] diff --git a/crates/psd/src/codepage.rs b/crates/psd/src/codepage.rs new file mode 100644 index 00000000000..3918cd1879d --- /dev/null +++ b/crates/psd/src/codepage.rs @@ -0,0 +1,461 @@ +//! Guessing the legacy code page of 8-bit names. +//! +//! Some formats store names as bytes in the writer's system ANSI code page: an `.atn` file's +//! event and dictionary names are CP936 (GBK) from Chinese Photoshop, CP932 (Shift_JIS) from +//! Japanese, Mac Roman from French Photoshop on a Mac, and so on. Nothing in the file says +//! which. When the file also stores some of those names as Unicode, [`match_known`] finds the +//! code page that turns the bytes into them. Otherwise [`guess`] infers one code page per file +//! from the names that are not valid UTF-8: +//! +//! 1. Candidates: Shift_JIS, GBK, Big5, EUC-KR, windows-1252, windows-1251, macintosh (Mac +//! Roman). A candidate that cannot decode every name without errors is dropped. +//! 2. Each survivor is scored by the share of non-ASCII bytes that fall in its common-text +//! ranges (GB2312 hanzi, JIS level-1 kanji and kana, Big5 level 1, KS X 1001 Hangul, +//! letters, and each page's punctuation). The highest share wins. +//! 3. A tie is broken by the script of a hint (text the file stores as UTF-16, so it decodes +//! fine): kana → Shift_JIS; Hangul → EUC-KR; Cyrillic → windows-1251; Han → GBK, then +//! Big5, then Shift_JIS; Latin letters → windows-1252, then Mac Roman. +//! 4. Still tied: windows-1252, flagged [`Guess::uncertain`]. +//! +//! Only the first [`GUESS_SAMPLE`] bytes of names are examined. + +use encoding_rs::{ + BIG5, DecoderResult, EUC_KR, Encoding, GBK, MACINTOSH, REPLACEMENT, SHIFT_JIS, UTF_8, UTF_16BE, UTF_16LE, WINDOWS_1251, WINDOWS_1252, X_USER_DEFINED, +}; + +use crate::error::{PsdError, Result}; + +/// At most this many bytes of legacy names are examined by [`guess`]. +pub(crate) const GUESS_SAMPLE: usize = 64 * 1024; +/// At most this many `(bytes, text)` pairs are examined by [`match_known`]. +pub(crate) const KNOWN_PAIRS: usize = 256; + +/// The code page [`guess`] settled on. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Guess { + /// The encoding to decode every legacy name with. + pub(crate) encoding: &'static Encoding, + /// Nothing told the candidates apart; `encoding` is the windows-1252 fallback. + pub(crate) uncertain: bool, +} + +/// Candidates in tie order (encoding_rs exposes encodings as statics, hence a function). +fn candidates() -> [&'static Encoding; 7] { + [SHIFT_JIS, GBK, BIG5, EUC_KR, WINDOWS_1252, WINDOWS_1251, MACINTOSH] +} + +/// The candidate that decodes the most of `pairs` (a name's bytes and the same name as Unicode) +/// exactly; ties go to the earlier candidate. `None` when it decodes none of them. Only the first +/// [`KNOWN_PAIRS`] pairs are examined. +pub(crate) fn match_known(pairs: &[(&[u8], &str)]) -> Option<&'static Encoding> { + let pairs = pairs.get(..KNOWN_PAIRS).unwrap_or(pairs); + let mut best = None; + let mut best_count = 0usize; + for enc in candidates() { + let count = pairs.iter().filter(|(bytes, text)| enc.decode_without_bom_handling_and_without_replacement(bytes).is_some_and(|d| d == *text)).count(); + if count > best_count { + best = Some(enc); + best_count = count; + } + } + best +} + +/// Guesses the one code page that `legacy` (names that are not valid UTF-8, in file order) were +/// written in. `hint` is text from the same file whose script points at the writer's locale. +pub(crate) fn guess(legacy: &[&[u8]], hint: &str) -> Guess { + let sample = sample(legacy); + if sample.is_empty() { + return Guess { encoding: UTF_8, uncertain: false }; + } + let mut best: Vec<&'static Encoding> = Vec::new(); + let mut best_score = (0u64, 1u64); + for enc in candidates() { + if !sample.iter().all(|(name, truncated)| decodes_cleanly(enc, name, *truncated)) { + continue; + } + let score = sample.iter().fold((0u64, 0u64), |(c, h), (name, _)| { + let (nc, nh) = score(enc, name); + (c.saturating_add(nc), h.saturating_add(nh)) + }); + let score = if score.1 == 0 { (0, 1) } else { score }; + // Compare common/high shares without division: a/b vs c/d ⇔ a·d vs c·b. + let lhs = u128::from(score.0) * u128::from(best_score.1); + let rhs = u128::from(best_score.0) * u128::from(score.1); + if best.is_empty() || lhs > rhs { + best = vec![enc]; + best_score = score; + } else if lhs == rhs { + best.push(enc); + } + } + match best.as_slice() { + [only] => Guess { encoding: only, uncertain: false }, + tied => match hinted(hint).iter().find(|enc| tied.contains(enc)) { + Some(enc) => Guess { encoding: enc, uncertain: false }, + None => Guess { encoding: WINDOWS_1252, uncertain: true }, + }, + } +} + +/// Decodes `bytes` with `enc`; invalid sequences become U+FFFD. +pub(crate) fn decode(bytes: &[u8], enc: &'static Encoding) -> String { + enc.decode_without_bom_handling(bytes).0.into_owned() +} + +/// Whether `name` decodes cleanly in the double-byte page `enc` and every non-ASCII byte of it is +/// common text there. A name in such a page can be valid UTF-8 by accident (GBK 去色 is +/// `C8 A5 C9 AB`, "ȥɫ"); real UTF-8 rarely passes, as its continuation bytes fall outside the +/// common ranges. Single-byte pages are never asked: their letters cover UTF-8's lead and +/// continuation bytes ("Weiß" is "Weiß" in windows-1252), and a legacy name there is valid UTF-8 +/// by accident only for unlikely pairs such as "é". +pub(crate) fn reads_as_common(name: &[u8], enc: &'static Encoding) -> bool { + if ![SHIFT_JIS, GBK, BIG5, EUC_KR].contains(&enc) { + return false; + } + let (common, high) = score(enc, name); + high > 0 && common == high && decodes_cleanly(enc, name, false) +} + +/// Resolves an encoding label (`shift_jis`, `gbk`, `big5`, `euc-kr`, `windows-1252`, `utf-8`…; +/// case and surrounding whitespace are ignored). Labels for encodings that cannot hold an 8-bit +/// name are rejected. +pub(crate) fn resolve_label(label: &str) -> Result<&'static Encoding> { + match Encoding::for_label(label.as_bytes()) { + Some(enc) if ![REPLACEMENT, UTF_16LE, UTF_16BE, X_USER_DEFINED].contains(&enc) => Ok(enc), + _ => Err(PsdError::Unsupported(format!("text encoding `{label}`: use a label such as shift_jis, gbk, big5, euc-kr, windows-1252 or utf-8"))), + } +} + +/// The names [`guess`] examines, each with whether it was cut short: names in order while they +/// fit in [`GUESS_SAMPLE`] bytes, and at least the first (truncated if it alone is longer). +fn sample<'a>(legacy: &[&'a [u8]]) -> Vec<(&'a [u8], bool)> { + let mut out = Vec::new(); + let mut total = 0usize; + for name in legacy { + let next = total.saturating_add(name.len()); + if next > GUESS_SAMPLE { + if out.is_empty() { + out.push((name.get(..GUESS_SAMPLE).unwrap_or(name), true)); + } + break; + } + out.push((*name, false)); + total = next; + } + out +} + +/// Whether `enc` decodes `bytes` without a single error. A `truncated` name may end inside a +/// character, which is not held against it. +fn decodes_cleanly(enc: &'static Encoding, bytes: &[u8], truncated: bool) -> bool { + let mut decoder = enc.new_decoder_without_bom_handling(); + // Every candidate decodes one byte to at most three UTF-8 bytes, so this is linear in + // `bytes` (a sampled name, or one name the file already holds). + let mut out = String::with_capacity(bytes.len().saturating_mul(3).saturating_add(16)); + let mut rest = bytes; + loop { + let (result, read) = decoder.decode_to_string_without_replacement(rest, &mut out, !truncated); + match result { + DecoderResult::InputEmpty => return true, + DecoderResult::Malformed(..) => return false, + DecoderResult::OutputFull => { + rest = rest.get(read..).unwrap_or_default(); + out.clear(); + } + } + } +} + +/// `(common, high)`: how many of a name's non-ASCII bytes `enc` reads as common text, and how +/// many non-ASCII bytes it has. +fn score(enc: &'static Encoding, name: &[u8]) -> (u64, u64) { + if enc == WINDOWS_1252 || enc == WINDOWS_1251 || enc == MACINTOSH { + // One byte is one character, and a non-ASCII byte is a non-ASCII character. Letters and + // typographic punctuation are common, as the double-byte pages' punctuation rows are. + let common = |ch: char| ch.is_alphabetic() || TYPOGRAPHIC.contains(&ch); + return decode(name, enc).chars().filter(|c| !c.is_ascii()).fold((0, 0), |(c, h), ch| (c + u64::from(common(ch)), h + 1)); + } + let (mut common, mut high) = (0u64, 0u64); + let mut i = 0usize; + while let Some(&lead) = name.get(i) { + if lead < 0x80 { + i += 1; + continue; + } + // Shift_JIS reads 0x80 and 0xA0–0xDF (half-width katakana, rare in real text) as one + // byte; elsewhere a lone non-ASCII byte is an error the decoder already rejected. + let single = if enc == SHIFT_JIS { lead == 0x80 || (0xA0..=0xDF).contains(&lead) || lead >= 0xFD } else { lead == 0x80 || lead == 0xFF }; + if single { + high += 1; + i += 1; + continue; + } + // A lead byte with nothing after it is where the sample was cut (the decoder rejects one + // at the real end of a name), so it is not scored. + let Some(&trail) = name.get(i + 1) else { break }; + // GB18030 four-byte sequences (second byte a digit) are never common text. + let len = if enc == GBK && trail.is_ascii_digit() { 4 } else { 2 }; + let len = len.min(name.len().saturating_sub(i)); + high += len as u64; + if len == 2 && is_common(enc, lead, trail) { + common += 2; + } + i += len; + } + (common, high) +} + +/// Quotes, dashes, ellipsis and bullet: windows-1252 and windows-1251 share them at 0x82–0x97; +/// Mac Roman has them too. +const TYPOGRAPHIC: [char; 10] = ['‘', '’', '‚', '“', '”', '„', '–', '—', '…', '•']; + +/// Whether the two-byte character `lead trail` is in `enc`'s common-text ranges. +fn is_common(enc: &'static Encoding, lead: u8, trail: u8) -> bool { + let both = u16::from_be_bytes([lead, trail]); + if enc == GBK { + // GB2312 hanzi, and the punctuation rows 0xA1 and 0xA3. + (0xA1..=0xFE).contains(&trail) && ((0xB0..=0xF7).contains(&lead) || lead == 0xA1 || lead == 0xA3) + } else if enc == BIG5 { + // Level-1 hanzi and punctuation. + (0xA4..=0xC6).contains(&lead) || lead == 0xA1 + } else if enc == SHIFT_JIS { + // Kana, level-1 kanji and punctuation. + (0x829F..=0x8396).contains(&both) || (0x889F..=0x9872).contains(&both) || (0x8140..=0x81FC).contains(&both) + } else if enc == EUC_KR { + // KS X 1001 Hangul and punctuation. + trail >= 0xA1 && ((0xB0..=0xC8).contains(&lead) || lead == 0xA1) + } else { + false + } +} + +/// The candidates the script of `hint` points at, strongest first. +fn hinted(hint: &str) -> Vec<&'static Encoding> { + let has = |lo: char, hi: char| hint.chars().any(|c| (lo..=hi).contains(&c) && c.is_alphabetic()); + if has('\u{3040}', '\u{30FF}') { + vec![SHIFT_JIS] + } else if has('\u{AC00}', '\u{D7A3}') { + vec![EUC_KR] + } else if has('\u{0400}', '\u{04FF}') { + vec![WINDOWS_1251] + } else if has('\u{4E00}', '\u{9FFF}') { + vec![GBK, BIG5, SHIFT_JIS] + } else if has('\u{00C0}', '\u{024F}') { + vec![WINDOWS_1252, MACINTOSH] + } else { + vec![] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const GBK_ISSUE: &[&[u8]] = &[b"\xbf\xc9\xd1\xa1\xd1\xd5\xc9\xab"]; // 可选颜色 (from #6743) + const SJIS_COMMENT: &[&[u8]] = &[ + b"\x91\x49\x91\xf0\x20\x3a", // 選択 : + b"\x90\xdd\x92\xe8\x20\x3a", // 設定 : + b"\x83\x52\x83\x73\x81\x5b", // コピー + b"\x95\xdb\x91\xb6", // 保存 + ]; + + fn encoded(enc: &'static Encoding, words: &[&str]) -> Vec> { + words.iter().map(|w| enc.encode(w).0.into_owned()).collect() + } + + fn guess_words(enc: &'static Encoding, words: &[&str], hint: &str) -> Guess { + let bytes = encoded(enc, words); + let refs: Vec<&[u8]> = bytes.iter().map(Vec::as_slice).collect(); + guess(&refs, hint) + } + + #[test] + fn issue_gbk_bytes_read_as_gbk() { + let g = guess(GBK_ISSUE, "调白"); + assert_eq!(g.encoding, GBK); + assert!(!g.uncertain); + assert_eq!(decode(GBK_ISSUE[0], g.encoding), "可选颜色"); + } + + #[test] + fn kanji_only_hint_still_reads_shift_jis() { + let g = guess(SJIS_COMMENT, "保存"); + assert_eq!(g.encoding, SHIFT_JIS); + assert_eq!(decode(SJIS_COMMENT[0], g.encoding), "選択 :"); + } + + #[test] + fn big5_reads_as_big5() { + assert_eq!(guess_words(BIG5, &["色彩範圍", "移動", "選取", "儲存"], "").encoding, BIG5); + } + + #[test] + fn hangul_hint_reads_euc_kr() { + let g = guess_words(EUC_KR, &["선택", "이동", "저장", "색상 범위"], "동작 1"); + assert_eq!(g.encoding, EUC_KR); + assert!(!g.uncertain); + } + + #[test] + fn cyrillic_hint_reads_1251() { + let g = guess_words(WINDOWS_1251, &["Выделить", "Переместить", "Сохранить"], "Набор 1"); + assert_eq!(g.encoding, WINDOWS_1251); + assert!(!g.uncertain); + } + + #[test] + fn latin_hint_reads_1252() { + let g = guess_words(WINDOWS_1252, &["Größe"], "Größe ändern"); + assert_eq!(g.encoding, WINDOWS_1252); + assert!(!g.uncertain); + } + + #[test] + fn tie_without_hint_is_1252_and_uncertain() { + let g = guess_words(WINDOWS_1252, &["Größe"], "Set 1"); + assert_eq!(g.encoding, WINDOWS_1252); + assert!(g.uncertain); + } + + #[test] + fn han_tie_prefers_gbk() { + // GBK 保存: GBK, Big5 and EUC-KR all read both characters as common text. + let names: &[&[u8]] = &[b"\xb1\xa3\xb4\xe6"]; + let g = guess(names, "动作"); + assert_eq!(g.encoding, GBK); + assert!(!g.uncertain); + assert_eq!(decode(names[0], g.encoding), "保存"); + assert_eq!(guess(names, "Set 1"), Guess { encoding: WINDOWS_1252, uncertain: true }); + } + + #[test] + fn typographic_punctuation_reads_as_1252() { + // ’ (0x92) then a letter is also a level-1 kanji pair in Shift_JIS. + let names: &[&[u8]] = &[b"Taille de l\x92image"]; + let g = guess(names, "Actions par défaut"); + assert_eq!(g.encoding, WINDOWS_1252); + assert!(!g.uncertain); + assert_eq!(decode(names[0], g.encoding), "Taille de l’image"); + assert_eq!(guess(names, "Set 1"), Guess { encoding: WINDOWS_1252, uncertain: true }); + } + + #[test] + fn utf8_lookalikes_read_as_common_text() { + // GBK 去色 and EUC-KR 칠 are also valid UTF-8 ("ȥɫ", "ĥ"). + assert!(reads_as_common(b"\xc8\xa5\xc9\xab", GBK)); + assert!(reads_as_common(b"\xc4\xa5", EUC_KR)); + // Real UTF-8 text does not: its continuation bytes fall outside the common ranges. + assert!(!reads_as_common("高斯模糊".as_bytes(), GBK)); + assert!(!reads_as_common("Gaussian Blur ✓".as_bytes(), GBK)); + assert!(!reads_as_common("Größe".as_bytes(), WINDOWS_1252)); + assert!(!reads_as_common(b"Blur", GBK), "ASCII has nothing to re-read"); + // Nor does UTF-8 in a single-byte page, though "Weiß" is à and Ÿ there and "Привет" is + // all Р, С and letters: accidental UTF-8 is a double-byte page's problem. + assert!(!reads_as_common("Weiß".as_bytes(), WINDOWS_1252)); + assert!(!reads_as_common("Привет".as_bytes(), WINDOWS_1251)); + assert!(!reads_as_common("Weiß".as_bytes(), MACINTOSH)); + } + + #[test] + fn latin_hint_reads_mac_roman_when_1252_does_not_fit() { + // Mac Roman "Arrière-plan": è is 0x8F, a control character in windows-1252. + let names: &[&[u8]] = &[b"Arri\x8fre-plan"]; + let g = guess(names, "Définir l’arrière-plan"); + assert_eq!(g.encoding, MACINTOSH); + assert!(!g.uncertain); + assert_eq!(decode(names[0], g.encoding), "Arrière-plan"); + } + + #[test] + fn known_names_pick_the_code_page() { + // Every step of the corpus/atn sets that has a non-ASCII panel name also stores it as + // Unicode (the descriptor's class name); here, Mac Roman "Définir". + let pairs: &[(&[u8], &str)] = &[(b"D\x8efinir", "Définir")]; + assert_eq!(match_known(pairs), Some(MACINTOSH)); + // GBK 保存 is a three-way tie for the statistics; the known name settles it. + assert_eq!(match_known(&[(b"\xb1\xa3\xb4\xe6", "保存")]), Some(GBK)); + } + + #[test] + fn most_matching_names_win() { + let pairs: &[(&[u8], &str)] = &[(b"\xb1\xa3\xb4\xe6", "保存"), (b"D\x8efinir", "Définir"), (b"Arri\x8fre-plan", "Arrière-plan")]; + assert_eq!(match_known(pairs), Some(MACINTOSH)); + } + + #[test] + fn known_name_ties_take_candidate_order() { + // Curly quotes are 0x93/0x94 in both windows-1252 and windows-1251. + assert_eq!(match_known(&[(b"\x93x\x94", "“x”")]), Some(WINDOWS_1252)); + } + + #[test] + fn known_names_that_match_nothing_decide_nothing() { + assert_eq!(match_known(&[(b"D\x8efinir", "Set")]), None); + assert_eq!(match_known(&[]), None); + // Past the cap, pairs are not examined. + let mut pairs = vec![(&b"D\x8efinir"[..], "x"); KNOWN_PAIRS]; + pairs.push((b"\xb1\xa3\xb4\xe6", "保存")); + assert_eq!(match_known(&pairs), None); + } + + #[test] + fn bytes_no_cjk_page_accepts_still_decode() { + // 0xFF is invalid in every double-byte candidate; windows-1251 (Ђ я Ђ) and Mac Roman + // (Ä ˇ Ä) read all three bytes as letters, windows-1252 only one (€ ÿ €). With nothing to + // break the tie, the fallback still decodes them. + let names: &[&[u8]] = &[b"\x80\xff\x80"]; + let g = guess(names, ""); + assert_eq!(g, Guess { encoding: WINDOWS_1252, uncertain: true }); + assert_eq!(decode(names[0], g.encoding), "€ÿ€"); + assert_eq!(guess(names, "Набор").encoding, WINDOWS_1251); + } + + #[test] + fn empty_or_utf8_input_is_utf8() { + let g = guess(&[], ""); + assert_eq!(g.encoding, UTF_8); + assert!(!g.uncertain); + } + + #[test] + fn mixed_code_pages_pick_one_and_never_fail() { + let names: &[&[u8]] = &[GBK_ISSUE[0], SJIS_COMMENT[0]]; + let g = guess(names, ""); + for name in names { + assert!(!decode(name, g.encoding).is_empty()); + } + } + + #[test] + fn huge_input_is_sampled() { + let names = vec![GBK_ISSUE[0]; 10_000]; + assert_eq!(guess(&names, "").encoding, GBK); + } + + #[test] + fn one_name_over_the_sample_cap_is_truncated_not_rejected() { + // "a" then 可 repeated past the cap, so the cut lands inside a two-byte character. + let mut name = b"a".to_vec(); + name.extend(b"\xbf\xc9".repeat(GUESS_SAMPLE / 2 + 1)); + assert_eq!(guess(&[&name], "可").encoding, GBK); + } + + #[test] + fn labels_resolve_and_reject() { + for ok in ["shift_jis", "gbk", "big5", "euc-kr", "windows-1252", "utf-8"] { + assert!(resolve_label(ok).is_ok(), "{ok}"); + } + for bad in ["nope", "replacement", "utf-16le", "x-user-defined", "", "iso-2022-kr"] { + let Err(e) = resolve_label(bad) else { panic!("{bad} should be rejected") }; + assert!(e.to_string().contains("shift_jis"), "{e}"); + } + } + + #[test] + fn labels_match_loosely() { + assert_eq!(resolve_label("Shift_JIS").ok(), Some(SHIFT_JIS)); + assert_eq!(resolve_label(" gbk ").ok(), Some(GBK)); + assert_eq!(resolve_label("gb2312").ok(), Some(GBK)); + } +} diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs index f5ffbed8b72..30509942163 100644 --- a/crates/psd/src/lib.rs +++ b/crates/psd/src/lib.rs @@ -48,6 +48,7 @@ pub mod asl; pub mod atn; pub mod blend; pub mod builder; +mod codepage; pub mod compression; pub mod descriptor; pub mod error; From a5066d9e88cb177c2953f3f19d0ec43395d42347 Mon Sep 17 00:00:00 2001 From: Ben Huyck Date: Thu, 22 Oct 2026 16:41:13 +0000 Subject: [PATCH 26/52] Actions: read .atn step names in the code page Photoshop wrote them in (#6743) --- crates/engine/src/cmd/atn_cmds/convert.rs | 2 +- crates/engine/src/cmd/atn_cmds/tests.rs | 13 + crates/psd/examples/atn_dump.rs | 7 +- crates/psd/src/atn.rs | 309 +++++++++++++++++++++- 4 files changed, 322 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/convert.rs b/crates/engine/src/cmd/atn_cmds/convert.rs index 78d65979bf0..79476cc5a7f 100644 --- a/crates/engine/src/cmd/atn_cmds/convert.rs +++ b/crates/engine/src/cmd/atn_cmds/convert.rs @@ -205,7 +205,7 @@ pub fn export( skip_unsupported: bool, ) -> std::result::Result<(Vec, Vec), String> { let mut skipped = Vec::new(); - let mut file = AtnFile { name: UnicodeString::new_nul(set), expanded: true, actions: Vec::new(), warnings: Vec::new() }; + let mut file = AtnFile { name: UnicodeString::new_nul(set), expanded: true, actions: Vec::new(), warnings: Vec::new(), ..Default::default() }; for a in actions { let mut out = AtnAction { name: UnicodeString::new_nul(&a.name), expanded: false, ..Default::default() }; if let Some((n, shift, command)) = function_keys.iter().find(|(n, _)| n == &a.name).and_then(|(_, key)| parse_function_key(key)) { diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index f9e633244c7..29a75b66087 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -45,6 +45,7 @@ fn layer_steps_with_string_id_blend_modes_import_with_their_mode() { ..Default::default() }], warnings: vec![], + ..Default::default() }; let imp = import(&atn::write(&file).unwrap()).unwrap(); assert!(imp.unsupported.is_empty(), "{:?}", imp.unsupported.iter().map(|u| &u.event).collect::>()); @@ -116,6 +117,7 @@ fn sample() -> AtnFile { AtnAction { name: UnicodeString::new_nul("Finish"), items: vec![item("Invs", "Inverse", None)], ..Default::default() }, ], warnings: Vec::new(), + ..Default::default() } } @@ -962,6 +964,7 @@ fn unsupported_shapes_become_photoshop_steps_not_errors() { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }], warnings: vec![], + ..Default::default() }; let imp = import(&atn::write(&file).unwrap()).unwrap(); let ids: Vec<&str> = imp.actions[0].steps.iter().map(|(id, _)| id.as_str()).collect(); @@ -985,6 +988,7 @@ fn save_preserves_the_kind_of_unsupported_atn_events() { ..Default::default() }], warnings: vec![], + ..Default::default() }; let mut session = Session::new(); session.execute("actions.load", json!({"data": b64(&atn::write(&source).unwrap())})).unwrap(); @@ -1060,6 +1064,7 @@ fn retouching_set_events_map_to_their_commands() { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }], warnings: vec![], + ..Default::default() }; let imp = import(&atn::write(&file).unwrap()).unwrap(); let steps = &imp.actions[0].steps; @@ -1352,6 +1357,7 @@ fn remaining_events_import_in_their_photoshop_shapes() { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }], warnings: vec![], + ..Default::default() }; let imp = import(&atn::write(&file).unwrap()).unwrap(); let steps = &imp.actions[0].steps; @@ -1440,6 +1446,7 @@ fn remaining_events_import_in_their_photoshop_shapes() { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }], warnings: vec![], + ..Default::default() }; let rest = import(&atn::write(&file).unwrap()).unwrap(); let rest_steps = &rest.actions[0].steps; @@ -1478,6 +1485,7 @@ fn remaining_events_import_in_their_photoshop_shapes() { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }], warnings: vec![], + ..Default::default() }; let more = import(&atn::write(&file).unwrap()).unwrap(); let more_steps = &more.actions[0].steps; @@ -1596,6 +1604,7 @@ fn set_of(name: &str, actions: Vec<(&str, Vec)>) -> String { expanded: false, actions: actions.into_iter().map(|(n, items)| AtnAction { name: UnicodeString::new_nul(n), items, ..Default::default() }).collect(), warnings: vec![], + ..Default::default() }; b64(&atn::write(&file).unwrap()) } @@ -2306,6 +2315,7 @@ fn fractional_translation_only_transform_keeps_offset_and_interpolation() { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items: vec![item("transform", "Transform", Some(d))], ..Default::default() }], warnings: vec![], + ..Default::default() }; let imp = import(&atn::write(&file).unwrap()).unwrap(); assert!(imp.unsupported.is_empty()); @@ -2718,6 +2728,7 @@ fn adjustment_layer_reset_still_resets() { ..Default::default() }], warnings: vec![], + ..Default::default() }; let steps = import(&atn::write(&file).unwrap()).unwrap().actions.remove(0).steps; assert_eq!(steps[0], ("layer.setAdjustment".to_string(), json!({}))); @@ -3069,6 +3080,7 @@ fn one_action(items: Vec) -> AtnFile { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }], warnings: vec![], + ..Default::default() } } @@ -3167,6 +3179,7 @@ fn long_names_are_clipped_instead_of_copied_into_every_diagnostic() { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul(&long), items: unknown(50), ..Default::default() }], warnings: vec![], + ..Default::default() }; let imp = import(&atn::write(&file).unwrap()).unwrap(); assert_eq!(imp.set.chars().count(), MAX_NAME_CHARS); diff --git a/crates/psd/examples/atn_dump.rs b/crates/psd/examples/atn_dump.rs index 04e268da947..bd341c7b006 100644 --- a/crates/psd/examples/atn_dump.rs +++ b/crates/psd/examples/atn_dump.rs @@ -56,9 +56,10 @@ fn main() { match atn::parse(&bytes) { Ok(f) => { println!( - "== {path}: set {:?}, {} actions{}", + "== {path}: set {:?}, {} actions{}{}", f.name.to_string_lossy(), f.actions.len(), + f.encoding.as_deref().map(|e| format!(", names in {e}")).unwrap_or_default(), if f.warnings.is_empty() { String::new() } else { format!(" ({})", f.warnings.join("; ")) } ); for a in &f.actions { @@ -66,8 +67,8 @@ fn main() { for item in &a.items { let flags = format!("{}{}", if item.enabled { "" } else { " off" }, if item.with_dialog { " dialog" } else { "" }); match &item.descriptor { - Some(d) => println!(" {:<22} {:<28}{flags} {}", item.event.id(), item.label(), keys(d)), - None => println!(" {:<22} {:<28}{flags}", item.event.id(), item.label()), + Some(d) => println!(" {:<22} {:<28}{flags} {}", item.event.id(), f.item_label(item), keys(d)), + None => println!(" {:<22} {:<28}{flags}", item.event.id(), f.item_label(item)), } } } diff --git a/crates/psd/src/atn.rs b/crates/psd/src/atn.rs index 6bb900d4351..ef620ad1f04 100644 --- a/crates/psd/src/atn.rs +++ b/crates/psd/src/atn.rs @@ -22,10 +22,19 @@ //! [`AtnItem::label`] gives a readable name. Photoshop 5-era files (version 12) use a //! different, undocumented layout and are rejected as unsupported. //! +//! Which legacy encoding is not recorded: Windows Photoshop uses the system code page (GBK in +//! Chinese, Shift_JIS in Japanese…), Mac Photoshop the Mac one. [`parse`] works it out once per +//! file into [`AtnFile::encoding`], first from steps that also store their name as Unicode (the +//! descriptor's class name), else by guessing from the bytes; [`parse_with_encoding`] takes it +//! from the caller. [`AtnFile::item_label`] reads names with it. The bytes themselves stay as +//! they are. +//! //! [`parse`] never panics: every count is bounds-checked against the bytes left, descriptor //! nesting is bounded, and allocations are capped. [`write`] produces the same layout, so -//! `parse(write(f)) == f`, and `write(parse(b)) == b` for files Photoshop wrote. +//! `parse(write(f)) == f` for files [`parse`] read, and `write(parse(b)) == b` for files Photoshop +//! wrote. +use crate::codepage; use crate::descriptor::{Descriptor, UnicodeString}; use crate::error::{PsdError, Result}; use crate::io::{Reader, WriteExt, decode_legacy_name}; @@ -50,6 +59,37 @@ pub struct AtnFile { /// Problems that did not stop the parse (trailing bytes…). #[cfg_attr(feature = "serde", serde(default))] pub warnings: Vec, + /// The encoding of the 8-bit names that are not ASCII or UTF-8 ("GBK", "Shift_JIS", + /// "macintosh"…): the one given to [`parse_with_encoding`], else the one that turns such + /// names into the Unicode class names stored with them, else a guess from the names shown + /// from their bytes alone. `None` when there are no such names, or nothing tells and no + /// name depends on it. [`write`] ignores it: names are written as stored. + #[cfg_attr(feature = "serde", serde(default))] + pub encoding: Option, +} + +impl AtnFile { + /// [`AtnItem::label`], with 8-bit names read in this file's [`encoding`](Self::encoding). + /// A name that is valid UTF-8 is read in that encoding only if it reads entirely as common + /// text there (GBK 去色 is also valid UTF-8, "ȥɫ"). + pub fn item_label(&self, item: &AtnItem) -> String { + let Some(enc) = self.encoding.as_deref().and_then(|label| codepage::resolve_label(label).ok()) else { return item.label() }; + let read = |bytes: &[u8]| match std::str::from_utf8(bytes) { + Ok(s) if s.is_ascii() || !codepage::reads_as_common(bytes, enc) => s.to_owned(), + _ => codepage::decode(bytes, enc), + }; + if let Some(class) = class_name(item) { + return class; + } + let dict = read(&item.dictionary); + if !dict.trim().is_empty() { + return dict; + } + match &item.event { + AtnEvent::Name(n) => read(n), + AtnEvent::Code(_) => item.event.id(), + } + } } /// One action of a set. @@ -116,8 +156,7 @@ impl AtnItem { /// A readable name for the step: the descriptor's class name when Photoshop stored one /// (Unicode, so a localised name survives), else [`Self::dictionary`], else the event id. pub fn label(&self) -> String { - let class = self.descriptor.as_ref().map(|d| d.name.to_string_lossy()).unwrap_or_default(); - if !class.trim().is_empty() { + if let Some(class) = class_name(self) { return class; } let dict = self.dictionary(); @@ -125,6 +164,12 @@ impl AtnItem { } } +/// The descriptor's class name, when Photoshop stored one: the step's name as Unicode. +fn class_name(item: &AtnItem) -> Option { + let class = item.descriptor.as_ref().map(|d| d.name.to_string_lossy())?; + (!class.trim().is_empty()).then_some(class) +} + /// A Photoshop event id: a four-character code (`GsnB`) or a string name (`trim`). #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -208,8 +253,25 @@ fn read_action(r: &mut Reader<'_>) -> Result { Ok(AtnAction { function_key, shift, command, color, name, expanded, items }) } -/// Parses an `.atn` file. +/// Parses an `.atn` file, working out the encoding of its 8-bit names (see the module docs). pub fn parse(data: &[u8]) -> Result { + parse_with_encoding(data, None) +} + +/// [`parse`], reading 8-bit names in `encoding` (a label such as `shift_jis`, `gbk`, `big5`, +/// `euc-kr`, `windows-1252`, `macintosh`) instead of working it out. An unknown label, or one +/// for an encoding that cannot hold an 8-bit name (UTF-16, `replacement`), is an error. +pub fn parse_with_encoding(data: &[u8], encoding: Option<&str>) -> Result { + let forced = encoding.map(codepage::resolve_label).transpose()?; + let mut f = parse_layout(data)?; + let mut warnings = Vec::new(); + let enc = forced.or_else(|| name_encoding(&f, &mut warnings)); + f.warnings.extend(warnings); + f.encoding = enc.map(|e| e.name().to_owned()); + Ok(f) +} + +fn parse_layout(data: &[u8]) -> Result { let mut r = Reader::new(data); let version = r.u32()?; if version != VERSION { @@ -231,7 +293,57 @@ pub fn parse(data: &[u8]) -> Result { if !r.is_empty() { warnings.push(format!("{} trailing bytes ignored", r.remaining())); } - Ok(AtnFile { name, expanded, actions, warnings }) + Ok(AtnFile { name, expanded, actions, warnings, encoding: None }) +} + +/// The encoding of `f`'s 8-bit names that are not ASCII or UTF-8, or `None` if no name shown +/// from them needs one; adds a warning when the guess is uncertain. +fn name_encoding(f: &AtnFile, warnings: &mut Vec) -> Option<&'static encoding_rs::Encoding> { + let items = || f.actions.iter().flat_map(|a| &a.items); + let legacy = |b: &[u8]| !b.is_ascii(); + // Steps that store their name as Unicode too: the encoding that turns one into the other. + let pairs: Vec<(&[u8], String)> = items() + .filter(|i| legacy(&i.dictionary)) + .filter_map(|i| class_name(i).filter(|c| std::str::from_utf8(&i.dictionary) != Ok(c.as_str())).map(|c| (i.dictionary.as_slice(), c))) + .take(codepage::KNOWN_PAIRS) + .collect(); + let pairs: Vec<(&[u8], &str)> = pairs.iter().map(|(b, c)| (*b, c.as_str())).collect(); + if let Some(enc) = codepage::match_known(&pairs) { + return Some(enc); + } + // Otherwise guess from the names shown from bytes alone. + let invalid = |b: &[u8]| std::str::from_utf8(b).is_err(); + let mut orphans: Vec<&[u8]> = Vec::new(); + for i in items() { + if class_name(i).is_none() && invalid(&i.dictionary) { + orphans.push(&i.dictionary); + } + if let AtnEvent::Name(n) = &i.event + && invalid(n) + { + orphans.push(n); + } + } + if orphans.is_empty() { + return None; + } + // The set, action and class names are UTF-16: their script points at the writer's locale. + let mut hint = f.name.to_string_lossy(); + for name in f.actions.iter().map(|a| a.name.to_string_lossy()).chain(items().filter_map(class_name)) { + if hint.len() > codepage::GUESS_SAMPLE { + break; + } + hint.push('\n'); + hint.push_str(&name); + } + let guess = codepage::guess(&orphans, &hint); + if guess.uncertain { + warnings.push(format!( + "step names aren't UTF-8 and their encoding couldn't be determined; read as {}; load with an explicit encoding to choose another", + guess.encoding.name() + )); + } + Some(guess.encoding) } fn write_item(out: &mut Vec, item: &AtnItem) -> Result<()> { @@ -336,6 +448,7 @@ mod tests { AtnAction { name: UnicodeString::new_nul("Empty"), ..Default::default() }, ], warnings: Vec::new(), + ..Default::default() } } @@ -390,6 +503,7 @@ mod tests { ..Default::default() }], warnings: Vec::new(), + ..Default::default() }; let mut expect = Vec::new(); expect.extend_from_slice(&[0, 0, 0, 16]); // version @@ -447,6 +561,191 @@ mod tests { assert!(matches!(parse(&bad_flag), Err(PsdError::Invalid(_)))); } + const GBK_SELECTIVE_COLOR: &[u8] = b"\xbf\xc9\xd1\xa1\xd1\xd5\xc9\xab"; // 可选颜色 (from #6743) + const GBK_DESATURATE: &[u8] = b"\xc8\xa5\xc9\xab"; // 去色: valid UTF-8 by accident ("ȥɫ") + const LABELS: [Option<&str>; 5] = [None, Some("shift_jis"), Some("gbk"), Some("utf-8"), Some("macintosh")]; + + /// A step stored with no descriptor, so nothing but its 8-bit names tells what it is called. + fn bare(event: AtnEvent, dictionary: &[u8]) -> AtnItem { + AtnItem { event, dictionary: dictionary.to_vec(), ..Default::default() } + } + + /// A step whose descriptor also stores its panel name as Unicode, as Photoshop does for most. + fn known(dictionary: &[u8], class: &str) -> AtnItem { + let descriptor = Descriptor { name: UnicodeString::new_nul(class), class_id: crate::descriptor::Id::new("setd"), items: Vec::new() }; + AtnItem { event: AtnEvent::name("set"), dictionary: dictionary.to_vec(), descriptor: Some(descriptor), ..Default::default() } + } + + fn one_action(set: &str, action: &str, items: Vec) -> Vec { + let f = AtnFile { + name: UnicodeString::new_nul(set), + actions: vec![AtnAction { name: UnicodeString::new_nul(action), items, ..Default::default() }], + ..Default::default() + }; + write(&f).unwrap() + } + + /// The issue's set: Chinese Photoshop's Selective Color step, named in GBK. + fn gbk_set() -> Vec { + one_action("相馆", "调白", vec![bare(AtnEvent::name("syntheticFill"), GBK_SELECTIVE_COLOR)]) + } + + fn labels(f: &AtnFile) -> Vec { + f.actions.iter().flat_map(|a| a.items.iter().map(|i| f.item_label(i))).collect() + } + + #[test] + fn gbk_step_names_read_as_gbk() { + let f = parse(&gbk_set()).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("GBK")); + assert_eq!(labels(&f), ["可选颜色"]); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + // The item itself, without the file's code page, reads as before. + assert_ne!(f.actions[0].items[0].label(), "可选颜色"); + } + + #[test] + fn legacy_names_are_kept_byte_for_byte() { + let bytes = gbk_set(); + let f = parse(&bytes).unwrap(); + assert_eq!(f.actions[0].items[0].dictionary, GBK_SELECTIVE_COLOR); + assert_eq!(write(&f).unwrap(), bytes); + assert_eq!(parse(&write(&f).unwrap()).unwrap(), f); + } + + #[test] + fn text_event_names_decode_too() { + let f = parse(&one_action("相馆", "调白", vec![bare(AtnEvent::Name(GBK_SELECTIVE_COLOR.to_vec()), b"")])).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("GBK")); + assert_eq!(labels(&f), ["可选颜色"]); + } + + #[test] + fn known_names_decide_the_code_page_of_the_rest() { + // French Photoshop on a Mac: "Définir" is stored as Mac Roman and as Unicode; the bare + // step's "Répéter" is only Mac Roman, which also reads as windows-1252 ("RŽpŽter"). + let items = vec![known(b"D\x8efinir", "Définir"), bare(AtnEvent::name("x"), b"R\x8ep\x8eter")]; + let f = parse(&one_action("Set 1", "Action 1", items)).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("macintosh")); + assert_eq!(labels(&f), ["Définir", "Répéter"]); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + } + + #[test] + fn class_names_hint_the_script() { + // GBK 保存 reads as common text in GBK, Big5 and EUC-KR alike; only the Chinese class + // name of another step (whose panel name is ASCII, so it settles nothing itself) says GBK. + let items = vec![known(b"Adjust", "调整"), bare(AtnEvent::name("x"), b"\xb1\xa3\xb4\xe6")]; + let f = parse(&one_action("Set 1", "Action 1", items)).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("GBK")); + assert_eq!(labels(&f), ["调整", "保存"]); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + } + + #[test] + fn known_names_alone_never_warn() { + // Nothing decodes to the Unicode name, but nothing is shown from the bytes either. + let f = parse(&one_action("Set 1", "Action 1", vec![known(b"\x80\xff\x80", "Something")])).unwrap(); + assert_eq!(f.encoding, None); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + assert_eq!(labels(&f), ["Something"]); + } + + #[test] + fn uncertain_guess_warns() { + let f = parse(&one_action("Set 1", "Action 1", vec![bare(AtnEvent::name("x"), b"\x80\xff\x80")])).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("windows-1252")); + assert_eq!(f.warnings.len(), 1, "{:?}", f.warnings); + assert!(f.warnings[0].contains("windows-1252"), "{:?}", f.warnings); + assert_eq!(labels(&f), ["€ÿ€"]); + } + + #[test] + fn utf8_files_have_no_encoding() { + let f = parse(&write(&set()).unwrap()).unwrap(); + assert_eq!(f.encoding, None); + let items: Vec<&AtnItem> = f.actions.iter().flat_map(|a| &a.items).collect(); + assert_eq!(labels(&f), items.iter().map(|i| i.label()).collect::>()); + let f = parse(&one_action("Set", "A", vec![bare(AtnEvent::name("x"), "高斯模糊 ✓".as_bytes())])).unwrap(); + assert_eq!((f.encoding.clone(), labels(&f)), (None, vec!["高斯模糊 ✓".to_string()])); + } + + #[test] + fn utf8_lookalike_names_decode_with_the_file() { + let items = vec![ + bare(AtnEvent::name("x"), GBK_SELECTIVE_COLOR), + bare(AtnEvent::name("y"), GBK_DESATURATE), + bare(AtnEvent::name("z"), "Gaussian Blur ✓".as_bytes()), + ]; + let f = parse(&one_action("相馆", "调白", items)).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("GBK")); + assert_eq!(labels(&f), ["可选颜色", "去色", "Gaussian Blur ✓"]); + } + + #[test] + fn utf8_names_stay_in_single_byte_files() { + // windows-1252 "Größe" beside a UTF-8 "Weiß"; windows-1251 "Уровни" beside a UTF-8 "Привет". + let latin = vec![bare(AtnEvent::name("x"), b"Gr\xf6\xdfe"), bare(AtnEvent::name("y"), "Weiß".as_bytes())]; + let f = parse(&one_action("Größe ändern", "Aktion", latin)).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("windows-1252")); + assert_eq!(labels(&f), ["Größe", "Weiß"]); + let cyrillic = vec![bare(AtnEvent::name("x"), b"\xd3\xf0\xee\xe2\xed\xe8"), bare(AtnEvent::name("y"), "Привет".as_bytes())]; + let f = parse(&one_action("Набор", "Операция", cyrillic)).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("windows-1251")); + assert_eq!(labels(&f), ["Уровни", "Привет"]); + // A forced single-byte encoding leaves UTF-8 names alone too. + let f = parse_with_encoding(&one_action("S", "A", vec![bare(AtnEvent::name("y"), "Weiß".as_bytes())]), Some("windows-1252")).unwrap(); + assert_eq!(labels(&f), ["Weiß"]); + } + + #[test] + fn forced_encoding_wins() { + let f = parse_with_encoding(&gbk_set(), Some("big5")).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("Big5")); + assert_ne!(labels(&f), ["可选颜色"]); + // A wrong override still loads, and saves the bytes it read. + let f = parse_with_encoding(&gbk_set(), Some("shift_jis")).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("Shift_JIS")); + assert_eq!(write(&f).unwrap(), gbk_set()); + // Forcing applies to all-UTF-8 files too. + assert_eq!(parse_with_encoding(&write(&set()).unwrap(), Some("gbk")).unwrap().encoding.as_deref(), Some("GBK")); + } + + #[test] + fn bad_labels_are_errors() { + for bad in ["nope", "replacement", "utf-16be", ""] { + assert!(matches!(parse_with_encoding(&gbk_set(), Some(bad)), Err(PsdError::Unsupported(_))), "{bad}"); + } + } + + #[test] + fn legacy_files_never_panic() { + let items = vec![known(b"D\x8efinir", "Définir"), bare(AtnEvent::Name(GBK_SELECTIVE_COLOR.to_vec()), GBK_DESATURATE)]; + let seed = one_action("相馆", "调白", items); + let check = |bytes: &[u8]| { + for label in LABELS { + if let Ok(f) = parse_with_encoding(bytes, label) { + let _ = labels(&f); + } + } + }; + for cut in 0..seed.len() { + check(&seed[..cut]); + } + let mut x: u32 = 0x85eb_ca6b; + for i in 0..500 { + let mut bytes = seed.clone(); + for _ in 0..(i % 5 + 1) { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + let at = (x as usize) % bytes.len(); + bytes[at] = (x >> 8) as u8; + } + check(&bytes); + } + } + #[test] fn garbage_never_panics() { let seed = write(&set()).unwrap(); From ab37e0d60671c9efefd46d9a6b546e3f6b66d768 Mon Sep 17 00:00:00 2001 From: Ben Huyck Date: Thu, 22 Oct 2026 16:48:15 +0000 Subject: [PATCH 27/52] Actions: Load Actions takes an encoding and reports the one it used (#6743) --- crates/engine/src/cmd/atn_cmds.rs | 4 +- crates/engine/src/cmd/atn_cmds/convert.rs | 26 ++++++++---- crates/engine/src/cmd/atn_cmds/files.rs | 11 +++++- crates/engine/src/cmd/atn_cmds/tests.rs | 48 +++++++++++++++++++++++ 4 files changed, 77 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds.rs b/crates/engine/src/cmd/atn_cmds.rs index 42a4722479f..1380853414b 100644 --- a/crates/engine/src/cmd/atn_cmds.rs +++ b/crates/engine/src/cmd/atn_cmds.rs @@ -40,7 +40,7 @@ mod tables; #[cfg(test)] use adjustments::{levels_from, selective_from}; -pub use convert::{Imported, Skipped, Unsupported, export, function_key_name, import, parse_function_key}; +pub use convert::{Imported, Skipped, Unsupported, export, function_key_name, import, import_with_encoding, parse_function_key}; #[cfg(test)] use convert::{MAX_NAME_CHARS, export_item, normalise}; #[cfg(test)] @@ -102,7 +102,7 @@ pub fn specs() -> Vec { label: "Load Actions…", menu: &[], shortcut: None, - params: r##"{"path":".atn file"?,"data":base64 bytes?,"set":name? (override the file's set name),"replace":bool=true (replace the actions of a set of the same name)} → {set, actions:[names], steps, unsupported:[{action, step, event, name}], functionKeys:[{action, key}], warnings}. Photoshop steps PhotoCraft cannot play become actions.photoshopStep steps (kept for Save Actions; they fail at playback with the step's name); tool selections and other steps with no document effect are imported switched off. Layer references by name replay in any document."##, + params: r##"{"path":".atn file"?,"data":base64 bytes?,"set":name? (override the file's set name),"replace":bool=true (replace the actions of a set of the same name),"encoding":"auto"|label="auto" (the encoding of 8-bit step names: shift_jis, gbk, big5, euc-kr, windows-1252, macintosh…; auto works it out)} → {set, actions:[names], steps, unsupported:[{action, step, event, name}], functionKeys:[{action, key}], warnings, encoding}. Photoshop steps PhotoCraft cannot play become actions.photoshopStep steps (kept for Save Actions; they fail at playback with the step's name); tool selections and other steps with no document effect are imported switched off. Layer references by name replay in any document."##, enabled: always, run: load, journal: false, diff --git a/crates/engine/src/cmd/atn_cmds/convert.rs b/crates/engine/src/cmd/atn_cmds/convert.rs index 79476cc5a7f..ccdbcf73480 100644 --- a/crates/engine/src/cmd/atn_cmds/convert.rs +++ b/crates/engine/src/cmd/atn_cmds/convert.rs @@ -23,15 +23,18 @@ pub struct Imported { pub function_keys: Vec<(String, String)>, pub unsupported: Vec, pub warnings: Vec, + /// The encoding the file's 8-bit step names were read in (`"GBK"`, `"Shift_JIS"`, + /// `"macintosh"`…); `None` when none needed one. + pub encoding: Option, } -fn photoshop_step(item: &AtnItem) -> (String, Value) { +fn photoshop_step(item: &AtnItem, label: String) -> (String, Value) { let descriptor = item.descriptor.as_ref().map(|d| photocraft_paint::tile::b64_encode(&d.to_bytes())); let event_kind = match &item.event { AtnEvent::Code(_) => "code", AtnEvent::Name(_) => "name", }; - (PHOTOSHOP_STEP.into(), json!({"event": item.event.id(), "eventKind": event_kind, "name": item.label(), "descriptor": descriptor})) + (PHOTOSHOP_STEP.into(), json!({"event": item.event.id(), "eventKind": event_kind, "name": label, "descriptor": descriptor})) } /// Integral floats become integers (`2.0` → `2`), as the commands' own docs and recordings @@ -61,7 +64,7 @@ pub(super) fn clip_name(s: &str) -> String { s.chars().take(MAX_NAME_CHARS).collect() } -fn convert_action(a: &AtnAction, set: &str, unsupported: &mut Vec) -> Action { +fn convert_action(file: &AtnFile, a: &AtnAction, set: &str, unsupported: &mut Vec) -> Action { let name = clip_name(&a.name.to_string_lossy()); let mut action = Action::new(name.clone(), Vec::new()); action.set = Some(clip_name(set)); @@ -74,8 +77,9 @@ fn convert_action(a: &AtnAction, set: &str, unsupported: &mut Vec) let (new_steps, enabled) = match mapped { Mapped::Steps(s) => (s, item.enabled), Mapped::Unsupported { harmless } => { - unsupported.push(Unsupported { action: name.clone(), step: i, event: item.event.id(), name: item.label() }); - (vec![photoshop_step(item)], item.enabled && !harmless) + let label = file.item_label(item); + unsupported.push(Unsupported { action: name.clone(), step: i, event: item.event.id(), name: label.clone() }); + (vec![photoshop_step(item, label)], item.enabled && !harmless) } }; for mut s in new_steps { @@ -96,12 +100,18 @@ fn convert_action(a: &AtnAction, set: &str, unsupported: &mut Vec) /// Convert a `.atn` file. Fails only when the file is unreadable: every step imports, as a /// command or as a kept Photoshop step. pub fn import(bytes: &[u8]) -> std::result::Result { - let file = atn::parse(bytes).map_err(|e| e.to_string())?; + import_with_encoding(bytes, None) +} + +/// [`import`], reading 8-bit step names in `encoding` (a label such as `"shift_jis"` or +/// `"gbk"`) instead of working it out. An unknown label fails. +pub fn import_with_encoding(bytes: &[u8], encoding: Option<&str>) -> std::result::Result { + let file = atn::parse_with_encoding(bytes, encoding).map_err(|e| e.to_string())?; let set = file.name.to_string_lossy(); let set = if set.trim().is_empty() { DEFAULT_SET.to_string() } else { clip_name(&set) }; - let mut out = Imported { set: set.clone(), warnings: file.warnings.clone(), ..Default::default() }; + let mut out = Imported { set: set.clone(), warnings: file.warnings.clone(), encoding: file.encoding.clone(), ..Default::default() }; for a in &file.actions { - let action = convert_action(a, &set, &mut out.unsupported); + let action = convert_action(&file, a, &set, &mut out.unsupported); if a.function_key > 0 { out.function_keys.push((action.name.clone(), function_key_name(a.function_key, a.shift, a.command))); } diff --git a/crates/engine/src/cmd/atn_cmds/files.rs b/crates/engine/src/cmd/atn_cmds/files.rs index be7bd451519..c22b673deb0 100644 --- a/crates/engine/src/cmd/atn_cmds/files.rs +++ b/crates/engine/src/cmd/atn_cmds/files.rs @@ -1,4 +1,4 @@ -use super::convert::{UniqueNames, export, import}; +use super::convert::{UniqueNames, export, import_with_encoding}; use super::{Action, DEFAULT_SET, EngineError, Result, Session, Value, bad, json}; pub(super) fn load(s: &mut Session, p: &Value) -> Result { @@ -6,8 +6,14 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result { if s.actions.recording.is_some() || s.actions.playing > 0 { return Err(bad(cmd, "stop recording or playing before loading actions")); } + let encoding = match p.get("encoding") { + None | Some(Value::Null) => None, + Some(Value::String(e)) if e == "auto" => None, + Some(Value::String(e)) if !e.is_empty() => Some(e.as_str()), + Some(_) => return Err(bad(cmd, "encoding must be \"auto\" or a label such as shift_jis, gbk, big5, euc-kr, windows-1252, macintosh")), + }; let (bytes, _) = crate::preset_import_cmds::file_bytes(p, cmd, ".atn file")?; - let mut imp = import(&bytes).map_err(|e| bad(cmd, e))?; + let mut imp = import_with_encoding(&bytes, encoding).map_err(|e| bad(cmd, e))?; match p.get("set") { None | Some(Value::Null) => {} Some(Value::String(n)) if !n.trim().is_empty() => { @@ -77,6 +83,7 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result { "unsupported": imp.unsupported, "functionKeys": keys.iter().map(|(n, k)| json!({"action": n, "key": k})).collect::>(), "warnings": imp.warnings, + "encoding": imp.encoding.as_deref().unwrap_or("UTF-8"), })) } diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 29a75b66087..937926e9d3b 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -3188,3 +3188,51 @@ 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 set from Chinese Photoshop: UTF-16 set and action names, a step name in GBK (可选颜色, +/// the bytes from #6743) on an event PhotoCraft has no command for, with no descriptor. +fn gbk_set() -> Vec { + let step = AtnItem { dictionary: b"\xbf\xc9\xd1\xa1\xd1\xd5\xc9\xab".to_vec(), ..item("syntheticFill", "", None) }; + let file = AtnFile { + name: UnicodeString::new_nul("相馆"), + actions: vec![AtnAction { name: UnicodeString::new_nul("调白"), items: vec![step], ..Default::default() }], + ..Default::default() + }; + atn::write(&file).unwrap() +} + +#[test] +fn load_decodes_legacy_step_names() { + let mut s = Session::new(); + let r = s.execute("actions.load", json!({"data": b64(&gbk_set())})).unwrap(); + assert_eq!(r["encoding"], "GBK", "{r}"); + assert_eq!(r["unsupported"][0]["name"], "可选颜色", "{r}"); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let played = s.execute("actions.play", json!({"action": "调白"})).unwrap(); + assert!(played["failed"]["error"].as_str().unwrap().contains("可选颜色"), "{played}"); +} + +#[test] +fn load_encoding_override() { + let mut s = Session::new(); + let r = s.execute("actions.load", json!({"data": b64(&gbk_set()), "encoding": "shift_jis"})).unwrap(); + assert_eq!(r["encoding"], "Shift_JIS", "{r}"); + let r = s.execute("actions.load", json!({"data": b64(&gbk_set()), "encoding": "auto"})).unwrap(); + assert_eq!(r["encoding"], "GBK", "{r}"); +} + +#[test] +fn load_reports_utf8() { + let mut s = Session::new(); + let r = s.execute("actions.load", json!({"data": b64(&atn::write(&sample()).unwrap())})).unwrap(); + assert_eq!(r["encoding"], "UTF-8", "{r}"); +} + +#[test] +fn load_rejects_bad_encodings() { + let mut s = Session::new(); + for bad in [json!(3), json!(""), json!("nope"), json!("replacement"), json!(["gbk"])] { + assert!(s.execute("actions.load", json!({"data": b64(&gbk_set()), "encoding": bad})).is_err(), "{bad}"); + } + assert!(s.actions.list.is_empty(), "nothing is loaded when the encoding is bad"); +} From 6d96ae9fabfaa71a250830221198935540ce6479 Mon Sep 17 00:00:00 2001 From: Ben Huyck Date: Wed, 21 Oct 2026 17:56:47 +0000 Subject: [PATCH 28/52] Contributors: credit regexer by GitHub profile name --- contributors/people.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index 2f4531910d3..84187c7ad96 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -295,3 +295,6 @@ sync_github_name = true real_name = "Simone Recchia" display_name = "Simone Recchia" sync_github_name = false + +[people.regexer] +sync_github_name = true From d244f11a853de06cf46276a225d66aac7f467a83 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 1 Nov 2026 00:28:04 -0600 Subject: [PATCH 29/52] =?UTF-8?q?Actions:=20Save=20Actions=E2=80=A6=20find?= =?UTF-8?q?s=20a=20set=20by=20its=20exact=20name=20(FredApps=20review)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A set name with surrounding spaces comes from a Photoshop .atn (load keeps the file's name) or an older actions.json, and New Action records into such a set under that exact name. `actions.save` trimmed the name it was given and then compared exactly, so Save Actions… on that set failed with "no actions in a set named …". It now takes an existing set's exact name, as `actions.record` does, and trims any other. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/atn_cmds/files.rs | 3 +++ crates/engine/src/cmd/atn_cmds/tests.rs | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/crates/engine/src/cmd/atn_cmds/files.rs b/crates/engine/src/cmd/atn_cmds/files.rs index be7bd451519..3c52826a5d0 100644 --- a/crates/engine/src/cmd/atn_cmds/files.rs +++ b/crates/engine/src/cmd/atn_cmds/files.rs @@ -90,6 +90,9 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result { }; let set_param = match p.get("set") { None | Some(Value::Null) => None, + // A set is found by its exact name, as `actions.record` finds it: one loaded from a + // Photoshop file or an older actions.json may have surrounding spaces. Others are trimmed. + Some(Value::String(n)) if crate::actions_edit_cmds::set_names(s).contains(n) => Some(n.clone()), Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()), Some(_) => return Err(bad(cmd, "`set` must be a non-empty string")), }; diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 011e9aa5e51..9ea07d0979c 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -3173,3 +3173,23 @@ 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)); } + +/// FredApps review on #10459: a set whose name has surrounding spaces (a Photoshop `.atn` or an +/// older actions.json can have one, and New Action records into it under that exact name) saves +/// by that name. `actions.save` used to trim it and then find no set. +#[test] +fn save_finds_a_set_by_its_exact_name_with_spaces() { + let mut s = Session::new(); + s.actions.list.push(Action { set: Some(" Web ".into()), ..Action::new("Old", Vec::new()) }); + s.execute("actions.record", json!({"name": "New", "set": " Web "})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let saved = s.execute("actions.save", json!({"set": " Web "})).unwrap(); + assert_eq!((&saved["set"], &saved["actions"]), (&json!(" Web "), &json!(["Old", "New"]))); + // The file keeps the name, as Photoshop's does. + let mut reloaded = Session::new(); + let r = reloaded.execute("actions.load", json!({"data": saved["data"]})).unwrap(); + assert_eq!(r["set"], " Web "); + // Other names are still trimmed. + s.execute("actions.assignSet", json!({"action": "Old", "set": "Print"})).unwrap(); + assert_eq!(s.execute("actions.save", json!({"set": " Print "})).unwrap()["set"], "Print"); +} From 63c541342ebd5c891defec82cde8471eecc3825e Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 1 Nov 2026 00:29:37 -0600 Subject: [PATCH 30/52] =?UTF-8?q?Actions:=20Save=20Actions=E2=80=A6=20writ?= =?UTF-8?q?es=20an=20empty=20New=20Set=20set=20(FredApps=20review)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An empty set made with New Set lasted only the session, and Save Actions… on it failed with "no actions in a set named …". Photoshop saves an empty set to the .atn, and the ATN writer handles a set with no actions, so `actions.save` now writes it; loading such a file brings it back as an empty folder (once, however often it is loaded). Saving every action with none is still refused, as is a set that doesn't exist. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/actions_cmds.rs | 6 ++++-- crates/engine/src/cmd/actions_edit_cmds.rs | 2 +- crates/engine/src/cmd/atn_cmds.rs | 2 +- crates/engine/src/cmd/atn_cmds/files.rs | 14 ++++++++---- crates/engine/src/cmd/atn_cmds/tests.rs | 25 ++++++++++++++++++++++ 5 files changed, 41 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index f7662cdbcc5..bfae856454d 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -106,8 +106,10 @@ pub struct ActionState { /// Steps run by the current top-level script and everything it calls. #[serde(skip)] pub script_steps: u64, - /// Sets made with New Set (`actions.newSet`) that hold no action yet: the Actions panel shows - /// them as empty folders. A set is saved through its actions, so an empty one lasts the session. + /// Sets made with New Set (`actions.newSet`), or loaded from an `.atn` with no actions, that + /// hold no action yet: the Actions panel shows them as empty folders. Save Actions… writes one + /// to an `.atn` as Photoshop does, but the preset store keeps sets through their actions, so + /// an empty one isn't remembered past the session. #[serde(skip)] pub sets: Vec, /// Bumped whenever `list` changes, so the preset store can skip unchanged writes. diff --git a/crates/engine/src/cmd/actions_edit_cmds.rs b/crates/engine/src/cmd/actions_edit_cmds.rs index 17d4ba729d0..380fc764e9d 100644 --- a/crates/engine/src/cmd/actions_edit_cmds.rs +++ b/crates/engine/src/cmd/actions_edit_cmds.rs @@ -323,7 +323,7 @@ pub fn specs() -> Vec { label: "New Set", menu: &[], shortcut: None, - params: r##"{"name":str? (default "Set N")} → {set}. An empty set folder in the Actions panel, as Photoshop's New Set… makes; New Action records into the selected set (actions.record's `set`). It is saved once it holds an action."##, + params: r##"{"name":str? (default "Set N")} → {set}. An empty set folder in the Actions panel, as Photoshop's New Set… makes; New Action records into the selected set (actions.record's `set`). Save Actions… (actions.save's `set`) writes it even while empty; it is remembered between sessions once it holds an action."##, enabled: always, run: new_set, journal: false, diff --git a/crates/engine/src/cmd/atn_cmds.rs b/crates/engine/src/cmd/atn_cmds.rs index 7c717701bf8..071aba793c5 100644 --- a/crates/engine/src/cmd/atn_cmds.rs +++ b/crates/engine/src/cmd/atn_cmds.rs @@ -111,7 +111,7 @@ pub fn specs() -> Vec { label: "Save Actions…", menu: &[], shortcut: None, - params: r##"{"path":".atn file"? (else the bytes come back as base64 `data`),"set":name? (that set's actions; default: every action, as the set "PhotoCraft Actions"),"action":name|index? (one action),"skipUnsupported":bool=false (leave out steps with no Photoshop equivalent instead of failing)} → {set, actions:[names], steps, bytes, skipped:[{action, step, id}], path|data}"##, + params: r##"{"path":".atn file"? (else the bytes come back as base64 `data`),"set":name? (that set's actions, none for an empty New Set set; default: every action, as the set "PhotoCraft Actions"),"action":name|index? (one action),"skipUnsupported":bool=false (leave out steps with no Photoshop equivalent instead of failing)} → {set, actions:[names], steps, bytes, skipped:[{action, step, id}], path|data}"##, enabled: always, run: save, journal: false, diff --git a/crates/engine/src/cmd/atn_cmds/files.rs b/crates/engine/src/cmd/atn_cmds/files.rs index 3c52826a5d0..2cb5d565d93 100644 --- a/crates/engine/src/cmd/atn_cmds/files.rs +++ b/crates/engine/src/cmd/atn_cmds/files.rs @@ -59,6 +59,11 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result { } } s.actions.list.extend(added); + // A set saved with no actions (Photoshop saves an empty set) is an empty folder, like one New + // Set made. + if !s.actions.list.iter().any(|a| a.set.as_deref() == Some(imp.set.as_str())) && !s.actions.sets.contains(&imp.set) { + s.actions.sets.push(imp.set.clone()); + } let keys: Vec<(String, String)> = imp.function_keys.into_iter().map(|(n, k)| (renamed.get(&n).cloned().unwrap_or(n), k)).collect(); if !keys.is_empty() { s.edit_prefs(|prefs| { @@ -102,16 +107,17 @@ pub(super) fn save(s: &mut Session, p: &Value) -> Result { (set_param.or_else(|| a.set.clone()).unwrap_or_else(|| a.name.clone()), vec![a]) } else if let Some(set) = set_param { let list: Vec<&Action> = s.actions.list.iter().filter(|a| a.set.as_deref() == Some(set.as_str())).collect(); - if list.is_empty() { + // An empty set New Set made is written with no actions, as Photoshop saves one. + if list.is_empty() && !s.actions.sets.contains(&set) { return Err(bad(cmd, format!("no actions in a set named `{set}`"))); } (set, list) } else { + if s.actions.list.is_empty() { + return Err(bad(cmd, "there are no actions to save")); + } (DEFAULT_SET.to_string(), s.actions.list.iter().collect()) }; - if actions.is_empty() { - return Err(bad(cmd, "there are no actions to save")); - } let names: Vec = actions.iter().map(|a| a.name.clone()).collect(); let keys: Vec<(String, String)> = s.prefs().shortcuts.iter().filter_map(|(k, v)| k.strip_prefix(crate::actions_cmds::PLAY_SHORTCUT_PREFIX).map(|n| (n.to_string(), v.clone()))).collect(); diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 9ea07d0979c..27b7e10e995 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -3193,3 +3193,28 @@ fn save_finds_a_set_by_its_exact_name_with_spaces() { s.execute("actions.assignSet", json!({"action": "Old", "set": "Print"})).unwrap(); assert_eq!(s.execute("actions.save", json!({"set": " Print "})).unwrap()["set"], "Print"); } + +/// FredApps review on #10459: Save Actions… on an empty set made with New Set writes it, as +/// Photoshop saves an empty set to the `.atn`, and loading that file brings the empty set back. +#[test] +fn an_empty_new_set_saves_and_loads_back() { + let mut s = Session::new(); + s.execute("actions.newSet", json!({"name": "Later"})).unwrap(); + let saved = s.execute("actions.save", json!({"set": "Later"})).unwrap(); + assert_eq!((&saved["set"], &saved["actions"], &saved["steps"]), (&json!("Later"), &json!([]), &json!(0))); + let mut other = Session::new(); + let r = other.execute("actions.load", json!({"data": saved["data"]})).unwrap(); + assert_eq!((&r["set"], &r["actions"]), (&json!("Later"), &json!([]))); + assert_eq!(crate::actions_edit_cmds::set_names(&other), ["Later"], "an empty folder"); + other.execute("actions.load", json!({"data": saved["data"]})).unwrap(); + assert_eq!(crate::actions_edit_cmds::set_names(&other), ["Later"], "loaded twice, still one folder"); + // New Action records into it as into any set, and it saves with that action. + other.execute("actions.record", json!({"name": "Now", "set": "Later"})).unwrap(); + other.execute("actions.stop", json!({})).unwrap(); + assert_eq!(other.execute("actions.save", json!({"set": "Later"})).unwrap()["actions"], json!(["Now"])); + // A set that doesn't exist is still refused, and so is saving every action when there is none. + let err = s.execute("actions.save", json!({"set": "Nope"})).unwrap_err().to_string(); + assert!(err.contains("no actions in a set named `Nope`"), "{err}"); + let err = Session::new().execute("actions.save", json!({})).unwrap_err().to_string(); + assert!(err.contains("there are no actions to save"), "{err}"); +} From 740ebe5d8c352f20028aacb9c2c45e1419a25332 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 1 Nov 2026 00:32:48 -0600 Subject: [PATCH 31/52] =?UTF-8?q?Actions=20panel:=20Save=20Actions?= =?UTF-8?q?=E2=80=A6=20suggests=20a=20file=20name=20without=20path=20chara?= =?UTF-8?q?cters=20(FredApps=20review)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The suggested file was "{set}.atn" with the set's name as it is, so a set named with `/`, `\` or `:` suggested a path in another folder (or an invalid name). Those characters, and the others a file name can't hold, become `_` in the suggestion, as Keyboard Shortcuts' Save does for a set name; the .atn keeps the set's own name. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/actions.rs | 10 ++++++- crates/ui-egui/src/panels/actions/tests.rs | 35 ++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index f95ceee635f..57c014d43b3 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -446,7 +446,15 @@ fn save_dialog(app: &mut PhotocraftApp, set: Option) -> Result' | '|') { '_' } else { c }) + .collect(); + let file = format!("{stem}.atn"); app.pick_save(&file, move |app, path| { let write = app.services.write.as_mut().ok_or("no writer configured")?; write(&path, &bytes)?; diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index 04b4f00dd2f..862ac8ff137 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -785,6 +785,41 @@ fn save_actions_with_a_set_selected_saves_that_set() { assert!(matches!(asked.borrow().as_slice(), [crate::file_dialog::FileDialogRequest::Save { suggested }] if suggested == "Web.atn"), "{:?}", asked.borrow()); } +/// FredApps review on #10459: a set name can hold characters a file name can't. Save Actions… +/// suggests the file with them replaced, and the set keeps its name in the file. The set here +/// is an empty one New Set made, which Save Actions… writes as Photoshop does. +#[test] +fn save_actions_suggests_a_file_name_without_path_characters() { + use egui_kittest::{Harness, kittest::Queryable}; + let (file_dialog, asked) = crate::file_dialog::fake(vec![None]); + let services = crate::Services { file_dialog: Some(file_dialog), ..Default::default() }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.session.actions.list.push(Action::new("Loose", vec![])); + let set = "Web/Print\\Mail: v2"; + app.run("actions.newSet", json!({"name": set})).unwrap(); + let mut h = Harness::builder().with_size(vec2(360.0, 600.0)).build_ui_state( + |ui, app| { + panel_menu(app, ui); + panel(app, ui); + }, + app, + ); + h.run_steps(2); + h.get_by_label(set).click(); + h.run_steps(2); + h.get_by_label("Save Actions…").click(); + h.run_steps(2); + h.state_mut().poll_file_dialog(&egui::Context::default(), None); + assert!( + matches!(asked.borrow().as_slice(), [crate::file_dialog::FileDialogRequest::Save { suggested }] if suggested == "Web_Print_Mail_ v2.atn"), + "{:?}", + asked.borrow() + ); + let saved = h.state_mut().run("actions.save", json!({"set": set})).unwrap(); + assert_eq!(saved["set"], set, "the file keeps the set's name"); +} + #[test] fn moving_an_action_next_to_another_set_joins_it() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); From 8a5ce6fa243b58a955c1d6162be50f04fb2307df Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 1 Nov 2026 00:34:54 -0600 Subject: [PATCH 32/52] Actions panel: test New Action with no set and reopening the panel (FredApps review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With no action and no set selected, New Action makes an action in no set even when sets, empty ones included, exist. Closing the Actions panel (Window › Actions) and opening it again keeps the selected set and the empty New Set sets, and New Action still records into the selected one. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/actions/tests.rs | 68 ++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index 862ac8ff137..9f80c2cfd0f 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -693,6 +693,74 @@ fn new_set_makes_an_empty_folder_that_new_action_records_into() { assert_eq!(h.state().session.actions.list[2].set.as_deref(), Some("Retouch")); } +/// FredApps review on #10459: with no action and no set selected, New Action makes an action +/// outside every set, even when sets (empty ones included) exist. +#[test] +fn new_action_with_no_set_selected_is_in_no_set() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let mut retouch = Action::new("Sharpen", vec![]); + retouch.set = Some("Retouch".into()); + app.session.actions.list.push(retouch); + app.run("actions.newSet", json!({"name": "Web"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(360.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(2); + assert_eq!((h.state().ui.actions.selected, h.state().ui.actions.selected_set.as_deref()), (None, None)); + h.get_by_label("Create new action").click(); + h.run_steps(2); + h.state_mut().run("actions.stop", json!({})).unwrap(); + let list = &h.state().session.actions.list; + assert_eq!((list.len(), list[1].name.as_str(), list[1].set.as_deref()), (2, "Action 2", None)); +} + +/// FredApps review on #10459: closing the Actions panel and opening it again keeps the selected +/// set and the empty sets New Set made, so New Action still records into the selected one. +#[test] +fn reopening_the_actions_panel_keeps_the_selected_set_and_empty_sets() { + use egui_kittest::{Harness, kittest::Queryable}; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let mut retouch = Action::new("Sharpen", vec![]); + retouch.set = Some("Retouch".into()); + app.session.actions.list.push(retouch); + app.run("actions.newSet", json!({"name": "Web"})).unwrap(); + app.run("actions.newSet", json!({"name": "Print"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(360.0, 400.0)).build_ui_state( + |ui, app| { + // The Actions panel is the History group's second tab. + if app.ui.panels.history && app.ui.dock_tabs.history == 1 { + panel(app, ui); + } + }, + app, + ); + let ctx = h.ctx.clone(); + let toggle = |h: &mut Harness<'_, PhotocraftApp>| { + crate::menus::invoke(h.state_mut(), &ctx, "window.panel.actions", json!({})).unwrap(); + h.run_steps(2); + }; + if !(h.state().ui.panels.history && h.state().ui.dock_tabs.history == 1) { + toggle(&mut h); + } + h.run_steps(2); + h.get_by_label("Web").click(); + h.run_steps(2); + assert_eq!(h.state().ui.actions.selected_set.as_deref(), Some("Web")); + toggle(&mut h); + assert!(!h.state().ui.panels.history, "closed"); + assert!(h.query_by_label("Web").is_none()); + toggle(&mut h); + assert!(h.state().ui.panels.history && h.state().ui.dock_tabs.history == 1, "open again"); + assert!(h.query_by_label("Web").is_some() && h.query_by_label("Print").is_some(), "the empty sets"); + assert_eq!(h.state().session.actions.sets, ["Web", "Print"]); + assert_eq!((h.state().ui.actions.selected, h.state().ui.actions.selected_set.as_deref()), (None, Some("Web"))); + h.get_by_label("Create new action").click(); + h.run_steps(2); + h.state_mut().run("actions.stop", json!({})).unwrap(); + assert_eq!(h.state().session.actions.list[1].set.as_deref(), Some("Web")); +} + /// #7535: with a set's folder row selected and no action, Start Recording (like the Record button) /// has no action to append to, so it records a new action into that set, as New Action does. #[test] From b544021d49a6c393dceb1d9d6d58df48e4bb595e Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 1 Nov 2026 00:59:36 -0600 Subject: [PATCH 33/52] Actions: recording into an empty loaded set keeps its exact name (CodeRabbit review on crates/engine/src/cmd/atn_cmds/files.rs:65) Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/actions_cmds.rs | 6 +++--- crates/engine/src/cmd/actions_cmds/tests.rs | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index bfae856454d..b9f98b98297 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -374,9 +374,9 @@ fn record(s: &mut Session, p: &Value) -> Result { } let set = match p.get("set") { None | Some(Value::Null) => None, - // An existing set keeps its exact name (an older actions.json may pad it); a new one - // is trimmed. - Some(Value::String(n)) if s.actions.list.iter().any(|a| a.set.as_deref() == Some(n.as_str())) => Some(n.clone()), + // An existing set, empty ones included, keeps its exact name (an older actions.json or + // a `.atn` may pad it); a new one is trimmed. + Some(Value::String(n)) if crate::actions_edit_cmds::set_names(s).contains(n) => Some(n.clone()), Some(Value::String(n)) if !n.trim().is_empty() => Some(n.trim().to_string()), Some(_) => return Err(bad("actions.record", "\"set\" must be a set name or null")), }; diff --git a/crates/engine/src/cmd/actions_cmds/tests.rs b/crates/engine/src/cmd/actions_cmds/tests.rs index 44366f423ef..1eef6d4b348 100644 --- a/crates/engine/src/cmd/actions_cmds/tests.rs +++ b/crates/engine/src/cmd/actions_cmds/tests.rs @@ -1191,3 +1191,20 @@ fn record_keeps_an_existing_sets_exact_name() { s.execute("actions.stop", json!({})).unwrap(); assert_eq!(set_of(&s, "Fresh").as_deref(), Some("Print"), "a new set is trimmed"); } + +/// CodeRabbit review on #10459: an empty set loaded from a `.atn` (or made by New Set) keeps its +/// exact name too, so the first action recorded into it lands in that folder and saves with it. +#[test] +fn record_keeps_an_empty_loaded_sets_exact_name() { + let mut src = Session::new(); + src.actions.sets.push(" Web ".into()); + let saved = src.execute("actions.save", json!({"set": " Web "})).unwrap(); + let mut s = Session::new(); + assert_eq!(s.execute("actions.load", json!({"data": saved["data"]})).unwrap()["set"], " Web "); + s.execute("actions.record", json!({"name": "First", "set": " Web "})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let set = s.actions.list.iter().find(|a| a.name == "First").and_then(|a| a.set.clone()); + assert_eq!(set.as_deref(), Some(" Web ")); + assert_eq!(crate::actions_edit_cmds::set_names(&s), [" Web "], "one folder, not a trimmed second one"); + assert_eq!(s.execute("actions.save", json!({"set": " Web "})).unwrap()["actions"], json!(["First"])); +} From 36404b7843c9ad5b62253a67c51b9022e257ec29 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 1 Nov 2026 01:04:50 -0600 Subject: [PATCH 34/52] =?UTF-8?q?Actions=20panel:=20Save=20Actions?= =?UTF-8?q?=E2=80=A6=20is=20enabled=20for=20a=20selected=20empty=20set=20(?= =?UTF-8?q?CodeRabbit=20review=20on=20crates/engine/src/cmd/atn=5Fcmds/fil?= =?UTF-8?q?es.rs:112)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/actions.rs | 4 +- crates/ui-egui/src/panels/actions/tests.rs | 45 ++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 57c014d43b3..627d1feba85 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -729,7 +729,9 @@ pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if ui.button(tl!("Load Actions…")).clicked() { act = Some("load"); } - if ui.add_enabled(any, egui::Button::new(tl!("Save Actions…"))).clicked() { + // A selected set folder saves even when empty, as Photoshop saves an empty set. + let set_selected = app.ui.actions.selected_set.as_ref().is_some_and(|set| photocraft_engine::actions_edit_cmds::set_names(&app.session).contains(set)); + if ui.add_enabled(any || set_selected, egui::Button::new(tl!("Save Actions…"))).clicked() { act = Some("save"); } let Some(a) = act else { return }; diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index 9f80c2cfd0f..31498359bf8 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -888,6 +888,51 @@ fn save_actions_suggests_a_file_name_without_path_characters() { assert_eq!(saved["set"], set, "the file keeps the set's name"); } +/// An app with no actions and one empty set New Set made, its folder row shown with the panel +/// menu, and a fake Save dialog whose requests the test reads. +fn empty_set_save_harness( + set: &str, +) -> (egui_kittest::Harness<'static, PhotocraftApp>, std::rc::Rc>>) { + let (file_dialog, asked) = crate::file_dialog::fake(vec![None]); + let services = crate::Services { file_dialog: Some(file_dialog), ..Default::default() }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + app.run("actions.newSet", json!({"name": set})).unwrap(); + // With no action, the panel shows its "Record ● … play ▶" hint, which the test fonts lack. + let mut h = egui_kittest::Harness::builder().with_size(vec2(360.0, 600.0)).allow_missing_glyphs().build_ui_state( + |ui, app| { + panel_menu(app, ui); + panel(app, ui); + }, + app, + ); + h.run_steps(2); + (h, asked) +} + +/// CodeRabbit review on #10459: with no action at all, Save Actions… is still enabled for a +/// selected empty set (the engine saves it), and stays disabled with nothing to save. +#[test] +fn save_actions_is_enabled_for_a_selected_empty_set_with_no_actions() { + use egui_kittest::kittest::Queryable; + let (mut h, asked) = empty_set_save_harness("Later"); + h.get_by_label("Save Actions…").click(); + h.run_steps(2); + h.state_mut().poll_file_dialog(&egui::Context::default(), None); + assert!(asked.borrow().is_empty(), "no set selected, nothing to save: {:?}", asked.borrow()); + h.get_by_label("Later").click(); + h.run_steps(2); + assert_eq!(h.state().ui.actions.selected_set.as_deref(), Some("Later")); + h.get_by_label("Save Actions…").click(); + h.run_steps(2); + h.state_mut().poll_file_dialog(&egui::Context::default(), None); + assert!( + matches!(asked.borrow().as_slice(), [crate::file_dialog::FileDialogRequest::Save { suggested }] if suggested == "Later.atn"), + "{:?}", + asked.borrow() + ); +} + #[test] fn moving_an_action_next_to_another_set_joins_it() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); From 7e00310493121d5f297dac2a2ded68908e97389b Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 1 Nov 2026 01:05:18 -0600 Subject: [PATCH 35/52] =?UTF-8?q?Actions=20panel:=20Save=20Set=E2=80=A6=20?= =?UTF-8?q?on=20an=20empty=20set=20folder=20opens=20the=20save=20dialog=20?= =?UTF-8?q?(CodeRabbit=20review=20on=20crates/ui-egui/src/panels/actions.r?= =?UTF-8?q?s:945)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/actions.rs | 18 ++++++++++++------ crates/ui-egui/src/panels/actions/tests.rs | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 627d1feba85..5e258744aba 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -945,17 +945,21 @@ fn draw_set_header(ui: &mut egui::Ui, set: &str, count: u64, collapsed: bool, se } /// The sets New Set made that hold no action yet: empty folder rows after the rest. Returns the -/// set whose row was clicked. -fn draw_empty_sets(app: &PhotocraftApp, ui: &mut egui::Ui, rows: &[Row], t: &Tokens) -> Option { - let mut clicked = None; +/// set whose row was clicked and the set whose Save Set… was chosen. +fn draw_empty_sets(app: &PhotocraftApp, ui: &mut egui::Ui, rows: &[Row], t: &Tokens) -> (Option, Option) { + let (mut clicked, mut save) = (None, None); for set in app.session.actions.sets.iter().filter(|set| !rows.iter().any(|r| r.set.as_ref() == Some(*set))) { let selected = app.ui.actions.selected.is_none() && app.ui.actions.selected_set.as_ref() == Some(set); let collapsed = app.ui.actions.collapsed_sets.contains(set); - if draw_set_header(ui, set, 0, collapsed, selected, t).toggled { + let result = draw_set_header(ui, set, 0, collapsed, selected, t); + if result.toggled { clicked = Some(set.clone()); } + if result.save { + save = Some(set.clone()); + } } - clicked + (clicked, save) } fn action_context_menu(app: &mut PhotocraftApp, response: &egui::Response, index: usize, name: &str, swatch: &str) { @@ -1170,7 +1174,9 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { dialog_toggled = dialog_toggled.or(events.dialog_toggled); } } - set_toggled = set_toggled.take().or_else(|| draw_empty_sets(app, ui, &rows, &t)); + let (empty_toggled, empty_save) = draw_empty_sets(app, ui, &rows, &t); + set_toggled = set_toggled.take().or(empty_toggled); + save_set = save_set.take().or(empty_save); }); if let Some((action, step)) = toggled { let _ = app.run("actions.toggle", json!({"action": action, "step": step})); diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index 31498359bf8..1f217c6d368 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -933,6 +933,24 @@ fn save_actions_is_enabled_for_a_selected_empty_set_with_no_actions() { ); } +/// CodeRabbit review on #10459: Save Set… in an empty set folder's context menu saves that set, +/// as it does for a folder with actions. +#[test] +fn save_set_on_an_empty_set_folder_opens_the_save_dialog() { + use egui_kittest::kittest::Queryable; + let (mut h, asked) = empty_set_save_harness("Later"); + h.get_by_label("Later").click_secondary(); + h.run_steps(2); + h.get_by_label("Save Set…").click(); + h.run_steps(2); + h.state_mut().poll_file_dialog(&egui::Context::default(), None); + assert!( + matches!(asked.borrow().as_slice(), [crate::file_dialog::FileDialogRequest::Save { suggested }] if suggested == "Later.atn"), + "{:?}", + asked.borrow() + ); +} + #[test] fn moving_an_action_next_to_another_set_joins_it() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); From b67fb07557e4843429bfb8ea6e065744ef006307 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 1 Nov 2026 01:07:16 -0600 Subject: [PATCH 36/52] =?UTF-8?q?Actions=20panel:=20Save=20Actions?= =?UTF-8?q?=E2=80=A6=20suggests=20a=20Windows-safe=20name=20for=20device?= =?UTF-8?q?=20and=20control-character=20sets=20(CodeRabbit=20review=20on?= =?UTF-8?q?=20crates/ui-egui/src/panels/actions/tests.rs:883)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/file_cmds.rs | 7 +++++-- crates/engine/src/cmd/file_cmds/paths.rs | 2 +- crates/ui-egui/src/panels/actions.rs | 8 ++++---- crates/ui-egui/src/panels/actions/tests.rs | 20 ++++++++++++++++++++ 4 files changed, 30 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 3925bf83215..82a54214452 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -45,8 +45,11 @@ pub(crate) use open::{import, tag_exr_colorspace}; use paths::is_file; #[cfg(test)] use paths::openable_name; -pub use paths::{extension, holds, holds_at, is_template, layered_extension, list_images, losses_at, same_file, saves_in_place, template_name, untitled_name}; -pub(crate) use paths::{file_name, forward_slashes, is_windows_device_name, join, portable_device_name, read_file, sanitize, stem, write_file}; +pub use paths::{ + extension, holds, holds_at, is_template, layered_extension, list_images, losses_at, portable_device_name, same_file, saves_in_place, template_name, + untitled_name, +}; +pub(crate) use paths::{file_name, forward_slashes, is_windows_device_name, join, read_file, sanitize, stem, write_file}; use processing::{conditional_mode_change, fit_image, flatten_all_effects, flatten_all_masks, image_processor, load_files_into_stack}; use save::save_a_copy; pub(crate) use save::{SaveOpts, encode, save_doc}; diff --git a/crates/engine/src/cmd/file_cmds/paths.rs b/crates/engine/src/cmd/file_cmds/paths.rs index 840609d8260..8f3abdc6b89 100644 --- a/crates/engine/src/cmd/file_cmds/paths.rs +++ b/crates/engine/src/cmd/file_cmds/paths.rs @@ -212,7 +212,7 @@ pub(crate) fn sanitize(name: &str) -> String { /// `name` with a `_` before its first dot when it is a Windows device name (`nul` → `nul_`, /// `com1.v2` → `com1_.v2`); a `_` at the end would leave the device stem in place. -pub(crate) fn portable_device_name(name: String) -> String { +pub fn portable_device_name(name: String) -> String { if !is_windows_device_name(&name) { return name; } diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 5e258744aba..5442eeff22d 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -446,15 +446,15 @@ fn save_dialog(app: &mut PhotocraftApp, set: Option) -> Result' | '|') { '_' } else { c }) + .map(|c| if c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c }) .collect(); - let file = format!("{stem}.atn"); + let file = format!("{}.atn", photocraft_engine::file_cmds::portable_device_name(stem)); app.pick_save(&file, move |app, path| { let write = app.services.write.as_mut().ok_or("no writer configured")?; write(&path, &bytes)?; diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index 1f217c6d368..b35ba653c07 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -951,6 +951,26 @@ fn save_set_on_an_empty_set_folder_opens_the_save_dialog() { ); } +/// CodeRabbit review on #10459: a set named after a Windows device (`CON`, `com1.v2`) or holding a +/// control character gets a suggested file name Windows can create. +#[test] +fn save_actions_suggests_a_windows_safe_name_for_device_and_control_character_sets() { + use egui_kittest::kittest::Queryable; + for (set, suggested) in [("CON", "CON_.atn"), ("com1.v2", "com1_.v2.atn"), ("Web\u{1}Print\tMail", "Web_Print_Mail.atn"), ("Print", "Print.atn")] { + let (mut h, asked) = empty_set_save_harness(set); + h.get_by_label(set).click(); + h.run_steps(2); + h.get_by_label("Save Actions…").click(); + h.run_steps(2); + h.state_mut().poll_file_dialog(&egui::Context::default(), None); + assert!( + matches!(asked.borrow().as_slice(), [crate::file_dialog::FileDialogRequest::Save { suggested: s }] if s == suggested), + "{set:?}: {:?}", + asked.borrow() + ); + } +} + #[test] fn moving_an_action_next_to_another_set_joins_it() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); From 4b053e15ae229cff1dce09d048f753ed2a2b7c67 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 14:25:51 +0100 Subject: [PATCH 37/52] Integration: keep the ATN contract tests, drop the extra workflow (#7561) The contract tests no longer compiled on main (AtnItem::dictionary is now Vec, so it is compared with b"Future event"), sat outside main's tests/it layout, and the new atn.yml added six legs (two macOS) to every PR against ci.yml's policy. Move the tests into tests/it so the existing CI runs them, drop atn.yml and docs/atn-testing.md, keep main's ci.yml and fuzz target, and note the committed fixtures in ATTRIBUTION.md. Co-authored-by: denstu473 <63150090+denstu473@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- .github/workflows/atn.yml | 166 ------------------ ATTRIBUTION.md | 7 +- crates/psd/fuzz/fuzz_targets/atn.rs | 12 +- crates/psd/tests/fixtures/atn/README.md | 4 +- crates/psd/tests/{ => it}/atn_contract.rs | 12 +- .../tests/{ => it}/common/atn_roundtrip.rs | 2 +- crates/psd/tests/it/main.rs | 1 + docs/atn-testing.md | 97 ---------- docs/development.md | 5 +- 9 files changed, 24 insertions(+), 282 deletions(-) delete mode 100644 .github/workflows/atn.yml rename crates/psd/tests/{ => it}/atn_contract.rs (96%) rename crates/psd/tests/{ => it}/common/atn_roundtrip.rs (96%) delete mode 100644 docs/atn-testing.md diff --git a/.github/workflows/atn.yml b/.github/workflows/atn.yml deleted file mode 100644 index 1895598e282..00000000000 --- a/.github/workflows/atn.yml +++ /dev/null @@ -1,166 +0,0 @@ -name: ATN - -on: - push: - branches: [main] - pull_request: - types: [opened, synchronize, reopened, ready_for_review] - merge_group: - schedule: - - cron: "17 4 * * *" - workflow_dispatch: - inputs: - fuzz_seconds: - description: "Seconds of ATN parser fuzzing" - type: choice - options: ["60", "300", "600"] - default: "60" - -permissions: - contents: read - -concurrency: - group: atn-${{ github.ref }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -env: - CARGO_TERM_COLOR: always - RUST_BACKTRACE: 1 - CARGO_PROFILE_DEV_DEBUG: "0" - CARGO_PROFILE_RELEASE_DEBUG: "0" - # Keep optimized arithmetic behavior without paying for release LTO in a parser test job. - CARGO_PROFILE_RELEASE_LTO: "false" - CARGO_PROFILE_RELEASE_CODEGEN_UNITS: "16" - -jobs: - parser: - name: ATN parser (${{ matrix.target }}) - runs-on: ${{ matrix.os }} - timeout-minutes: 20 - strategy: - fail-fast: false - # These small CPU-only jobs can share the macOS pool with release builds. - max-parallel: 3 - matrix: - include: - - { os: ubuntu-24.04, target: x86_64-unknown-linux-gnu, arch: X64 } - - { os: ubuntu-24.04-arm, target: aarch64-unknown-linux-gnu, arch: ARM64 } - - { os: windows-2025, target: x86_64-pc-windows-msvc, arch: X64 } - - { os: windows-11-arm, target: aarch64-pc-windows-msvc, arch: ARM64 } - - { os: macos-15-intel, target: x86_64-apple-darwin, arch: X64 } - - { os: macos-15, target: aarch64-apple-darwin, arch: ARM64 } - defaults: - run: - shell: bash - steps: - - uses: actions/checkout@v4 - with: - persist-credentials: false - - uses: dtolnay/rust-toolchain@stable - with: - targets: ${{ matrix.target }} - - uses: Swatinem/rust-cache@v2 - with: - key: atn-parser-${{ matrix.target }} - save-if: ${{ github.ref == 'refs/heads/main' }} - cache-on-failure: true - - name: Record native execution environment - env: - EXPECTED_ARCH: ${{ matrix.arch }} - TEST_TARGET: ${{ matrix.target }} - run: | - mkdir -p atn-results - # A successful cross-compilation must never stand in for native execution. - test "$RUNNER_ARCH" = "$EXPECTED_ARCH" - { - git rev-parse HEAD - printf 'runner=%s arch=%s target=%s\n' "$RUNNER_OS" "$RUNNER_ARCH" "$TEST_TARGET" - printf 'image=%s version=%s\n' "${ImageOS:-unknown}" "${ImageVersion:-unknown}" - rustc -vV - cargo -V - } | tee atn-results/environment.txt - - name: Parser unit tests - env: - TEST_TARGET: ${{ matrix.target }} - run: | - set -o pipefail - cargo test --locked -p photocraft-psd --target "$TEST_TARGET" --lib atn::tests:: -- --nocapture 2>&1 | tee atn-results/unit.log - - name: Parser contract tests (debug) - env: - TEST_TARGET: ${{ matrix.target }} - run: | - set -o pipefail - cargo test --locked -p photocraft-psd --target "$TEST_TARGET" --test atn_contract -- --nocapture 2>&1 | tee atn-results/debug.log - - name: Parser contract tests (release) - env: - TEST_TARGET: ${{ matrix.target }} - run: | - set -o pipefail - cargo test --locked --release -p photocraft-psd --target "$TEST_TARGET" --test atn_contract -- --nocapture 2>&1 | tee atn-results/release.log - - name: Upload parser evidence - if: always() - uses: actions/upload-artifact@v4 - with: - name: atn-parser-${{ matrix.target }} - path: atn-results/ - if-no-files-found: error - retention-days: 14 - - parser-gate: - name: ATN parser gate - needs: parser - if: always() - runs-on: ubuntu-24.04 - timeout-minutes: 5 - steps: - - name: Require every native parser leg - env: - PARSER_RESULT: ${{ needs.parser.result }} - run: test "$PARSER_RESULT" = success - - fuzz: - name: ATN parser fuzz - if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' - runs-on: ubuntu-24.04 - timeout-minutes: 20 - steps: - - uses: actions/checkout@v4 - with: - persist-credentials: false - - uses: dtolnay/rust-toolchain@nightly - - uses: Swatinem/rust-cache@v2 - with: - key: atn-fuzz - workspaces: crates/psd/fuzz - save-if: ${{ github.ref == 'refs/heads/main' }} - cache-on-failure: true - - name: Install cargo-fuzz - run: cargo install cargo-fuzz --locked - - name: Seed parser fuzzing with the contract fixtures - run: | - mkdir -p crates/psd/fuzz/corpus/atn atn-results - cp crates/psd/tests/fixtures/atn/*.atn crates/psd/fuzz/corpus/atn/ - { - git rev-parse HEAD - rustc -vV - cargo fuzz --version - sha256sum crates/psd/tests/fixtures/atn/*.atn - } | tee atn-results/fuzz-environment.txt - - name: Fuzz ATN parsing and writing - working-directory: crates/psd - env: - FUZZ_SECONDS: ${{ inputs.fuzz_seconds || '60' }} - run: | - set -o pipefail - cargo fuzz run atn -- -max_total_time="$FUZZ_SECONDS" -max_len=65536 -rss_limit_mb=512 -timeout=5 2>&1 | tee ../../atn-results/fuzz.log - - name: Upload fuzz evidence - if: always() - uses: actions/upload-artifact@v4 - with: - name: atn-fuzz-evidence - path: | - atn-results/ - crates/psd/fuzz/artifacts/atn/ - crates/psd/fuzz/corpus/atn/ - if-no-files-found: warn - retention-days: 14 diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 9088da74b70..94f30b1be37 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -120,7 +120,8 @@ Artwork shown in the screenshots (all public domain, via Wikimedia Commons; deta ## Test data (not committed, not shipped) -`corpus/` is gitignored and no test fixtures are committed to the repository. +`corpus/` is gitignored and no test fixtures are committed to the repository, except the small +synthetic parser fixtures listed under *Synthetic parser test fixtures* below. `cargo xtask corpus --all` fetches every corpus at the pinned commits in `xtask/src/corpus_pins.rs` and verifies each file against the sha256 lists in `xtask/*.sha256`, with the upstream licence next to the files: @@ -138,14 +139,14 @@ next to the files: | `corpus/pngsuite/` | PngSuite | Willem van Schaik | | Public domain | | `corpus/pixls/` (11 files) | Real camera raws, one per decode path: Canon PowerShot SX50 HS (CR2 and its DNG conversion), Nikon D3 uncompressed NEF and Z6 paired 12/14-bit lossy and packed NEFs, Sony DSC-RX0 cRAW ARW, Panasonic DC-G9 high-res RW2, Olympus E-1 GRBG ORF, plus the E-5 packed ORF as the documented known-unsupported case. Per file (each CC0, per its database entry): [IMG_4059.CR2](https://raw.pixls.us/data/Canon/PowerShot%20SX50%20HS/IMG_4059.CR2), [CRW_4061.DNG](https://raw.pixls.us/data/Canon/PowerShot%20SX50%20HS/CRW_4061.DNG), [JD1_8203.NEF](https://raw.pixls.us/data/Nikon/D3/JD1_8203.NEF), [DSC00009.ARW](https://raw.pixls.us/data/Sony/DSC-RX0/DSC00009.ARW), [P1000475.RW2](https://raw.pixls.us/data/Panasonic/DC-G9/P1000475.RW2), [E_1__C106743_gredos.ORF](https://raw.pixls.us/data/Olympus/E-1/E_1__C106743_gredos.ORF), [_7061961_copy.ORF](https://raw.pixls.us/data/Olympus/E-5/_7061961_copy.ORF), [DSC_0750.NEF](https://raw.pixls.us/data/Nikon/Z%206/DSC_0750.NEF), [DSC_0751.NEF](https://raw.pixls.us/data/Nikon/Z%206/DSC_0751.NEF), [DSC_0753.NEF](https://raw.pixls.us/data/Nikon/Z%206/DSC_0753.NEF), [DSC_0754.NEF](https://raw.pixls.us/data/Nikon/Z%206/DSC_0754.NEF) | The photographers of the pixls.us raw samples database | [raw.pixls.us](https://raw.pixls.us) `data/`, fetched per [xtask/src/corpus_pins.rs](xtask/src/corpus_pins.rs) | CC0 / public domain, per file as linked | +Files copied into `corpus/` by hand (tiff, exr, raw) must be MIT, BSD or CC0. + ## Synthetic parser test fixtures | Path | Title | Author | Source | License | |---|---|---|---|---| | `crates/psd/tests/fixtures/atn/*.atn` | Independently encoded ATN version-16 parser fixtures | PhotoCraft contributors | Original synthetic test data; wire layout documented in `crates/psd/src/atn.rs`; provenance in the adjacent README | MIT OR Apache-2.0 | -Files copied into `corpus/` by hand (tiff, exr, raw) must be MIT, BSD or CC0. - ## Embedded-vector editor source The external SVG watcher, engine/UI handoff and bounded SVG rendering in this change diff --git a/crates/psd/fuzz/fuzz_targets/atn.rs b/crates/psd/fuzz/fuzz_targets/atn.rs index 7d719a0b809..3bb1777c8a3 100644 --- a/crates/psd/fuzz/fuzz_targets/atn.rs +++ b/crates/psd/fuzz/fuzz_targets/atn.rs @@ -1,12 +1,14 @@ //! Fuzz the `.atn` actions parser: any input must return `Ok` or `Err`, never panic, and -//! anything that parses must survive writing, reparsing and stable canonical writing. +//! anything that parses must survive a write and parse back equal. #![no_main] use libfuzzer_sys::fuzz_target; - -#[path = "../../tests/common/atn_roundtrip.rs"] -mod atn_roundtrip; +use photocraft_psd::atn; fuzz_target!(|data: &[u8]| { - atn_roundtrip::check(data); + if let Ok(f) = atn::parse(data) { + let bytes = atn::write(&f).expect("a parsed set is writable"); + let again = atn::parse(&bytes).expect("a written set parses"); + assert_eq!(again.actions, f.actions); + } }); diff --git a/crates/psd/tests/fixtures/atn/README.md b/crates/psd/tests/fixtures/atn/README.md index e26382f1ea3..119f098c3ea 100644 --- a/crates/psd/tests/fixtures/atn/README.md +++ b/crates/psd/tests/fixtures/atn/README.md @@ -13,7 +13,7 @@ oracles. | `descriptors.atn` | 859 | Every descriptor value variant and every reference form currently represented by the parser | `6c76502822c1f36c8060a71adb227c4540663518785bbab1b70951dac0ef58ad` | | `float-bits.atn` | 428 | NaN payload, negative zero, infinities, and floats inside lists, objects and arrays | `0aa6278a569c777f249b305e889896132c2a87e44a24cb1a55d1d3fc0928fd0c` | -`tests/atn_contract.rs` checks the independently encoded bytes and expected public structures. -The ATN fuzz job copies the same files into its seed corpus. A fixture change should explain +`tests/it/atn_contract.rs` checks the independently encoded bytes and expected public structures. +A fixture change should explain the changed wire fields and update this table; do not regenerate expectations merely to make a failing parser pass. diff --git a/crates/psd/tests/atn_contract.rs b/crates/psd/tests/it/atn_contract.rs similarity index 96% rename from crates/psd/tests/atn_contract.rs rename to crates/psd/tests/it/atn_contract.rs index 55d7a6623de..522d4ad2d43 100644 --- a/crates/psd/tests/atn_contract.rs +++ b/crates/psd/tests/it/atn_contract.rs @@ -1,4 +1,4 @@ -//! Portable public-API contract, executed natively in debug and release by ATN CI. +//! Public-API contract for the `.atn` parser, against independently encoded wire fixtures. use photocraft_psd::PsdError; use photocraft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; use photocraft_psd::descriptor::{Class, Descriptor, Id, MAX_DEPTH, ObjectArray, ReferenceItem, UnicodeString, Value}; @@ -7,10 +7,10 @@ use photocraft_psd::descriptor::{Class, Descriptor, Id, MAX_DEPTH, ObjectArray, mod atn_roundtrip; const FIXTURES: &[(&str, &[u8])] = &[ - ("empty", include_bytes!("fixtures/atn/empty.atn")), - ("metadata", include_bytes!("fixtures/atn/metadata.atn")), - ("descriptors", include_bytes!("fixtures/atn/descriptors.atn")), - ("float bits", include_bytes!("fixtures/atn/float-bits.atn")), + ("empty", include_bytes!("../fixtures/atn/empty.atn")), + ("metadata", include_bytes!("../fixtures/atn/metadata.atn")), + ("descriptors", include_bytes!("../fixtures/atn/descriptors.atn")), + ("float bits", include_bytes!("../fixtures/atn/float-bits.atn")), ]; fn file_with(desc: Descriptor) -> AtnFile { @@ -55,7 +55,7 @@ fn unicode_metadata_unknown_events_and_dialog_flags_are_preserved() { let future = &action.items[1]; assert_eq!(future.event, AtnEvent::Name("syntheticFutureEvent".into())); assert_eq!((future.expanded, future.enabled, future.with_dialog, future.dialog_options), (false, false, true, 255)); - assert_eq!(future.dictionary, "Future event"); + assert_eq!(future.dictionary, b"Future event"); assert!(future.descriptor.is_none()); assert_eq!(file.actions[1].name, UnicodeString::new_nul("Empty")); assert!(file.actions[1].items.is_empty()); diff --git a/crates/psd/tests/common/atn_roundtrip.rs b/crates/psd/tests/it/common/atn_roundtrip.rs similarity index 96% rename from crates/psd/tests/common/atn_roundtrip.rs rename to crates/psd/tests/it/common/atn_roundtrip.rs index 8b71754b561..ded43b55e2f 100644 --- a/crates/psd/tests/common/atn_roundtrip.rs +++ b/crates/psd/tests/it/common/atn_roundtrip.rs @@ -1,4 +1,4 @@ -//! Shared invariant for the parser contract suite and the actual cargo-fuzz target. +//! Shared round-trip invariant for the `.atn` parser contract suite. use photocraft_psd::atn::{self, AtnFile}; use photocraft_psd::descriptor::{Descriptor, Value}; diff --git a/crates/psd/tests/it/main.rs b/crates/psd/tests/it/main.rs index ee6879aa661..8d83a12c176 100644 --- a/crates/psd/tests/it/main.rs +++ b/crates/psd/tests/it/main.rs @@ -1,5 +1,6 @@ //! The crate's integration tests, linked into one test binary. +mod atn_contract; mod builder; mod corpus; mod corpus_atn; diff --git a/docs/atn-testing.md b/docs/atn-testing.md deleted file mode 100644 index e882f76bdc8..00000000000 --- a/docs/atn-testing.md +++ /dev/null @@ -1,97 +0,0 @@ -# ATN parser tests and CI - -`.github/workflows/atn.yml` adds a focused parser check on every pull request, merge-group run, -main push, nightly run and manual dispatch. It runs even on unrelated pull requests so its -stable `ATN parser gate` check is always available for branch protection. Making that check -required is a repository setting; adding the workflow does not change branch protection. - -## Native platform matrix - -| OS image | Executed target | -|---|---| -| Ubuntu 24.04 x64 | `x86_64-unknown-linux-gnu` | -| Ubuntu 24.04 ARM64 | `aarch64-unknown-linux-gnu` | -| Windows Server 2025 x64 | `x86_64-pc-windows-msvc` | -| Windows 11 ARM64 | `aarch64-pc-windows-msvc` | -| macOS 15 Intel | `x86_64-apple-darwin` | -| macOS 15 Apple Silicon | `aarch64-apple-darwin` | - -Runner labels are listed in GitHub's -[hosted-runner reference](https://docs.github.com/en/actions/reference/runners/github-hosted-runners). - -Every leg verifies the runner architecture, runs the parser unit tests, and executes the public -parser contract suite in debug and release. These are native test executions, not cross-compile -checks. The release check disables LTO to keep CI small while retaining optimized arithmetic -behavior. At most three matrix legs run concurrently. Full workspace CI keeps its existing -platform selection; this separate job builds only the standalone PSD crate and its dependencies. - -The matrix tests CPU parsing and writing. It does not certify graphics drivers, GPU previews, -UI cancellation, ATN command conversion/playback, WebAssembly execution or Photoshop parity. -Those need their own execution and expected-result checks. Processor architecture coverage is -not an exhaustive inventory of CPU models or operating-system versions. - -## Contract and fixtures - -`crates/psd/tests/atn_contract.rs` exercises the public `photocraft_psd::atn::{parse, write}` APIs. -Its four committed synthetic fixtures are independently encoded, not generated by the writer -under test. The checks cover: - -- Byte-exact parsing/writing, explicit endianness, names, action/step order and empty actions. -- UTF-16 units, including supplementary characters and unpaired surrogates. -- Function keys, modifiers, panel state, enabled state, dialog flags and unknown event names. -- Every descriptor value variant and reference form, including opaque alias/path/raw bytes. -- Exact floating-point bits, including NaN payloads, signed zero and infinities. -- Every truncated fixture, invalid versions/tags, declared action/step limits and excessive - descriptor nesting, with passing valid controls. -- Deterministic generated metadata/float cases and seed mutations through the same invariant - called by the real fuzz target. - -The parser preserves file representation; native engine option semantics remain the -responsibility of `crates/engine/src/atn_cmds/tests.rs` and future playback regression suites. - -Run the focused checks from the repository root: - -```sh -cargo test --locked -p photocraft-psd --lib atn::tests:: -cargo test --locked -p photocraft-psd --test atn_contract -cargo test --locked --release -p photocraft-psd --test atn_contract -``` - -Fixtures and their provenance/checksums are documented in -`crates/psd/tests/fixtures/atn/README.md`. New Photoshop-authored interoperability oracles belong -in the separately pinned `photocraft-corpus` repository, following the existing corpus policy. - -## Fuzzing - -The dedicated ATN workflow runs the existing `psd/atn` cargo-fuzz target on Linux nightly and on -manual dispatch. It starts with the four valid fixtures, runs for 60 seconds nightly, and caps -input length at 64 KiB, resident memory at 512 MiB and a single input at five seconds. Manual -runs can select 60, 300 or 600 seconds. The general CI workflow's existing manual fuzz matrix -also includes `psd/atn`. - -The shared invariant in `tests/common/atn_roundtrip.rs` requires every successfully parsed set -to write and reparse with the same set/action metadata, descriptor structure and floating-point -bits. NaNs are compared by bits before normalization for AST equality, avoiding false failures -from `NaN != NaN`. Only trailing-input diagnostic warnings are excluded from serialized state. -Canonical output must remain byte-stable on another write. - -```sh -mkdir -p crates/psd/fuzz/corpus/atn -cp crates/psd/tests/fixtures/atn/*.atn crates/psd/fuzz/corpus/atn/ -cd crates/psd -cargo +nightly fuzz run atn -- -max_total_time=60 -max_len=65536 -rss_limit_mb=512 -timeout=5 -``` - -Run cargo-fuzz where its sanitizer/runtime are supported; the deterministic contract suite runs -on every matrix platform. Every real failure gets a minimized committed regression fixture and -an expected behavior assertion. Do not hide a failure by adding an ignore or weakening a check. - -## Evidence and scope - -Parser legs upload the exact commit, runner/image, architecture, Rust/Cargo versions, and test -logs, including failures. Fuzz runs upload environment details, fixture checksums, the evolved -corpus, logs and crash artifacts. Evidence is retained for 14 days. A failed, cancelled or -skipped parser matrix prevents the aggregate gate from succeeding. - -Local validation on one platform does not establish that hosted jobs have passed. Confirm all -six native legs in GitHub Actions before describing the change as verified on that matrix. diff --git a/docs/development.md b/docs/development.md index 12cf20da742..dee2b99638a 100644 --- a/docs/development.md +++ b/docs/development.md @@ -631,8 +631,9 @@ PhotoCraft equivalent. Events outside the table load as `actions.photoshopStep` steps that keep the descriptor verbatim (so Save Actions writes them back) and fail at playback with the step's Photoshop name. -The focused native parser matrix, public-API contract fixtures, scheduled fuzzing and local -commands are described in [ATN parser tests and CI](atn-testing.md). +`crates/psd/tests/it/atn_contract.rs` checks the parser's public API against four small, +independently encoded fixtures in `crates/psd/tests/fixtures/atn/` (provenance and checksums in +its README): `cargo test -p photocraft-psd --test it atn_contract::`. ## Remove Tool quality From 5ff10e120dbb2e1255b5457176ca155f0b89a9b2 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 14:30:55 +0100 Subject: [PATCH 38/52] Integration: keep the NaN-safe .atn fuzz invariant (#7561) The previous fix-up put main's atn fuzz target back. It compares the parsed actions with assert_eq!, so any valid file holding a NaN double fails the fuzzer falsely (NaN != NaN); the PR's own contract test nan_payloads_signed_zero_and_infinities_survive_without_false_fuzz_failures covers exactly that. The target now calls the shared check again, at its new path under tests/it/common. Co-authored-by: denstu473 <63150090+denstu473@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/psd/fuzz/fuzz_targets/atn.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/crates/psd/fuzz/fuzz_targets/atn.rs b/crates/psd/fuzz/fuzz_targets/atn.rs index 3bb1777c8a3..e02e25b0731 100644 --- a/crates/psd/fuzz/fuzz_targets/atn.rs +++ b/crates/psd/fuzz/fuzz_targets/atn.rs @@ -1,14 +1,12 @@ //! Fuzz the `.atn` actions parser: any input must return `Ok` or `Err`, never panic, and -//! anything that parses must survive a write and parse back equal. +//! anything that parses must survive writing, reparsing and stable canonical writing. #![no_main] use libfuzzer_sys::fuzz_target; -use photocraft_psd::atn; + +#[path = "../../tests/it/common/atn_roundtrip.rs"] +mod atn_roundtrip; fuzz_target!(|data: &[u8]| { - if let Ok(f) = atn::parse(data) { - let bytes = atn::write(&f).expect("a parsed set is writable"); - let again = atn::parse(&bytes).expect("a written set parses"); - assert_eq!(again.actions, f.actions); - } + atn_roundtrip::check(data); }); From 4d2fd2214dcceaabb1966ecf4ff0edc4b8499d61 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 14:31:13 +0100 Subject: [PATCH 39/52] Integration: Camera Raw Filter steps save back and refuse unknown keys (#8714) A loaded Camera Raw Filter step became an import-only filter.cameraRaw, so Save Actions dropped it (skipUnsupported) or failed, where before it was written back byte for byte. Keys outside the table (e.g. PerV = 20, a profile name) were ignored, so the step replayed a different look without being reported. The step now keeps its recorded descriptor in a hidden param and saves back as that descriptor while its params are still what it imports as; edited or PhotoCraft-recorded steps are still refused. A step with any unknown key, or with no settings, stays a kept Photoshop step, as the PSD mapping does. Co-authored-by: FinnNk <1424666+FinnNk@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/atn_cmds/events.rs | 10 +-- crates/engine/src/cmd/atn_cmds/steps_image.rs | 47 +++++++++-- crates/engine/src/cmd/atn_cmds/tests.rs | 78 ++++++++++++++++++- 3 files changed, 124 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index cffb144f4bf..e77b088878b 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -7,8 +7,8 @@ use super::steps_doc::{ place_from, place_to, profile_from, profile_to, purge_from, purge_to, reset_from, reset_to, save_from, save_to, stop_from, stop_to, }; use super::steps_image::{ - GALLERY_IDS, REFINE_EDGE, RIPPLE_SIZE, SMART_BRUSH, apply_image_from, apply_image_to, camera_raw_from, color_range_from, color_range_to, gallery_from, - gallery_to, has_refine_strokes, radial_blur_from, radial_blur_to, refine_edge_to, transform_from, transform_to, + GALLERY_IDS, REFINE_EDGE, RIPPLE_SIZE, SMART_BRUSH, apply_image_from, apply_image_to, camera_raw_from, camera_raw_to, color_range_from, color_range_to, + gallery_from, gallery_to, has_refine_strokes, radial_blur_from, radial_blur_to, refine_edge_to, transform_from, transform_to, }; use super::steps_layer::{ STROKE, apply_comp_from, apply_comp_to, clear_from, clear_to, delete_from, delete_to, duplicate_from, duplicate_to, fill_from, fill_to, flip_from, flip_to, @@ -249,9 +249,9 @@ pub(super) const EVENTS: &[Event] = &[ ev!("Rple", "ripple", "Ripple", "filter.distort.ripple", &[F("Amnt", "amount", Kind::ExactLong), F("RplS", "size", Kind::Enum("RplS", RIPPLE_SIZE))]), ev!("Crst", "crystallize", "Crystallize", "filter.pixelate.crystallize", &[F("ClSz", "cellSize", Kind::ExactLong)]), Event { code: "GEfc", name: "filterGallery", label: "Filter Gallery", ids: GALLERY_IDS, from: gallery_from, to: gallery_to }, - // Import only: what Photoshop needs in a written step (process version, the full settings - // set) is unverified, so Save Actions still refuses `filter.cameraRaw`. - Event { code: "", name: "Adobe Camera Raw Filter", label: "Camera Raw Filter", ids: &[], from: camera_raw_from, to: |_, _| None }, + // What Photoshop needs in a written step (process version, the full settings set) is + // unverified, so only an imported step saves back, as its recorded descriptor while unedited. + Event { code: "", name: "Adobe Camera Raw Filter", label: "Camera Raw Filter", ids: &[crate::lens_cmds::RAW], from: camera_raw_from, to: camera_raw_to }, // Adjustments (Image › Adjustments). Event { code: "", diff --git a/crates/engine/src/cmd/atn_cmds/steps_image.rs b/crates/engine/src/cmd/atn_cmds/steps_image.rs index 50ad30f1397..b84b21c227d 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_image.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_image.rs @@ -304,15 +304,37 @@ fn camera_raw_range(key: &str) -> std::ops::RangeInclusive { } } +/// The hidden param an imported Camera Raw Filter step keeps its recorded descriptor in, so +/// Save Actions writes the step back unchanged while its settings are the ones it imported with. +const CAMERA_RAW_DESCRIPTOR: &str = "__atnDescriptor"; + +/// The colour grading wheels' keys, the tone curve splits and the vignette style. +const CAMERA_RAW_GRADES: &[&str] = + &["STSH", "STSS", "CgSL", "CgMH", "CgMS", "CgML", "STHH", "STHS", "CgHL", "CgGH", "CgGS", "CgGL", "PC_1", "PC_2", "PC_3", "PCVS"]; + /// A recorded Camera Raw Filter step (`Adobe Camera Raw Filter`) as `filter.cameraRaw` (#6745). /// Settings the command has no counterpart for refuse the step rather than replaying a different -/// look: the Calibration panel, a white balance other than Custom, and the controls the PSD -/// mapping keeps only at their neutral values. Version metadata and a full settings snapshot's -/// lens and geometry keys are ignored, as other events ignore keys they don't map. +/// look: the Calibration panel, a white balance other than Custom, the controls the PSD mapping +/// keeps only at their neutral values, and any key outside this table (lens, geometry, profile, +/// masks…), as the PSD mapping's `known_key` does. pub(super) fn camera_raw_from(d: &Descriptor) -> Mapped { const CALIBRATION: &[&str] = &["RHue", "RSat", "GHue", "GSat", "BHue", "BSat", "BlkB"]; const NEUTRAL_ONLY: &[(&str, f64)] = &[("LNRC", 0.0), ("CNRS", 50.0), ("MDis", 0.0), ("VigA", 0.0), ("VigM", 50.0), ("crfs", 100.0), ("TMMs", 0.0), ("PGTM", 0.0), ("RGBt", 0.0)]; + const OTHER: &[&str] = &["CrVe", "PrVe", "PrVN", "WBal", "Crv ", "CrvR", "CrvG", "CrvB"]; + let known = |k: &str| { + (k.len() == 4 && ["HA_", "SA_", "LA_"].iter().any(|p| k.starts_with(p)) && ["R", "O", "Y", "G", "A", "B", "P", "M"].iter().any(|c| k.ends_with(c))) + || CAMERA_RAW.iter().any(|F(f, ..)| *f == k) + || CAMERA_RAW_GRADES.contains(&k) + || OTHER.contains(&k) + || CALIBRATION.contains(&k) + || NEUTRAL_ONLY.iter().any(|(n, _)| *n == k) + }; + // An empty step (no descriptor) would play as a no-op, and a key the table doesn't know may + // be active processing (lens, geometry, profile, masks) that playback would leave out. + if d.items.is_empty() || d.items.iter().any(|(k, _)| !std::str::from_utf8(k.as_bytes()).is_ok_and(known)) { + return Mapped::Unsupported { harmless: false }; + } let active = |k: &str, neutral: f64| d.get(k).is_some() && get_num(d, k) != Some(neutral); let custom_wb = d.get("WBal").is_none() || get_enum(d, "WBal").as_deref() == Some("Cst"); if !custom_wb || CALIBRATION.iter().any(|k| active(k, 0.0)) || NEUTRAL_ONLY.iter().any(|(k, n)| active(k, *n)) { @@ -327,8 +349,7 @@ pub(super) fn camera_raw_from(d: &Descriptor) -> Mapped { (Some(_), Some(v)) => k != "PCVS" && !(v.is_finite() && camera_raw_range(k).contains(&v)), }; let grouped = ["HA_", "SA_", "LA_"].iter().flat_map(|p| ["R", "O", "Y", "G", "A", "B", "P", "M"].map(|c| format!("{p}{c}"))); - let grades = ["STSH", "STSS", "CgSL", "CgMH", "CgMS", "CgML", "STHH", "STHS", "CgHL", "CgGH", "CgGS", "CgGL", "PC_1", "PC_2", "PC_3", "PCVS"]; - if CAMERA_RAW.iter().any(|F(k, ..)| unreadable(k)) || grouped.into_iter().any(|k| unreadable(&k)) || grades.iter().any(|k| unreadable(k)) { + if CAMERA_RAW.iter().any(|F(k, ..)| unreadable(k)) || grouped.into_iter().any(|k| unreadable(&k)) || CAMERA_RAW_GRADES.iter().any(|k| unreadable(k)) { return Mapped::Unsupported { harmless: false }; } let Some(mut m) = fields_from(d, CAMERA_RAW) else { return Mapped::Unsupported { harmless: false } }; @@ -390,9 +411,25 @@ pub(super) fn camera_raw_from(d: &Descriptor) -> Mapped { m.insert(param.into(), Value::Array(flat.as_chunks::<2>().0.iter().map(|[a, b]| json!([a, b])).collect())); } } + m.insert(CAMERA_RAW_DESCRIPTOR.into(), json!(photocraft_paint::tile::b64_encode(&d.to_bytes()))); step(crate::lens_cmds::RAW, Value::Object(m)) } +/// An imported Camera Raw Filter step back as its recorded descriptor, unchanged. Only while the +/// params are still what that descriptor imports as: an edited step, or one PhotoCraft recorded, +/// has no verified Photoshop form and Save Actions refuses it. +pub(super) fn camera_raw_to(_: &str, p: &Value) -> Option { + let d = Descriptor::from_bytes(&photocraft_paint::tile::b64_decode(jstr(p, CAMERA_RAW_DESCRIPTOR)?)?).ok()?; + let Mapped::Steps(steps) = camera_raw_from(&d) else { return None }; + let [(_, imported)] = steps.as_slice() else { return None }; + let (mut a, mut b) = (imported.clone(), p.clone()); + for v in [&mut a, &mut b] { + super::convert::normalise(v); + v.as_object_mut()?.remove(CAMERA_RAW_DESCRIPTOR); + } + (a == b).then_some(d) +} + /// Whether a Select and Mask step carries Refine Edge Brush strokes or the workspace's tool /// edits (Quick Selection, Brush, Lasso…), which no descriptor holds. pub(super) fn has_refine_strokes(p: &Value) -> bool { diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 979e6864fba..91435c2ca54 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -764,6 +764,8 @@ fn every_mapped_command_exports_and_imports_back() { "filter.sharpen.sharpen", "filter.sharpen.sharpenEdges", "filter.sharpen.sharpenMore", + // Saves back only as the descriptor it was loaded from (loaded_camera_raw_filter_steps_save_back_unchanged). + "filter.cameraRaw", ]; let unexpected: Vec<&str> = missing.iter().copied().filter(|id| !allowed.contains(id)).collect(); assert!(unexpected.is_empty(), "add round-trip cases for {unexpected:?}"); @@ -3096,8 +3098,11 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { let steps = &imp.actions[0].steps; let (id, p) = &steps[0]; assert_eq!(id, "filter.cameraRaw"); + // The recorded descriptor rides along, so Save Actions can write the step back. + let mut p = p.clone(); + assert!(p.as_object_mut().unwrap().remove("__atnDescriptor").is_some(), "{p}"); assert_eq!( - *p, + p, json!({ "temperature": 12, "tint": -4, "exposure": 0.35, "contrast": 10, "highlights": -30, "shadows": 25, "clarity": 8, "vibrance": 15, "curveSplits": [20, 50, 80], @@ -3119,6 +3124,77 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { s.execute(id, p.clone()).unwrap(); } +/// Review of #8714: a Camera Raw Filter step that was loaded saves back as the recorded step, +/// byte for byte, as it did while it was a kept Photoshop step; once edited (or when PhotoCraft +/// recorded it) Save Actions refuses it as before. The loaded step plays. +#[test] +fn loaded_camera_raw_filter_steps_save_back_unchanged() { + let recorded = desc("null") + .with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))) + .with("PrVe", D::Integer(184_549_376)) + .with("WBal", enm("WBal", "Cst ")) + .with("Ex12", D::Double(0.35)) + .with("Cr12", D::Integer(10)) + .with("Crv ", D::List([0, 0, 64, 50, 255, 255].map(D::Integer).to_vec())); + let file = one_action(vec![item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(recorded.clone()))]); + let mut s = Session::new(); + let loaded = s.execute("actions.load", json!({"data": b64(&atn::write(&file).unwrap())})).unwrap(); + assert_eq!(loaded["unsupported"], json!([]), "{loaded}"); + assert_eq!(s.actions.list[0].steps[0].0, "filter.cameraRaw"); + let saved_step = |r: &Value| { + let saved = atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap(); + saved.actions[0].items.first().map(|i| (i.event.clone(), i.descriptor.clone())) + }; + // Strict save, and the Actions panel's save (which skips what can't be written). + for skip in [false, true] { + let r = s.execute("actions.save", json!({"action": "A", "skipUnsupported": skip})).unwrap(); + assert_eq!(r["skipped"], json!([]), "{r}"); + assert_eq!(saved_step(&r), Some((AtnEvent::name("Adobe Camera Raw Filter"), Some(recorded.clone())))); + } + // It plays. + s.execute("file.new", json!({"width": 16, "height": 12})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"color": "#808080"})).unwrap(); + let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + assert!(played.get("failed").is_none(), "{played}"); + // Edited, it no longer matches what was recorded. + let original = s.actions.list[0].steps[0].1.clone(); + s.actions.list[0].steps[0].1["exposure"] = json!(1.5); + let e = s.execute("actions.save", json!({"action": "A"})).unwrap_err().to_string(); + assert!(e.contains("filter.cameraRaw"), "{e}"); + // Recorded by PhotoCraft: no descriptor to write back. + s.actions.list[0].steps[0].1 = original; + s.actions.list[0].steps[0].1.as_object_mut().unwrap().remove("__atnDescriptor"); + let r = s.execute("actions.save", json!({"action": "A", "skipUnsupported": true})).unwrap(); + assert_eq!(r["skipped"].as_array().unwrap().len(), 1, "{r}"); +} + +/// Review of #8714: a Camera Raw Filter step with a key the table doesn't map (an Upright +/// setting, a profile name, any other panel) or with no settings at all stays a Photoshop step +/// and is reported, rather than replaying without that processing. +#[test] +fn camera_raw_filter_steps_with_unknown_keys_stay_photoshop_steps() { + let upright = desc("null").with("Ex12", D::Double(0.2)).with("PerV", D::Integer(20)); + let profile = desc("null").with("Cr12", D::Integer(10)).with("LookName", D::Text(UnicodeString::new_nul("B&W 05"))); + let file = one_action(vec![ + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(upright.clone())), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(profile)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", None), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(desc("null").with("Ex12", D::Double(0.2)))), + ]); + let mut s = Session::new(); + let loaded = s.execute("actions.load", json!({"data": b64(&atn::write(&file).unwrap())})).unwrap(); + let unsupported: Vec = loaded["unsupported"].as_array().unwrap().iter().map(|u| u["step"].as_u64().unwrap()).collect(); + assert_eq!(unsupported, [0, 1, 2], "{loaded}"); + let ids: Vec<&str> = s.actions.list[0].steps.iter().map(|(id, _)| id.as_str()).collect(); + assert_eq!(ids, [PHOTOSHOP_STEP, PHOTOSHOP_STEP, PHOTOSHOP_STEP, "filter.cameraRaw"]); + // Kept, it still saves back as recorded. + let r = s.execute("actions.save", json!({"action": "A"})).unwrap(); + let saved = atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap(); + assert_eq!(saved.actions[0].items[0].descriptor, Some(upright)); +} + fn one_action(items: Vec) -> AtnFile { AtnFile { name: UnicodeString::new_nul("Saves"), From 68b869eac4dece10f078bfbc3a3d145da6c0bbaa Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 14:34:17 +0100 Subject: [PATCH 40/52] Integration: save Vibrance adjustment steps with the string class vibrance (#8858) Vibrance's adjustment class is now Photoshop's string id `vibrance`, so Set and Make steps save back with the class Photoshop runs instead of the `Vbrn` code it refuses (#8383). `Vbrn` moves to LEGACY_CLASSES, so actions saved before still load. A recorded Vibrance with non-zero temperature or tint stays a kept step and saves back unchanged. Co-authored-by: jturnbach <70334515+jturnbach@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/atn_cmds/adjustments.rs | 18 ++++- crates/engine/src/cmd/atn_cmds/events.rs | 2 +- crates/engine/src/cmd/atn_cmds/tests.rs | 67 +++++++++++++++++++ 3 files changed, 84 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/adjustments.rs b/crates/engine/src/cmd/atn_cmds/adjustments.rs index 5da802b800a..c5439864705 100644 --- a/crates/engine/src/cmd/atn_cmds/adjustments.rs +++ b/crates/engine/src/cmd/atn_cmds/adjustments.rs @@ -395,6 +395,18 @@ macro_rules! adj_fields { }; } +const VIBRANCE: &[F] = &[F("vibrance", "vibrance", Kind::Long), F("Strt", "saturation", Kind::Long)]; + +/// Vibrance. Photoshop's recording also carries `temperature` and `tint`, which our Vibrance has +/// no params for: with either one non-zero the step stays a kept Photoshop step (saved back +/// unchanged) instead of playing and saving without them. +fn vibrance_from(d: &Descriptor) -> Option { + if ["temperature", "tint"].iter().any(|k| get_num(d, k).is_some_and(|v| v != 0.0)) { + return None; + } + fields_from(d, VIBRANCE).map(Value::Object) +} + const ADJUSTMENTS: &[Adjustment] = &[ Adjustment { class: "Lvls", suffix: "levels", from: levels_from, to: levels_to }, Adjustment { class: "Crvs", suffix: "curves", from: curves_from, to: curves_to }, @@ -404,7 +416,7 @@ const ADJUSTMENTS: &[Adjustment] = &[ adj_fields!("Pstr", "posterize", &[F("Lvls", "levels", Kind::Long)]), adj_fields!("Invr", "invert", &[]), 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)]), + Adjustment { class: "vibrance", suffix: "vibrance", from: vibrance_from, to: |p| fields_to(p, VIBRANCE, desc("vibrance")) }, 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 }, adj_fields!("BanW", "blackWhite", BW), @@ -417,7 +429,9 @@ const ADJUSTMENTS: &[Adjustment] = &[ /// Photoshop (#8481): a Make whose Black & White type is `BlnW` fails ("the command Make is not /// currently available"), `BanW` runs. Import keeps accepting them so actions saved before still /// load; export never writes them. -const LEGACY_CLASSES: &[(&str, &str)] = &[("BlnW", "BanW")]; +/// `Vbrn` is a code PhotoCraft invented for Vibrance: Photoshop records the class by its string id +/// `vibrance` (#8534), and refuses the `Vbrn` code (#8383). +const LEGACY_CLASSES: &[(&str, &str)] = &[("BlnW", "BanW"), ("Vbrn", "vibrance")]; /// The adjustment with Photoshop class `c`, or the one an old PhotoCraft class stands for. pub(super) fn adjustment_by_class(c: &str) -> Option<&'static Adjustment> { diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 5723c93c598..08b998672ae 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -275,7 +275,7 @@ pub(super) const EVENTS: &[Event] = &[ adjustment_event!("Pstr", "Pstr", "posterize", "Posterize"), adjustment_event!("Invr", "Invr", "invert", "Invert"), adjustment_event!("ClrB", "ClrB", "colorBalance", "Color Balance"), - adjustment_event!("Vbrn", "Vbrn", "vibrance", "Vibrance"), + adjustment_event!("Vbrn", "vibrance", "vibrance", "Vibrance"), adjustment_event!("Exps", "Exps", "exposure", "Exposure"), // Photoshop runs Photo Filter by name only: `PhtF` is the class, not an event (#8301). adjustment_event!("", "PhtF", "photoFilter", "Photo Filter"), diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index d1634338c46..7c46b0ddd09 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -2748,6 +2748,73 @@ fn adjustment_layer_set_accepts_the_vibrance_string_class() { assert_eq!(action.steps[0], action.steps[1]); } +/// A Vibrance Set and Make as Photoshop records them (class `vibrance`) save back with that +/// class, not the `Vbrn` code Photoshop refuses (#8383); old PhotoCraft files with `Vbrn` still +/// load and now save with `vibrance` too. +#[test] +fn vibrance_adjustment_layer_steps_save_with_the_string_class() { + let set = |class: &str| { + let t = desc(class).with("temperature", long(0.0)).with("tint", long(0.0)).with("vibrance", long(28.0)).with("Strt", long(-7.0)); + desc("null").with("null", target_ref("AdjL")).with("T ", D::Descriptor(t)) + }; + let make = |class: &str| { + let t = desc(class).with("vibrance", long(10.0)).with("Strt", long(5.0)); + desc("null").with("null", class_ref("AdjL")).with("Usng", D::Descriptor(desc("AdjL").with("Type", D::Descriptor(t)))) + }; + let data = set_of( + "Vibrance", + vec![( + "A", + vec![ + item("set", "Set", Some(set("vibrance"))), + item("Mk ", "Make", Some(make("vibrance"))), + item("set", "Set", Some(set("Vbrn"))), + item("Mk ", "Make", Some(make("Vbrn"))), + ], + )], + ); + let mut s = Session::new(); + let loaded = s.execute("actions.load", json!({"data": data})).unwrap(); + assert_eq!(loaded["unsupported"], json!([]), "{loaded}"); + let steps = &s.actions.list[0].steps; + assert_eq!(steps[1], ("layer.newAdjustmentLayer.vibrance".to_string(), json!({"vibrance": 10, "saturation": 5})), "{steps:?}"); + assert_eq!((&steps[0], &steps[1]), (&steps[2], &steps[3]), "the old `Vbrn` class imports the same"); + let saved = s.execute("actions.save", json!({"set": "Vibrance"})).unwrap(); + assert_eq!(saved["skipped"], json!([])); + let bytes = photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); + let file = atn::parse(&bytes).unwrap(); + let items = &file.actions[0].items; + assert_eq!(items.len(), 4); + for pair in items.chunks(2) { + let t = get_obj(pair[0].descriptor.as_ref().unwrap(), "T ").unwrap(); + assert!(t.class_id.is("vibrance"), "Set class {:?}", t.class_id); + let ty = get_obj(pair[1].descriptor.as_ref().unwrap(), "Usng").and_then(|u| get_obj(u, "Type")).unwrap(); + assert!(ty.class_id.is("vibrance"), "Make class {:?}", ty.class_id); + } + let mut reloaded = Session::new(); + reloaded.execute("actions.load", json!({"data": saved["data"]})).unwrap(); + assert_eq!(reloaded.actions.list[0].steps, s.actions.list[0].steps); +} + +/// Our Vibrance has no `temperature` or `tint`: a recorded Vibrance Set or Make with either one +/// non-zero stays a kept Photoshop step and saves back unchanged instead of losing them. +#[test] +fn vibrance_steps_with_temperature_or_tint_save_back_unchanged() { + let t = || desc("vibrance").with("temperature", long(0.0)).with("tint", long(12.0)).with("vibrance", long(28.0)).with("Strt", long(-7.0)); + let set = desc("null").with("null", target_ref("AdjL")).with("T ", D::Descriptor(t())); + let warm = desc("vibrance").with("temperature", long(-20.0)).with("vibrance", long(5.0)); + let make = desc("null").with("null", class_ref("AdjL")).with("Usng", D::Descriptor(desc("AdjL").with("Type", D::Descriptor(warm)))); + let data = set_of("Vibrance", vec![("A", vec![item("set", "Set", Some(set.clone())), item("Mk ", "Make", Some(make.clone()))])]); + let mut s = Session::new(); + s.execute("actions.load", json!({"data": data})).unwrap(); + assert!(s.actions.list[0].steps.iter().all(|(id, _)| id == "actions.photoshopStep"), "{:?}", s.actions.list[0].steps); + let saved = s.execute("actions.save", json!({"set": "Vibrance"})).unwrap(); + let bytes = photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); + let file = atn::parse(&bytes).unwrap(); + assert_eq!(file.actions[0].items[0].descriptor, Some(set)); + assert_eq!(file.actions[0].items[1].descriptor, Some(make)); +} + /// A Free Transform recorded against an unlinked mask or an alpha channel must not export as a /// layer transform that moves the layer's pixels on replay (#7195). #[test] From 92ec412f54ae195ec8af942a19054e04ec8caaa7 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 14:36:09 +0100 Subject: [PATCH 41/52] Integration: Play with a set selected plays that set (#10459) A click on a set folder row (also how a set collapses or expands) now clears the selected action, so Play fell back to the first action of the whole list, often from another set, and Batch and Create Droplet started on it too. Example: select Resize (set Web), collapse Retouch, press Play: Retouch's first action ran instead. With a set selected, Play now plays every action of that set in order, stopping at the first that fails or pauses for a dialog (an empty set plays nothing), as the reference application plays a selected set. Batch and Create Droplet start on the selected set's first action. A click on an action row clears the selected set, so a later Delete doesn't bring the old set back as the target of New Action or Play. Co-authored-by: hectorviov <1501713+hectorviov@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/actions.rs | 81 ++++++++++++++++++---- crates/ui-egui/src/panels/actions/tests.rs | 79 +++++++++++++++++++++ 2 files changed, 146 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 5442eeff22d..e31a0141918 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -55,11 +55,56 @@ pub(crate) fn label_of(id: &str) -> String { .unwrap_or_else(|| id.to_string()) } -/// The selected action, or the first one when nothing is selected. +/// The selected action, else the first action of the selected set (Batch and Create Droplet start +/// on the panel's selection), else the first one. pub fn selected_action(app: &PhotocraftApp) -> Option<&Action> { let list = &app.session.actions.list; let idx = app.ui.actions.selected.filter(|i| *i < list.len()); - idx.and_then(|i| list.get(i)).or_else(|| list.first()) + idx.and_then(|i| list.get(i)).or_else(|| selected_set_actions(app).first().and_then(|i| list.get(*i))).or_else(|| list.first()) +} + +/// The selected set folder, if no action is selected and the set still exists. +fn selected_set(app: &PhotocraftApp) -> Option<&str> { + if app.ui.actions.selected.is_some_and(|i| i < app.session.actions.list.len()) { + return None; + } + let set = app.ui.actions.selected_set.as_deref()?; + photocraft_engine::actions_edit_cmds::set_names(&app.session).iter().any(|n| n == set).then_some(set) +} + +/// The actions of the selected set, in list order (empty when no set is selected, or it is empty). +fn selected_set_actions(app: &PhotocraftApp) -> Vec { + let Some(set) = selected_set(app) else { return Vec::new() }; + app.session.actions.list.iter().enumerate().filter(|(_, a)| a.set.as_deref() == Some(set)).map(|(i, _)| i).collect() +} + +/// What Play plays: the selected action; with a set folder selected, every action of that set in +/// order, as Photoshop plays a selected set (nothing for an empty set); else the first action. +fn playback_targets(app: &PhotocraftApp) -> Vec { + if selected_set(app).is_some() { + return selected_set_actions(app); + } + playback_selection(app).into_iter().collect() +} + +/// Play `targets` one after another, stopping at the first that fails, pauses for a dialog or +/// can't start. Returns the last result with `ran` counting the steps of all of them, or `None` +/// when there was nothing to play. +fn play_targets(app: &mut PhotocraftApp, targets: &[usize]) -> Result, String> { + let (mut last, mut ran) = (None, 0u64); + for &i in targets { + let mut v = app.run("actions.play", json!({"action": i}))?; + ran = ran.saturating_add(v.get("ran").and_then(Value::as_u64).unwrap_or(0)); + let stop = v.get("failed").is_some_and(Value::is_object) || v.get("paused").is_some_and(Value::is_object); + if let Some(o) = v.as_object_mut() { + o.insert("ran".into(), json!(ran)); + } + last = Some(v); + if stop { + break; + } + } + Ok(last) } /// Index of the playback target. Photoshop's Play button uses the first action when @@ -746,11 +791,15 @@ pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { Ok(Value::Null) } "stopRec" => app.run("actions.stop", json!({})), - "play" => playback_selection(app).map_or(Ok(Value::Null), |i| { - let v = app.run("actions.play", json!({"action": i}))?; - report_play(app, &v); - Ok(v) - }), + "play" => { + let targets = playback_targets(app); + play_targets(app, &targets).map(|v| { + if let Some(v) = &v { + report_play(app, v); + } + v.unwrap_or(Value::Null) + }) + } "delete" => { delete_selection(app); Ok(Value::Null) @@ -1043,7 +1092,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let mut set_toggled: Option = None; let mut save_set: Option = None; let max_h = (ui.available_height() - 38.0).max(0.0); - let mut play_idx = None; + let mut play_idx: Option> = None; let mut moved = None; let recording_row = recording.and_then(|(_, i)| rows.get(i).map(|r| (i, r.steps.len()))); let reveal = recording_row.filter(|row| app.ui.actions.reveal_recording != Some(*row)); @@ -1144,9 +1193,12 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if resp.clicked() { app.ui.actions.selected = Some(i); app.ui.actions.selected_step = None; + // The action replaces the set as the selection, so a later deselect (Delete) + // doesn't bring back a set the user moved away from. + app.ui.actions.selected_set = None; if button_mode { if !resp.double_clicked() { - play_idx = Some(i); + play_idx = Some(vec![i]); } } else if resp.interact_pointer_pos().is_some_and(|p| p.x < x0 + 20.0) { if app.ui.actions.expanded.len() <= i { @@ -1163,7 +1215,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if resp.interact_pointer_pos().is_some_and(|p| name_rect.expand2(vec2(4.0, 13.0)).contains(p)) { app.ui.actions.renaming = Some(RenameAction { index: i, text: name.clone(), focused: false }); } else { - play_idx = Some(i); + play_idx = Some(vec![i]); } } if expanded { @@ -1227,7 +1279,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let play = crate::icons::button(ui, "play", 24.0, false, tl!("Play selection")); play.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Play selection"))); if play.clicked() { - play_idx = playback_selection(app); + play_idx = Some(playback_targets(app)); } if crate::icons::button(ui, "folder", 24.0, false, tl!("Create new set")).clicked() && let Err(e) = new_set_dialog(app) @@ -1253,9 +1305,10 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { app.ui.actions.button_mode = !app.ui.actions.button_mode; } }); - if let Some(i) = play_idx { - match app.run("actions.play", json!({"action": i})) { - Ok(v) => report_play(app, &v), + if let Some(targets) = play_idx { + match play_targets(app, &targets) { + Ok(Some(v)) => report_play(app, &v), + Ok(None) => {} Err(e) => { let template = "Action playback failed: {error}"; app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e)]); diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index b35ba653c07..7564eed7a23 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -655,6 +655,85 @@ fn set_folders_group_actions_and_collapse() { assert!(h.query_by_label("Sharpen").is_some()); } +/// Two sets, Web listed first: "Resize" (Web) adds a layer "w", "Sharpen" and "Soften" (Retouch) +/// add "r1" and "r2". +fn two_set_panel() -> egui_kittest::Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + for (name, set, layer) in [("Resize", "Web", "w"), ("Sharpen", "Retouch", "r1"), ("Soften", "Retouch", "r2")] { + let mut a = Action::new(name, vec![("layer.new.layer".into(), json!({"name": layer}))]); + a.set = Some(set.into()); + app.session.actions.list.push(a); + } + let mut h = egui_kittest::Harness::builder().with_size(vec2(360.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(2); + h +} + +fn layer_names(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().doc.walk().iter().map(|(_, _, l)| l.name.clone()).filter(|n| n != "Background").collect() +} + +/// #10459 fix-up: a click on a set folder (also how a set collapses) selects the set, and Play +/// then plays every action of that set in order, as Photoshop plays a selected set, not the first +/// action of the whole list. +#[test] +fn play_with_a_set_folder_selected_plays_that_sets_actions() { + use egui_kittest::kittest::Queryable; + let mut h = two_set_panel(); + h.get_by_label("Resize").click(); + h.run_steps(2); + // Collapse and expand Retouch: the set stays selected. + h.get_by_label("Retouch").click(); + h.run_steps(2); + h.get_by_label("Retouch").click(); + h.run_steps(2); + h.get_by_label("Play selection").click(); + h.run_steps(2); + let mut names = layer_names(h.state()); + names.sort(); + assert_eq!(names, ["r1", "r2"], "the Retouch set played, not Resize"); + assert!(!h.state().ui.status_error, "{}", h.state().ui.status); + // Batch and Create Droplet start on the selected set too. + assert_eq!(selected_action(h.state()).map(|a| a.name.as_str()), Some("Sharpen")); +} + +/// #10459 fix-up: Play with an empty set selected plays nothing. +#[test] +fn play_with_an_empty_set_selected_plays_nothing() { + use egui_kittest::kittest::Queryable; + let mut h = two_set_panel(); + h.state_mut().run("actions.newSet", json!({"name": "Print"})).unwrap(); + h.run_steps(2); + h.get_by_label("Print").click(); + h.run_steps(2); + assert_eq!(h.state().ui.actions.selected_set.as_deref(), Some("Print")); + h.get_by_label("Play selection").click(); + h.run_steps(2); + assert!(layer_names(h.state()).is_empty(), "{:?}", layer_names(h.state())); +} + +/// #10459 fix-up: the common case is unchanged: a selected action plays alone, also after a set +/// folder was selected before it, and a later Delete doesn't bring that set back. +#[test] +fn play_with_an_action_selected_plays_only_that_action() { + use egui_kittest::kittest::Queryable; + let mut h = two_set_panel(); + h.get_by_label("Retouch").click(); + h.run_steps(2); + h.get_by_label("Retouch").click(); + h.run_steps(2); + h.get_by_label("Sharpen").click(); + h.run_steps(2); + h.get_by_label("Play selection").click(); + h.run_steps(2); + assert_eq!(layer_names(h.state()), ["r1"]); + assert_eq!(selected_action(h.state()).map(|a| a.name.as_str()), Some("Sharpen")); + h.get_by_label("Delete").click(); + h.run_steps(2); + assert_eq!((h.state().ui.actions.selected, h.state().ui.actions.selected_set.as_deref()), (None, None)); +} + /// #7535: the folder button (and the panel menu's New Set…) names an empty set, shown as a folder /// row with no actions; New Action then records into it, as into any selected set. #[test] From adc4e45fe732c86b09f757407b5ec1ebdb3f99fe Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 14:36:29 +0100 Subject: [PATCH 42/52] Integration: look up a recorded pattern id by id alone before the name (#7642) `resolve_or_named` resolved the recorded `Idnt` with `resolve`, which also matches by name in each collection. So a document pattern named like the id beat the library pattern with that id, and a foreign id equal to some pattern's name (`Idnt "Red"`, `Nm "Blue"`) played "Red" and never tried the recorded name. The id is now looked up by id only (document, then library), then the name decides. A library pattern found by id whose pixels can't be read reports that instead of falling back, main's paintable check still runs, and a pattern installed neither way is named in the error (`no pattern "My Wood" (id "...")`) instead of only its UUID. Co-authored-by: Silvertree2010 <133535268+Silvertree2010@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/atn_cmds/tests.rs | 72 ++++++++++++++++++++++ crates/engine/src/cmd/pattern_cmds.rs | 37 +++++++---- crates/engine/src/cmd/pattern_fill_cmds.rs | 4 +- 3 files changed, 99 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index f084b3c8f13..bad3d7dd1a1 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -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})), @@ -3176,6 +3177,27 @@ fn long_names_are_clipped_instead_of_copied_into_every_diagnostic() { 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 { + 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] @@ -3211,3 +3233,53 @@ fn pattern_fill_prefers_an_installed_id_over_a_colliding_name() { 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}"); +} diff --git a/crates/engine/src/cmd/pattern_cmds.rs b/crates/engine/src/cmd/pattern_cmds.rs index e9fdadd38ad..c5484f4b4ab 100644 --- a/crates/engine/src/cmd/pattern_cmds.rs +++ b/crates/engine/src/cmd/pattern_cmds.rs @@ -182,19 +182,32 @@ pub fn resolve(s: &Session, key: &str) -> Option { pub(crate) fn resolve_param(s: &Session, cmd: &str, p: &Value) -> Result { let key = p.get("pattern").and_then(Value::as_str).unwrap_or(""); - if let Some(pat) = resolve_or_named(s, key, p) { - 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)) } -/// [`resolve`]s `key`, else the optional `patternName` of `p`: an imported action's pattern -/// recorded with both an id and a name, whose id may not be installed here. -pub(crate) fn resolve_or_named(s: &Session, key: &str, p: &Value) -> Option { - resolve(s, key).or_else(|| p.get("patternName").and_then(Value::as_str).filter(|n| !n.is_empty()).and_then(|n| resolve(s, n))) +/// 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 { + 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)"), + }), + } } /// `pat`, or the reason it would paint nothing: a pattern too large for the compositor renders as @@ -594,7 +607,7 @@ pub fn specs() -> Vec { label: "Pattern…", menu: &["Layer", "New Fill Layer"], shortcut: None, - params: r##"{"pattern":id|name?=first library pattern,"patternName":name? (used when `pattern` is not found),"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, diff --git a/crates/engine/src/cmd/pattern_fill_cmds.rs b/crates/engine/src/cmd/pattern_fill_cmds.rs index d9169bf204f..8372fed5303 100644 --- a/crates/engine/src/cmd/pattern_fill_cmds.rs +++ b/crates/engine/src/cmd/pattern_fill_cmds.rs @@ -37,7 +37,7 @@ fn edited(s: &Session, base: &Fill, p: &Value) -> Result<(Fill, Option) 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_or_named(s, key, p).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 { 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?,"patternName":name? (used when `pattern` is not found),"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, From af59f65b826daa3e45ad04319826498af1d6faf8 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 14:43:03 +0100 Subject: [PATCH 43/52] Integration: keep windows-1252 symbols in .atn step names (#8327) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The code-page guess counted only letters and typographic marks as common text in single-byte pages, so a Windows step name with no Unicode copy and a Latin-1 symbol read better as Mac Roman, whose letters sit on those bytes: "Logo ®" showed as "Logo Æ", "Größe »" as "Grˆfle ª" (main showed them right), and Save Actions wrote that text back. When the guess lands on Mac Roman, weigh it against windows-1252 once more with common Latin-1 symbols (© ® ° § « » ± ½ …) counted and the letters windows-1252 has only at 0x80-0x9F left out. Mac Roman keeps the names only when it still reads better; a tie goes to windows-1252, confident with a Latin hint and flagged uncertain otherwise. Mac Roman "Größe", "Ändern", "Contrôle", "Arrière-plan" and the corpus French sets still read as Mac Roman. Co-authored-by: regexer <3689390+regexer@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/atn_cmds/tests.rs | 24 ++++++++ crates/psd/src/atn.rs | 18 ++++++ crates/psd/src/codepage.rs | 74 +++++++++++++++++++++++-- 3 files changed, 111 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 937926e9d3b..cdbdce110da 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -3212,6 +3212,30 @@ fn load_decodes_legacy_step_names() { assert!(played["failed"]["error"].as_str().unwrap().contains("可选颜色"), "{played}"); } +#[test] +fn load_keeps_windows_1252_symbols() { + // Windows Photoshop step names with no Unicode copy: ® and » are letters in Mac Roman, which + // must not win ("Logo Æ", "Grˆfle ª"). Save Actions writes the names back as that text. + let steps = vec![ + AtnItem { dictionary: b"Logo \xae".to_vec(), ..item("syntheticFill", "", None) }, + AtnItem { dictionary: b"Gr\xf6\xdfe \xbb".to_vec(), ..item("syntheticFill", "", None) }, + ]; + let file = AtnFile { + name: UnicodeString::new_nul("Größe ändern"), + actions: vec![AtnAction { name: UnicodeString::new_nul("Logo"), items: steps, ..Default::default() }], + ..Default::default() + }; + let mut s = Session::new(); + let r = s.execute("actions.load", json!({"data": b64(&atn::write(&file).unwrap())})).unwrap(); + assert_eq!(r["encoding"], "windows-1252", "{r}"); + assert_eq!(r["unsupported"][0]["name"], "Logo ®", "{r}"); + assert_eq!(r["unsupported"][1]["name"], "Größe »", "{r}"); + let saved = s.execute("actions.save", json!({"set": "Größe ändern"})).unwrap(); + let saved = atn::parse(&photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap()).unwrap(); + let names: Vec = saved.actions[0].items.iter().map(|i| saved.item_label(i)).collect(); + assert_eq!(names, ["Logo ®", "Größe »"]); +} + #[test] fn load_encoding_override() { let mut s = Session::new(); diff --git a/crates/psd/src/atn.rs b/crates/psd/src/atn.rs index ef620ad1f04..bce1e5f09f9 100644 --- a/crates/psd/src/atn.rs +++ b/crates/psd/src/atn.rs @@ -642,6 +642,24 @@ mod tests { assert!(f.warnings.is_empty(), "{:?}", f.warnings); } + #[test] + fn latin1_symbol_names_read_as_windows_1252() { + // Windows Photoshop "Logo ®" and "Größe »" with no Unicode copy: Mac Roman reads these + // bytes as letters ("Logo Æ", "Grˆfle ª"), but they are windows-1252, as before #6743. + let f = parse(&one_action("Set 1", "Action 1", vec![bare(AtnEvent::name("x"), b"Logo \xae")])).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("windows-1252")); + assert_eq!(labels(&f), ["Logo ®"]); + let f = parse(&one_action("Größe ändern", "Aktion", vec![bare(AtnEvent::name("x"), b"Gr\xf6\xdfe \xbb")])).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("windows-1252")); + assert_eq!(labels(&f), ["Größe »"]); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + // Mac Roman bytes that windows-1252 reads as controls or rare letters stay Mac Roman. + let f = + parse(&one_action("Définir", "Action 1", vec![bare(AtnEvent::name("x"), b"Gr\x9a\xa7e"), bare(AtnEvent::name("y"), b"Arri\x8fre-plan")])).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("macintosh")); + assert_eq!(labels(&f), ["Größe", "Arrière-plan"]); + } + #[test] fn known_names_alone_never_warn() { // Nothing decodes to the Unicode name, but nothing is shown from the bytes either. diff --git a/crates/psd/src/codepage.rs b/crates/psd/src/codepage.rs index 3918cd1879d..75e2ea7ec4a 100644 --- a/crates/psd/src/codepage.rs +++ b/crates/psd/src/codepage.rs @@ -16,6 +16,9 @@ //! fine): kana → Shift_JIS; Hangul → EUC-KR; Cyrillic → windows-1251; Han → GBK, then //! Big5, then Shift_JIS; Latin letters → windows-1252, then Mac Roman. //! 4. Still tied: windows-1252, flagged [`Guess::uncertain`]. +//! 5. Mac Roman must also beat windows-1252 when Latin-1's symbols (© ® ° § « » ± ½…) count +//! as common text, as Mac Roman's letters sit on those bytes (1252 "Logo ®" is Mac Roman +//! "Logo Æ"). Otherwise the names are windows-1252, with step 3's hint and step 4's warning. //! //! Only the first [`GUESS_SAMPLE`] bytes of names are examined. @@ -89,12 +92,32 @@ pub(crate) fn guess(legacy: &[&[u8]], hint: &str) -> Guess { best.push(enc); } } - match best.as_slice() { + let picked = match best.as_slice() { [only] => Guess { encoding: only, uncertain: false }, tied => match hinted(hint).iter().find(|enc| tied.contains(enc)) { Some(enc) => Guess { encoding: enc, uncertain: false }, None => Guess { encoding: WINDOWS_1252, uncertain: true }, }, + }; + if picked.encoding != MACINTOSH { + return picked; + } + // windows-1252 maps every byte, so it is always a survivor here. + let latin = |enc| { + sample.iter().fold((0u64, 0u64), |(c, h), (name, _)| { + let (nc, nh) = single_byte_score(enc, name, is_latin_common); + (c.saturating_add(nc), h.saturating_add(nh)) + }) + }; + let (windows, mac) = (latin(WINDOWS_1252), latin(MACINTOSH)); + let lhs = u128::from(windows.0) * u128::from(mac.1.max(1)); + let rhs = u128::from(mac.0) * u128::from(windows.1.max(1)); + if lhs < rhs { + picked + } else if lhs > rhs || hinted(hint).contains(&WINDOWS_1252) { + Guess { encoding: WINDOWS_1252, uncertain: false } + } else { + Guess { encoding: WINDOWS_1252, uncertain: true } } } @@ -171,10 +194,9 @@ fn decodes_cleanly(enc: &'static Encoding, bytes: &[u8], truncated: bool) -> boo /// many non-ASCII bytes it has. fn score(enc: &'static Encoding, name: &[u8]) -> (u64, u64) { if enc == WINDOWS_1252 || enc == WINDOWS_1251 || enc == MACINTOSH { - // One byte is one character, and a non-ASCII byte is a non-ASCII character. Letters and - // typographic punctuation are common, as the double-byte pages' punctuation rows are. - let common = |ch: char| ch.is_alphabetic() || TYPOGRAPHIC.contains(&ch); - return decode(name, enc).chars().filter(|c| !c.is_ascii()).fold((0, 0), |(c, h), ch| (c + u64::from(common(ch)), h + 1)); + // Letters and typographic punctuation are common, as the double-byte pages' punctuation + // rows are. + return single_byte_score(enc, name, |ch| ch.is_alphabetic() || TYPOGRAPHIC.contains(&ch)); } let (mut common, mut high) = (0u64, 0u64); let mut i = 0usize; @@ -206,6 +228,23 @@ fn score(enc: &'static Encoding, name: &[u8]) -> (u64, u64) { (common, high) } +/// [`score`] for a single-byte page, where one byte is one character and a non-ASCII byte is a +/// non-ASCII character: `common` decides which of them count. +fn single_byte_score(enc: &'static Encoding, name: &[u8], common: impl Fn(char) -> bool) -> (u64, u64) { + decode(name, enc).chars().filter(|c| !c.is_ascii()).fold((0, 0), |(c, h), ch| (c.saturating_add(u64::from(common(ch))), h.saturating_add(1))) +} + +/// Whether `ch` is common in Western names, for weighing windows-1252 against Mac Roman: letters +/// (but not those windows-1252 has only at 0x80–0x9F, where Mac Roman keeps its accented +/// lowercase: Mac "Größe" is 1252 "Grš§e"), typographic punctuation and [`LATIN_SYMBOLS`]. +fn is_latin_common(ch: char) -> bool { + (ch.is_alphabetic() && !['Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ', 'ƒ', 'ˆ'].contains(&ch)) || TYPOGRAPHIC.contains(&ch) || LATIN_SYMBOLS.contains(&ch) +} + +/// Latin-1 symbols people type in names (windows-1252 0xA1–0xF7). Not € or ™: windows-1252 has +/// them at 0x80 and 0x99, Mac Roman's Ä and ô. +const LATIN_SYMBOLS: [char; 20] = ['¡', '¢', '£', '¥', '§', '©', '«', '®', '°', '±', '²', '³', '¶', '·', '¹', '»', '¼', '½', '¾', '¿']; + /// Quotes, dashes, ellipsis and bullet: windows-1252 and windows-1251 share them at 0x82–0x97; /// Mac Roman has them too. const TYPOGRAPHIC: [char; 10] = ['‘', '’', '‚', '“', '”', '„', '–', '—', '…', '•']; @@ -357,6 +396,31 @@ mod tests { assert!(!reads_as_common("Weiß".as_bytes(), MACINTOSH)); } + #[test] + fn latin1_symbols_read_as_1252_not_mac_roman() { + // Mac Roman has letters where windows-1252 has © ® « » §: 1252 "Logo ®" is Mac Roman + // "Logo Æ", "Größe »" is "Grˆfle ª". Latin-1 (what a code-page-blind reader shows) wins. + let logo: &[&[u8]] = &[b"Logo \xae"]; + assert_eq!(guess(logo, "Set 1"), Guess { encoding: WINDOWS_1252, uncertain: true }); + assert_eq!(guess(logo, "Größe ändern"), Guess { encoding: WINDOWS_1252, uncertain: false }); + assert_eq!(decode(logo[0], WINDOWS_1252), "Logo ®"); + for words in [&["Größe »"][..], &["Contraste « auto »", "§ 3 Größe", "½ Größe", "Teinte ¾ ©"]] { + let g = guess_words(WINDOWS_1252, words, "Größe ändern"); + assert_eq!(g, Guess { encoding: WINDOWS_1252, uncertain: false }, "{words:?}"); + assert_eq!(guess_words(WINDOWS_1252, words, "Set 1").encoding, WINDOWS_1252, "{words:?}"); + } + } + + #[test] + fn mac_roman_letters_still_read_as_mac_roman() { + // Mac Roman "Größe" is 1252 "Grš§e", "Ändern" "€ndern", "Contrôle" "Contr™le": Mac Roman + // still wins once § counts as common text in windows-1252. + for word in ["Größe", "Ändern", "Contrôle"] { + let g = guess_words(MACINTOSH, &[word], "Définir l’arrière-plan"); + assert_eq!(g, Guess { encoding: MACINTOSH, uncertain: false }, "{word}"); + } + } + #[test] fn latin_hint_reads_mac_roman_when_1252_does_not_fit() { // Mac Roman "Arrière-plan": è is 0x8F, a control character in windows-1252. From a89b7cc4a7555f828304b00d1a440b1db325ec50 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 14:54:25 +0100 Subject: [PATCH 44/52] Integration: set playback continues after a step dialog; the triangle only collapses (#10459) Three gaps in the set selection the fix-up added: - Play on a set whose action paused at a step dialog dropped the rest of the set after OK. The pause now carries the remaining actions (also across a second dialog of the same action), and OK plays them under the same gate. Cancel still stops the whole set. - A collapse or expand selected the set and cleared the action, so Play then ran a whole other set. As on action rows, the triangle's column now only collapses or expands, and the rest of the folder row selects the set. - Selecting a step (or an action through Load, Insert Stop, a drag or recording) kept an old selected set, which came back after Delete. Every action selection now clears it. Co-authored-by: hectorviov <1501713+hectorviov@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/actions.rs | 128 ++++++++++++++------- crates/ui-egui/src/panels/actions/tests.rs | 125 ++++++++++++++++++-- 2 files changed, 201 insertions(+), 52 deletions(-) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index e31a0141918..c0d816853c8 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -38,6 +38,16 @@ pub struct ActionsUi { renaming: Option, } +impl ActionsUi { + /// Select an action (and one of its steps): it replaces a selected set, so a later deselect + /// (Delete, a removed row) doesn't bring back a set the user moved away from. + fn select(&mut self, action: usize, step: Option) { + self.selected = Some(action); + self.selected_step = step; + self.selected_set = None; + } +} + #[derive(Clone, Debug, PartialEq)] struct RenameAction { index: usize, @@ -87,20 +97,30 @@ fn playback_targets(app: &PhotocraftApp) -> Vec { playback_selection(app).into_iter().collect() } -/// Play `targets` one after another, stopping at the first that fails, pauses for a dialog or -/// can't start. Returns the last result with `ran` counting the steps of all of them, or `None` -/// when there was nothing to play. +/// Play `targets` one after another, stopping at the first that fails or can't start. One that +/// pauses for a step dialog hands the rest to that dialog, which plays them after its OK (Cancel +/// stops them all, as it stops one action). Returns the last result with `ran` counting the steps +/// of all of them, or `None` when there was nothing to play. fn play_targets(app: &mut PhotocraftApp, targets: &[usize]) -> Result, String> { let (mut last, mut ran) = (None, 0u64); - for &i in targets { + for (n, &i) in targets.iter().enumerate() { let mut v = app.run("actions.play", json!({"action": i}))?; ran = ran.saturating_add(v.get("ran").and_then(Value::as_u64).unwrap_or(0)); - let stop = v.get("failed").is_some_and(Value::is_object) || v.get("paused").is_some_and(Value::is_object); + let failed = v.get("failed").is_some_and(Value::is_object); + let paused = v.get("paused").filter(|p| p.is_object()).and_then(|p| p.get("dialog")).and_then(Value::as_u64); if let Some(o) = v.as_object_mut() { o.insert("ran".into(), json!(ran)); } last = Some(v); - if stop { + if let Some(dialog) = paused.filter(|_| !failed) { + let rest = targets.get(n + 1..).unwrap_or_default().to_vec(); + let token = app.ui.dialog_mut(dialog).and_then(|d| d.fields.get(RESUME)).and_then(Value::as_u64); + if let Some(entry) = token.and_then(|t| app.paused_playbacks.paused.get_mut(&t)) { + entry.then = rest; + } + break; + } + if failed { break; } } @@ -322,13 +342,12 @@ fn begin_recording(app: &mut PhotocraftApp, append: bool) { }; let Ok(v) = app.run("actions.record", params) else { return }; let Some(i) = v.get("index").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()) else { return }; - app.ui.actions.selected = Some(i); - app.ui.actions.selected_step = None; + app.ui.actions.select(i, None); if app.ui.actions.expanded.len() <= i { app.ui.actions.expanded.resize(i + 1, false); } app.ui.actions.expanded[i] = true; - // Its set too: a click that selected the set's folder row may have collapsed it. + // Its set too, in case its folder is collapsed. if let Some(set) = app.session.actions.list.get(i).and_then(|a| a.set.as_ref()) { app.ui.actions.collapsed_sets.retain(|c| c != set); } @@ -462,8 +481,7 @@ pub fn load_bytes(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Result, + /// The actions still to play after this one, when Play started a whole set. + then: Vec, } /// The paused playbacks, by the token their dialog carries. The dialog's fields hold only the @@ -682,7 +701,7 @@ pub(crate) struct PausedPlaybacks { impl PausedPlaybacks { fn pause(&mut self, action: String, from: usize, gate: Option) -> u64 { self.last = self.last.wrapping_add(1); - self.paused.insert(self.last, PausedPlayback { action, from, gate, record: None }); + self.paused.insert(self.last, PausedPlayback { action, from, gate, record: None, then: Vec::new() }); self.last } @@ -715,7 +734,31 @@ pub fn resume(app: &mut PhotocraftApp, fields: &serde_json::Map) let params = json!({"action": paused.action, "from": paused.from}); let saved = app.session.authorize; app.session.authorize = paused.gate.or(saved); - let played = play_owned(app, ¶ms, owner); + let mut played = play_owned(app, ¶ms, owner); + // Paused again at a later dialog of the same action: that dialog carries the rest of the set. + if let Ok(v) = &played + && let Some(dialog) = v.get("paused").and_then(|p| p.get("dialog")).and_then(Value::as_u64) + && let Some(token) = app.ui.dialog_mut(dialog).and_then(|d| d.fields.get(RESUME)).and_then(Value::as_u64) + && let Some(entry) = app.paused_playbacks.paused.get_mut(&token) + { + entry.then = paused.then.clone(); + } + // The rest of a set Play started: under the same gate, and only if this action finished. + if let Ok(v) = &played + && !paused.then.is_empty() + && v.get("failed").is_none() + && v.get("paused").is_none() + { + let ran = v.get("ran").and_then(Value::as_u64).unwrap_or(0); + played = play_targets(app, &paused.then).map(|rest| { + let mut rest = rest.unwrap_or(Value::Null); + let total = ran.saturating_add(rest.get("ran").and_then(Value::as_u64).unwrap_or(0)); + if let Some(o) = rest.as_object_mut() { + o.insert("ran".into(), json!(total)); + } + rest + }); + } app.session.authorize = saved; match played { Ok(v) => { @@ -849,16 +892,14 @@ fn move_row(app: &mut PhotocraftApp, source: DragRow, to: usize) { return; } if source.step.is_some() { - app.ui.actions.selected = Some(source.action); - app.ui.actions.selected_step = Some(to); + app.ui.actions.select(source.action, Some(to)); } else { app.ui.actions.expanded.resize(app.session.actions.list.len(), false); if source.action < app.ui.actions.expanded.len() && to < app.ui.actions.expanded.len() { let expanded = app.ui.actions.expanded.remove(source.action); app.ui.actions.expanded.insert(to, expanded); } - app.ui.actions.selected = Some(to); - app.ui.actions.selected_step = None; + app.ui.actions.select(to, None); // Dropped among another set's actions: the action joins that set (the row above wins). let list = &app.session.actions.list; let neighbour = to.checked_sub(1).and_then(|j| list.get(j)).or_else(|| list.get(to + 1)).and_then(|a| a.set.clone()); @@ -953,7 +994,10 @@ fn display_order(rows: &[Row]) -> Vec { } struct SetHeaderResult { + /// A click on the disclosure triangle: collapse or expand, the selection stays. toggled: bool, + /// A click on the rest of the row: select the set. + picked: bool, save: bool, } @@ -982,7 +1026,10 @@ fn draw_set_header(ui: &mut egui::Ui, set: &str, count: u64, collapsed: bool, se ui.painter().text(pos2(rect.left() + 44.0, rect.center().y), Align2::LEFT_CENTER, set, egui::FontId::proportional(12.0), tokens.text); let summary = crate::i18n::trn(crate::i18n::current(), count, "{n} action", "{n} actions"); ui.painter().text(pos2(rect.right() - 8.0, rect.center().y), Align2::RIGHT_CENTER, summary, egui::FontId::proportional(11.0), tokens.text_faint); - let toggled = response.clicked(); + // As on an action row, the triangle's column collapses or expands and the rest of the row + // selects; neither does the other's job. + let toggled = response.clicked() && response.interact_pointer_pos().is_some_and(|p| p.x < rect.left() + 20.0); + let picked = response.clicked() && !toggled; let mut save = false; response.context_menu(|ui| { if ui.button(tl!("Save Set…")).clicked() { @@ -990,19 +1037,19 @@ fn draw_set_header(ui: &mut egui::Ui, set: &str, count: u64, collapsed: bool, se ui.close(); } }); - SetHeaderResult { toggled, save } + SetHeaderResult { toggled, picked, save } } /// The sets New Set made that hold no action yet: empty folder rows after the rest. Returns the -/// set whose row was clicked and the set whose Save Set… was chosen. -fn draw_empty_sets(app: &PhotocraftApp, ui: &mut egui::Ui, rows: &[Row], t: &Tokens) -> (Option, Option) { +/// set whose row was clicked (and whether on its triangle) and the set whose Save Set… was chosen. +fn draw_empty_sets(app: &PhotocraftApp, ui: &mut egui::Ui, rows: &[Row], t: &Tokens) -> (Option<(String, bool)>, Option) { let (mut clicked, mut save) = (None, None); for set in app.session.actions.sets.iter().filter(|set| !rows.iter().any(|r| r.set.as_ref() == Some(*set))) { let selected = app.ui.actions.selected.is_none() && app.ui.actions.selected_set.as_ref() == Some(set); let collapsed = app.ui.actions.collapsed_sets.contains(set); let result = draw_set_header(ui, set, 0, collapsed, selected, t); - if result.toggled { - clicked = Some(set.clone()); + if result.toggled || result.picked { + clicked = Some((set.clone(), result.toggled)); } if result.save { save = Some(set.clone()); @@ -1089,7 +1136,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let mut renamed = None; let mut toggled = None; let mut dialog_toggled = None; - let mut set_toggled: Option = None; + let mut set_toggled: Option<(String, bool)> = None; let mut save_set: Option = None; let max_h = (ui.available_height() - 38.0).max(0.0); let mut play_idx: Option> = None; @@ -1120,8 +1167,8 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let count = rows.iter().filter(|r| r.set.as_deref() == Some(set)).count() as u64; let selected = app.ui.actions.selected.is_none() && app.ui.actions.selected_set.as_deref() == Some(set); let result = draw_set_header(ui, set, count, collapsed, selected, &t); - if result.toggled { - set_toggled = Some(set.to_string()); + if result.toggled || result.picked { + set_toggled = Some((set.to_string(), result.toggled)); } if result.save { save_set = Some(set.to_string()); @@ -1191,11 +1238,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ui.painter().circle_filled(pos2(rect.right() - 64.0, rect.center().y), 4.0, Color32::from_rgb(230, 60, 60)); } if resp.clicked() { - app.ui.actions.selected = Some(i); - app.ui.actions.selected_step = None; - // The action replaces the set as the selection, so a later deselect (Delete) - // doesn't bring back a set the user moved away from. - app.ui.actions.selected_set = None; + app.ui.actions.select(i, None); if button_mode { if !resp.double_clicked() { play_idx = Some(vec![i]); @@ -1236,17 +1279,21 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if let Some((action, step)) = dialog_toggled { let _ = app.run("actions.dialog", json!({"action": action, "step": step})); } - if let Some(set) = set_toggled { - // A click on a set's folder row also selects the set, for New Action. - app.ui.actions.selected = None; - app.ui.actions.selected_step = None; - app.ui.actions.selected_set = Some(set.clone()); - match app.ui.actions.collapsed_sets.iter().position(|c| *c == set) { + match set_toggled { + // The disclosure triangle collapses or expands the set and leaves the selection alone. + Some((set, true)) => match app.ui.actions.collapsed_sets.iter().position(|c| *c == set) { Some(i) => { app.ui.actions.collapsed_sets.remove(i); } None => app.ui.actions.collapsed_sets.push(set), + }, + // The rest of the folder row selects the set, for New Action and Play. + Some((set, false)) => { + app.ui.actions.selected = None; + app.ui.actions.selected_step = None; + app.ui.actions.selected_set = Some(set); } + None => {} } if let Some(set) = save_set && let Err(e) = save_dialog(app, Some(set)) @@ -1371,8 +1418,7 @@ fn draw_step_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, context: &StepRows } else if dialog.clicked() { events.dialog_toggled = Some((context.action, step)); } else if response.clicked() { - app.ui.actions.selected = Some(context.action); - app.ui.actions.selected_step = Some(step); + app.ui.actions.select(context.action, Some(step)); } } events diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index 7564eed7a23..b4ad34b97b5 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -643,14 +643,12 @@ fn set_folders_group_actions_and_collapse() { assert!(h.get_by_label("Sharpen").rect().top() > folder.top()); assert!(h.get_by_label("Soften").rect().top() > h.get_by_label("Sharpen").rect().top()); assert_eq!(display_order(&[]), Vec::::new()); - // Clicking the folder collapses it; its actions disappear and the state is remembered. - h.get_by_label("Retouch").click(); - h.run_steps(3); + // Clicking the folder's triangle collapses it; its actions disappear and the state is remembered. + click_set_triangle(&mut h, "Retouch"); assert_eq!(h.state().ui.actions.collapsed_sets, ["Retouch"]); assert!(h.query_by_label("Sharpen").is_none()); assert!(h.query_by_label("Loose").is_some()); - h.get_by_label("Retouch").click(); - h.run_steps(3); + click_set_triangle(&mut h, "Retouch"); assert!(h.state().ui.actions.collapsed_sets.is_empty()); assert!(h.query_by_label("Sharpen").is_some()); } @@ -674,7 +672,19 @@ fn layer_names(app: &PhotocraftApp) -> Vec { app.session.active().unwrap().doc.walk().iter().map(|(_, _, l)| l.name.clone()).filter(|n| n != "Background").collect() } -/// #10459 fix-up: a click on a set folder (also how a set collapses) selects the set, and Play +/// Click a set folder row's disclosure triangle (a plain `click()` lands on the row's middle, +/// which selects the set). +fn click_set_triangle(h: &mut egui_kittest::Harness<'_, PhotocraftApp>, set: &str) { + use egui_kittest::kittest::Queryable; + let pos = h.get_by_label(set).rect().left_center() + vec2(12.0, 0.0); + h.event(egui::Event::PointerMoved(pos)); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + } + h.run_steps(2); +} + +/// #10459 fix-up: a click on a set folder row (not its triangle) selects the set, and Play /// then plays every action of that set in order, as Photoshop plays a selected set, not the first /// action of the whole list. #[test] @@ -683,11 +693,9 @@ fn play_with_a_set_folder_selected_plays_that_sets_actions() { let mut h = two_set_panel(); h.get_by_label("Resize").click(); h.run_steps(2); - // Collapse and expand Retouch: the set stays selected. - h.get_by_label("Retouch").click(); - h.run_steps(2); h.get_by_label("Retouch").click(); h.run_steps(2); + assert!(h.state().ui.actions.collapsed_sets.is_empty(), "a click on the row selects, it doesn't collapse"); h.get_by_label("Play selection").click(); h.run_steps(2); let mut names = layer_names(h.state()); @@ -734,6 +742,100 @@ fn play_with_an_action_selected_plays_only_that_action() { assert_eq!((h.state().ui.actions.selected, h.state().ui.actions.selected_set.as_deref()), (None, None)); } +/// #10459 fix-up: the disclosure triangle collapses and expands a set and leaves the selection +/// alone, so Play still plays the selected action, not the set that was looked into. +#[test] +fn collapsing_a_set_keeps_the_selected_action_for_play() { + use egui_kittest::kittest::Queryable; + let mut h = two_set_panel(); + h.get_by_label("Resize").click(); + h.run_steps(2); + click_set_triangle(&mut h, "Retouch"); + assert_eq!(h.state().ui.actions.collapsed_sets, ["Retouch"]); + assert!(h.query_by_label("Sharpen").is_none()); + click_set_triangle(&mut h, "Retouch"); + assert!(h.state().ui.actions.collapsed_sets.is_empty()); + assert_eq!((h.state().ui.actions.selected, h.state().ui.actions.selected_set.as_deref()), (Some(0), None)); + h.get_by_label("Play selection").click(); + h.run_steps(2); + assert_eq!(layer_names(h.state()), ["w"]); +} + +/// #10459 fix-up: selecting a step (or any other way an action becomes the selection) drops a +/// selected set, so deleting that step doesn't bring the set back as Play's target. +#[test] +fn a_selected_step_replaces_the_selected_set() { + use egui_kittest::kittest::Queryable; + let mut h = two_set_panel(); + h.state_mut().session.actions.list[0].steps.push(("select.all".into(), json!({}))); + h.state_mut().ui.actions.expanded = vec![true, false, false]; + h.run_steps(2); + h.get_by_label("Retouch").click(); + h.run_steps(2); + assert_eq!(h.state().ui.actions.selected_set.as_deref(), Some("Retouch")); + h.get_by_label(&label_of("select.all")).click(); + h.run_steps(2); + assert_eq!((h.state().ui.actions.selected, h.state().ui.actions.selected_step), (Some(0), Some(1))); + h.get_by_label("Delete").click(); + h.run_steps(2); + assert_eq!(h.state().session.actions.list[0].steps.len(), 1, "the step went"); + assert_eq!((h.state().ui.actions.selected, h.state().ui.actions.selected_set.as_deref()), (None, None)); + h.get_by_label("Play selection").click(); + h.run_steps(2); + assert_eq!(layer_names(h.state()), ["w"], "the first action, not the Retouch set"); +} + +/// #10459 fix-up: a set whose first action pauses at step dialogs plays the rest of the set +/// after OK, and Cancel stops the whole set, as it stops one action. +#[test] +fn a_set_paused_at_a_step_dialog_plays_its_other_actions_after_ok() { + use egui_kittest::kittest::Queryable; + for ok in [true, false] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let mut a = Action::new( + "A", + vec![ + ("layer.new.layer".into(), json!({"name": "a"})), + ("filter.blur.gaussianBlur".into(), json!({"radius": 1})), + ("filter.blur.gaussianBlur".into(), json!({"radius": 2})), + ("layer.new.layer".into(), json!({"name": "a2"})), + ], + ); + a.set = Some("S".into()); + a.dialogs.extend([1, 2]); + let mut b = Action::new("B", vec![("layer.new.layer".into(), json!({"name": "b"}))]); + b.set = Some("S".into()); + app.session.actions.list.extend([a, b]); + let mut h = egui_kittest::Harness::builder().with_size(vec2(360.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(2); + h.get_by_label("S").click(); + h.run_steps(2); + h.get_by_label("Play selection").click(); + h.run_steps(2); + assert_eq!(layer_names(h.state()), ["a"]); + assert!(h.state().ui.status.contains("dialog"), "{}", h.state().ui.status); + let first = h.state().ui.dialogs.last().map(|d| d.id).expect("the first blur's dialog"); + if !ok { + crate::dialogs::cancel(h.state_mut(), first).unwrap(); + h.run_steps(2); + assert_eq!(layer_names(h.state()), ["a"], "Cancel stops the set"); + continue; + } + crate::dialogs::confirm(h.state_mut(), first).unwrap(); + h.run_steps(2); + // The second dialog of A pauses again; the rest of the set waits behind it. + let second = h.state().ui.dialogs.last().map(|d| d.id).expect("the second blur's dialog"); + assert_ne!(first, second); + crate::dialogs::confirm(h.state_mut(), second).unwrap(); + h.run_steps(2); + let mut names = layer_names(h.state()); + names.sort(); + assert_eq!(names, ["a", "a2", "b"], "B played after A's dialogs"); + assert!(h.state().ui.status.starts_with("Played"), "{}", h.state().ui.status); + } +} + /// #7535: the folder button (and the panel menu's New Set…) names an empty set, shown as a folder /// row with no actions; New Action then records into it, as into any selected set. #[test] @@ -870,8 +972,8 @@ fn start_recording_with_a_set_selected_records_a_new_action_into_it() { assert_eq!(list[1].set.as_deref(), Some("Web")); } -/// A click on an expanded set's folder row selects it and collapses it; recording into it (New -/// Action or Start Recording) expands the set again, so the new action and its steps show. +/// Recording into a collapsed, selected set (New Action or Start Recording) expands the set +/// again, so the new action and its steps show. #[test] fn recording_into_a_collapsed_set_expands_it() { use egui_kittest::{Harness, kittest::Queryable}; @@ -889,6 +991,7 @@ fn recording_into_a_collapsed_set_expands_it() { app, ); h.run_steps(2); + click_set_triangle(&mut h, "Retouch"); h.get_by_label("Retouch").click(); h.run_steps(2); assert_eq!(h.state().ui.actions.collapsed_sets, ["Retouch"], "{label}"); From 1d0bc23c3ecfc18406e77e1ce70182c5daa38e01 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 15:00:36 +0100 Subject: [PATCH 45/52] Integration: don't count symbols on Mac Roman letters as windows-1252 (#8327) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous fix-up counted § ® ¾ ¿ (and ¹ » ¼ ½) as common windows-1252 text, but those bytes are Mac Roman ß Æ æ ø (π ª º Ω). Mac names with no Unicode copy such as "Weiß", "Gaußscher Weichzeichner", "Størrelse", "Lærredstørrelse" and "Æble" then tied and read as windows-1252 ("Wei§", "St¿rrelse"), where the PR read them right. Keep only the 12 symbols whose byte is not a letter in Mac Roman (¡ ¢ £ ¥ © « ° ± ² ³ ¶ ·). Windows "Größe »", "50 °" and "« auto »" still read as windows-1252; a name whose only non-ASCII character is ® ("Logo ®") reads as Mac Roman "Logo Æ" again, as on the PR head (tested as a known limitation). Co-authored-by: regexer <3689390+regexer@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/atn_cmds/tests.rs | 10 ++--- crates/psd/src/atn.rs | 32 +++++++++++++--- crates/psd/src/codepage.rs | 51 ++++++++++++++++++------- 3 files changed, 69 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index cdbdce110da..f9868d44f18 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -3214,10 +3214,10 @@ fn load_decodes_legacy_step_names() { #[test] fn load_keeps_windows_1252_symbols() { - // Windows Photoshop step names with no Unicode copy: ® and » are letters in Mac Roman, which - // must not win ("Logo Æ", "Grˆfle ª"). Save Actions writes the names back as that text. + // Windows Photoshop step names with no Unicode copy: Mac Roman reads ° and » as ∞ and ª, + // which must not win ("50 ∞", "Grˆfle ª"). Save Actions writes the names back as that text. let steps = vec![ - AtnItem { dictionary: b"Logo \xae".to_vec(), ..item("syntheticFill", "", None) }, + AtnItem { dictionary: b"50 \xb0".to_vec(), ..item("syntheticFill", "", None) }, AtnItem { dictionary: b"Gr\xf6\xdfe \xbb".to_vec(), ..item("syntheticFill", "", None) }, ]; let file = AtnFile { @@ -3228,12 +3228,12 @@ fn load_keeps_windows_1252_symbols() { let mut s = Session::new(); let r = s.execute("actions.load", json!({"data": b64(&atn::write(&file).unwrap())})).unwrap(); assert_eq!(r["encoding"], "windows-1252", "{r}"); - assert_eq!(r["unsupported"][0]["name"], "Logo ®", "{r}"); + assert_eq!(r["unsupported"][0]["name"], "50 °", "{r}"); assert_eq!(r["unsupported"][1]["name"], "Größe »", "{r}"); let saved = s.execute("actions.save", json!({"set": "Größe ändern"})).unwrap(); let saved = atn::parse(&photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap()).unwrap(); let names: Vec = saved.actions[0].items.iter().map(|i| saved.item_label(i)).collect(); - assert_eq!(names, ["Logo ®", "Größe »"]); + assert_eq!(names, ["50 °", "Größe »"]); } #[test] diff --git a/crates/psd/src/atn.rs b/crates/psd/src/atn.rs index bce1e5f09f9..4820d44e456 100644 --- a/crates/psd/src/atn.rs +++ b/crates/psd/src/atn.rs @@ -644,15 +644,20 @@ mod tests { #[test] fn latin1_symbol_names_read_as_windows_1252() { - // Windows Photoshop "Logo ®" and "Größe »" with no Unicode copy: Mac Roman reads these - // bytes as letters ("Logo Æ", "Grˆfle ª"), but they are windows-1252, as before #6743. - let f = parse(&one_action("Set 1", "Action 1", vec![bare(AtnEvent::name("x"), b"Logo \xae")])).unwrap(); - assert_eq!(f.encoding.as_deref(), Some("windows-1252")); - assert_eq!(labels(&f), ["Logo ®"]); + // Windows Photoshop "Größe »" and "50 °" with no Unicode copy: Mac Roman reads these + // bytes as letters and symbols ("Grˆfle ª", "50 ∞"), but they are windows-1252, as before + // #6743. let f = parse(&one_action("Größe ändern", "Aktion", vec![bare(AtnEvent::name("x"), b"Gr\xf6\xdfe \xbb")])).unwrap(); assert_eq!(f.encoding.as_deref(), Some("windows-1252")); assert_eq!(labels(&f), ["Größe »"]); assert!(f.warnings.is_empty(), "{:?}", f.warnings); + let f = parse(&one_action("Größe ändern", "Aktion", vec![bare(AtnEvent::name("x"), b"50 \xb0")])).unwrap(); + assert_eq!(labels(&f), ["50 °"]); + // Known limitation: "Logo ®" alone reads as Mac Roman "Logo Æ", as Mac "Æble" needs that + // byte (codepage's symbols_on_mac_roman_letters_stay_ambiguous). + let f = parse(&one_action("Set 1", "Action 1", vec![bare(AtnEvent::name("x"), b"Logo \xae")])).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("macintosh")); + assert_eq!(labels(&f), ["Logo Æ"]); // Mac Roman bytes that windows-1252 reads as controls or rare letters stay Mac Roman. let f = parse(&one_action("Définir", "Action 1", vec![bare(AtnEvent::name("x"), b"Gr\x9a\xa7e"), bare(AtnEvent::name("y"), b"Arri\x8fre-plan")])).unwrap(); @@ -660,6 +665,23 @@ mod tests { assert_eq!(labels(&f), ["Größe", "Arrière-plan"]); } + #[test] + fn mac_roman_sharp_s_and_slashed_o_stay_mac_roman() { + // Mac Roman ß ø æ Æ are the bytes of windows-1252 § ¿ ¾ ®: German and Danish Mac names + // with no Unicode copy still read as Mac Roman, each alone and as a set. + let words: [&[u8]; 5] = [b"Wei\xa7", b"Gau\xa7scher Weichzeichner", b"St\xbfrrelse", b"L\xberredst\xbfrrelse", b"\xaeble"]; + let text = ["Weiß", "Gaußscher Weichzeichner", "Størrelse", "Lærredstørrelse", "Æble"]; + for (bytes, text) in words.iter().zip(text) { + let f = parse(&one_action("Größe ändern", "Aktion 1", vec![bare(AtnEvent::name("x"), bytes)])).unwrap(); + assert_eq!((f.encoding.as_deref(), labels(&f)), (Some("macintosh"), vec![text.to_string()])); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + } + let items = words.iter().map(|w| bare(AtnEvent::name("x"), w)).collect(); + let f = parse(&one_action("Größe ändern", "Aktion 1", items)).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("macintosh")); + assert_eq!(labels(&f), text); + } + #[test] fn known_names_alone_never_warn() { // Nothing decodes to the Unicode name, but nothing is shown from the bytes either. diff --git a/crates/psd/src/codepage.rs b/crates/psd/src/codepage.rs index 75e2ea7ec4a..8f6ab5daad6 100644 --- a/crates/psd/src/codepage.rs +++ b/crates/psd/src/codepage.rs @@ -16,9 +16,9 @@ //! fine): kana → Shift_JIS; Hangul → EUC-KR; Cyrillic → windows-1251; Han → GBK, then //! Big5, then Shift_JIS; Latin letters → windows-1252, then Mac Roman. //! 4. Still tied: windows-1252, flagged [`Guess::uncertain`]. -//! 5. Mac Roman must also beat windows-1252 when Latin-1's symbols (© ® ° § « » ± ½…) count -//! as common text, as Mac Roman's letters sit on those bytes (1252 "Logo ®" is Mac Roman -//! "Logo Æ"). Otherwise the names are windows-1252, with step 3's hint and step 4's warning. +//! 5. Mac Roman must also beat windows-1252 when the Latin-1 symbols that are no letter in +//! Mac Roman (© ° « ± …) count as common text (1252 "Größe »" is Mac Roman "Grˆfle ª"). +//! Otherwise the names are windows-1252, with step 3's hint and step 4's warning. //! //! Only the first [`GUESS_SAMPLE`] bytes of names are examined. @@ -241,9 +241,12 @@ fn is_latin_common(ch: char) -> bool { (ch.is_alphabetic() && !['Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ', 'ƒ', 'ˆ'].contains(&ch)) || TYPOGRAPHIC.contains(&ch) || LATIN_SYMBOLS.contains(&ch) } -/// Latin-1 symbols people type in names (windows-1252 0xA1–0xF7). Not € or ™: windows-1252 has -/// them at 0x80 and 0x99, Mac Roman's Ä and ô. -const LATIN_SYMBOLS: [char; 20] = ['¡', '¢', '£', '¥', '§', '©', '«', '®', '°', '±', '²', '³', '¶', '·', '¹', '»', '¼', '½', '¾', '¿']; +/// Latin-1 symbols people type in names (windows-1252 0xA1–0xB7) whose byte is not a letter in +/// Mac Roman. Left out because Mac Roman has a letter there: § ® ¹ » ¼ ½ ¾ ¿ (ß Æ π ª º Ω æ ø, +/// as in Mac "Weiß", "Størrelse", "Æble"), € and ™ (0x80, 0x99: Ä, ô). So a windows-1252 name +/// whose only non-ASCII character is one of those ("Logo ®") still reads as Mac Roman ("Logo +/// Æ"). +const LATIN_SYMBOLS: [char; 12] = ['¡', '¢', '£', '¥', '©', '«', '°', '±', '²', '³', '¶', '·']; /// Quotes, dashes, ellipsis and bullet: windows-1252 and windows-1251 share them at 0x82–0x97; /// Mac Roman has them too. @@ -398,24 +401,44 @@ mod tests { #[test] fn latin1_symbols_read_as_1252_not_mac_roman() { - // Mac Roman has letters where windows-1252 has © ® « » §: 1252 "Logo ®" is Mac Roman - // "Logo Æ", "Größe »" is "Grˆfle ª". Latin-1 (what a code-page-blind reader shows) wins. - let logo: &[&[u8]] = &[b"Logo \xae"]; - assert_eq!(guess(logo, "Set 1"), Guess { encoding: WINDOWS_1252, uncertain: true }); - assert_eq!(guess(logo, "Größe ändern"), Guess { encoding: WINDOWS_1252, uncertain: false }); - assert_eq!(decode(logo[0], WINDOWS_1252), "Logo ®"); - for words in [&["Größe »"][..], &["Contraste « auto »", "§ 3 Größe", "½ Größe", "Teinte ¾ ©"]] { + // Mac Roman has letters where windows-1252 has some symbols: 1252 "Größe »" is Mac Roman + // "Grˆfle ª", "50 °" is "50 ∞". Latin-1 (what a code-page-blind reader shows) wins. + for words in [&["Größe »"][..], &["50 °"], &["Contraste « auto »", "© Größe", "± 5"]] { let g = guess_words(WINDOWS_1252, words, "Größe ändern"); assert_eq!(g, Guess { encoding: WINDOWS_1252, uncertain: false }, "{words:?}"); assert_eq!(guess_words(WINDOWS_1252, words, "Set 1").encoding, WINDOWS_1252, "{words:?}"); } } + #[test] + fn symbols_on_mac_roman_letters_stay_ambiguous() { + // Known limitation: 1252 "Logo ®" is Mac Roman "Logo Æ", and ® is not counted for + // windows-1252 because Mac "Æble" and "Weiß" use those bytes, so the name reads as Mac + // Roman whatever the hint, as it did before the symbols counted at all. + let logo: &[&[u8]] = &[b"Logo \xae"]; + assert_eq!(guess(logo, "Größe ändern"), Guess { encoding: MACINTOSH, uncertain: false }); + assert_eq!(guess(logo, "Set 1"), Guess { encoding: MACINTOSH, uncertain: false }); + } + #[test] fn mac_roman_letters_still_read_as_mac_roman() { // Mac Roman "Größe" is 1252 "Grš§e", "Ändern" "€ndern", "Contrôle" "Contr™le": Mac Roman // still wins once § counts as common text in windows-1252. - for word in ["Größe", "Ändern", "Contrôle"] { + // Mac Roman ß ø æ Æ are 1252 § ¿ ¾ ®, which windows-1252 must not count as common. + let words = [ + "Größe", + "Ändern", + "Contrôle", + "Weiß", + "Schwarzweiß", + "Gaußscher Weichzeichner", + "Schließen", + "Størrelse", + "Lærredstørrelse", + "Fjern støy", + "Æble", + ]; + for word in words { let g = guess_words(MACINTOSH, &[word], "Définir l’arrière-plan"); assert_eq!(g, Guess { encoding: MACINTOSH, uncertain: false }, "{word}"); } From e2789c041c03f3d0bd4bc6af11824b67cb30daec Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 15:11:33 +0100 Subject: [PATCH 46/52] Integration: a set stops at a called action's dialog; folders toggle without a pointer (#10459) - A set whose action paused at a step dialog inside an action it calls handed the rest of the set to the called action's dialog, which resumes alone: after OK the set's next action ran and the caller's own remaining steps never did. The rest of a set now rides only on a pause of the target action itself; otherwise the set stops there. - Set folders could only be collapsed with the pointer on the triangle: a keyboard or accessibility activation always just selected. Without a pointer it now selects and toggles, as before, and the row reports whether it is selected (not whether it is expanded). Co-authored-by: hectorviov <1501713+hectorviov@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/actions.rs | 64 +++++++++++++--------- crates/ui-egui/src/panels/actions/tests.rs | 47 ++++++++++++++++ 2 files changed, 84 insertions(+), 27 deletions(-) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index c0d816853c8..5f2ab0a45c6 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -98,12 +98,14 @@ fn playback_targets(app: &PhotocraftApp) -> Vec { } /// Play `targets` one after another, stopping at the first that fails or can't start. One that -/// pauses for a step dialog hands the rest to that dialog, which plays them after its OK (Cancel -/// stops them all, as it stops one action). Returns the last result with `ran` counting the steps +/// pauses for a step dialog of its own hands the rest to that dialog, which plays them after its OK +/// (Cancel stops them all, as it stops one action). A pause inside an action it calls resumes only +/// the called action, so the set stops there rather than run its next action on an unfinished one. Returns the last result with `ran` counting the steps /// of all of them, or `None` when there was nothing to play. fn play_targets(app: &mut PhotocraftApp, targets: &[usize]) -> Result, String> { let (mut last, mut ran) = (None, 0u64); for (n, &i) in targets.iter().enumerate() { + let name = app.session.actions.list.get(i).map(|a| a.name.clone()); let mut v = app.run("actions.play", json!({"action": i}))?; ran = ran.saturating_add(v.get("ran").and_then(Value::as_u64).unwrap_or(0)); let failed = v.get("failed").is_some_and(Value::is_object); @@ -115,7 +117,9 @@ fn play_targets(app: &mut PhotocraftApp, targets: &[usize]) -> Result) let saved = app.session.authorize; app.session.authorize = paused.gate.or(saved); let mut played = play_owned(app, ¶ms, owner); - // Paused again at a later dialog of the same action: that dialog carries the rest of the set. + // Paused again at a later dialog of the same action (not of one it calls, which resumes + // alone): that dialog carries the rest of the set. if let Ok(v) = &played && let Some(dialog) = v.get("paused").and_then(|p| p.get("dialog")).and_then(Value::as_u64) && let Some(token) = app.ui.dialog_mut(dialog).and_then(|d| d.fields.get(RESUME)).and_then(Value::as_u64) && let Some(entry) = app.paused_playbacks.paused.get_mut(&token) + && entry.action == paused.action { entry.then = paused.then.clone(); } @@ -994,16 +1000,16 @@ fn display_order(rows: &[Row]) -> Vec { } struct SetHeaderResult { - /// A click on the disclosure triangle: collapse or expand, the selection stays. + /// A click on the disclosure triangle (or an activation without a pointer): collapse or expand. toggled: bool, - /// A click on the rest of the row: select the set. + /// A click on the rest of the row (or an activation without a pointer): select the set. picked: bool, save: bool, } fn draw_set_header(ui: &mut egui::Ui, set: &str, count: u64, collapsed: bool, selected: bool, tokens: &Tokens) -> SetHeaderResult { let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::click()); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, !collapsed, set)); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, set)); if selected { ui.painter().rect_filled(rect, 0.0, tokens.row_selected); } else if response.hovered() { @@ -1026,10 +1032,12 @@ fn draw_set_header(ui: &mut egui::Ui, set: &str, count: u64, collapsed: bool, se ui.painter().text(pos2(rect.left() + 44.0, rect.center().y), Align2::LEFT_CENTER, set, egui::FontId::proportional(12.0), tokens.text); let summary = crate::i18n::trn(crate::i18n::current(), count, "{n} action", "{n} actions"); ui.painter().text(pos2(rect.right() - 8.0, rect.center().y), Align2::RIGHT_CENTER, summary, egui::FontId::proportional(11.0), tokens.text_faint); - // As on an action row, the triangle's column collapses or expands and the rest of the row - // selects; neither does the other's job. - let toggled = response.clicked() && response.interact_pointer_pos().is_some_and(|p| p.x < rect.left() + 20.0); - let picked = response.clicked() && !toggled; + // As on an action row, a click in the triangle's column collapses or expands and one on the + // rest of the row selects. An activation without a pointer (keyboard, accessibility) does + // both, so the set can still be collapsed and expanded without a mouse. + let pointer = response.interact_pointer_pos(); + let toggled = response.clicked() && pointer.is_none_or(|p| p.x < rect.left() + 20.0); + let picked = response.clicked() && pointer.is_none_or(|p| p.x >= rect.left() + 20.0); let mut save = false; response.context_menu(|ui| { if ui.button(tl!("Save Set…")).clicked() { @@ -1041,15 +1049,16 @@ fn draw_set_header(ui: &mut egui::Ui, set: &str, count: u64, collapsed: bool, se } /// The sets New Set made that hold no action yet: empty folder rows after the rest. Returns the -/// set whose row was clicked (and whether on its triangle) and the set whose Save Set… was chosen. -fn draw_empty_sets(app: &PhotocraftApp, ui: &mut egui::Ui, rows: &[Row], t: &Tokens) -> (Option<(String, bool)>, Option) { +/// set whose row was clicked (whether it toggles, whether it selects) and the set whose Save Set… +/// was chosen. +fn draw_empty_sets(app: &PhotocraftApp, ui: &mut egui::Ui, rows: &[Row], t: &Tokens) -> (Option<(String, bool, bool)>, Option) { let (mut clicked, mut save) = (None, None); for set in app.session.actions.sets.iter().filter(|set| !rows.iter().any(|r| r.set.as_ref() == Some(*set))) { let selected = app.ui.actions.selected.is_none() && app.ui.actions.selected_set.as_ref() == Some(set); let collapsed = app.ui.actions.collapsed_sets.contains(set); let result = draw_set_header(ui, set, 0, collapsed, selected, t); if result.toggled || result.picked { - clicked = Some((set.clone(), result.toggled)); + clicked = Some((set.clone(), result.toggled, result.picked)); } if result.save { save = Some(set.clone()); @@ -1136,7 +1145,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let mut renamed = None; let mut toggled = None; let mut dialog_toggled = None; - let mut set_toggled: Option<(String, bool)> = None; + let mut set_toggled: Option<(String, bool, bool)> = None; let mut save_set: Option = None; let max_h = (ui.available_height() - 38.0).max(0.0); let mut play_idx: Option> = None; @@ -1168,7 +1177,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let selected = app.ui.actions.selected.is_none() && app.ui.actions.selected_set.as_deref() == Some(set); let result = draw_set_header(ui, set, count, collapsed, selected, &t); if result.toggled || result.picked { - set_toggled = Some((set.to_string(), result.toggled)); + set_toggled = Some((set.to_string(), result.toggled, result.picked)); } if result.save { save_set = Some(set.to_string()); @@ -1279,21 +1288,22 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if let Some((action, step)) = dialog_toggled { let _ = app.run("actions.dialog", json!({"action": action, "step": step})); } - match set_toggled { - // The disclosure triangle collapses or expands the set and leaves the selection alone. - Some((set, true)) => match app.ui.actions.collapsed_sets.iter().position(|c| *c == set) { - Some(i) => { - app.ui.actions.collapsed_sets.remove(i); - } - None => app.ui.actions.collapsed_sets.push(set), - }, + if let Some((set, toggle, pick)) = set_toggled { // The rest of the folder row selects the set, for New Action and Play. - Some((set, false)) => { + if pick { app.ui.actions.selected = None; app.ui.actions.selected_step = None; - app.ui.actions.selected_set = Some(set); + app.ui.actions.selected_set = Some(set.clone()); + } + // The disclosure triangle collapses or expands the set and leaves the selection alone. + if toggle { + match app.ui.actions.collapsed_sets.iter().position(|c| *c == set) { + Some(i) => { + app.ui.actions.collapsed_sets.remove(i); + } + None => app.ui.actions.collapsed_sets.push(set), + } } - None => {} } if let Some(set) = save_set && let Err(e) = save_dialog(app, Some(set)) diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index b4ad34b97b5..7a233fcdf57 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -836,6 +836,53 @@ fn a_set_paused_at_a_step_dialog_plays_its_other_actions_after_ok() { } } +/// #10459 fix-up: a set whose action pauses at a dialog inside an action it calls stops there: +/// the called action resumes alone, so the next action of the set must not run on a caller that +/// never finished. +#[test] +fn a_set_paused_inside_a_called_action_stops_there() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + let mut a = Action::new("A", vec![("actions.play".into(), json!({"action": "C"})), ("layer.new.layer".into(), json!({"name": "a-tail"}))]); + a.set = Some("S".into()); + let mut b = Action::new("B", vec![("layer.new.layer".into(), json!({"name": "b"}))]); + b.set = Some("S".into()); + let mut c = Action::new("C", vec![("filter.blur.gaussianBlur".into(), json!({"radius": 1})), ("layer.new.layer".into(), json!({"name": "c"}))]); + c.dialogs.insert(0); + app.session.actions.list.extend([a, b, c]); + let mut h = egui_kittest::Harness::builder().with_size(vec2(360.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(2); + h.get_by_label("S").click(); + h.run_steps(2); + h.get_by_label("Play selection").click(); + h.run_steps(2); + let dialog = h.state().ui.dialogs.last().map(|d| d.id).expect("C's blur dialog"); + crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); + h.run_steps(2); + assert_eq!(layer_names(h.state()), ["c"], "C finished; B didn't run ahead of A's tail"); +} + +/// #10459 fix-up: a set folder activated without a pointer (keyboard, accessibility) still +/// collapses and expands, and selects the set; the row reports whether it is selected. +#[test] +fn a_set_folder_toggles_without_a_pointer() { + use egui_kittest::kittest::Queryable; + let mut h = two_set_panel(); + use egui::accesskit::Toggled; + use egui_kittest::kittest::NodeT; + let selected = |h: &egui_kittest::Harness<'_, PhotocraftApp>| h.get_by_label("Retouch").accesskit_node().toggled(); + assert_eq!(selected(&h), Some(Toggled::False)); + h.get_by_label("Retouch").click_accesskit(); + h.run_steps(2); + assert_eq!(h.state().ui.actions.collapsed_sets, ["Retouch"]); + assert_eq!(h.state().ui.actions.selected_set.as_deref(), Some("Retouch")); + assert_eq!(selected(&h), Some(Toggled::True), "selected and collapsed reads as selected"); + h.get_by_label("Retouch").click_accesskit(); + h.run_steps(2); + assert!(h.state().ui.actions.collapsed_sets.is_empty()); +} + /// #7535: the folder button (and the panel menu's New Set…) names an empty set, shown as a folder /// row with no actions; New Action then records into it, as into any selected set. #[test] From bd04a88292d7ab498ef46a70ad62f664b9bd0b56 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 15:19:58 +0100 Subject: [PATCH 47/52] Integration: keep Mac Roman bullets and Latin words out of the wrong page (#8327) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mac Roman 0xA5 is the bullet, windows-1252 0xA5 is ¥: with ¥ counted in the windows-1252 re-weigh, Mac "Ebene • Kopie" read as "Ebene ¥ Kopie". Drop ¥; the other kept symbols are no letter or typographic mark in Mac Roman. windows-1251 has І і д where windows-1252 has ² ³ ä, so "Fläche m²" read as "Flдche mІ" (already so in the PR head; main showed it right). In a single-byte page, a letter glued to an ASCII letter now counts as common only when it is a Latin letter. Real Cyrillic names ("Новый слой", "Копия слоя 2", "Канал RGB") still read as windows-1251. "Preis £5" (Ј between a space and a digit) still reads as windows-1251; documented. Co-authored-by: regexer <3689390+regexer@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/psd/src/atn.rs | 40 ++++++++++++++++++++++++++++++++++++++ crates/psd/src/codepage.rs | 29 +++++++++++++++++++++------ 2 files changed, 63 insertions(+), 6 deletions(-) diff --git a/crates/psd/src/atn.rs b/crates/psd/src/atn.rs index 4820d44e456..4b06ba72bca 100644 --- a/crates/psd/src/atn.rs +++ b/crates/psd/src/atn.rs @@ -682,6 +682,46 @@ mod tests { assert_eq!(labels(&f), text); } + #[test] + fn mac_roman_bullets_stay_mac_roman() { + // Mac Roman • (0xA5) is windows-1252 ¥, which must not count for windows-1252. + for (set, bytes, text) in [ + ("Größe ändern", &b"Ebene \xa5 Kopie"[..], "Ebene • Kopie"), + ("Définir", b"Niveaux \xa5 Courbes", "Niveaux • Courbes"), + ("Tamaño de imagen", b"Tama\x96o \xa5 50%", "Tamaño • 50%"), + ] { + let f = parse(&one_action(set, "Aktion 1", vec![bare(AtnEvent::name("x"), bytes)])).unwrap(); + assert_eq!((f.encoding.as_deref(), labels(&f)), (Some("macintosh"), vec![text.to_string()])); + } + } + + #[test] + fn latin_words_do_not_read_as_cyrillic() { + // windows-1251 has І і (0xB2 0xB3) and д (0xE4) where windows-1252 has ² ³ ä: a letter + // glued to a Latin word is read as Latin. + for (bytes, text) in [(&b"Fl\xe4che m\xb2"[..], "Fläche m²"), (b"Volumen m\xb3", "Volumen m³"), (b"Gr\xf6\xdfe \xb2", "Größe ²")] { + let f = parse(&one_action("Größe ändern", "Aktion 1", vec![bare(AtnEvent::name("x"), bytes)])).unwrap(); + assert_eq!((f.encoding.as_deref(), labels(&f)), (Some("windows-1252"), vec![text.to_string()])); + } + // Real windows-1251 names still read as Cyrillic, alone, as a set, and beside Latin. + let words: [&[u8]; 4] = [ + b"\xcd\xee\xe2\xfb\xe9 \xf1\xeb\xee\xe9", + b"\xd0\xe0\xe7\xec\xe5\xf0 \xe8\xe7\xee\xe1\xf0\xe0\xe6\xe5\xed\xe8\xff", + b"\xca\xee\xef\xe8\xff \xf1\xeb\xee\xff 2", + b"\xca\xe0\xed\xe0\xeb RGB", + ]; + let text = ["Новый слой", "Размер изображения", "Копия слоя 2", "Канал RGB"]; + for (bytes, text) in words.iter().zip(text) { + let f = parse(&one_action("Набор 1", "Операция 1", vec![bare(AtnEvent::name("x"), bytes)])).unwrap(); + assert_eq!((f.encoding.as_deref(), labels(&f)), (Some("windows-1251"), vec![text.to_string()])); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); + } + let items = words.iter().map(|w| bare(AtnEvent::name("x"), w)).collect(); + let f = parse(&one_action("Набор 1", "Операция 1", items)).unwrap(); + assert_eq!(f.encoding.as_deref(), Some("windows-1251")); + assert_eq!(labels(&f), text); + } + #[test] fn known_names_alone_never_warn() { // Nothing decodes to the Unicode name, but nothing is shown from the bytes either. diff --git a/crates/psd/src/codepage.rs b/crates/psd/src/codepage.rs index 8f6ab5daad6..c83bbe6e318 100644 --- a/crates/psd/src/codepage.rs +++ b/crates/psd/src/codepage.rs @@ -229,9 +229,25 @@ fn score(enc: &'static Encoding, name: &[u8]) -> (u64, u64) { } /// [`score`] for a single-byte page, where one byte is one character and a non-ASCII byte is a -/// non-ASCII character: `common` decides which of them count. +/// non-ASCII character: `common` decides which of them count. A letter glued to an ASCII letter +/// counts only when it is a Latin letter: windows-1252 "Fläche m²" is windows-1251 "Flдche mІ", +/// and Cyrillic, Greek or Mac Roman's fl inside a Latin word is a misreading (real Cyrillic +/// names have Cyrillic or spaces around each letter). A letter beside digits or spaces still +/// counts, so windows-1252 "Preis £5" still reads as windows-1251 "Preis Ј5". fn single_byte_score(enc: &'static Encoding, name: &[u8], common: impl Fn(char) -> bool) -> (u64, u64) { - decode(name, enc).chars().filter(|c| !c.is_ascii()).fold((0, 0), |(c, h), ch| (c.saturating_add(u64::from(common(ch))), h.saturating_add(1))) + let chars: Vec = decode(name, enc).chars().collect(); + let latin_at = |i: Option| i.and_then(|i| chars.get(i)).is_some_and(char::is_ascii_alphabetic); + let (mut c, mut h) = (0u64, 0u64); + for (i, &ch) in chars.iter().enumerate() { + if ch.is_ascii() { + continue; + } + h = h.saturating_add(1); + let glued = latin_at(i.checked_sub(1)) || latin_at(i.checked_add(1)); + let misread = glued && ch.is_alphabetic() && !('\u{00C0}'..='\u{024F}').contains(&ch); + c = c.saturating_add(u64::from(common(ch) && !misread)); + } + (c, h) } /// Whether `ch` is common in Western names, for weighing windows-1252 against Mac Roman: letters @@ -243,10 +259,11 @@ fn is_latin_common(ch: char) -> bool { /// Latin-1 symbols people type in names (windows-1252 0xA1–0xB7) whose byte is not a letter in /// Mac Roman. Left out because Mac Roman has a letter there: § ® ¹ » ¼ ½ ¾ ¿ (ß Æ π ª º Ω æ ø, -/// as in Mac "Weiß", "Størrelse", "Æble"), € and ™ (0x80, 0x99: Ä, ô). So a windows-1252 name -/// whose only non-ASCII character is one of those ("Logo ®") still reads as Mac Roman ("Logo -/// Æ"). -const LATIN_SYMBOLS: [char; 12] = ['¡', '¢', '£', '¥', '©', '«', '°', '±', '²', '³', '¶', '·']; +/// as in Mac "Weiß", "Størrelse", "Æble"), € and ™ (0x80, 0x99: Ä, ô), and ¥ (0xA5, Mac Roman's +/// bullet in [`TYPOGRAPHIC`]: Mac "Ebene • Kopie"). So a windows-1252 name whose only non-ASCII +/// character is one of those ("Logo ®", "¿Tamaño?", "Preis ¥100") still reads as Mac Roman +/// ("Logo Æ"). +const LATIN_SYMBOLS: [char; 11] = ['¡', '¢', '£', '©', '«', '°', '±', '²', '³', '¶', '·']; /// Quotes, dashes, ellipsis and bullet: windows-1252 and windows-1251 share them at 0x82–0x97; /// Mac Roman has them too. From 7e50896afbf318685ec3fd529ff17b43a91dc13b Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 15:35:14 +0100 Subject: [PATCH 48/52] Integration: drop the glued-letter rule again (#8327) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous fix-up counted a letter glued to an ASCII letter as common only when it was Latin. That turned ordinary windows-1251 names such as "CMYKканал" or Ukrainian "Копiя" (Latin i) into a windows-1252 (or GBK) reading of the whole set, with no warning, where the PR read them right. Back to the PR's scoring for single-byte pages; the ¥ removal stays. windows-1252 "Fläche m²" / "Preis £5" reading as windows-1251 is the PR's own known limitation, now noted in the code. A Russian set plus "CMYKканал" is pinned as windows-1251. Co-authored-by: regexer <3689390+regexer@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/psd/src/atn.rs | 22 +++++++--------------- crates/psd/src/codepage.rs | 26 ++++++++------------------ 2 files changed, 15 insertions(+), 33 deletions(-) diff --git a/crates/psd/src/atn.rs b/crates/psd/src/atn.rs index 4b06ba72bca..797845e2fee 100644 --- a/crates/psd/src/atn.rs +++ b/crates/psd/src/atn.rs @@ -696,30 +696,22 @@ mod tests { } #[test] - fn latin_words_do_not_read_as_cyrillic() { - // windows-1251 has І і (0xB2 0xB3) and д (0xE4) where windows-1252 has ² ³ ä: a letter - // glued to a Latin word is read as Latin. - for (bytes, text) in [(&b"Fl\xe4che m\xb2"[..], "Fläche m²"), (b"Volumen m\xb3", "Volumen m³"), (b"Gr\xf6\xdfe \xb2", "Größe ²")] { - let f = parse(&one_action("Größe ändern", "Aktion 1", vec![bare(AtnEvent::name("x"), bytes)])).unwrap(); - assert_eq!((f.encoding.as_deref(), labels(&f)), (Some("windows-1252"), vec![text.to_string()])); - } - // Real windows-1251 names still read as Cyrillic, alone, as a set, and beside Latin. - let words: [&[u8]; 4] = [ + fn russian_sets_with_latin_compounds_stay_windows_1251() { + // Ordinary windows-1251 names plus one glued to a Latin word ("CMYKканал"): the whole + // set reads as Cyrillic, with no warning. + let words: [&[u8]; 5] = [ b"\xcd\xee\xe2\xfb\xe9 \xf1\xeb\xee\xe9", b"\xd0\xe0\xe7\xec\xe5\xf0 \xe8\xe7\xee\xe1\xf0\xe0\xe6\xe5\xed\xe8\xff", b"\xca\xee\xef\xe8\xff \xf1\xeb\xee\xff 2", b"\xca\xe0\xed\xe0\xeb RGB", + b"CMYK\xea\xe0\xed\xe0\xeb", ]; - let text = ["Новый слой", "Размер изображения", "Копия слоя 2", "Канал RGB"]; - for (bytes, text) in words.iter().zip(text) { - let f = parse(&one_action("Набор 1", "Операция 1", vec![bare(AtnEvent::name("x"), bytes)])).unwrap(); - assert_eq!((f.encoding.as_deref(), labels(&f)), (Some("windows-1251"), vec![text.to_string()])); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); - } + let text = ["Новый слой", "Размер изображения", "Копия слоя 2", "Канал RGB", "CMYKканал"]; let items = words.iter().map(|w| bare(AtnEvent::name("x"), w)).collect(); let f = parse(&one_action("Набор 1", "Операция 1", items)).unwrap(); assert_eq!(f.encoding.as_deref(), Some("windows-1251")); assert_eq!(labels(&f), text); + assert!(f.warnings.is_empty(), "{:?}", f.warnings); } #[test] diff --git a/crates/psd/src/codepage.rs b/crates/psd/src/codepage.rs index c83bbe6e318..e44cf0d7ce5 100644 --- a/crates/psd/src/codepage.rs +++ b/crates/psd/src/codepage.rs @@ -229,25 +229,15 @@ fn score(enc: &'static Encoding, name: &[u8]) -> (u64, u64) { } /// [`score`] for a single-byte page, where one byte is one character and a non-ASCII byte is a -/// non-ASCII character: `common` decides which of them count. A letter glued to an ASCII letter -/// counts only when it is a Latin letter: windows-1252 "Fläche m²" is windows-1251 "Flдche mІ", -/// and Cyrillic, Greek or Mac Roman's fl inside a Latin word is a misreading (real Cyrillic -/// names have Cyrillic or spaces around each letter). A letter beside digits or spaces still -/// counts, so windows-1252 "Preis £5" still reads as windows-1251 "Preis Ј5". +/// non-ASCII character: `common` decides which of them count. +/// +/// Known limitation: windows-1251 has Cyrillic letters (І і Ј д) where windows-1252 has ² ³ £ ä, +/// so a windows-1252 name like "Fläche m²" or "Preis £5" scores higher as windows-1251 ("Flдche +/// mІ", "Preis Ј5"). Discounting a Cyrillic letter glued to a Latin word would fix those but +/// break ordinary Russian names such as "CMYKканал" or Ukrainian "Копiя" (Latin i), which turn a +/// whole set into windows-1252. fn single_byte_score(enc: &'static Encoding, name: &[u8], common: impl Fn(char) -> bool) -> (u64, u64) { - let chars: Vec = decode(name, enc).chars().collect(); - let latin_at = |i: Option| i.and_then(|i| chars.get(i)).is_some_and(char::is_ascii_alphabetic); - let (mut c, mut h) = (0u64, 0u64); - for (i, &ch) in chars.iter().enumerate() { - if ch.is_ascii() { - continue; - } - h = h.saturating_add(1); - let glued = latin_at(i.checked_sub(1)) || latin_at(i.checked_add(1)); - let misread = glued && ch.is_alphabetic() && !('\u{00C0}'..='\u{024F}').contains(&ch); - c = c.saturating_add(u64::from(common(ch) && !misread)); - } - (c, h) + decode(name, enc).chars().filter(|c| !c.is_ascii()).fold((0, 0), |(c, h), ch| (c.saturating_add(u64::from(common(ch))), h.saturating_add(1))) } /// Whether `ch` is common in Western names, for weighing windows-1252 against Mac Roman: letters From 4614b3e119b844871f25f93f1ac5b92ad61b9ec9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 15:43:28 +0100 Subject: [PATCH 49/52] Integration: build two ATN test files with defaults (#8714, #8858, #8327) #8327 adds `AtnFile::encoding`. Two tests from other PRs in the batch build an AtnFile literal without it (#8714 fix-up's Camera Raw save-back test, #8858's Vibrance string-class test), so the engine's lib tests didn't compile on the batch. They now fill the rest with `..Default::default()`, as the other literals in the file do. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/atn_cmds/tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index b803fd92ed6..c06dd1576fb 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -2823,6 +2823,7 @@ fn adjustment_layer_set_accepts_the_vibrance_string_class() { ..Default::default() }], warnings: vec![], + ..Default::default() }; let action = import(&atn::write(&file).unwrap()).unwrap().actions.remove(0); assert_eq!(action.steps[0].0, "layer.setAdjustment", "{:?}", action.steps); @@ -3314,6 +3315,7 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { expanded: false, actions: vec![AtnAction { name: UnicodeString::new_nul("Warm"), items, ..Default::default() }], warnings: vec![], + ..Default::default() }; let imp = import(&atn::write(&file).unwrap()).unwrap(); let steps = &imp.actions[0].steps; From 5f63b3fe4c4f524e91fd74bdc65378fa04481375 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 17:51:02 +0100 Subject: [PATCH 50/52] Integration: address CodeRabbit review of batch 11 - #8714: a Camera Raw Filter step imports only with a process version the PSD mapping has verified (PrVN/PrVe 5/184549376 or 6/251920384) and a CrVe text; other steps stay kept steps that save back unchanged. - #7642: the patternName fallback matches names only, so a pattern whose id equals that text no longer wins. A step that names its pattern only by patternName exports that name. - #8327: the iso-2022-jp label is refused (its names are 7-bit escape sequences that would pass through as ASCII). - #10417: the Levels export gate also refuses endpoints of the wrong shape (both ends text, a text gamma) and channels that aren't objects. - #10459: a set paused at a step dialog keeps the rest of the set by action name, so actions.move while the dialog is open neither plays a foreign action nor skips one; "Played N steps" covers the whole Play (steps before the pause and the dialog's own step); the suggested .atn name is cut to 255 bytes at a character boundary; actions.list returns every set, empty ones too; set_names dedups with a HashSet. Co-authored-by: FinnNk <1424666+FinnNk@users.noreply.github.com> Co-authored-by: Silvertree2010 <133535268+Silvertree2010@users.noreply.github.com> Co-authored-by: regexer <3689390+regexer@users.noreply.github.com> Co-authored-by: marshiyar <57055687+marshiyar@users.noreply.github.com> Co-authored-by: hectorviov <1501713+hectorviov@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/actions_cmds.rs | 4 +- crates/engine/src/cmd/actions_edit_cmds.rs | 11 +-- crates/engine/src/cmd/atn_cmds/adjustments.rs | 8 +- crates/engine/src/cmd/atn_cmds/steps_image.rs | 8 +- crates/engine/src/cmd/atn_cmds/steps_make.rs | 4 +- crates/engine/src/cmd/atn_cmds/tests.rs | 91 ++++++++++++++----- crates/engine/src/cmd/pattern_cmds.rs | 6 +- crates/psd/src/codepage.rs | 10 +- crates/ui-egui/src/panels/actions.rs | 60 ++++++++---- crates/ui-egui/src/panels/actions/tests.rs | 63 ++++++++++++- 10 files changed, 204 insertions(+), 61 deletions(-) diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index b9f98b98297..ea68d86b509 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -339,7 +339,7 @@ fn from_step(p: &Value, len: usize) -> Result { fn list(s: &mut Session, _p: &Value) -> Result { let actions: Vec = s.actions.list.iter().map(|a| json!({"name": a.name, "steps": a.steps.len(), "set": a.set})).collect(); let recording = s.actions.recording.and_then(|(_, i)| s.actions.list.get(i).map(|a| a.name.clone())); - Ok(json!({"actions": actions, "recording": recording})) + Ok(json!({"actions": actions, "sets": crate::actions_edit_cmds::set_names(s), "recording": recording})) } fn get(s: &mut Session, p: &Value) -> Result { @@ -760,7 +760,7 @@ pub fn specs() -> Vec { label: "List Actions", menu: &[], shortcut: None, - params: "{} → {actions:[{name, steps:count, set:name|null}], recording:name|null}", + params: "{} → {actions:[{name, steps:count, set:name|null}], sets:[name…] (every set in panel order, empty ones too), recording:name|null}", enabled: always, run: list, journal: false, diff --git a/crates/engine/src/cmd/actions_edit_cmds.rs b/crates/engine/src/cmd/actions_edit_cmds.rs index 380fc764e9d..f8e4da4f54d 100644 --- a/crates/engine/src/cmd/actions_edit_cmds.rs +++ b/crates/engine/src/cmd/actions_edit_cmds.rs @@ -130,13 +130,8 @@ fn assign_set(s: &mut Session, p: &Value) -> Result { /// Every set name, in the Actions panel's order: the sets of the actions as they first appear, /// then the empty ones New Set made. pub fn set_names(s: &Session) -> Vec { - let mut names: Vec = Vec::new(); - for set in s.actions.list.iter().filter_map(|a| a.set.as_ref()).chain(&s.actions.sets) { - if !names.contains(set) { - names.push(set.clone()); - } - } - names + let mut seen = std::collections::HashSet::new(); + s.actions.list.iter().filter_map(|a| a.set.as_ref()).chain(&s.actions.sets).filter(|set| seen.insert(set.as_str())).cloned().collect() } /// New Set…: an empty set folder, named `name` or "Set N" (the first number no set has), that New @@ -463,6 +458,8 @@ mod tests { assert_eq!(s.execute("actions.newSet", json!({})).unwrap()["set"], "Set 2"); assert_eq!(s.execute("actions.newSet", json!({"name": " Retouch "})).unwrap()["set"], "Retouch"); assert_eq!(set_names(&s), ["Set 1", "Set 2", "Retouch"]); + // CodeRabbit on batch 11: Actions List names the empty sets too, so an agent can find them. + assert_eq!(s.execute("actions.list", json!({})).unwrap()["sets"], json!(["Set 1", "Set 2", "Retouch"])); assert!(s.execute("actions.newSet", json!({"name": "Set 1"})).is_err(), "a set an action is in"); assert!(s.execute("actions.newSet", json!({"name": "Retouch"})).is_err(), "an empty set"); assert!(s.execute("actions.newSet", json!({"name": " "})).is_err()); diff --git a/crates/engine/src/cmd/atn_cmds/adjustments.rs b/crates/engine/src/cmd/atn_cmds/adjustments.rs index 640d243f4e4..4b66e586586 100644 --- a/crates/engine/src/cmd/atn_cmds/adjustments.rs +++ b/crates/engine/src/cmd/atn_cmds/adjustments.rs @@ -69,11 +69,15 @@ fn levels_entry(chan: Option<&str>, p: &Value) -> Descriptor { /// Whether the Levels settings in `p` (the master curve and every channel object) name both ends /// of each range they touch, or neither. `levels_entry` writes a whole `Inpt` or `Otpt` pair and /// fills the end a partial edit left out with 0 or 255, so replaying `inBlack: 31` alone would -/// also reset a retained Input White (#8530). +/// also reset a retained Input White (#8530). A value given in a shape the writer can't read (a +/// text endpoint, a channel that isn't an object) would be left out, so it isn't complete either. pub(super) fn levels_complete(p: &Value) -> bool { + let shaped = + |v: &Value| ["inBlack", "inWhite", "gamma", "outBlack", "outWhite"].iter().all(|k| v.get(*k).is_none_or(|x| x.is_null() || jnum(v, k).is_some())); let pairs_whole = |v: &Value| [("inBlack", "inWhite"), ("outBlack", "outWhite")].iter().all(|(low, high)| jnum(v, low).is_some() == jnum(v, high).is_some()); - pairs_whole(p) && CHANNELS.iter().filter_map(|(_, k)| p.get(*k).filter(|v| v.is_object())).all(pairs_whole) + let whole = |v: &Value| shaped(v) && pairs_whole(v); + whole(p) && CHANNELS.iter().filter_map(|(_, k)| p.get(*k).filter(|v| !v.is_null())).all(|v| v.is_object() && whole(v)) } pub(super) fn levels_to(p: &Value) -> Option { diff --git a/crates/engine/src/cmd/atn_cmds/steps_image.rs b/crates/engine/src/cmd/atn_cmds/steps_image.rs index d3a0ec3465f..897544b1092 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_image.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_image.rs @@ -316,7 +316,8 @@ const CAMERA_RAW_GRADES: &[&str] = /// Settings the command has no counterpart for refuse the step rather than replaying a different /// look: the Calibration panel, a white balance other than Custom, the controls the PSD mapping /// keeps only at their neutral values, and any key outside this table (lens, geometry, profile, -/// masks…), as the PSD mapping's `known_key` does. +/// masks…), as the PSD mapping's `known_key` does, and a process version the PSD mapping hasn't +/// verified (Camera Raw renders each version differently). pub(super) fn camera_raw_from(d: &Descriptor) -> Mapped { const CALIBRATION: &[&str] = &["RHue", "RSat", "GHue", "GSat", "BHue", "BSat", "BlkB"]; const NEUTRAL_ONLY: &[(&str, f64)] = @@ -335,6 +336,11 @@ pub(super) fn camera_raw_from(d: &Descriptor) -> Mapped { if d.items.is_empty() || d.items.iter().any(|(k, _)| !std::str::from_utf8(k.as_bytes()).is_ok_and(known)) { return Mapped::Unsupported { harmless: false }; } + let version = (get_num(d, "PrVN"), get_num(d, "PrVe")); + let verified = [(5.0, 184_549_376.0), (6.0, 251_920_384.0)].iter().any(|(n, v)| version == (Some(*n), Some(*v))); + if !verified || !matches!(d.get("CrVe"), Some(D::Text(_))) { + return Mapped::Unsupported { harmless: false }; + } let active = |k: &str, neutral: f64| d.get(k).is_some() && get_num(d, k) != Some(neutral); let custom_wb = d.get("WBal").is_none() || get_enum(d, "WBal").as_deref() == Some("Cst"); if !custom_wb || CALIBRATION.iter().any(|k| active(k, 0.0)) || NEUTRAL_ONLY.iter().any(|(k, n)| active(k, *n)) { diff --git a/crates/engine/src/cmd/atn_cmds/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs index c56d0a112f2..4a0fad4ef03 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_make.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -44,8 +44,8 @@ fn pattern_desc(p: &Value) -> Option { let mut t = desc("patternLayer"); 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)))), - _ => {} + (Some(n), None) | (None, Some(n)) => t = t.with("Ptrn", D::Descriptor(desc("Ptrn").with("Nm ", text(n)))), + (None, None) => {} } if let Some(s) = jnum(p, "scale") { t = t.with("Scl ", pct(s)); diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index c06dd1576fb..5de59280525 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -2336,6 +2336,13 @@ fn partial_levels_edits_refuse_strict_export() { json!({"kind": "levels", "inBlack": 1, "inWhite": 250, "blue": {"outBlack": 3}}), // A value of the wrong shape is no value: the other end is then alone. json!({"kind": "levels", "inBlack": 31, "inWhite": "239"}), + // CodeRabbit on batch 11: both ends of the wrong shape, or a channel that isn't an object, + // would be written as nothing too. + json!({"kind": "levels", "inBlack": "31", "inWhite": "239"}), + json!({"kind": "levels", "gamma": "1.2"}), + json!({"kind": "levels", "red": 5}), + json!({"kind": "levels", "green": [0, 255]}), + json!({"kind": "levels", "blue": {"outBlack": "3", "outWhite": "250"}}), ] { let err = export("Audit8", &[&one(p.clone())], &[], false).unwrap_err(); assert!(err.contains("`layer.setAdjustment`"), "{p}: {err}"); @@ -3244,9 +3251,9 @@ fn hue_saturation_uses_photoshops_hue_key() { #[test] fn camera_raw_filter_steps_import_as_filter_camera_raw() { let int = |v: i32| D::Integer(v); - let mut d = desc("null") - .with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))) - .with("PrVe", int(184_549_376)) + // Every step carries the version keys a recording has (a verified process version). + let cr = || desc("null").with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))).with("PrVN", int(5)).with("PrVe", int(184_549_376)); + let mut d = cr() .with("WBal", enm("WBal", "Cst ")) .with("Temp", int(12)) .with("Tint", int(-4)) @@ -3278,21 +3285,28 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { d = d.with(&format!("HA_{k}"), int(v)); } d = d.with("SA_O", int(-15)); - let calibrated = desc("null").with("Ex12", D::Double(0.2)).with("RHue", int(8)); - let smoothed = desc("null").with("CNR ", int(25)).with("CNRS", int(70)); - let auto_wb = desc("null").with("WBal", enm("WBal", "Atmt")).with("Temp", int(5)); - let partial_splits = desc("null").with("PC_1", int(20)); - let odd_curve = desc("null").with("Crv ", int(3)); + let calibrated = cr().with("Ex12", D::Double(0.2)).with("RHue", int(8)); + let smoothed = cr().with("CNR ", int(25)).with("CNRS", int(70)); + let auto_wb = cr().with("WBal", enm("WBal", "Atmt")).with("Temp", int(5)); + let partial_splits = cr().with("PC_1", int(20)); + let odd_curve = cr().with("Crv ", int(3)); // Review of #8714: values that would replay differently, or fail to play, stay Photoshop steps. - let reversed_splits = desc("null").with("PC_1", int(80)).with("PC_2", int(50)).with("PC_3", int(20)); - let split_past_100 = desc("null").with("PC_1", int(20)).with("PC_2", int(50)).with("PC_3", int(120)); - let one_point_curve = desc("null").with("Crv ", D::List([0, 0].map(int).to_vec())); - let unordered_curve = desc("null").with("CrvG", D::List([0, 0, 128, 90, 64, 50, 255, 255].map(int).to_vec())); - let text_contrast = desc("null").with("Cr12", D::Text(UnicodeString::new_nul("ten"))); - let text_hue = desc("null").with("HA_R", D::Text(UnicodeString::new_nul("red"))); - let text_grade = desc("null").with("STSH", D::Text(UnicodeString::new_nul("blue"))); - let exposure_past_5 = desc("null").with("Ex12", D::Double(6.0)); - let negative_sharpening = desc("null").with("Shrp", int(-10)); + let reversed_splits = cr().with("PC_1", int(80)).with("PC_2", int(50)).with("PC_3", int(20)); + let split_past_100 = cr().with("PC_1", int(20)).with("PC_2", int(50)).with("PC_3", int(120)); + let one_point_curve = cr().with("Crv ", D::List([0, 0].map(int).to_vec())); + let unordered_curve = cr().with("CrvG", D::List([0, 0, 128, 90, 64, 50, 255, 255].map(int).to_vec())); + let text_contrast = cr().with("Cr12", D::Text(UnicodeString::new_nul("ten"))); + let text_hue = cr().with("HA_R", D::Text(UnicodeString::new_nul("red"))); + let text_grade = cr().with("STSH", D::Text(UnicodeString::new_nul("blue"))); + let exposure_past_5 = cr().with("Ex12", D::Double(6.0)); + let negative_sharpening = cr().with("Shrp", int(-10)); + // CodeRabbit on batch 11: a process version the PSD mapping hasn't verified renders differently. + let unknown_version = + desc("null").with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))).with("PrVN", int(4)).with("PrVe", int(184_549_376)).with("Ex12", D::Double(0.2)); + let no_version_number = desc("null").with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))).with("PrVe", int(184_549_376)).with("Ex12", D::Double(0.2)); + let mismatched_pair = + desc("null").with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))).with("PrVN", int(6)).with("PrVe", int(184_549_376)).with("Ex12", D::Double(0.2)); + let no_camera_raw_version = desc("null").with("PrVN", int(5)).with("PrVe", int(184_549_376)).with("Ex12", D::Double(0.2)); let items = vec![ item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(d)), item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(calibrated)), @@ -3309,6 +3323,10 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(text_grade)), item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(exposure_past_5)), item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(negative_sharpening)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(unknown_version)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(no_version_number)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(mismatched_pair)), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(no_camera_raw_version)), ]; let file = AtnFile { name: UnicodeString::new_nul("Looks"), @@ -3338,7 +3356,7 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { for (k, (id, _)) in steps.iter().enumerate().skip(1) { assert_eq!(id, PHOTOSHOP_STEP, "step {k}"); } - assert_eq!(imp.unsupported.iter().map(|u| u.step).collect::>(), (1..=14).collect::>()); + assert_eq!(imp.unsupported.iter().map(|u| u.step).collect::>(), (1..=18).collect::>()); // The imported step plays. let mut s = Session::new(); s.execute("file.new", json!({"width": 16, "height": 12})).unwrap(); @@ -3354,6 +3372,7 @@ fn camera_raw_filter_steps_import_as_filter_camera_raw() { fn loaded_camera_raw_filter_steps_save_back_unchanged() { let recorded = desc("null") .with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))) + .with("PrVN", D::Integer(5)) .with("PrVe", D::Integer(184_549_376)) .with("WBal", enm("WBal", "Cst ")) .with("Ex12", D::Double(0.35)) @@ -3398,13 +3417,14 @@ fn loaded_camera_raw_filter_steps_save_back_unchanged() { /// and is reported, rather than replaying without that processing. #[test] fn camera_raw_filter_steps_with_unknown_keys_stay_photoshop_steps() { - let upright = desc("null").with("Ex12", D::Double(0.2)).with("PerV", D::Integer(20)); - let profile = desc("null").with("Cr12", D::Integer(10)).with("LookName", D::Text(UnicodeString::new_nul("B&W 05"))); + let cr = || desc("null").with("CrVe", D::Text(UnicodeString::new_nul("16.1.1"))).with("PrVN", D::Integer(5)).with("PrVe", D::Integer(184_549_376)); + let upright = cr().with("Ex12", D::Double(0.2)).with("PerV", D::Integer(20)); + let profile = cr().with("Cr12", D::Integer(10)).with("LookName", D::Text(UnicodeString::new_nul("B&W 05"))); let file = one_action(vec![ item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(upright.clone())), item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(profile)), item("Adobe Camera Raw Filter", "Camera Raw Filter", None), - item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(desc("null").with("Ex12", D::Double(0.2)))), + item("Adobe Camera Raw Filter", "Camera Raw Filter", Some(cr().with("Ex12", D::Double(0.2)))), ]); let mut s = Session::new(); let loaded = s.execute("actions.load", json!({"data": b64(&atn::write(&file).unwrap())})).unwrap(); @@ -3623,6 +3643,35 @@ fn pattern_fill_ids_beat_names_across_document_and_library() { } } +/// CodeRabbit on batch 11: a pattern step that names its pattern only by `patternName` exports +/// that name, rather than a step with no pattern (which plays the current one). +#[test] +fn pattern_steps_named_only_by_pattern_name_export_the_name() { + let one = Action { name: "P".into(), steps: vec![("layer.newFillLayer.pattern".into(), json!({"patternName": "Checkerboard"}))], ..Default::default() }; + let (bytes, skipped) = export("Pat", &[&one], &[], false).unwrap(); + assert!(skipped.is_empty()); + let steps = import(&bytes).unwrap().actions[0].steps.clone(); + assert_eq!(steps[0].0, "layer.newFillLayer.pattern"); + assert_eq!(steps[0].1["pattern"], json!("Checkerboard"), "{}", steps[0].1); +} + +/// CodeRabbit on batch 11: when the recorded id is installed nowhere, the recorded name is looked +/// up as a name only. A pattern whose id equals that name text doesn't beat the one named so. +#[test] +fn pattern_fill_name_fallback_matches_names_not_ids() { + 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"); + // Green is named like the red pattern's id. + define_pattern(&mut s, "#00ff00", &red); + let data = set_of("Pat", vec![("NameIsAnId", vec![pattern_fill_step("5e1c0000-aaaa-4bbb-8ccc-000000000000", &red)])]); + s.execute("actions.load", json!({"data": data})).unwrap(); + s.execute("file.new", json!({"width": 4, "height": 4, "mode": "rgb", "depth": 8})).unwrap(); + let r = s.execute("actions.play", json!({"action": "NameIsAnId"})).unwrap(); + assert!(r.get("failed").is_none(), "{r}"); + assert_eq!(pixel(&mut s), [0.0, 1.0, 0.0, 1.0]); +} + /// 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] diff --git a/crates/engine/src/cmd/pattern_cmds.rs b/crates/engine/src/cmd/pattern_cmds.rs index c5484f4b4ab..d1a93b42d4f 100644 --- a/crates/engine/src/cmd/pattern_cmds.rs +++ b/crates/engine/src/cmd/pattern_cmds.rs @@ -197,7 +197,11 @@ pub(crate) fn resolve_or_named(s: &Session, key: &str, p: &Value) -> std::result 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)), + // The name is a name: another pattern whose id happens to equal it doesn't count. + Some(n) => in_doc(key, "") + .or_else(|| find(&s.patterns.items, key, "").map(|p| (p, true))) + .or_else(|| in_doc("", n)) + .or_else(|| find(&s.patterns.items, "", n).map(|p| (p, true))), None => by_key(key), }; match found { diff --git a/crates/psd/src/codepage.rs b/crates/psd/src/codepage.rs index e44cf0d7ce5..75e0f7c468a 100644 --- a/crates/psd/src/codepage.rs +++ b/crates/psd/src/codepage.rs @@ -23,7 +23,8 @@ //! Only the first [`GUESS_SAMPLE`] bytes of names are examined. use encoding_rs::{ - BIG5, DecoderResult, EUC_KR, Encoding, GBK, MACINTOSH, REPLACEMENT, SHIFT_JIS, UTF_8, UTF_16BE, UTF_16LE, WINDOWS_1251, WINDOWS_1252, X_USER_DEFINED, + BIG5, DecoderResult, EUC_KR, Encoding, GBK, ISO_2022_JP, MACINTOSH, REPLACEMENT, SHIFT_JIS, UTF_8, UTF_16BE, UTF_16LE, WINDOWS_1251, WINDOWS_1252, + X_USER_DEFINED, }; use crate::error::{PsdError, Result}; @@ -142,10 +143,11 @@ pub(crate) fn reads_as_common(name: &[u8], enc: &'static Encoding) -> bool { /// Resolves an encoding label (`shift_jis`, `gbk`, `big5`, `euc-kr`, `windows-1252`, `utf-8`…; /// case and surrounding whitespace are ignored). Labels for encodings that cannot hold an 8-bit -/// name are rejected. +/// name are rejected, and so is ISO-2022-JP: its names are 7-bit escape sequences, which would +/// pass through as ASCII. pub(crate) fn resolve_label(label: &str) -> Result<&'static Encoding> { match Encoding::for_label(label.as_bytes()) { - Some(enc) if ![REPLACEMENT, UTF_16LE, UTF_16BE, X_USER_DEFINED].contains(&enc) => Ok(enc), + Some(enc) if ![REPLACEMENT, UTF_16LE, UTF_16BE, X_USER_DEFINED, ISO_2022_JP].contains(&enc) => Ok(enc), _ => Err(PsdError::Unsupported(format!("text encoding `{label}`: use a label such as shift_jis, gbk, big5, euc-kr, windows-1252 or utf-8"))), } } @@ -540,7 +542,7 @@ mod tests { for ok in ["shift_jis", "gbk", "big5", "euc-kr", "windows-1252", "utf-8"] { assert!(resolve_label(ok).is_ok(), "{ok}"); } - for bad in ["nope", "replacement", "utf-16le", "x-user-defined", "", "iso-2022-kr"] { + for bad in ["nope", "replacement", "utf-16le", "x-user-defined", "", "iso-2022-kr", "iso-2022-jp", "csISO2022JP"] { let Err(e) = resolve_label(bad) else { panic!("{bad} should be rejected") }; assert!(e.to_string().contains("shift_jis"), "{e}"); } diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 5f2ab0a45c6..6fa9e7877e6 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -101,9 +101,9 @@ fn playback_targets(app: &PhotocraftApp) -> Vec { /// pauses for a step dialog of its own hands the rest to that dialog, which plays them after its OK /// (Cancel stops them all, as it stops one action). A pause inside an action it calls resumes only /// the called action, so the set stops there rather than run its next action on an unfinished one. Returns the last result with `ran` counting the steps -/// of all of them, or `None` when there was nothing to play. -fn play_targets(app: &mut PhotocraftApp, targets: &[usize]) -> Result, String> { - let (mut last, mut ran) = (None, 0u64); +/// of all of them plus `before` (steps the same Play ran before a pause), or `None` when there was nothing to play. +fn play_targets(app: &mut PhotocraftApp, targets: &[usize], before: u64) -> Result, String> { + let (mut last, mut ran) = (None, before); for (n, &i) in targets.iter().enumerate() { let name = app.session.actions.list.get(i).map(|a| a.name.clone()); let mut v = app.run("actions.play", json!({"action": i}))?; @@ -115,12 +115,15 @@ fn play_targets(app: &mut PhotocraftApp, targets: &[usize]) -> Result = targets.get(n + 1..).unwrap_or_default().iter().filter_map(|i| list.get(*i).map(|a| a.name.clone())).collect(); let token = app.ui.dialog_mut(dialog).and_then(|d| d.fields.get(RESUME)).and_then(Value::as_u64); if let Some(entry) = token.and_then(|t| app.paused_playbacks.paused.get_mut(&t)) && name.as_ref() == Some(&entry.action) { entry.then = rest; + entry.ran = ran; } break; } @@ -521,7 +524,14 @@ fn save_dialog(app: &mut PhotocraftApp, set: Option) -> Result' | '|') { '_' } else { c }) .collect(); - let file = format!("{}.atn", photocraft_engine::file_cmds::portable_device_name(stem)); + // A file name holds at most 255 bytes: the stem gets what `.atn` leaves, cut at a character. + let mut stem = photocraft_engine::file_cmds::portable_device_name(stem); + let mut cut = 255 - ".atn".len(); + while !stem.is_char_boundary(cut.min(stem.len())) { + cut -= 1; + } + stem.truncate(cut); + let file = format!("{stem}.atn"); app.pick_save(&file, move |app, path| { let write = app.services.write.as_mut().ok_or("no writer configured")?; write(&path, &bytes)?; @@ -690,8 +700,11 @@ pub(crate) struct PausedPlayback { /// box, automation), which end the call through `resume`, `abandoned` or `stopped`, so the /// recording comes back exactly once. record: Option, - /// The actions still to play after this one, when Play started a whole set. - then: Vec, + /// The actions still to play after this one, by name, when Play started a whole set. + then: Vec, + /// The steps that Play ran before this pause (earlier actions of the set, and this one's + /// steps before the dialog), so the final count covers the whole Play. + ran: u64, } /// The paused playbacks, by the token their dialog carries. The dialog's fields hold only the @@ -705,7 +718,7 @@ pub(crate) struct PausedPlaybacks { impl PausedPlaybacks { fn pause(&mut self, action: String, from: usize, gate: Option) -> u64 { self.last = self.last.wrapping_add(1); - self.paused.insert(self.last, PausedPlayback { action, from, gate, record: None, then: Vec::new() }); + self.paused.insert(self.last, PausedPlayback { action, from, gate, record: None, then: Vec::new(), ran: 0 }); self.last } @@ -748,22 +761,29 @@ pub fn resume(app: &mut PhotocraftApp, fields: &serde_json::Map) && entry.action == paused.action { entry.then = paused.then.clone(); + entry.ran = paused.ran.saturating_add(1).saturating_add(v.get("ran").and_then(Value::as_u64).unwrap_or(0)); } - // The rest of a set Play started: under the same gate, and only if this action finished. + // The count covers the steps this Play ran before the pause, and the step the dialog ran. + let ran = paused.ran.saturating_add(1).saturating_add(played.as_ref().ok().and_then(|v| v.get("ran")).and_then(Value::as_u64).unwrap_or(0)); + if let Ok(Some(o)) = played.as_mut().map(Value::as_object_mut) + && o.contains_key("ran") + { + o.insert("ran".into(), json!(ran)); + } + // The rest of a set Play started: under the same gate, and only if this action finished. An + // action of it deleted or renamed meanwhile ends the set there. if let Ok(v) = &played && !paused.then.is_empty() && v.get("failed").is_none() && v.get("paused").is_none() { - let ran = v.get("ran").and_then(Value::as_u64).unwrap_or(0); - played = play_targets(app, &paused.then).map(|rest| { - let mut rest = rest.unwrap_or(Value::Null); - let total = ran.saturating_add(rest.get("ran").and_then(Value::as_u64).unwrap_or(0)); - if let Some(o) = rest.as_object_mut() { - o.insert("ran".into(), json!(total)); - } - rest - }); + let list = &app.session.actions.list; + let rest: Vec = paused.then.iter().map_while(|name| list.iter().position(|a| &a.name == name)).collect(); + match play_targets(app, &rest, ran) { + Ok(Some(r)) => played = Ok(r), + Ok(None) => {} + Err(e) => played = Err(e), + } } app.session.authorize = saved; match played { @@ -842,7 +862,7 @@ pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { "stopRec" => app.run("actions.stop", json!({})), "play" => { let targets = playback_targets(app); - play_targets(app, &targets).map(|v| { + play_targets(app, &targets, 0).map(|v| { if let Some(v) = &v { report_play(app, v); } @@ -1363,7 +1383,7 @@ pub fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } }); if let Some(targets) = play_idx { - match play_targets(app, &targets) { + match play_targets(app, &targets, 0) { Ok(Some(v)) => report_play(app, &v), Ok(None) => {} Err(e) => { diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index 7a233fcdf57..cf1758bcf8e 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -721,6 +721,19 @@ fn play_with_an_empty_set_selected_plays_nothing() { assert!(layer_names(h.state()).is_empty(), "{:?}", layer_names(h.state())); } +/// CodeRabbit on batch 11: with an empty set selected, Batch and Create Droplet start on the first +/// action, as `selected_action` documents. +#[test] +fn an_empty_selected_set_falls_back_to_the_first_action() { + use egui_kittest::kittest::Queryable; + let mut h = two_set_panel(); + h.state_mut().run("actions.newSet", json!({"name": "Print"})).unwrap(); + h.run_steps(2); + h.get_by_label("Print").click(); + h.run_steps(2); + assert_eq!(selected_action(h.state()).map(|a| a.name.as_str()), Some("Resize")); +} + /// #10459 fix-up: the common case is unchanged: a selected action plays alone, also after a set /// folder was selected before it, and a later Delete doesn't bring that set back. #[test] @@ -832,10 +845,41 @@ fn a_set_paused_at_a_step_dialog_plays_its_other_actions_after_ok() { let mut names = layer_names(h.state()); names.sort(); assert_eq!(names, ["a", "a2", "b"], "B played after A's dialogs"); - assert!(h.state().ui.status.starts_with("Played"), "{}", h.state().ui.status); + // CodeRabbit on batch 11: the count covers the whole Play, also the steps before each pause. + assert_eq!(h.state().ui.status, "Played 5 steps"); } } +/// CodeRabbit on batch 11: the rest of a paused set is kept by name, so an action moved into the +/// middle of the list while the dialog is open neither plays in its place nor skips one of the set. +#[test] +fn a_set_paused_at_a_dialog_plays_its_own_actions_after_a_move() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + for (name, set, layer) in [("A", "S", "a"), ("B", "S", "b"), ("C", "S", "c"), ("X", "Other", "x")] { + let mut a = Action::new(name, vec![("layer.new.layer".into(), json!({"name": layer}))]); + a.set = Some(set.into()); + app.session.actions.list.push(a); + } + app.session.actions.list[0].steps.push(("filter.blur.gaussianBlur".into(), json!({"radius": 1}))); + app.session.actions.list[0].dialogs.insert(1); + let mut h = egui_kittest::Harness::builder().with_size(vec2(360.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(2); + h.get_by_label("S").click(); + h.run_steps(2); + h.get_by_label("Play selection").click(); + h.run_steps(2); + assert_eq!(layer_names(h.state()), ["a"]); + let dialog = h.state().ui.dialogs.last().map(|d| d.id).expect("the blur's dialog"); + h.state_mut().run("actions.move", json!({"action": "X", "to": 1})).unwrap(); + crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); + h.run_steps(2); + let mut names = layer_names(h.state()); + names.sort(); + assert_eq!(names, ["a", "b", "c"]); +} + /// #10459 fix-up: a set whose action pauses at a dialog inside an action it calls stops there: /// the called action resumes alone, so the next action of the set must not run on a caller that /// never finished. @@ -1200,6 +1244,23 @@ fn save_actions_suggests_a_windows_safe_name_for_device_and_control_character_se } } +/// CodeRabbit on batch 11: a set name longer than a file name may be is cut to 255 bytes with its +/// suffix, at a character boundary. +#[test] +fn save_actions_suggests_a_file_name_of_at_most_255_bytes() { + use egui_kittest::kittest::Queryable; + let set = "é".repeat(200); + let (mut h, asked) = empty_set_save_harness(&set); + h.get_by_label(set.as_str()).click(); + h.run_steps(2); + h.get_by_label("Save Actions…").click(); + h.run_steps(2); + h.state_mut().poll_file_dialog(&egui::Context::default(), None); + let asked = asked.borrow(); + let [crate::file_dialog::FileDialogRequest::Save { suggested }] = asked.as_slice() else { panic!("{asked:?}") }; + assert_eq!(*suggested, format!("{}.atn", "é".repeat(125))); +} + #[test] fn moving_an_action_next_to_another_set_joins_it() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); From 02316e552d2b51742c8400451646da6788eadb3b Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 21:20:38 +0100 Subject: [PATCH 51/52] Integration: a paused set Play ends at an action replaced under its name (#10459) CodeRabbit on batch 11: the rest of a set paused at a step dialog was kept by name, so an action deleted and made again under the same name while the dialog was open played under the original Play. Actions have no id, so the rest is now kept as the actions themselves and continues only while each one is unchanged; moving them in the list still works. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/actions.rs | 16 ++++++----- crates/ui-egui/src/panels/actions/tests.rs | 31 ++++++++++++++++++++++ 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 6fa9e7877e6..88034ab2c8d 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -115,9 +115,10 @@ fn play_targets(app: &mut PhotocraftApp, targets: &[usize], before: u64) -> Resu } last = Some(v); if let Some(dialog) = paused.filter(|_| !failed) { - // By name: the list can be reordered while the dialog is open (`actions.move`). + // As they are now, not by index: the list can be reordered while the dialog is open + // (`actions.move`), and one deleted and made again under its name isn't the same action. let list = &app.session.actions.list; - let rest: Vec = targets.get(n + 1..).unwrap_or_default().iter().filter_map(|i| list.get(*i).map(|a| a.name.clone())).collect(); + let rest: Vec = targets.get(n + 1..).unwrap_or_default().iter().filter_map(|i| list.get(*i).cloned()).collect(); let token = app.ui.dialog_mut(dialog).and_then(|d| d.fields.get(RESUME)).and_then(Value::as_u64); if let Some(entry) = token.and_then(|t| app.paused_playbacks.paused.get_mut(&t)) && name.as_ref() == Some(&entry.action) @@ -700,8 +701,10 @@ pub(crate) struct PausedPlayback { /// box, automation), which end the call through `resume`, `abandoned` or `stopped`, so the /// recording comes back exactly once. record: Option, - /// The actions still to play after this one, by name, when Play started a whole set. - then: Vec, + /// The actions still to play after this one, as they were when Play started a whole set. + /// Actions have no id, so the whole action stands in for one: an action deleted and made again + /// under the same name, or edited, while the dialog is open no longer matches. + then: Vec, /// The steps that Play ran before this pause (earlier actions of the set, and this one's /// steps before the dialog), so the final count covers the whole Play. ran: u64, @@ -771,14 +774,15 @@ pub fn resume(app: &mut PhotocraftApp, fields: &serde_json::Map) o.insert("ran".into(), json!(ran)); } // The rest of a set Play started: under the same gate, and only if this action finished. An - // action of it deleted or renamed meanwhile ends the set there. + // action of it deleted, renamed, edited or replaced by a new one of the same name meanwhile + // ends the set there. if let Ok(v) = &played && !paused.then.is_empty() && v.get("failed").is_none() && v.get("paused").is_none() { let list = &app.session.actions.list; - let rest: Vec = paused.then.iter().map_while(|name| list.iter().position(|a| &a.name == name)).collect(); + let rest: Vec = paused.then.iter().map_while(|then| list.iter().position(|a| a == then)).collect(); match play_targets(app, &rest, ran) { Ok(Some(r)) => played = Ok(r), Ok(None) => {} diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index cf1758bcf8e..06a5cd5fb3d 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -880,6 +880,37 @@ fn a_set_paused_at_a_dialog_plays_its_own_actions_after_a_move() { assert_eq!(names, ["a", "b", "c"]); } +/// CodeRabbit on batch 11: an action of the paused set deleted and made again under its name while +/// the dialog is open is a different action, so the set ends there instead of playing it. +#[test] +fn a_set_paused_at_a_dialog_ends_at_an_action_replaced_under_its_name() { + use egui_kittest::kittest::Queryable; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + for (name, layer) in [("A", "a"), ("B", "b"), ("C", "c")] { + let mut a = Action::new(name, vec![("layer.new.layer".into(), json!({"name": layer}))]); + a.set = Some("S".into()); + app.session.actions.list.push(a); + } + app.session.actions.list[0].steps.push(("filter.blur.gaussianBlur".into(), json!({"radius": 1}))); + app.session.actions.list[0].dialogs.insert(1); + let mut h = egui_kittest::Harness::builder().with_size(vec2(360.0, 400.0)).build_ui_state(|ui, app| panel(app, ui), app); + h.run_steps(2); + h.get_by_label("S").click(); + h.run_steps(2); + h.get_by_label("Play selection").click(); + h.run_steps(2); + assert_eq!(layer_names(h.state()), ["a"]); + let dialog = h.state().ui.dialogs.last().map(|d| d.id).expect("the blur's dialog"); + h.state_mut().run("actions.delete", json!({"action": "B"})).unwrap(); + let mut b = Action::new("B", vec![("layer.new.layer".into(), json!({"name": "new b"}))]); + b.set = Some("S".into()); + h.state_mut().session.actions.list.insert(1, b); + crate::dialogs::confirm(h.state_mut(), dialog).unwrap(); + h.run_steps(2); + assert_eq!(layer_names(h.state()), ["a"], "neither the new B nor C after it played"); +} + /// #10459 fix-up: a set whose action pauses at a dialog inside an action it calls stops there: /// the called action resumes alone, so the next action of the set must not run on a caller that /// never finished. From 24be8ea6e2b117929ad2f168382a379e0b07e64a Mon Sep 17 00:00:00 2001 From: Gabriel Heuser Date: Mon, 2 Nov 2026 01:46:05 +0200 Subject: [PATCH 52/52] Add editable arrowheads to Line tool (#6408) (#9259) * Add configurable arrowheads to line tool * Add editable arrowheads to Line tool * Fix arrow scaling validation and PSD import defaults * Preserve arrow geometry under affine transforms * Preserve scaled arrowhead dimensions and prevent non-finite geometry * Localize arrowhead Start and End labels * Fix arrow transform editability and short line handling * Fix PSD arrow concavity serialization * Fix arrow dimension fallback validation * Refine arrowhead options UI to match Photoshop * Add opt-in arrowhead defaults to Shape properties * Fix tool reset syntax after upstream merge * Validate arrowhead flags and clamp copied defaults * Preserve editable headless lines under transforms * Fix arrowhead UI imports and formatting after v0.17 merge * Format arrowhead properties after v0.18 merge * Fix Clippy lint errors in arrow geometry and tests * Fix headless arrow geometry after nonuniform scaling * Fix proportional arrow scaling in Properties panel * Fix Rust formatting in Properties arrow scaling tests * test: validate invalid arrowhead dimensions without mutation * fix: preserve arrow compatibility with older pcraft versions --- crates/doc/src/vector.rs | 11 + crates/engine/src/cmd/vector_cmds.rs | 4 +- crates/engine/src/cmd/vector_cmds/params.rs | 48 +++- crates/engine/src/cmd/vector_cmds/shape.rs | 270 +++++++++++++++++- crates/engine/src/cmd/vector_cmds/tests.rs | 144 ++++++++++ crates/format/src/convert.rs | 15 +- crates/format/src/manifest.rs | 4 + crates/format/tests/it/roundtrip.rs | 54 ++++ crates/io/src/vector_map.rs | 41 ++- crates/ui-egui/src/panels/layer_props_ui.rs | 74 ++++- crates/ui-egui/src/panels/options_bar.rs | 1 + crates/ui-egui/src/state/tool_options.rs | 11 + crates/ui-egui/src/tools/corner_radius.rs | 2 +- crates/ui-egui/src/tools/tool_reset.rs | 18 +- crates/ui-egui/src/tools/vector_ui.rs | 67 +++++ crates/ui-egui/src/tools/vector_ui/options.rs | 98 ++++++- crates/ui-egui/src/tools/vector_ui/overlay.rs | 7 +- crates/ui-egui/src/tools/vector_ui/shapes.rs | 5 +- crates/vector/src/shapes.rs | 119 ++++++++ docs/shape-strokes.md | 13 + 20 files changed, 979 insertions(+), 27 deletions(-) diff --git a/crates/doc/src/vector.rs b/crates/doc/src/vector.rs index a66aed85871..9dc8edf2584 100644 --- a/crates/doc/src/vector.rs +++ b/crates/doc/src/vector.rs @@ -318,6 +318,17 @@ pub enum LiveShape { to: [f64; 2], weight: f64, }, + /// Editable vector arrow with parameters preserved by serde in the project document. + ArrowLine { + from: [f64; 2], + to: [f64; 2], + weight: f64, + start: bool, + end: bool, + width: f64, + length: f64, + concavity: f64, + }, } /// A shape layer: a filled and/or stroked path. diff --git a/crates/engine/src/cmd/vector_cmds.rs b/crates/engine/src/cmd/vector_cmds.rs index 5f6b3c301a5..f331a303353 100644 --- a/crates/engine/src/cmd/vector_cmds.rs +++ b/crates/engine/src/cmd/vector_cmds.rs @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "New Shape Layer", ["Layer", "New"], leak(format!( - r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (polygon/star: rounds every vertex; the Triangle tool is a 3-sided polygon),"from":[x,y],"to":[x,y],"weight":px=1 (line),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"## + r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (polygon/star: rounds every vertex; the Triangle tool is a 3-sided polygon),"from":[x,y],"to":[x,y],"weight":px=1 (line),"arrowStart":bool=false,"arrowEnd":bool=false,"arrowWidth":px=52,"arrowLength":px=50,"arrowConcavity":0..100=0 (line),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"## )), has_doc, shape_create @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Edit Shape", [], leak(format!( - r##"{{"layer":id?,"path":{{…}}? (replaces; drops live shape),"kind":str?,"rect":[x,y,w,h]?,"radii":[tl,tr,br,bl]|r?,"sides":n?,"starRatio":r?,"cornerRadius":px?,"from":[x,y]?,"to":[x,y]?,"weight":px? (live-shape params regenerate the path),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"op":"combine|…"? + "subpath":index? (default all but the first),"fillRule":"nonzero|evenodd"?,{fill}?,{stroke}? (merged into the current stroke),"name":str?}} → shape.info"## + r##"{{"layer":id?,"path":{{…}}? (replaces; drops live shape),"kind":str?,"rect":[x,y,w,h]?,"radii":[tl,tr,br,bl]|r?,"sides":n?,"starRatio":r?,"cornerRadius":px?,"from":[x,y]?,"to":[x,y]?,"weight":px? (live-shape params regenerate the path),"arrowStart":bool?,"arrowEnd":bool?,"arrowWidth":px?,"arrowLength":px?,"arrowConcavity":0..100? (line arrows),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"op":"combine|…"? + "subpath":index? (default all but the first),"fillRule":"nonzero|evenodd"?,{fill}?,{stroke}? (merged into the current stroke),"name":str?}} → shape.info"## )), has_layer, shape_edit diff --git a/crates/engine/src/cmd/vector_cmds/params.rs b/crates/engine/src/cmd/vector_cmds/params.rs index cf73f96a415..bab083c1620 100644 --- a/crates/engine/src/cmd/vector_cmds/params.rs +++ b/crates/engine/src/cmd/vector_cmds/params.rs @@ -357,13 +357,51 @@ pub(super) fn live_from_params(cmd: &str, kind: &str, p: &Value, prev: Option<&L } "line" => { let (pf, pto, pw) = match prev { - Some(LiveShape::Line { from, to, weight }) => (Some(*from), Some(*to), *weight), + Some(LiveShape::Line { from, to, weight }) | Some(LiveShape::ArrowLine { from, to, weight, .. }) => (Some(*from), Some(*to), *weight), _ => (None, None, 1.0), }; - LiveShape::Line { - from: nums::<2>(p, "from").or(pf).ok_or_else(|| bad(cmd, "`from`: [x, y] is required"))?, - to: nums::<2>(p, "to").or(pto).ok_or_else(|| bad(cmd, "`to`: [x, y] is required"))?, - weight: f64p(p, "weight").unwrap_or(pw).max(0.0), + let from = nums::<2>(p, "from").or(pf).ok_or_else(|| bad(cmd, "`from`: [x, y] is required"))?; + let to = nums::<2>(p, "to").or(pto).ok_or_else(|| bad(cmd, "`to`: [x, y] is required"))?; + let weight = f64p(p, "weight").unwrap_or(pw).max(0.0); + let arrow_fields = ["arrowStart", "arrowEnd", "arrowWidth", "arrowLength", "arrowConcavity"]; + let is_arrow = matches!(prev, Some(LiveShape::ArrowLine { .. })) || arrow_fields.iter().any(|k| p.get(*k).is_some()); + if is_arrow { + let (ps, pe, pwidth, plen, pc) = match prev { + Some(LiveShape::ArrowLine { start, end, width, length, concavity, .. }) => (*start, *end, *width, *length, *concavity), + _ => (false, false, 52.0, 50.0, 0.0), + }; + let dim = |key: &str, fallback: f64, min: f64, max: f64| -> Result { + let value = match p.get(key) { + Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("`{key}` must be numeric")))?, + None => fallback, + }; + // Preserve scaled arrowhead dimensions when editing other properties. + let preserved_scaled_size = p.get(key).is_none() && matches!(key, "arrowWidth" | "arrowLength") && value.is_finite(); + let value = if preserved_scaled_size { value.max(min) } else { value }; + if !value.is_finite() || (!preserved_scaled_size && !(min..=max).contains(&value)) { + return Err(bad(cmd, format!("`{key}` must be within {min}..={max}"))); + } + Ok(value) + }; + // Reject invalid flag types rather than silently using defaults. + let flag = |key: &str, fallback: bool| -> Result { + match p.get(key) { + Some(v) => v.as_bool().ok_or_else(|| bad(cmd, format!("`{key}` must be a boolean"))), + None => Ok(fallback), + } + }; + LiveShape::ArrowLine { + from, + to, + weight, + start: flag("arrowStart", ps)?, + end: flag("arrowEnd", pe)?, + width: dim("arrowWidth", pwidth, 1.0, 4096.0)?, + length: dim("arrowLength", plen, 1.0, 4096.0)?, + concavity: dim("arrowConcavity", pc, 0.0, 100.0)?, + } + } else { + LiveShape::Line { from, to, weight } } } o => return Err(bad(cmd, format!("unknown kind `{o}`"))), diff --git a/crates/engine/src/cmd/vector_cmds/shape.rs b/crates/engine/src/cmd/vector_cmds/shape.rs index 961e7679245..33e1bfe3cfa 100644 --- a/crates/engine/src/cmd/vector_cmds/shape.rs +++ b/crates/engine/src/cmd/vector_cmds/shape.rs @@ -80,7 +80,7 @@ fn live_kind(l: &LiveShape) -> &'static str { LiveShape::Ellipse { .. } => "ellipse", LiveShape::Polygon { star_ratio, .. } if *star_ratio < 1.0 => "star", LiveShape::Polygon { .. } => "polygon", - LiveShape::Line { .. } => "line", + LiveShape::Line { .. } | LiveShape::ArrowLine { .. } => "line", } } @@ -148,12 +148,61 @@ pub(crate) fn shift_shape(doc: &Document, sh: &mut ShapeLayer, dx: f64, dy: f64) } } +/// Returns arrow-local scales when the transformed axes remain perpendicular. +fn arrow_axis_scales(a: &Affine, from: [f64; 2], to: [f64; 2]) -> Option<(f64, f64)> { + let [m0, m1, m2, m3, _, _] = a.m; + let (dx, dy) = (to[0] - from[0], to[1] - from[1]); + let old_length = dx.hypot(dy); + if !old_length.is_finite() || old_length <= 1e-12 { + return None; + } + let (ux, uy) = (dx / old_length, dy / old_length); + let (ax, ay) = (m0 * ux + m2 * uy, m1 * ux + m3 * uy); + let (px, py) = (-m0 * uy + m2 * ux, -m1 * uy + m3 * ux); + let axial = ax.hypot(ay); + let perpendicular = px.hypot(py); + if !axial.is_finite() || !perpendicular.is_finite() || axial <= 1e-12 || perpendicular <= 1e-12 { + return None; + } + let dot = ax * px + ay * py; + (dot.abs() <= 1e-10 * axial * perpendicular).then_some((axial, perpendicular)) +} + /// Applies an affine transform to a shape's path, keeping the live shape when the transform /// is a translation plus axis-aligned scale (otherwise the shape stops being parametric). pub fn transform_shape(sh: &mut ShapeLayer, a: &Affine) { + // Check original arrow dimensions before transforming the path. + // Parameters already clamped by arrow_line cannot faithfully + // regenerate the transformed geometry. + if let Some(LiveShape::ArrowLine { from, to, weight, start, end, width, length, .. }) = sh.live.as_ref() + && (*start || *end) + { + let original_length = (to[0] - from[0]).hypot(to[1] - from[1]); + + if !weight.is_finite() + || *weight < 0.1 + || !width.is_finite() + || *width < 1.0 + || !length.is_finite() + || *length < 1.0 + || !original_length.is_finite() + || original_length < 1.0 + { + sh.live = None; + } + } + sh.path = sh.path.transform(a); let [m0, m1, m2, m3, tx, ty] = a.m; let axis_aligned = m1.abs() < 1e-12 && m2.abs() < 1e-12 && m0 > 0.0 && m3 > 0.0; + // The path has already received the exact affine transform. Drop live arrow + // parameters if later edits would regenerate a different, unskewed head. + if let Some(LiveShape::ArrowLine { from, to, .. }) = sh.live.as_ref() + && (to[0] - from[0]).hypot(to[1] - from[1]) > 1e-12 + && arrow_axis_scales(a, *from, *to).is_none() + { + sh.live = None; + } sh.live = match (sh.live.take(), axis_aligned) { (Some(l), true) => { let r = |r: [f64; 4]| [r[0] * m0 + tx, r[1] * m3 + ty, r[2] * m0, r[3] * m3]; @@ -167,6 +216,22 @@ pub fn transform_shape(sh: &mut ShapeLayer, a: &Affine) { LiveShape::Polygon { rect, sides, star_ratio, corner_radius } => { LiveShape::Polygon { rect: r(rect), sides, star_ratio, corner_radius: corner_radius * m0.min(m3) } } + LiveShape::ArrowLine { from, to, weight, start, end, width, length, concavity } => { + let (dx, dy) = (to[0] - from[0], to[1] - from[1]); + let old_len = dx.hypot(dy); + let new_len = (dx * m0).hypot(dy * m3); + let perpendicular_scale = if old_len > 0.0 && new_len > 0.0 { m0 * m3 * old_len / new_len } else { m0.min(m3) }; + LiveShape::ArrowLine { + from: pt(from), + to: pt(to), + weight: weight * perpendicular_scale, + start, + end, + width: width * perpendicular_scale, + length: length * if old_len > 0.0 { new_len / old_len } else { m0.min(m3) }, + concavity, + } + } LiveShape::Line { from, to, weight } => { // Live-shape edits regenerate the line's filled bar from its parameters. // Keep the weight in sync with a positive scale of the path, or an @@ -195,11 +260,61 @@ pub fn transform_shape(sh: &mut ShapeLayer, a: &Affine) { } LiveShape::Ellipse { rect } => Some(LiveShape::Ellipse { rect: r(rect) }), LiveShape::Line { from, to, weight } => Some(LiveShape::Line { from: pt(from), to: pt(to), weight: weight * k }), + LiveShape::ArrowLine { from, to, weight, start, end, width, length, concavity } => { + // Flips and quarter-turns can have different axial and perpendicular + // scales; using the smaller axis for both loses arrowhead length. + let (axial_scale, perpendicular_scale) = arrow_axis_scales(a, from, to).unwrap_or((k, k)); + Some(LiveShape::ArrowLine { + from: pt(from), + to: pt(to), + weight: weight * perpendicular_scale, + start, + end, + width: width * perpendicular_scale, + length: length * axial_scale, + concavity, + }) + } _ => None, } } + // Arbitrary rotations and other orthogonal-axis affine transforms also + // preserve arrow geometry and should keep their editable live parameters. + (Some(LiveShape::ArrowLine { from, to, weight, start, end, width, length, concavity }), false) => { + arrow_axis_scales(a, from, to).map(|(axial_scale, perpendicular_scale)| { + let pt = |p: [f64; 2]| [m0 * p[0] + m2 * p[1] + tx, m1 * p[0] + m3 * p[1] + ty]; + LiveShape::ArrowLine { + from: pt(from), + to: pt(to), + weight: weight * perpendicular_scale, + start, + end, + width: width * perpendicular_scale, + length: length * axial_scale, + concavity, + } + }) + } _ => None, }; + // Keep the exact transformed outline. Remove live arrow parameters + // when minimum-size constraints would alter its regenerated geometry. + if let Some(LiveShape::ArrowLine { from, to, weight, start, end, width, length, .. }) = sh.live.as_ref() + && (*start || *end) + { + let line_length = (to[0] - from[0]).hypot(to[1] - from[1]); + if !weight.is_finite() + || *weight < 0.1 + || !width.is_finite() + || *width < 1.0 + || !length.is_finite() + || *length < 1.0 + || !line_length.is_finite() + || line_length < 1.0 + { + sh.live = None; + } + } sh.psd_raw = None; } @@ -360,7 +475,23 @@ pub(super) fn shape_edit(s: &mut Session, p: &Value) -> Result { sh.live = None; sh.psd_raw = None; } - let geom_keys = ["kind", "rect", "radii", "radius", "sides", "starRatio", "cornerRadius", "from", "to", "weight"]; + let geom_keys = [ + "kind", + "rect", + "radii", + "radius", + "sides", + "starRatio", + "cornerRadius", + "from", + "to", + "weight", + "arrowStart", + "arrowEnd", + "arrowWidth", + "arrowLength", + "arrowConcavity", + ]; if geom_keys.iter().any(|k| p.get(*k).is_some()) { let kind = p.get("kind").and_then(Value::as_str).map(str::to_string).or_else(|| sh.live.as_ref().map(|l| live_kind(l).to_string())); let kind = kind.ok_or_else(|| bad(CMD, "this shape has no live-shape parameters; pass `kind` or `path`"))?; @@ -572,3 +703,138 @@ pub(super) fn selection_to_shape(s: &mut Session, p: &Value) -> Result { } shape_create(s, &q) } + +#[cfg(test)] +mod arrow_affine_regression_tests { + use super::*; + + #[test] + fn forty_five_degree_rotation_retains_live_arrow_and_geometry() { + let live = + LiveShape::ArrowLine { from: [0.0, 0.0], to: [100.0, 0.0], weight: 8.0, start: false, end: true, width: 31.0, length: 31.0, concavity: 50.0 }; + let mut sh = ShapeLayer { path: vector::shapes::live_path(&live), live: Some(live), ..ShapeLayer::default() }; + let mut a = Affine::translate(0.0, 0.0); + let c = std::f64::consts::FRAC_PI_4.cos(); + let s = std::f64::consts::FRAC_PI_4.sin(); + a.m = [c, s, -s, c, 0.0, 0.0]; + transform_shape(&mut sh, &a); + let Some(LiveShape::ArrowLine { width, length, .. }) = sh.live.as_ref() else { + panic!("Arrow must remain parametrically editable after 45-degree rotation"); + }; + assert!((*width - 31.0).abs() < 1e-9); + assert!((*length - 31.0).abs() < 1e-9); + let rebuilt = vector::shapes::live_path(sh.live.as_ref().unwrap()); + assert_eq!(sh.path.subpaths.len(), rebuilt.subpaths.len()); + for (existing, generated) in sh.path.subpaths.iter().zip(rebuilt.subpaths.iter()) { + assert_eq!(existing.knots.len(), generated.knots.len()); + for (a, b) in existing.knots.iter().zip(generated.knots.iter()) { + assert!((a.anchor.x - b.anchor.x).abs() < 1e-8); + assert!((a.anchor.y - b.anchor.y).abs() < 1e-8); + } + } + } + + #[test] + fn subpixel_scale_keeps_transformed_path_but_drops_unreproducible_live_parameters() { + let live = LiveShape::ArrowLine { from: [0.0, 0.0], to: [100.0, 0.0], weight: 5.0, start: false, end: true, width: 31.0, length: 31.0, concavity: 0.0 }; + let mut sh = ShapeLayer { path: vector::shapes::live_path(&live), live: Some(live), ..ShapeLayer::default() }; + let mut a = Affine::translate(0.0, 0.0); + a.m = [0.01, 0.0, 0.0, 0.01, 0.0, 0.0]; + + let expected_path = sh.path.transform(&a); + transform_shape(&mut sh, &a); + + assert_eq!(sh.path, expected_path); + assert!(sh.live.is_none()); + } + + #[test] + fn headless_arrow_survives_nonuniform_diagonal_scale() { + let live = + LiveShape::ArrowLine { from: [0.0, 0.0], to: [100.0, 100.0], weight: 5.0, start: false, end: false, width: 52.0, length: 50.0, concavity: 0.0 }; + + let mut sh = ShapeLayer { path: vector::shapes::live_path(&live), live: Some(live), ..ShapeLayer::default() }; + + let mut a = Affine::translate(0.0, 0.0); + a.m = [2.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + + let expected_path = sh.path.transform(&a); + transform_shape(&mut sh, &a); + + assert_eq!(sh.path, expected_path); + assert!(sh.live.is_none()); + } + + #[test] + fn zero_length_headless_arrow_survives_scale() { + let live = LiveShape::ArrowLine { from: [0.0, 0.0], to: [0.0, 0.0], weight: 5.0, start: false, end: false, width: 52.0, length: 50.0, concavity: 0.0 }; + + let mut sh = ShapeLayer { path: vector::shapes::live_path(&live), live: Some(live), ..ShapeLayer::default() }; + + let mut a = Affine::translate(0.0, 0.0); + a.m = [2.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + + let expected_path = sh.path.transform(&a); + transform_shape(&mut sh, &a); + + assert_eq!(sh.path, expected_path); + assert!(matches!(sh.live, Some(LiveShape::ArrowLine { start: false, end: false, .. }))); + } + + #[test] + fn headless_short_arrow_remains_editable_after_scaling() { + let live = LiveShape::ArrowLine { from: [0.0, 0.0], to: [0.5, 0.0], weight: 0.05, start: false, end: false, width: 31.0, length: 31.0, concavity: 0.0 }; + let mut sh = ShapeLayer { path: vector::shapes::live_path(&live), live: Some(live), ..ShapeLayer::default() }; + + let mut a = Affine::translate(0.0, 0.0); + a.m = [0.5, 0.0, 0.0, 0.5, 0.0, 0.0]; + + let expected = sh.path.transform(&a); + transform_shape(&mut sh, &a); + + assert_eq!(sh.path, expected); + assert!(matches!(sh.live, Some(LiveShape::ArrowLine { start: false, end: false, .. }))); + } + + #[test] + fn scale_above_minimum_still_keeps_live_arrow_editable() { + let live = LiveShape::ArrowLine { from: [0.0, 0.0], to: [100.0, 0.0], weight: 5.0, start: false, end: true, width: 31.0, length: 31.0, concavity: 0.0 }; + let mut sh = ShapeLayer { path: vector::shapes::live_path(&live), live: Some(live), ..ShapeLayer::default() }; + let mut a = Affine::translate(0.0, 0.0); + a.m = [0.5, 0.0, 0.0, 0.5, 0.0, 0.0]; + + transform_shape(&mut sh, &a); + + let Some(LiveShape::ArrowLine { width, length, .. }) = sh.live else { + panic!("Ordinary scaling must preserve editable arrow parameters"); + }; + + assert!((width - 15.5).abs() < 1e-9); + assert!((length - 15.5).abs() < 1e-9); + } + + #[test] + fn reflected_horizontal_arrow_uses_axial_scale_for_head_length() { + let mut a = Affine::translate(0.0, 0.0); + a.m = [-2.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + let (axial, perpendicular) = arrow_axis_scales(&a, [0.0, 0.0], [100.0, 0.0]).unwrap(); + assert!((axial - 2.0).abs() < 1e-10); + assert!((perpendicular - 1.0).abs() < 1e-10); + } + + #[test] + fn anisotropic_diagonal_arrow_cannot_remain_parametric() { + let mut a = Affine::translate(0.0, 0.0); + a.m = [2.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + assert!(arrow_axis_scales(&a, [0.0, 0.0], [100.0, 100.0]).is_none()); + } + + #[test] + fn uniform_scale_preserves_diagonal_arrow_axes() { + let mut a = Affine::translate(0.0, 0.0); + a.m = [2.0, 0.0, 0.0, 2.0, 0.0, 0.0]; + let (axial, perpendicular) = arrow_axis_scales(&a, [0.0, 0.0], [100.0, 100.0]).unwrap(); + assert!((axial - 2.0).abs() < 1e-10); + assert!((perpendicular - 2.0).abs() < 1e-10); + } +} diff --git a/crates/engine/src/cmd/vector_cmds/tests.rs b/crates/engine/src/cmd/vector_cmds/tests.rs index 0b5b89aae96..b659cbd656d 100644 --- a/crates/engine/src/cmd/vector_cmds/tests.rs +++ b/crates/engine/src/cmd/vector_cmds/tests.rs @@ -1238,3 +1238,147 @@ fn triangles_and_polygons_take_a_corner_radius_kept_through_edits_and_scaling() s.execute("shape.edit", json!({"layer": id, "transform": [0.5, 0, 0, 0.5, 0, 0]})).unwrap(); assert!(matches!(live(&s), Some(LiveShape::Polygon { corner_radius, .. }) if (corner_radius - 5.0).abs() < 1e-9)); } + +#[test] +fn arrowhead_flags_reject_wrong_types_without_mutation() { + let mut s = session(160, 120, 8); + let id = s + .execute( + "shape.create", + json!({ + "kind": "line", + "from": [10, 20], + "to": [120, 20], + "arrowStart": true, + "arrowEnd": false + }), + ) + .unwrap()["layer"] + .as_u64() + .unwrap(); + + let original_doc = s.active().unwrap().doc.clone(); + let original_history = s.active().unwrap().history.past_len(); + + for key in ["arrowStart", "arrowEnd"] { + for invalid in [json!("true"), json!(null), json!(1), json!([])] { + let mut create = json!({ + "kind": "line", + "from": [10, 40], + "to": [120, 40] + }); + create[key] = invalid.clone(); + + assert!(s.execute("shape.create", create).is_err(), "{key} must reject {invalid}"); + + let mut edit = json!({"layer": id}); + edit[key] = invalid.clone(); + + assert!(s.execute("shape.edit", edit).is_err(), "{key} edit must reject {invalid}"); + + assert_eq!(s.active().unwrap().doc, original_doc); + assert_eq!(s.active().unwrap().history.past_len(), original_history); + } + } + + // Valid boolean values remain accepted. + s.execute( + "shape.edit", + json!({ + "layer": id, + "arrowStart": false, + "arrowEnd": true + }), + ) + .unwrap(); +} + +#[test] +fn arrowhead_dimensions_reject_invalid_values_without_mutation() { + let mut s = session(160, 120, 8); + let id = s + .execute( + "shape.create", + json!({ + "kind": "line", + "from": [10, 20], + "to": [120, 20], + "arrowEnd": true + }), + ) + .unwrap()["layer"] + .as_u64() + .unwrap(); + + let original_doc = s.active().unwrap().doc.clone(); + let original_history = s.active().unwrap().history.past_len(); + + for (key, invalids) in [ + ("arrowWidth", [json!("52"), json!(null), json!([]), json!(0), json!(4097)]), + ("arrowLength", [json!("50"), json!(null), json!([]), json!(0), json!(4097)]), + ("arrowConcavity", [json!("0"), json!(null), json!([]), json!(-1), json!(101)]), + ] { + for invalid in invalids { + let mut create = json!({ + "kind": "line", + "from": [10, 40], + "to": [120, 40] + }); + create[key] = invalid.clone(); + assert!(s.execute("shape.create", create).is_err(), "{key} create must reject {invalid}"); + assert_eq!(s.active().unwrap().doc, original_doc, "{key} create changed document"); + assert_eq!(s.active().unwrap().history.past_len(), original_history, "{key} create changed history"); + + let mut edit = json!({"layer": id}); + edit[key] = invalid.clone(); + assert!(s.execute("shape.edit", edit).is_err(), "{key} edit must reject {invalid}"); + assert_eq!(s.active().unwrap().doc, original_doc, "{key} edit changed document"); + assert_eq!(s.active().unwrap().history.past_len(), original_history, "{key} edit changed history"); + } + } +} + +#[test] +fn headless_diagonal_arrow_preserves_geometry_after_nonuniform_scale() { + let mut s = session(400, 400, 8); + + let created = s + .execute( + "shape.create", + json!({ + "kind": "line", + "from": [40.0, 40.0], + "to": [140.0, 140.0], + "weight": 5.0, + "arrowStart": false, + "arrowEnd": false + }), + ) + .unwrap(); + + let id = created["layer"].as_u64().unwrap(); + + let transformed = s + .execute( + "shape.edit", + json!({ + "layer": id, + "transform": [2.0, 0.0, 0.0, 1.0, 0.0, 0.0] + }), + ) + .unwrap(); + + assert_ne!(transformed["path"], created["path"]); + assert!(transformed["live"].is_null()); + + let before = s.active().unwrap().doc.clone(); + + // Editing live parameters must not regenerate a different shape. + assert!(s.execute("shape.edit", json!({"layer": id, "weight": 8.0}),).is_err()); + + assert_eq!(s.active().unwrap().doc, before); + + let info = s.execute("shape.info", json!({"layer": id})).unwrap(); + + assert_eq!(info["path"], transformed["path"]); +} diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs index e408297abea..b5cfda9ad56 100644 --- a/crates/format/src/convert.rs +++ b/crates/format/src/convert.rs @@ -159,7 +159,16 @@ fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM { psd_raw: opt_blob(&s.psd_raw, sink), path: s.path.clone(), stroke: s.stroke.clone(), - live: s.live.clone(), + // Older PhotoCraft versions cannot deserialize ArrowLine. + // The saved path preserves the arrow's visual appearance. + live: match &s.live { + Some(photocraft_doc::LiveShape::ArrowLine { .. }) => None, + other => other.clone(), + }, + arrow_live: match &s.live { + Some(arrow @ photocraft_doc::LiveShape::ArrowLine { .. }) => Some(arrow.clone()), + _ => None, + }, density: s.density, feather: s.feather, }, @@ -480,11 +489,11 @@ impl Loader<'_> { warp: warp.clone(), }) } - ContentM::Shape { fill, cache, psd_raw, path, stroke, live, density, feather } => LayerContent::Shape(ShapeLayer { + ContentM::Shape { fill, cache, psd_raw, path, stroke, live, arrow_live, density, feather } => LayerContent::Shape(ShapeLayer { path: path.clone(), fill: fill.clone(), stroke: stroke.clone(), - live: live.clone(), + live: arrow_live.as_ref().filter(|shape| matches!(shape, photocraft_doc::LiveShape::ArrowLine { .. })).cloned().or_else(|| live.clone()), cache: self.opt_surface(cache)?, psd_raw: self.opt_blob(psd_raw)?, density: *density, diff --git a/crates/format/src/manifest.rs b/crates/format/src/manifest.rs index 768a3f43204..1164bc0a683 100644 --- a/crates/format/src/manifest.rs +++ b/crates/format/src/manifest.rs @@ -300,6 +300,10 @@ pub enum ContentM { stroke: Option, #[serde(default)] live: Option, + /// Arrow parameters stored separately for backward compatibility. + /// Older PhotoCraft versions ignore this optional field. + #[serde(default, skip_serializing_if = "Option::is_none")] + arrow_live: Option, /// The path's density as the fill's mask; older files have none (100 %). #[serde(default = "full_density")] density: f32, diff --git a/crates/format/tests/it/roundtrip.rs b/crates/format/tests/it/roundtrip.rs index 32ef5031393..25af8b22a62 100644 --- a/crates/format/tests/it/roundtrip.rs +++ b/crates/format/tests/it/roundtrip.rs @@ -975,3 +975,57 @@ fn locked_stale_preview_does_not_fail_committed_save() { assert!(!dir.join("thumb.png").exists()); std::fs::remove_dir_all(dir).unwrap(); } + +#[test] +fn arrow_document_is_backward_compatible() { + use photocraft_doc::{Fill, LiveShape, Path, ShapeLayer, Subpath}; + + let arrow = + LiveShape::ArrowLine { from: [12.0, 64.0], to: [140.0, 64.0], weight: 16.0, start: false, end: true, width: 52.0, length: 50.0, concavity: 20.0 }; + + let path = Path::new(vec![Subpath::polygon(&[(12.0, 56.0), (100.0, 56.0), (100.0, 44.0), (140.0, 64.0), (100.0, 84.0), (100.0, 72.0), (12.0, 72.0)])]); + + let mut doc = Document::new("Arrow compatibility", photocraft_doc::Size::new(256, 256), ColorMode::Rgb, SampleType::U8); + + doc.layers.push(Layer::new( + "Editable arrow", + LayerContent::Shape(ShapeLayer { + path: path.clone(), + fill: Some(Fill::Solid(photocraft_doc::Color::BLACK)), + live: Some(arrow.clone()), + ..Default::default() + }), + )); + + let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap(); + let manifest = read_manifest(&bytes).unwrap(); + let json = serde_json::to_value(&manifest).unwrap(); + let saved = &json["document"]["layers"][0]["content"]; + + assert_eq!(saved["kind"], "shape"); + assert!(saved["live"].is_null()); + assert_eq!(saved["arrow_live"]["kind"], "arrowLine"); + assert_eq!(saved["path"], serde_json::to_value(&path).unwrap()); + + // Simulate an old reader that knows no ArrowLine or arrow_live. + #[derive(serde::Deserialize)] + struct LegacyShape { + live: Option, + path: Path, + } + + #[derive(serde::Deserialize)] + #[serde(tag = "kind", rename_all = "camelCase")] + #[allow(dead_code)] + enum LegacyLive { + Line { from: [f64; 2], to: [f64; 2], weight: f64 }, + } + + let legacy: LegacyShape = serde_json::from_value(saved.clone()).unwrap(); + assert!(legacy.live.is_none()); + assert_eq!(legacy.path, path); + + // The new reader restores full parametric editability. + let loaded = load_from_bytes(&bytes).unwrap(); + assert_eq!(loaded, doc); +} diff --git a/crates/io/src/vector_map.rs b/crates/io/src/vector_map.rs index 621edf47b86..d7667d408bb 100644 --- a/crates/io/src/vector_map.rs +++ b/crates/io/src/vector_map.rs @@ -407,11 +407,25 @@ pub fn live_from_vogk(data: &[u8]) -> Option { Some(LiveShape::Rect { rect: rect_of(o)?, radii: [g("topLeft"), g("topRight"), g("bottomRight"), g("bottomLeft")] }) } 5 => Some(LiveShape::Ellipse { rect: rect_of(o)? }), - 4 => Some(LiveShape::Line { - from: point_of(o, "keyOriginLineStart")?, - to: point_of(o, "keyOriginLineEnd")?, - weight: num(o.get("keyOriginLineWeight")).unwrap_or(1.0), - }), + 4 => { + let from = point_of(o, "keyOriginLineStart")?; + let to = point_of(o, "keyOriginLineEnd")?; + let weight = num(o.get("keyOriginLineWeight")).unwrap_or(1.0); + let start = bool_of(o, "keyOriginLineArrowSt"); + let end = bool_of(o, "keyOriginLineArrowEnd"); + let width = num(o.get("keyOriginLineArrWdth")).unwrap_or(0.0); + let length = num(o.get("keyOriginLineArrLngth")).unwrap_or(0.0); + let concavity = num(o.get("keyOriginLineArrConc")).unwrap_or(0.0); + if start || end || width > 0.0 || length > 0.0 { + // Missing or invalid PSD arrow sizes must not prevent later edits. + let width = if width.is_finite() && width >= 1.0 { width } else { 52.0 }; + let length = if length.is_finite() && length >= 1.0 { length } else { 50.0 }; + let concavity = if concavity.is_finite() { concavity.clamp(0.0, 100.0) } else { 0.0 }; + Some(LiveShape::ArrowLine { from, to, weight, start, end, width, length, concavity }) + } else { + Some(LiveShape::Line { from, to, weight }) + } + } _ => None, } } @@ -463,6 +477,20 @@ pub fn vogk_bytes(s: &LiveShape, dpi: f32) -> Option> { .with("keyOriginLineArrLngth", Value::Double(0.0)) .with("keyOriginLineArrConc", Value::Integer(0)) } + LiveShape::ArrowLine { from, to, weight, start, end, width, length, concavity } => { + let pnt = |p: [f64; 2]| Value::Descriptor(Descriptor::new("Pnt ").with("Hrzn", Value::Double(p[0])).with("Vrtc", Value::Double(p[1]))); + let r = [from[0].min(to[0]), from[1].min(to[1]), (from[0] - to[0]).abs(), (from[1] - to[1]).abs()]; + base(4) + .with("keyOriginShapeBBox", bbox(r)) + .with("keyOriginLineEnd", pnt(*to)) + .with("keyOriginLineStart", pnt(*from)) + .with("keyOriginLineWeight", Value::Double(*weight)) + .with("keyOriginLineArrowSt", Value::Boolean(*start)) + .with("keyOriginLineArrowEnd", Value::Boolean(*end)) + .with("keyOriginLineArrWdth", Value::Double(*width)) + .with("keyOriginLineArrLngth", Value::Double(*length)) + .with("keyOriginLineArrConc", Value::Integer(concavity.round() as i32)) + } LiveShape::Polygon { .. } => return None, }; let o = o.with("keyOriginIndex", Value::Integer(0)); @@ -709,6 +737,9 @@ mod tests { LiveShape::Rect { rect: [1.0, 2.0, 30.0, 40.0], radii: [1.0, 2.0, 3.0, 4.0] }, LiveShape::Ellipse { rect: [5.0, 6.0, 7.0, 8.0] }, LiveShape::Line { from: [0.0, 10.0], to: [20.0, 0.0], weight: 3.0 }, + LiveShape::ArrowLine { from: [0.0, 10.0], to: [20.0, 0.0], weight: 3.0, start: false, end: true, width: 31.0, length: 31.0, concavity: 50.0 }, + // Both arrowheads off still needs to retain the adjustable parameters. + LiveShape::ArrowLine { from: [0.0, 10.0], to: [20.0, 0.0], weight: 3.0, start: false, end: false, width: 31.0, length: 31.0, concavity: 0.0 }, ] { let b = vogk_bytes(&s, 72.0).unwrap(); assert_eq!(live_from_vogk(&b), Some(s)); diff --git a/crates/ui-egui/src/panels/layer_props_ui.rs b/crates/ui-egui/src/panels/layer_props_ui.rs index 62f84ecc8a5..6f500049bce 100644 --- a/crates/ui-egui/src/panels/layer_props_ui.rs +++ b/crates/ui-egui/src/panels/layer_props_ui.rs @@ -14,11 +14,14 @@ use crate::{PhotocraftApp, widgets}; /// the top-left corner (Photoshop's Properties W/H fields), or `layer.translate` params for X/Y. /// `tol` is the smallest change, in px, that counts as an edit (see [`edit_tolerance`]). pub fn transform_params(layer: u64, b: [f64; 4], w: Option, h: Option, linked: bool, tol: f32) -> Option { - let (bw, bh) = ((b[2] - b[0]) as f32, (b[3] - b[1]) as f32); - if bw <= 0.0 || bh <= 0.0 { + // Keep the transform geometry in f64. Rounding the linked W/H ratio and + // quad corners to f32 can introduce a tiny anisotropic scale, which makes + // a diagonal live ArrowLine lose its editable parameters after resizing. + let (bw, bh) = (b[2] - b[0], b[3] - b[1]); + if !bw.is_finite() || !bh.is_finite() || bw <= 0.0 || bh <= 0.0 { return None; } - let (mut nw, mut nh) = (w.unwrap_or(bw).max(1.0), h.unwrap_or(bh).max(1.0)); + let (mut nw, mut nh) = (w.map(f64::from).unwrap_or(bw).max(1.0), h.map(f64::from).unwrap_or(bh).max(1.0)); if linked { if w.is_some() { nh = (nw * bh / bw).max(1.0); @@ -26,10 +29,10 @@ pub fn transform_params(layer: u64, b: [f64; 4], w: Option, h: Option, nw = (nh * bw / bh).max(1.0); } } - if (nw - bw).abs() < tol && (nh - bh).abs() < tol { + if (nw - bw).abs() < f64::from(tol) && (nh - bh).abs() < f64::from(tol) { return None; } - let (x0, y0) = (b[0] as f32, b[1] as f32); + let (x0, y0) = (b[0], b[1]); let quad = [[x0, y0], [x0 + nw, y0], [x0 + nw, y0 + nh], [x0, y0 + nh]]; Some(json!({"layer": layer, "rect": b, "quad": quad})) } @@ -385,6 +388,67 @@ mod tests { assert_eq!((b.x0, b.y0, b.width(), b.height()), (10, 20, 50, 25)); } + /// Linked W/H edits must generate a truly uniform affine scale, not one + /// rounded independently on each axis to f32 precision. + #[test] + fn linked_transform_preserves_scale_precision() { + let b = [203.6, 171.7, 712.4, 690.3]; + let p = transform_params(7, b, Some(600.0), None, true, 0.05).unwrap(); + let x0 = p["quad"][0][0].as_f64().unwrap(); + let y0 = p["quad"][0][1].as_f64().unwrap(); + let x1 = p["quad"][1][0].as_f64().unwrap(); + let y1 = p["quad"][2][1].as_f64().unwrap(); + let sx = (x1 - x0) / (b[2] - b[0]); + let sy = (y1 - y0) / (b[3] - b[1]); + assert!((sx - sy).abs() < 1e-12, "linked resize produced different scales: {sx} and {sy}"); + } + + /// A diagonal arrow must remain live after a proportional width edit in + /// Properties, while its outline is transformed by the engine as usual. + #[test] + fn linked_properties_resize_keeps_diagonal_arrow_editable() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 1200, "height": 1200})).unwrap(); + s.execute( + "shape.create", + json!({ + "kind": "line", + "from": [203.6, 171.7], + "to": [712.4, 690.3], + "weight": 20.0, + "arrowStart": false, + "arrowEnd": true, + "arrowWidth": 55.0, + "arrowLength": 85.0, + "arrowConcavity": 50.0 + }), + ) + .unwrap(); + let (id, b) = { + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let layer = st.doc.layer(id).unwrap(); + let LayerContent::Shape(shape) = &layer.content else { panic!("expected shape layer") }; + assert!(matches!(shape.live.as_ref(), Some(photocraft_doc::vector::LiveShape::ArrowLine { .. }))); + let px = photocraft_compose::bounds::content_bounds(layer.surface().unwrap()); + (id, frame(layer, px)) + }; + let p = transform_params(id.0, b, Some(600.0), None, true, 0.05).unwrap(); + s.execute("edit.transform", p).unwrap(); + let layer = s.active().unwrap().doc.layer(id).unwrap(); + let LayerContent::Shape(shape) = &layer.content else { panic!("expected shape layer") }; + assert!( + matches!(shape.live.as_ref(), Some(photocraft_doc::vector::LiveShape::ArrowLine { .. })), + "proportional Properties resize must preserve live arrow settings" + ); + + // The next live-property edit must still be accepted after resizing. + s.execute("shape.edit", json!({"layer": id.0, "arrowConcavity": 60.0})).unwrap(); + let layer = s.active().unwrap().doc.layer(id).unwrap(); + let LayerContent::Shape(shape) = &layer.content else { panic!("expected shape layer") }; + assert!(matches!(shape.live.as_ref(), Some(photocraft_doc::vector::LiveShape::ArrowLine { concavity, .. }) if (*concavity - 60.0).abs() < 1e-9)); + } + /// A stroked shape's Transform fields show its path, not the stroke's pixels, and a W edit /// scales the path to that width, as in Photoshop. #[test] diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index e03fa24e7a4..fc67eccacab 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -40,6 +40,7 @@ pub(super) fn options_bar_height(pro: bool, narrow: bool) -> f32 { } pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + crate::vector_ui::track_arrow_default_selection(app, ui.ctx()); let t = Tokens::get(ui.ctx()); let narrow = app.session.prefs().workspace.narrow_options_bar(); egui::Panel::top("options_bar") diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index d5774751031..bf5303e0d52 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -109,6 +109,12 @@ pub struct ToolOptions { pub corner_radius: f32, pub polygon_sides: u32, pub line_weight: f32, + /// Line arrowheads. + pub arrow_start: bool, + pub arrow_end: bool, + pub arrow_width: f32, + pub arrow_length: f32, + pub arrow_concavity: f32, /// Freeform Pen › Curve Fit: how far (px) the fitted path may stray from the pointer trace. #[serde(default = "default_curve_fit")] pub curve_fit: f32, @@ -423,6 +429,11 @@ impl Default for ToolOptions { corner_radius: 0.0, polygon_sides: 5, line_weight: 3.0, + arrow_start: false, + arrow_end: false, + arrow_width: 52.0, + arrow_length: 50.0, + arrow_concavity: 0.0, curve_fit: default_curve_fit(), pen_auto_add_delete: true, marquee_style: default_marquee_style(), diff --git a/crates/ui-egui/src/tools/corner_radius.rs b/crates/ui-egui/src/tools/corner_radius.rs index a5199b6c9d2..6358ffd1394 100644 --- a/crates/ui-egui/src/tools/corner_radius.rs +++ b/crates/ui-egui/src/tools/corner_radius.rs @@ -178,7 +178,7 @@ fn target(layer: u64, live: &LiveShape) -> Option { let vertices = sharp.subpaths.first()?.knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); Some(Target { layer, geom: Geom::Polygon { rect, sides, star_ratio, vertices }, radii: [corner_radius.max(0.0); 4] }) } - LiveShape::Ellipse { .. } | LiveShape::Line { .. } => None, + LiveShape::Ellipse { .. } | LiveShape::Line { .. } | LiveShape::ArrowLine { .. } => None, } } diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index 701914b0b9d..4a6ee2c2d83 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -211,7 +211,23 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { Tool::Pen => reset!(vector_mode, pen_path_op, pen_auto_add_delete), Tool::CurvaturePen => reset!(vector_mode, pen_path_op), Tool::FreeformPen => reset!(vector_mode, pen_path_op, curve_fit), - Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line | Tool::CustomShape => { + Tool::Line => reset!( + vector_mode, + shape_fill, + stroke_width, + shape_stroke, + shape_fill_gradient, + shape_stroke_gradient, + corner_radius, + polygon_sides, + line_weight, + arrow_start, + arrow_end, + arrow_width, + arrow_length, + arrow_concavity, + ), + Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::CustomShape => { reset!(vector_mode, shape_fill, stroke_width, shape_stroke, shape_fill_gradient, shape_stroke_gradient, corner_radius, polygon_sides, line_weight) } Tool::ColorSampler diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index 72ec518f819..0749b874340 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -62,6 +62,73 @@ pub use shapes::{create_shape, draw_shape_preview, finish_shape, is_shape_tool, #[cfg(test)] use shapes::{shape_geometry, shape_preview}; +// "Set as default" is a temporary UI choice, not a document property. +#[derive(Clone, Copy, Default)] +struct ArrowDefaultLink { + target: Option<(u64, u64)>, + enabled: bool, +} + +fn arrow_default_link_id() -> egui::Id { + egui::Id::unique("arrow-default-link") +} + +/// Reset the checkbox whenever the selected document, layer or shape changes. +pub(crate) fn track_arrow_default_selection(app: &PhotocraftApp, ctx: &egui::Context) { + let target = app.session.active().and_then(|st| { + let id = st.active_layer?; + let layer = st.doc.layer(id)?; + match &layer.content { + LayerContent::Shape(sh) if matches!(sh.live.as_ref(), Some(photocraft_doc::vector::LiveShape::ArrowLine { .. })) => Some((st.doc.id.0, id.0)), + _ => None, + } + }); + + ctx.data_mut(|data| { + let key = arrow_default_link_id(); + let previous = data.get_temp::(key).unwrap_or_default(); + if previous.target != target { + data.insert_temp(key, ArrowDefaultLink { target, enabled: false }); + } + }); +} + +/// Copy only the selected arrow's live parameters into new-arrow defaults. +/// Existing shapes and geometry are not modified. +fn copy_arrow_to_tool_defaults(app: &mut PhotocraftApp, id: photocraft_doc::LayerId) { + let values = app.session.active().and_then(|st| st.doc.layer(id)).and_then(|layer| match &layer.content { + LayerContent::Shape(sh) => match sh.live.as_ref() { + Some(photocraft_doc::vector::LiveShape::ArrowLine { start, end, width, length, concavity, weight, .. }) => { + { + // Live dimensions may exceed new-arrow input limits after scaling. + // Clamp only the defaults, never the existing shape. + let bounded = |v: f64, min: f64, max: f64| -> f32 { if v.is_finite() { v.clamp(min, max) as f32 } else { min as f32 } }; + Some(( + *start, + *end, + bounded(*width, 1.0, 4096.0), + bounded(*length, 1.0, 4096.0), + bounded(*concavity, 0.0, 100.0), + bounded(*weight, 1.0, 10000.0), + )) + } + } + _ => None, + }, + _ => None, + }); + + if let Some((start, end, width, length, concavity, weight)) = values { + let o = &mut app.ui.tool_options; + o.arrow_start = start; + o.arrow_end = end; + o.arrow_width = width; + o.arrow_length = length; + o.arrow_concavity = concavity; + o.line_weight = weight; + } +} + /// Pen tool path under construction: knots as [anchor, in, out] (document px). #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct PenPath { diff --git a/crates/ui-egui/src/tools/vector_ui/options.rs b/crates/ui-egui/src/tools/vector_ui/options.rs index 571e5dcffc8..cd68a6bcb64 100644 --- a/crates/ui-egui/src/tools/vector_ui/options.rs +++ b/crates/ui-egui/src/tools/vector_ui/options.rs @@ -1,6 +1,7 @@ use super::path_ops::active_path_name; use super::pen::path_operations_menu; use super::shapes::is_shape_tool; +use super::{ArrowDefaultLink, arrow_default_link_id, copy_arrow_to_tool_defaults}; use super::{GradientChoices, LayerContent, PaintChange, PhotocraftApp, Tokens, Tool, Value, json, paint_param, swatch}; // --------------------------------------------------------------------------------------------- @@ -114,6 +115,34 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo crate::widgets::dropdown(ui, "shape-mode", tl!("Mode"), &mut mode, &[("shape".to_string(), tl!("Shape"))], 80.0); crate::widgets::vline(ui, 22.0); crate::shape_options::options_bar(app, ui, tool); + // Photoshop-style arrowhead settings at the right of Line options. + if tool == Tool::Line { + crate::widgets::vline(ui, 22.0); + ui.menu_image_button(crate::icons::image("settings", 18.0, t.icon), |ui| { + let o = &mut app.ui.tool_options; + ui.set_min_width(170.0); + ui.label(tl!("Arrowheads")); + ui.separator(); + ui.horizontal(|ui| { + ui.checkbox(&mut o.arrow_start, tl!("Start")); + ui.checkbox(&mut o.arrow_end, tl!("End")); + }); + ui.horizontal(|ui| { + ui.label(tl!("Width")); + ui.add(egui::DragValue::new(&mut o.arrow_width).range(1.0..=4096.0).suffix(" px")); + }); + ui.horizontal(|ui| { + ui.label(tl!("Length")); + ui.add(egui::DragValue::new(&mut o.arrow_length).range(1.0..=4096.0).suffix(" px")); + }); + ui.horizontal(|ui| { + ui.label(tl!("Concavity")); + ui.add(egui::DragValue::new(&mut o.arrow_concavity).range(0.0..=100.0).suffix(" %")); + }); + }) + .response + .on_hover_text(tl!("Arrowhead options")); + } true } @@ -279,7 +308,7 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra } }); } - photocraft_doc::vector::LiveShape::Line { .. } => {} + photocraft_doc::vector::LiveShape::Line { .. } | photocraft_doc::vector::LiveShape::ArrowLine { .. } => {} } ui.vertical(|ui| match live { photocraft_doc::vector::LiveShape::Rect { radii, .. } => { @@ -323,6 +352,59 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra }) .inner } + photocraft_doc::vector::LiveShape::ArrowLine { weight, start, end, width, length, concavity, .. } => { + // This is a selected, saved Arrow; unlike the tool's defaults, edits update its geometry. + ui.horizontal(|ui| { + let mut value = *start; + if ui.checkbox(&mut value, tl!("Start")).changed() { + edit = Some(json!({"arrowStart": value, "coalesce": key("arrow-start")})); + } + let mut value = *end; + if ui.checkbox(&mut value, tl!("End")).changed() { + edit = Some(json!({"arrowEnd": value, "coalesce": key("arrow-end")})); + } + }); + ui.horizontal(|ui| { + let mut v = *width as f32; + if num(ui, "Width", &mut v, 1.0..=4096.0, "px") { + edit = Some(json!({"arrowWidth": v, "coalesce": key("arrow-width")})); + } + }); + ui.horizontal(|ui| { + let mut v = *length as f32; + if num(ui, "Length", &mut v, 1.0..=4096.0, "px") { + edit = Some(json!({"arrowLength": v, "coalesce": key("arrow-length")})); + } + }); + ui.horizontal(|ui| { + let mut v = *weight as f32; + if num(ui, "Weight", &mut v, 1.0..=10000.0, "px") { + edit = Some(json!({"weight": v, "coalesce": key("arrow-weight")})); + } + }); + ui.horizontal(|ui| { + let mut v = *concavity as f32; + if num(ui, "Concavity", &mut v, 0.0..=100.0, "%") { + edit = Some(json!({"arrowConcavity": v, "coalesce": key("arrow-concavity")})); + } + }); + + // Explicitly adopt this arrow's values as defaults for new arrows. + let target = app.session.active().map(|st| (st.doc.id.0, id.0)); + let mut linked = ui.ctx().data(|data| { + let state = data.get_temp::(arrow_default_link_id()).unwrap_or_default(); + state.target == target && state.enabled + }); + + if ui.checkbox(&mut linked, tl!("Set as default")).on_hover_text(tl!("Use these settings for new arrows")).changed() { + ui.ctx().data_mut(|data| { + data.insert_temp(arrow_default_link_id(), ArrowDefaultLink { target, enabled: linked }); + }); + if linked { + copy_arrow_to_tool_defaults(app, id); + } + } + } photocraft_doc::vector::LiveShape::Line { weight, .. } => { ui.horizontal(|ui| { let mut w = *weight as f32; @@ -337,11 +419,25 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra } if let Some(mut p) = edit { p["layer"] = json!(id.0); + match app.run("shape.edit", p) { Ok(_) => { + // Remember recently used colors after a successful edit. if let Some(rgb) = recent { crate::paint_picker::remember(app, rgb); } + + // Only a successful Properties edit updates new-arrow defaults, + // and only while the user explicitly enables the checkbox. + let target = app.session.active().map(|st| (st.doc.id.0, id.0)); + let linked = ui.ctx().data(|data| { + let state = data.get_temp::(arrow_default_link_id()).unwrap_or_default(); + state.enabled && state.target == target + }); + + if linked { + copy_arrow_to_tool_defaults(app, id); + } } Err(e) => { app.ui.status = e; diff --git a/crates/ui-egui/src/tools/vector_ui/overlay.rs b/crates/ui-egui/src/tools/vector_ui/overlay.rs index b72bdd64c5d..6bc967e34ef 100644 --- a/crates/ui-egui/src/tools/vector_ui/overlay.rs +++ b/crates/ui-egui/src/tools/vector_ui/overlay.rs @@ -170,7 +170,12 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform if let Some(l) = st.and_then(|s| s.active_layer.and_then(|id| s.doc.layer(id))) && let LayerContent::Shape(sh) = &l.content { - draw_path(&sh.path, anchors); + // Hide the stale shape path while its transform preview is active. + let transforming_this_shape = + app.ui.transform.as_ref().is_some_and(|t| t.layer == l.id.0 && !t.selection && t.target.is_none() && t.path.is_none()); + if !transforming_this_shape { + draw_path(&sh.path, anchors); + } } // A targeted vector mask shows its path with any tool (#196). if let Some((_, p)) = targeted_vector_mask(app) { diff --git a/crates/ui-egui/src/tools/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs index dc72a120f08..fe96e7b1778 100644 --- a/crates/ui-egui/src/tools/vector_ui/shapes.rs +++ b/crates/ui-egui/src/tools/vector_ui/shapes.rs @@ -59,7 +59,10 @@ pub(super) fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end: if dx.hypot(dy) < 1.0 { return None; } - json!({"kind": "line", "from": start, "to": [start[0] + dx, start[1] + dy], "weight": o.line_weight.max(1.0)}) + json!({"kind": "line", "from": start, "to": [start[0] + dx, start[1] + dy], "weight": o.line_weight.max(1.0), + "arrowStart": o.arrow_start, "arrowEnd": o.arrow_end, + "arrowWidth": o.arrow_width, "arrowLength": o.arrow_length, + "arrowConcavity": o.arrow_concavity}) } else { let (mut w, mut h) = (end[0] - start[0], end[1] - start[1]); if mods.shift { diff --git a/crates/vector/src/shapes.rs b/crates/vector/src/shapes.rs index d259d278715..0b7e65a48d0 100644 --- a/crates/vector/src/shapes.rs +++ b/crates/vector/src/shapes.rs @@ -215,6 +215,65 @@ pub fn line(a: (f64, f64), b: (f64, f64), weight: f64) -> Path { Path::new(vec![Subpath::polygon(&[(a.0 + nx, a.1 + ny), (b.0 + nx, b.1 + ny), (b.0 - nx, b.1 - ny), (a.0 - nx, a.1 - ny)])]) } +/// A filled vector line with optional arrowheads at its endpoints (#6408). +/// `width` and `length` measure the head in document pixels, independently of the shaft weight. +/// `concavity` is 0..100 percent: 0 has a flat rear edge, 100 a deep V-shaped notch. +/// The shaft stops at the notch, so a concave head remains concave after filling. +// The arguments correspond to the stored LiveShape::ArrowLine parameters. +#[allow(clippy::too_many_arguments)] +pub fn arrow_line(a: (f64, f64), b: (f64, f64), weight: f64, start: bool, end: bool, width: f64, length: f64, concavity: f64) -> Path { + let (dx, dy) = (b.0 - a.0, b.1 - a.1); + let distance = dx.hypot(dy); + if !distance.is_finite() || !weight.is_finite() { + return Path::default(); + } + // Without arrowheads, use the ordinary line even for segments shorter than 1 px. + if !start && !end { + return line(a, b, weight); + } + if distance < 1.0 { + return Path::default(); + } + let (ux, uy) = (dx / distance, dy / distance); + let (vx, vy) = (-uy, ux); + let size = (if length.is_finite() { length.max(1.0) } else { 1.0 }).min(distance * if start && end { 0.49 } else { 0.9 }); + let half = (if width.is_finite() { width.max(1.0) } else { 1.0 }) / 2.0; + let requested_notch = concavity.clamp(0.0, 100.0) / 100.0; + // Preserve 0..50%. Beyond that compress the usable range so the head never collapses. + let max_notch = 0.75; + let notch = if requested_notch <= 0.5 { requested_notch } else { 0.5 + (requested_notch - 0.5) * (max_notch - 0.5) / 0.5 }; + // Put the shaft up to the notch, leaving the head's concave edges visible. + let inner = size * (1.0 - notch); + let shaft_a = if start { (a.0 + ux * inner, a.1 + uy * inner) } else { a }; + let shaft_b = if end { (b.0 - ux * inner, b.1 - uy * inner) } else { b }; + let hw = weight.max(0.1) / 2.0; + let mut pieces = vec![Subpath::polygon(&[ + (shaft_a.0 + vx * hw, shaft_a.1 + vy * hw), + (shaft_b.0 + vx * hw, shaft_b.1 + vy * hw), + (shaft_b.0 - vx * hw, shaft_b.1 - vy * hw), + (shaft_a.0 - vx * hw, shaft_a.1 - vy * hw), + ])]; + // The tip, both outer corners of the head and the recessed midpoint. + // Positive `sign` points towards the tail of the head (away from its tip). + let mut head = |tip: (f64, f64), sign: f64| { + let base = (tip.0 + ux * sign * size, tip.1 + uy * sign * size); + let rear_middle = (base.0 - ux * sign * size * notch, base.1 - uy * sign * size * notch); + pieces.push(Subpath::polygon(&[tip, (base.0 + vx * half, base.1 + vy * half), rear_middle, (base.0 - vx * half, base.1 - vy * half)])); + }; + if start { + head(a, 1.0); + } + if end { + head(b, -1.0); + } + // Never return non-finite arrow geometry. + // Large but valid scaled arrowheads remain unchanged. + if pieces.iter().flat_map(|sp| &sp.knots).any(|k| !k.anchor.x.is_finite() || !k.anchor.y.is_finite()) { + return Path::default(); + } + Path::new(pieces) +} + /// The path of a live shape. pub fn live_path(s: &LiveShape) -> Path { match s { @@ -224,6 +283,9 @@ pub fn live_path(s: &LiveShape) -> Path { round_corners(polygon(*x, *y, *w, *h, *sides, *star_ratio), *corner_radius) } LiveShape::Line { from, to, weight } => line((from[0], from[1]), (to[0], to[1]), *weight), + LiveShape::ArrowLine { from, to, weight, start, end, width, length, concavity } => { + arrow_line((from[0], from[1]), (to[0], to[1]), *weight, *start, *end, *width, *length, *concavity) + } } } @@ -231,6 +293,33 @@ pub fn live_path(s: &LiveShape) -> Path { mod tests { use super::*; + #[test] + fn rejects_non_finite_arrowhead_coordinates() { + let path = arrow_line((1.5e308, 0.0), (1.5e308, 200.0), 8.0, false, true, f64::MAX, 50.0, 0.0); + assert!(path.subpaths.is_empty()); + } + + #[test] + fn preserves_scaled_head_dimensions_above_ui_limit() { + let path = arrow_line((0.0, 0.0), (20000.0, 0.0), 8.0, false, true, 5200.0, 5200.0, 0.0); + let head = &path.subpaths[1].knots; + assert!((head[1].anchor.x - 14800.0).abs() < 1e-6); + assert!((head[1].anchor.y - 2600.0).abs() < 1e-6); + } + + #[test] + fn live_arrow_can_be_regenerated_after_edit() { + let shape = + LiveShape::ArrowLine { from: [10.0, 10.0], to: [200.0, 10.0], weight: 4.0, start: false, end: true, width: 31.0, length: 31.0, concavity: 50.0 }; + let before = live_path(&shape); + assert_eq!(before.subpaths.len(), 2); + let mut edited = shape; + if let LiveShape::ArrowLine { width, .. } = &mut edited { + *width = 60.0; + } + let after = live_path(&edited); + assert_ne!(before, after); + } /// The point at `t` of the cubic leaving `a` towards `b`. fn at(a: &Knot, b: &Knot, t: f64) -> [f64; 2] { let u = 1.0 - t; @@ -317,3 +406,33 @@ mod tests { assert!((top.x - 5.0).abs() < 1e-9 && top.y.abs() < 1e-9); } } + +#[cfg(test)] +mod line_arrow_6408_tests { + use super::*; + + #[test] + fn short_line_without_heads_matches_regular_line() { + let a = (0.0, 0.0); + let b = (0.25, 0.0); + assert_eq!(arrow_line(a, b, 5.0, false, false, 52.0, 50.0, 0.0), line(a, b, 5.0)); + } + + #[test] + fn plain_line_has_single_subpath() { + let p = arrow_line((0.0, 0.0), (100.0, 0.0), 5.0, false, false, 52.0, 50.0, 0.0); + assert_eq!(p.subpaths.len(), 1); + } + + #[test] + fn start_end_arrowheads_add_two_vector_subpaths() { + let p = arrow_line((0.0, 0.0), (100.0, 0.0), 5.0, true, true, 52.0, 50.0, 25.0); + assert_eq!(p.subpaths.len(), 3); + } + + #[test] + fn degenerate_line_returns_empty_path() { + let p = arrow_line((2.0, 2.0), (2.0, 2.0), 5.0, true, true, 52.0, 50.0, 0.0); + assert!(p.subpaths.is_empty()); + } +} diff --git a/docs/shape-strokes.md b/docs/shape-strokes.md index 8271fa10230..54293ab7920 100644 --- a/docs/shape-strokes.md +++ b/docs/shape-strokes.md @@ -128,3 +128,16 @@ not offered yet. [cap/join reference](https://helpx.adobe.com/ca/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/change-the-caps-or-joins-of-a-line.html) defines endpoint and corner behavior and the 1–500 miter range. Dash units reuse PhotoCraft's existing documented `ShapeStroke`/`vstk` convention. + +## Editable arrows and older PhotoCraft versions + +Native `.pcraft` documents store arrow geometry in the regular shape path and +the editable arrow parameters separately in the optional `arrow_live` field. + +PhotoCraft versions that do not support editable arrows can open these documents +and display the saved arrow geometry as a regular vector shape. They cannot edit +the arrowhead parameters. + +Re-saving the document in an older version may discard the `arrow_live` +metadata, permanently removing parametric arrow editability from that copy. +Keep the original file when working across versions. \ No newline at end of file