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/77] 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/77] 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 9750d8a455f36d58fcef2da326ca7ce6d088d03c Mon Sep 17 00:00:00 2001 From: Daniel Date: Tue, 20 Oct 2026 03:49:34 +0200 Subject: [PATCH 03/77] fix(linux): rebase font-free Wayland controls with original title bar defaults --- Cargo.lock | 12 +++++++ NOTICE | 31 +++++++++++++++++++ apps/photocraft/Cargo.toml | 3 +- docs/development.md | 2 ++ packaging/env.sh | 2 +- .../flatpak/ai.storyteller.photocraft.yml | 1 + packaging/linux/package.sh | 2 ++ 7 files changed, 51 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index aff38ac01b9..b8c9b9f2e3e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6217,6 +6217,17 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "sctk-adwaita" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" +dependencies = [ + "log", + "smithay-client-toolkit 0.19.2", + "tiny-skia", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -8433,6 +8444,7 @@ dependencies = [ "raw-window-handle", "redox_syscall 0.4.1", "rustix 0.38.44", + "sctk-adwaita", "smithay-client-toolkit 0.19.2", "smol_str", "tracing", diff --git a/NOTICE b/NOTICE index a7302a940c9..821969da8af 100644 --- a/NOTICE +++ b/NOTICE @@ -22,3 +22,34 @@ Builds made with craft-fonts (CRAFT_FONTS_DIR; all official releases) also embed https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (today BIZ UDPGothic, Shippori Mincho and BIZ UDMincho; not the web build), under the SIL Open Font License 1.1. Their licence texts ship with the package as OFL-.txt. + +Linux Wayland window decorations +------------------------------- +sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita, +commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux +for vector window controls. Its title-font features are disabled: no Cantarell +font is embedded by this dependency and no font file is added to this repo. + +sctk-adwaita's MIT licence: + +MIT License + +Copyright (c) 2022 Bartłomiej Maryńczak + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/apps/photocraft/Cargo.toml b/apps/photocraft/Cargo.toml index 505947e222f..a0f2a75a5ad 100644 --- a/apps/photocraft/Cargo.toml +++ b/apps/photocraft/Cargo.toml @@ -81,7 +81,8 @@ futures-lite = "=2.6.1" async-io = "=2.6.0" # Open the window through Xwayland for a pen on Wayland (`tablet.rs`, #639): eframe doesn't # re-export winit's `EventLoopBuilderExtX11`. Already in Cargo.lock (eframe); pinned exactly. -winit = { version = "=0.30.13", default-features = false, features = ["x11"] } +# Preserve XWayland support; enable font-free Adwaita controls for native Wayland. +winit = { version = "=0.30.13", default-features = false, features = ["wayland-csd-adwaita-notitle", "x11"] } # Safe Win32 wrappers on Windows: the pointer position for file drops (`cursor.rs`, # GetCursorPos) and the window frame for the custom title bar (`window_frame.rs`, window styles), diff --git a/docs/development.md b/docs/development.md index 6891e88a9c2..fcf3339b7da 100644 --- a/docs/development.md +++ b/docs/development.md @@ -34,6 +34,8 @@ building locally; the downloaded app is still subject to Windows application-con ## Build and run +On GNOME/Wayland, **System Title Bar** uses winit's font-free Adwaita controls; existing custom-title-bar preferences and defaults are unchanged. + ```sh cargo run --release -p photocraft -- path/to/image.psd # desktop app cargo run --release -p photocraft -- --control 7878 --control-token-file .private/control.token \ diff --git a/packaging/env.sh b/packaging/env.sh index 0007227058d..782c4721f08 100644 --- a/packaging/env.sh +++ b/packaging/env.sh @@ -47,7 +47,7 @@ warn() { # Copy licence and readme files that exist into a package directory. copy_docs() { local dest="$1" f - for f in README.md LICENSE LICENSE-MIT LICENSE-APACHE COPYRIGHT; do + for f in README.md LICENSE LICENSE-MIT LICENSE-APACHE COPYRIGHT NOTICE; do if [ -f "$ROOT/$f" ]; then cp "$ROOT/$f" "$dest/"; fi done copy_font_licences "$dest" diff --git a/packaging/linux/flatpak/ai.storyteller.photocraft.yml b/packaging/linux/flatpak/ai.storyteller.photocraft.yml index e3ac74cffd7..21893746655 100644 --- a/packaging/linux/flatpak/ai.storyteller.photocraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.photocraft.yml @@ -49,6 +49,7 @@ modules: build-commands: - cargo --offline build --release --locked -p photocraft --features heif - install -Dm755 target/release/photocraft /app/bin/photocraft + - install -Dm644 NOTICE /app/share/doc/photocraft/NOTICE - install -Dm644 packaging/linux/ai.storyteller.photocraft.desktop /app/share/applications/ai.storyteller.photocraft.desktop - install -Dm644 packaging/linux/ai.storyteller.photocraft.mime.xml /app/share/mime/packages/ai.storyteller.photocraft.xml - mkdir -p /app/share/icons && cp -R assets/app-icon/hicolor /app/share/icons/ diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 615bef25bf4..2091ace48a7 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -108,6 +108,8 @@ if has appimage; then APPDIR="$WORK/PhotoCraft.AppDir" cp -R "$STAGE" "$APPDIR" mv "$APPDIR/usr/share/doc" "$WORK/doc-unused" + # Preserve the sctk-adwaita MIT notice in the packaged AppImage. + install -Dm644 "$ROOT/NOTICE" "$APPDIR/usr/share/doc/photocraft/NOTICE" # AppRun is a script, not a symlink: it installs the .desktop entry and icons into # $XDG_DATA_HOME before launching, so Wayland compositors can resolve the window's # app_id to our icon instead of the generic Wayland logo (#593; opt-out env in the From 1d70f5d6bf943474cbff61568cc290e0217627f8 Mon Sep 17 00:00:00 2001 From: Daniel Miguel Date: Wed, 21 Oct 2026 20:02:27 +0200 Subject: [PATCH 04/77] M0: default to the system title bar on Linux and preserve saved choices --- ROADMAP.md | 1 + apps/photocraft/src/main.rs | 18 ++++++++++-------- crates/engine/src/prefs.rs | 5 +++-- crates/engine/src/prefs/tests.rs | 16 ++++++++++++++++ crates/ui-egui/src/panels.rs | 5 +++-- crates/ui-egui/src/prefs_ui.rs | 7 ++++--- docs/development.md | 2 +- 7 files changed, 38 insertions(+), 16 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index f41b71bfc9f..aa6b993ab0e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -122,6 +122,7 @@ Detail and the next releases: [docs/roadmap.md](docs/roadmap.md). | Date | Entry | |---|---| +| 2026-10-21 | Linux defaults to System Title Bar so GNOME/Wayland has window controls. Saved choices and other platform defaults are preserved; startup and preference-dialog regressions cover both choices (#6266). | | 2026-10-10 | Full re-measure against Photoshop 2026 27.11.0 (installed bundle inspected): breadth ~76%, ready ~45%, alpha. Progress docs reorganized to the craftrules standard (`parity.md` → `parity-checklist.md`, `parity-estimate.md` merged into `target-app-parity.md`). 0.6.0 released. | | 2026-10-09 | Remove tool, Rotate View, crop rotation; OpenRaster and Paint.NET; 39 Affinity documents in the corpus | | 2026-10-08 | 0.5.0. Affinity import; Magnetic Lasso, Pattern Stamp, Mixer Brush, Pencil, Patch, Vertical Type on the toolbar | diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index b0b00a865cc..8a1f6d73513 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -83,14 +83,13 @@ use photocraft_ui_egui::PhotocraftApp; /// Matches the `.desktop` file and hicolor icon name, so Wayland docks pick up the icon. const APP_ID: &str = "ai.storyteller.photocraft"; -/// Windows and Linux: no OS title bar; the app's top bar is the title bar, with its own caption -/// buttons and edge resizing (`photocraft_ui_egui::titlebar`), as Photoshop does on Windows. macOS -/// keeps its traffic lights over the integrated title strip. +/// Windows and Linux can use the app's title bar, with its own caption buttons and edge resizing +/// (`photocraft_ui_egui::titlebar`); the preference below selects the mode. macOS always keeps its +/// system traffic lights over the integrated title strip. const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos"); -/// Whether this start draws its own title bar: Windows and Linux do, unless Preferences › -/// Interface › System Title Bar asks for the system's (#1271, #1316). Read from the saved -/// preferences before the window opens; a missing or unreadable file keeps the default. +/// Whether this start draws its own title bar. Linux defaults to the system frame; Windows +/// defaults to the in-app title bar. Saved preferences override those defaults (#1271, #1316). fn custom_titlebar(prefs_file: Option<&std::path::Path>) -> bool { let prefs: photocraft_engine::prefs::Preferences = prefs_file.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default(); @@ -1027,9 +1026,12 @@ mod tests { let dir = std::env::temp_dir().join(format!("pc-titlebar-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let file = dir.join("prefs.json"); - assert_eq!(super::custom_titlebar(None), super::CUSTOM_TITLEBAR, "no preferences file: the default"); + let default_custom = super::CUSTOM_TITLEBAR && !cfg!(target_os = "linux"); + assert_eq!(super::custom_titlebar(None), default_custom, "no preferences file: the platform default"); std::fs::write(&file, "not json").unwrap(); - assert_eq!(super::custom_titlebar(Some(&file)), super::CUSTOM_TITLEBAR, "an unreadable file: the default"); + assert_eq!(super::custom_titlebar(Some(&file)), default_custom, "an unreadable file: the platform default"); + std::fs::write(&file, r#"{"interface":{}}"#).unwrap(); + assert_eq!(super::custom_titlebar(Some(&file)), default_custom, "an older preference file: the platform default"); std::fs::write(&file, r#"{"interface":{"systemTitleBar":true}}"#).unwrap(); assert!(!super::custom_titlebar(Some(&file))); assert_eq!(super::native_options(false).viewport.decorations, Some(true)); diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 77acd2e3464..c2c06d767e8 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -284,7 +284,8 @@ pub struct Interface { pub show_bounding_box_when_dragging_layer: bool, /// Windows and Linux: use the system's title bar and window buttons instead of PhotoCraft's /// own one-row title bar (tiling window managers, desktops that draw their own decorations; - /// #1271, #1316). Read when the app starts. macOS always uses the system's. + /// #1271, #1316). Enabled by default on Linux, where GNOME/Wayland needs the client frame. + /// Read when the app starts. macOS always uses the system's. pub system_title_bar: bool, /// Show the active document's file name in the title bar and the OS window title. The tabs /// already name the file, so this can be turned off for a plain "PhotoCraft" title (#5037). @@ -320,7 +321,7 @@ impl Default for Interface { show_tooltips: true, enable_animations: true, show_bounding_box_when_dragging_layer: false, - system_title_bar: false, + system_title_bar: cfg!(target_os = "linux"), show_file_name_in_title: true, notification_auto_hide: true, notification_duration_seconds: 6, diff --git a/crates/engine/src/prefs/tests.rs b/crates/engine/src/prefs/tests.rs index 55e41949b9c..e9fedd48006 100644 --- a/crates/engine/src/prefs/tests.rs +++ b/crates/engine/src/prefs/tests.rs @@ -1,5 +1,21 @@ use super::*; +#[test] +fn system_title_bar_defaults_by_platform_and_preserves_saved_choices() { + let default = cfg!(target_os = "linux"); + assert_eq!(Interface::default().system_title_bar, default); + for saved in [json!({}), json!({"interface": {}})] { + let prefs: Preferences = serde_json::from_value(saved).unwrap(); + assert_eq!(prefs.interface.system_title_bar, default); + } + for saved in [false, true] { + let prefs: Preferences = serde_json::from_value(json!({"interface": {"systemTitleBar": saved}})).unwrap(); + assert_eq!(prefs.interface.system_title_bar, saved); + let restored: Preferences = serde_json::from_value(prefs.to_json()).unwrap(); + assert_eq!(restored.interface.system_title_bar, saved); + } +} + fn session() -> Session { let mut s = Session::new(); s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 04e775439ed..5af5b96183c 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -801,8 +801,9 @@ mod title_tests { #[test] fn without_the_preference_the_mark_stays() { - // The default (e.g. the web build or the snapshot example): no custom bar, no preference. - let app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + // An explicit choice to keep the app's title, independent of the platform default. + let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.edit_prefs(|p| p.interface.system_title_bar = false); assert!(!system_title_bar(&app)); } diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index d808ae32f42..5bf06fe971b 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -3795,6 +3795,7 @@ mod tests { let (mut app, store) = app_with_store(); app.run("prefs.set", json!({"values": {"interface.language": "en"}})).unwrap(); + let initial = app.session.prefs().interface.system_title_bar; app.custom_titlebar = true; let id = open_preferences(&mut app, "interface"); let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { @@ -3805,7 +3806,7 @@ mod tests { h.get_by_label("System title bar").scroll_to_me(); h.run_steps(4); h.get_by_label("Applies at next launch."); - for desired in [true, false] { + for desired in [!initial, initial] { h.get_by_label("System title bar").click(); h.run_steps(4); assert_eq!(h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields["values"]["interface"]["systemTitleBar"], desired); @@ -3825,8 +3826,8 @@ mod tests { h.get_by_label("Cancel").click(); h.run_steps(4); assert!(h.state().ui.dialogs.iter().all(|d| d.id != id)); - assert!(!h.state().session.prefs().interface.system_title_bar); - assert_eq!(stored(&store)["interface"]["systemTitleBar"], false); + assert_eq!(h.state().session.prefs().interface.system_title_bar, initial); + assert_eq!(stored(&store)["interface"]["systemTitleBar"], initial); assert!(h.state().custom_titlebar); } diff --git a/docs/development.md b/docs/development.md index fcf3339b7da..fcab7b7fc15 100644 --- a/docs/development.md +++ b/docs/development.md @@ -34,7 +34,7 @@ building locally; the downloaded app is still subject to Windows application-con ## Build and run -On GNOME/Wayland, **System Title Bar** uses winit's font-free Adwaita controls; existing custom-title-bar preferences and defaults are unchanged. +On Linux, **System Title Bar** is enabled by default. GNOME/Wayland uses winit's font-free Adwaita controls; X11 uses the window manager's frame. Saved choices still override the default, and other platforms keep their existing defaults. Changes in Preferences apply at the next launch. ```sh cargo run --release -p photocraft -- path/to/image.psd # desktop app From 17f5c041d8419e9e65819680fc74c6a4821cebda Mon Sep 17 00:00:00 2001 From: Finn Newick Date: Thu, 22 Oct 2026 22:50:19 +0100 Subject: [PATCH 05/77] 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 06/77] 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 07/77] 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 08/77] 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 09/77] 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 10/77] 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 11/77] 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 12/77] 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 13/77] 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 bcd8f891687257b5beb35097d2f5b978e878f16b Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:14:21 +0100 Subject: [PATCH 14/77] Prefs: startup reads Graphics Adapter through the typed Performance section Graphics Adapter (performance.gpuAdapter) always took effect, but startup read it by its raw JSON key, which the scorecard prefs audit can't see, so it was counted as a setting that does nothing. read_gpu_adapter now deserialises the performance section into prefs::Performance, as read_display_server already does. A malformed value elsewhere in the section falls back to automatic, as the display server does. Settings that do nothing: 12 -> 11 of 178. Scorecard regenerated; gaps G9, ui-parity and target-app-parity updated. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft/src/gpu_startup.rs | 8 ++++++-- docs/gaps.md | 5 +++-- docs/scorecard.md | 6 +++--- docs/target-app-parity.md | 7 ++++--- docs/ui-parity.md | 5 +++-- 5 files changed, 19 insertions(+), 12 deletions(-) diff --git a/apps/photocraft/src/gpu_startup.rs b/apps/photocraft/src/gpu_startup.rs index 9b08d4d2920..2c73418fd58 100644 --- a/apps/photocraft/src/gpu_startup.rs +++ b/apps/photocraft/src/gpu_startup.rs @@ -543,10 +543,14 @@ pub fn read_display_server(path: Option<&Path>) -> photocraft_engine::prefs::Lin } /// Preferences › Performance › Graphics Adapter (`performance.gpuAdapter`), read before the window -/// opens; empty (automatic) when the file or value is missing. +/// opens; empty (automatic) when the file or value is missing or the section doesn't parse, as +/// [`read_display_server`] reads its section. pub fn read_gpu_adapter(path: Option<&Path>) -> String { let v: Value = path.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null); - v.get("performance").and_then(|p| p.get("gpuAdapter")).and_then(Value::as_str).unwrap_or("").chars().take(256).collect() + v.get("performance") + .and_then(|p| serde_json::from_value::(p.clone()).ok()) + .map(|performance| performance.gpu_adapter.chars().take(256).collect()) + .unwrap_or_default() } /// Preferences › Performance › Low-Latency Drawing (`performance.lowLatencyDrawing`, off unless diff --git a/docs/gaps.md b/docs/gaps.md index 9168b453ba1..b5927859b38 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (G9: 12 of 178 preferences do nothing, as the scorecard prefs audit counts them; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (G9: 11 of 178 preferences do nothing: startup reads Graphics Adapter (`performance.gpuAdapter`) through the typed Performance section, so the scorecard prefs audit sees it; G9: 12 of 178 preferences do nothing, as the scorecard prefs audit counts them; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -285,7 +285,7 @@ what an agent can't finish alone. - **Progress (2026-10-15):** the Color panel has Photoshop's panel-menu modes (Hue Cube, Brightness Cube, Color Wheel, Grayscale/RGB/HSB/CMYK/Lab/Web Color sliders), its colour ramp and copy commands, the same in every theme (UI-217-17, #2569, #6000; `ui-egui/src/color_panel_ui.rs`). -- **Missing:** 12 of 178 preferences do nothing (scorecard prefs audit, 2026-10-25); panel groups can't +- **Missing:** 11 of 178 preferences do nothing (scorecard prefs audit, 2026-10-26); panel groups can't float or tear off into OS windows (UI-217-5, #1828, #1213, #2305); more themes (UI-217-11, #2661); a single pixel layer copies without its mask and styles (UI-217-23; fill and adjustment layers copy whole, #2344); tool-specific context menus beyond brushes, selections, Pen and Crop @@ -390,6 +390,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | G9: 11 of 178 preferences do nothing (was 12): Graphics Adapter (`performance.gpuAdapter`) always worked, but startup read it by raw JSON key, which the scorecard prefs audit can't see; it now reads the typed Performance section; no estimate changed | | 2026-10-25 | minor | G9: the count of preferences that do nothing is the scorecard's again, 12 of 178 (it still said 24 of 171, from 2026-10-15); no estimate changed | | 2026-10-25 | minor | G6: Art History Brush landed as partial (TOOL-213-20, #1610), so no toolbar tool is missing; no percentage or estimate changed | | 2026-10-23 | minor | G4: hard-round built-in presets use 5% spacing (#8842), guarded by large-stroke outline and pressure-opacity pixel regressions at 8/16/32-bit; percentages and estimates unchanged | diff --git a/docs/scorecard.md b/docs/scorecard.md index d025e679443..566d521fa22 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 31 | 65 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 27 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 12 of 178 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 11 of 178 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -187,9 +187,9 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 12 of 178** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 11 of 178** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. -Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.gpu_adapter`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. +Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. | Id | Target | Status | Issue | Note | |---|---|---|---|---| diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5c9fcd4b993..b8c13c00a70 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # PhotoCraft vs Adobe Photoshop: target-app parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-25 · **Change:** minor (12 of 178 preferences do nothing, from the scorecard; the Camera Raw row names per-camera colour for non-DNG cameras as missing, not the Calibration panel, which landed 2026-10-13; Content-Aware Scale measurements added, #5236; Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged; PSD spot plates in Photoshop's polarity, #7415 split; TIFF spot plates, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-26 · **Change:** minor (11 of 178 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; 12 of 178 preferences do nothing, from the scorecard; the Camera Raw row names per-camera colour for non-DNG cameras as missing, not the Calibration panel, which landed 2026-10-13; Content-Aware Scale measurements added, #5236; Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged; PSD spot plates in Photoshop's polarity, #7415 split; TIFF spot plates, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 The authoritative answer to "how close is PhotoCraft to Photoshop, and how much work is left". The one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md); @@ -76,7 +76,7 @@ Weights reflect what a working Photoshop user depends on (photographers, retouch | Dimension | Weight | % ready | Remaining (agent-h) | Evidence | Detail | |---|---:|---:|---:|---|---| | Features in depth (tools, layers, selections, type, filters, transforms) | 25% | 55% | 600–1,000 | Scorecard checklists: Tools 20 done / 15 partial / 6 missing, Type 5 / 5 / 0 (2026-10-22, area type partial), Automation 3 / 2 / 6. 14 tools missing; Select and Mask, Vanishing Point and Content-Aware Fill are parameter dialogs, not workspaces; type on a path partial; paragraph direction buttons exist but the visual RTL caret is missing | [gaps.md](gaps.md) | -| UI / UX fidelity and feel | 15% | 40% | 350–600 | ~150 open UI issues; Workspace checklist 13 / 5 / 5 (2026-10-12; 5 / 7 / 11 on 2026-10-10); 12 of 178 preferences do nothing (scorecard, 2026-10-25; was 27 of 156); no floating panel groups, thin Color panel, brush lag and pressure jumps reported | [ui-parity.md](ui-parity.md), [brush-parity.md](brush-parity.md) | +| UI / UX fidelity and feel | 15% | 40% | 350–600 | ~150 open UI issues; Workspace checklist 13 / 5 / 5 (2026-10-12; 5 / 7 / 11 on 2026-10-10); 11 of 178 preferences do nothing (scorecard, 2026-10-26; was 12 of 178); no floating panel groups, thin Color panel, brush lag and pressure jumps reported | [ui-parity.md](ui-parity.md), [brush-parity.md](brush-parity.md) | | File formats and fidelity | 15% | 60% | 300–500 | PSD oracle on Photoshop-authored files 133/256 (52%); io corpus 146/170 (86%); psd-tools 236/309 (76%); round trips ~100% of corpus; but users report Photoshop refusing our files (#1281, #2469; a text-layer case, #2374, was fixed 2026-10-10); no Photoshop PDF, EPS, JPEG 2000, JPEG XL, AVIF read, CR3 | [file-format-parity.md](file-format-parity.md) | | Performance | 10% | 25% | 200–350 | 3 of 25 budgeted scenarios meet budget (baseline 2026-10-05); 150-layer nudge crashes the GPU path (P12); layer move on 15000×10000 16-bit 2.7 s p50; users report brush and cursor lag (#2619, #2566, #1994) | [scorecard.md](scorecard.md#performance) | | Stability | 10% | 45% | 150–250 | Never-crash lints on 28/28 crates, `panic_hunt` in the gate, atomic saves; but field reports of freezes (#2518 Type tool 60 s on macOS), GPU panics (#2020, #1215), no-GPU start failures (#2519, #2412) | [gaps.md](gaps.md) | @@ -181,7 +181,7 @@ parity for the area and are already contained in the dimension rows above. | File I/O | 60% | 300–500 | See [file-format-parity.md](file-format-parity.md) | | Print, export, Save for Web | 50% | 60–100 | JPEG Options without Matte, progressive Scans or size preview (FILE-215-19), no Photoshop PDF, no separations, Save for Web settings not remembered | | Video / timeline, data-driven graphics | 30% | 100–200 | Menu items live; frame model persists in `.pcraft`; no PSD video-layer mapping | -| Workspace, panels, preferences | 40% | 150–250 | 12 of 178 prefs do nothing (scorecard, 2026-10-25); no floating/OS-window panel groups; Libraries, Comments, Contextual Task Bar missing | +| Workspace, panels, preferences | 40% | 150–250 | 11 of 178 prefs do nothing (scorecard, 2026-10-26); no floating/OS-window panel groups; Libraries, Comments, Contextual Task Bar missing | | AI / generative | 10% | 300–600 | See the dimension row | Batch supports [output naming templates](batch-naming.md); AUTO-219-5 remains partial. @@ -574,6 +574,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md). | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | UI / UX and Workspace rows: 11 of 178 preferences do nothing (was 12); Graphics Adapter always worked, but startup read it by raw JSON key, which the scorecard audit can't see. Percentages and estimates unchanged | | 2026-10-25 | minor | UI / UX and Workspace rows: 12 of 178 preferences do nothing, the scorecard's count. Camera Raw row: the Calibration panel landed on 2026-10-13 (#5128); what is missing is per-camera colour for non-DNG cameras ([gaps.md](gaps.md) G14). Percentages and estimates unchanged | | 2026-10-23 | minor | Colour management and modes: PSD spot plates are stored as Photoshop stores them (ink 0 = solid), and PSDs from earlier PhotoCraft versions keep their ink (#7415 split, part 4); estimates unchanged | | 2026-10-23 | minor | Colour management and modes: spot plates now save and open in TIFF (#7415); estimates unchanged | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 81b0ab81d63..79b33ceda1a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (12 of 178 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (11 of 178 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; 12 of 178 preferences do nothing, from the scorecard; Art History Brush in the History group of the Y flyout, partial, TOOL-213-20, #1610; Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests; Properties › Transform shows a shape's path geometry, without its stroke) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -230,7 +230,7 @@ Paragraph; the rest open as in-app floating windows. | Histogram panel: Compact (the default, of the entire image), Expanded and All Channels views (the channel kept across them); RGB/CMYK/Lab/Gray channels, Luminosity and Colors (overlaid, mixed where they overlap); Show Channels in Color and Show Statistics; Source (Entire Image, Selected Layer, Adjustment Composite) for multilayer documents; Mean, Std Dev, Median, Pixels, Level, Count, Percentile and Cache Level for the pointer level or a dragged range; the cached-data warning, Uncached Refresh (menu, button, warning click, double-click); the adjusted histogram over the original while an adjustment previews; Cache Levels 1–8 in Preferences › Performance; Color Sampler levels marked on the graph | partial | `histogram_panel.rs`, `histogram_panel_tests.rs`, `tone.rs`; differs: filter dialogs that preview on the CPU proxy aren't counted live, a selection doesn't limit the histogram yet, with Source Selected Layer an adjustment dialog's preview isn't counted, and new strings are English-only so far | | Command palette with recents | done | UI-217-7 | | Menu bar from the keyboard: Alt / F10 focus the bar, ← → ↓ ↩ drive it, Alt+letter opens a menu, underlined mnemonics run items | done | `menu_keys.rs`, #4988; macOS uses the native bar | -| Every preference takes effect | partial | 12 of 178 do nothing (scorecard, 2026-10-25) | +| Every preference takes effect | partial | 11 of 178 do nothing (scorecard, 2026-10-26) | | UI scale presets | done | UI-217-9; 75–125% in 5% steps (#2492, #3222) | | History snapshots: camera button, New Snapshot dialog (⌥-click: Name, From), the first snapshot (the document as opened), snapshot rows (click returns and selects, rename, delete; the trash deletes the selected snapshot, and a snapshot or state dragged onto it, #5324), `history.*Snapshot` commands | partial | `history_cmds.rs`, `snapshot_rows` in `panels.rs`, `snapshot_dialog.rs`; the snapshot History Options and History Brush sources to come (#2966) | | Themes: Photoshop's four greys | partial | five themes; #2661 | @@ -246,6 +246,7 @@ Paragraph; the rest open as in-app floating windows. | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | Every preference takes effect: 11 of 178 do nothing (was 12); Graphics Adapter always worked, but startup read it by raw JSON key, which the scorecard audit can't see | | 2026-10-25 | minor | Every preference takes effect: 12 of 178 do nothing, the scorecard's count (it still said 46 of 149) | | 2026-10-25 | minor | Art History Brush is in the History group of the Y flyout (partial, TOOL-213-20, #1610) | | 2026-10-24 | minor | Swatches: a click recolours the selected type layers and shape fills whatever the tool, as Photoshop 2025 does (measured with the Move and Brush tools); the Color panel still recolours them only with a Type, shape or Pen tool (#9238). Scores unchanged. | From 8103d35dee0bb5f1e132b3e35c9d5a461e3d3a9f Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:39:04 +0100 Subject: [PATCH 15/77] Prefs: startup reads the Performance section leniently, as the app does Review (CodeRabbit on #9618): deserialising the whole performance section strictly meant one wrongly typed value (say "cacheLevels": "four") reset Graphics Adapter to automatic at startup, while the app, which loads the file through read_lenient (#6611), kept the user's adapter. read_display_server had the same flaw. prefs::read_section exposes the engine's lenient reader for one section; gpu_startup's read_performance uses it for both the graphics adapter and the Linux display server. Tests: a valid adapter and display server survive a malformed sibling value. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft/src/gpu_startup.rs | 24 +++++++++++++----------- crates/engine/src/prefs.rs | 10 ++++++++++ 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/apps/photocraft/src/gpu_startup.rs b/apps/photocraft/src/gpu_startup.rs index 2c73418fd58..ae550d269c6 100644 --- a/apps/photocraft/src/gpu_startup.rs +++ b/apps/photocraft/src/gpu_startup.rs @@ -535,22 +535,20 @@ impl Sentinel { /// file, read before the window opens; `Auto` when the file or value is missing or unknown. #[cfg(any(target_os = "linux", test))] pub fn read_display_server(path: Option<&Path>) -> photocraft_engine::prefs::LinuxDisplayServer { + read_performance(path).map(|performance| performance.linux_display_server).unwrap_or_default() +} + +/// The preferences file's Performance section, read as the app reads it: a value of the wrong +/// type keeps its default without resetting the others. `None` without a file or section. +fn read_performance(path: Option<&Path>) -> Option { let v: Value = path.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null); - v.get("performance") - .and_then(|p| serde_json::from_value::(p.clone()).ok()) - .map(|performance| performance.linux_display_server) - .unwrap_or_default() + v.get("performance").cloned().map(photocraft_engine::prefs::read_section) } /// Preferences › Performance › Graphics Adapter (`performance.gpuAdapter`), read before the window -/// opens; empty (automatic) when the file or value is missing or the section doesn't parse, as -/// [`read_display_server`] reads its section. +/// opens; empty (automatic) when the file or value is missing or not text. pub fn read_gpu_adapter(path: Option<&Path>) -> String { - let v: Value = path.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(Value::Null); - v.get("performance") - .and_then(|p| serde_json::from_value::(p.clone()).ok()) - .map(|performance| performance.gpu_adapter.chars().take(256).collect()) - .unwrap_or_default() + read_performance(path).map(|performance| performance.gpu_adapter.chars().take(256).collect()).unwrap_or_default() } /// Preferences › Performance › Low-Latency Drawing (`performance.lowLatencyDrawing`, off unless @@ -613,6 +611,8 @@ mod tests { // Unknown values, other types, broken JSON and a missing file all start as Auto. assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"wayland"}}"#), LinuxDisplayServer::Auto); assert_eq!(read(r#"{"performance":{"linuxDisplayServer":11}}"#), LinuxDisplayServer::Auto); + // A bad value beside it resets only itself, as when the app loads the file (#6611). + assert_eq!(read(r#"{"performance":{"linuxDisplayServer":"x11","cacheLevels":"four"}}"#), LinuxDisplayServer::X11); assert_eq!(read("{not json"), LinuxDisplayServer::Auto); assert_eq!(read_display_server(Some(&dir.join("missing.json"))), LinuxDisplayServer::Auto); assert_eq!(read_display_server(None), LinuxDisplayServer::Auto); @@ -786,6 +786,8 @@ mod tests { }; assert_eq!(read(r#"{"performance":{"gpuAdapter":"nvidia"}}"#), "nvidia"); assert_eq!(read(r#"{"performance":{"gpuAdapter":7}}"#), ""); + // A bad value beside it resets only itself, as when the app loads the file (#6611). + assert_eq!(read(r#"{"performance":{"gpuAdapter":"nvidia","cacheLevels":"four"}}"#), "nvidia"); assert_eq!(read(r#"{"performance":{}}"#), ""); assert_eq!(read("not json"), ""); assert_eq!(read_gpu_adapter(None), ""); diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 1525741a5e9..f6a8d50c67e 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -1793,6 +1793,16 @@ where } } +/// One section of a preferences file (`performance`, …) read as [`Session::load_prefs_json`] +/// reads it: a value of the wrong type keeps its default and the rest still loads (#6611). +/// Startup reads the graphics settings with it before a session exists. +pub fn read_section(v: Value) -> T +where + T: Default + Serialize + for<'de> Deserialize<'de>, +{ + read_lenient(v, &[], &mut Vec::new()) +} + /// [`read_lenient`]'s walk: lay `file` over the object at `at` inside `root`, key by key, so that /// `root` always reads (`fits`). fn lay_over( From 56c720105547c01e9b931457d48aa3de4f37b00e Mon Sep 17 00:00:00 2001 From: Daniel Date: Mon, 26 Oct 2026 11:57:34 +0100 Subject: [PATCH 16/77] fix(linux): retain integrated CSD as default title bar --- crates/engine/src/prefs.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 793bfc56e10..5aa97df4ef8 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -293,8 +293,8 @@ pub struct Interface { pub show_bounding_box_when_dragging_layer: bool, /// Windows and Linux: use the system's title bar and window buttons instead of PhotoCraft's /// own one-row title bar (tiling window managers, desktops that draw their own decorations; - /// #1271, #1316). Enabled by default on Linux, where GNOME/Wayland needs the client frame. - /// Read when the app starts. macOS always uses the system's. + /// #1271, #1316). The integrated title bar remains the default on Linux and Windows; + /// the system frame is opt-in. Read when the app starts. macOS always uses the system's. pub system_title_bar: bool, /// Show the active document's file name in the title bar and the OS window title. The tabs /// already name the file, so this can be turned off for a plain "PhotoCraft" title (#5037). @@ -330,7 +330,7 @@ impl Default for Interface { show_tooltips: true, enable_animations: true, show_bounding_box_when_dragging_layer: false, - system_title_bar: cfg!(target_os = "linux"), + system_title_bar: false, show_file_name_in_title: true, notification_auto_hide: true, notification_duration_seconds: 6, From 5833b153e4a8c621f9b8a6bdc1a6143ff8b34687 Mon Sep 17 00:00:00 2001 From: Daniel Date: Mon, 26 Oct 2026 11:57:37 +0100 Subject: [PATCH 17/77] test(docs): preserve integrated Linux title bar and remove redundant NOTICE install --- crates/engine/src/prefs/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/prefs/tests.rs b/crates/engine/src/prefs/tests.rs index c0378dafb24..3506487c804 100644 --- a/crates/engine/src/prefs/tests.rs +++ b/crates/engine/src/prefs/tests.rs @@ -1,8 +1,8 @@ use super::*; #[test] -fn system_title_bar_defaults_by_platform_and_preserves_saved_choices() { - let default = cfg!(target_os = "linux"); +fn system_title_bar_defaults_to_integrated_and_preserves_saved_choices() { + let default = false; assert_eq!(Interface::default().system_title_bar, default); for saved in [json!({}), json!({"interface": {}})] { let prefs: Preferences = serde_json::from_value(saved).unwrap(); From 6927d058fc0f9054302dfcbda37fa326f5d17a0e Mon Sep 17 00:00:00 2001 From: Daniel Date: Mon, 26 Oct 2026 11:57:40 +0100 Subject: [PATCH 18/77] test(docs): preserve integrated Linux title bar and remove redundant NOTICE install --- apps/photocraft/src/main.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index 4e2c4aa7aca..96b22973283 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -83,8 +83,8 @@ const APP_ID: &str = "ai.storyteller.photocraft"; /// system traffic lights over the integrated title strip. const CUSTOM_TITLEBAR: bool = !cfg!(target_os = "macos"); -/// Whether this start draws its own title bar. Linux defaults to the system frame; Windows -/// defaults to the in-app title bar. Saved preferences override those defaults (#1271, #1316). +/// Whether this start draws its own title bar. Linux and Windows default to the integrated +/// title bar, with optional system decorations selected by saved preferences (#1271, #1316). fn custom_titlebar(prefs_file: Option<&std::path::Path>) -> bool { let prefs: photocraft_engine::prefs::Preferences = prefs_file.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default(); @@ -829,7 +829,7 @@ mod tests { let dir = std::env::temp_dir().join(format!("pc-titlebar-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let file = dir.join("prefs.json"); - let default_custom = super::CUSTOM_TITLEBAR && !cfg!(target_os = "linux"); + let default_custom = super::CUSTOM_TITLEBAR; assert_eq!(super::custom_titlebar(None), default_custom, "no preferences file: the platform default"); std::fs::write(&file, "not json").unwrap(); assert_eq!(super::custom_titlebar(Some(&file)), default_custom, "an unreadable file: the platform default"); From 17c5fb36af3152bf586cd37dfba60b8884fa8277 Mon Sep 17 00:00:00 2001 From: Daniel Date: Mon, 26 Oct 2026 11:57:44 +0100 Subject: [PATCH 19/77] test(docs): preserve integrated Linux title bar and remove redundant NOTICE install --- ROADMAP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ROADMAP.md b/ROADMAP.md index ada399071a5..27a3ac8bac3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -122,7 +122,7 @@ Detail and the next releases: [docs/roadmap.md](docs/roadmap.md). | Date | Entry | |---|---| -| 2026-10-21 | Linux defaults to System Title Bar so GNOME/Wayland has window controls. Saved choices and other platform defaults are preserved; startup and preference-dialog regressions cover both choices (#6266). | +| 2026-10-21 | Linux can use font-free Adwaita controls when System Title Bar is selected, while the integrated CSD title bar remains the default (as in #4439). Saved preferences are respected; startup and preference-dialog regressions cover both choices (#6266). | | 2026-10-17 | Object Finder classifies background by boundary coverage, retaining large enclosed foregrounds and rejecting surrounding backdrop (#6548); learned segmentation remains open (#2788) | | 2026-10-10 | Full re-measure against Photoshop 2026 27.11.0 (installed bundle inspected): breadth ~76%, ready ~45%, alpha. Progress docs reorganized to the craftrules standard (`parity.md` → `parity-checklist.md`, `parity-estimate.md` merged into `target-app-parity.md`). 0.6.0 released. | | 2026-10-09 | Remove tool, Rotate View, crop rotation; OpenRaster and Paint.NET; 39 Affinity documents in the corpus | From a0e1e4d836b7fab4a3f4cdedfea65181d73986ae Mon Sep 17 00:00:00 2001 From: Daniel Date: Mon, 26 Oct 2026 11:57:47 +0100 Subject: [PATCH 20/77] test(docs): preserve integrated Linux title bar and remove redundant NOTICE install --- docs/development.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/development.md b/docs/development.md index b8d2d6e6369..f39e93e9609 100644 --- a/docs/development.md +++ b/docs/development.md @@ -36,7 +36,7 @@ building locally; the downloaded app is still subject to Windows application-con ## Build and run -On Linux, **System Title Bar** is enabled by default. GNOME/Wayland uses winit's font-free Adwaita controls; X11 uses the window manager's frame. Saved choices still override the default, and other platforms keep their existing defaults. Changes in Preferences apply at the next launch. +On Linux, PhotoCraft keeps its integrated client-side decorated title bar by default (#4439), including desktop-matched buttons. Enabling **System Title Bar** in Preferences switches to the system frame at the next launch: on GNOME/Wayland, winit provides font-free Adwaita controls; on X11, the window manager supplies the frame. Explicit saved choices are respected and Windows/macOS defaults are unchanged. ```sh cargo run --release -p photocraft -- path/to/image.psd # desktop app From 7a9ee6256767e761e8c5fa89203527531f5c989a Mon Sep 17 00:00:00 2001 From: Daniel Date: Mon, 26 Oct 2026 11:57:50 +0100 Subject: [PATCH 21/77] test(docs): preserve integrated Linux title bar and remove redundant NOTICE install --- packaging/linux/flatpak/ai.storyteller.photocraft.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/packaging/linux/flatpak/ai.storyteller.photocraft.yml b/packaging/linux/flatpak/ai.storyteller.photocraft.yml index eb36821c23a..21893746655 100644 --- a/packaging/linux/flatpak/ai.storyteller.photocraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.photocraft.yml @@ -50,7 +50,6 @@ modules: - cargo --offline build --release --locked -p photocraft --features heif - install -Dm755 target/release/photocraft /app/bin/photocraft - install -Dm644 NOTICE /app/share/doc/photocraft/NOTICE - - install -Dm644 NOTICE /app/share/doc/photocraft/NOTICE - install -Dm644 packaging/linux/ai.storyteller.photocraft.desktop /app/share/applications/ai.storyteller.photocraft.desktop - install -Dm644 packaging/linux/ai.storyteller.photocraft.mime.xml /app/share/mime/packages/ai.storyteller.photocraft.xml - mkdir -p /app/share/icons && cp -R assets/app-icon/hicolor /app/share/icons/ From bef973a1c51268279dcd268ab699710b4c64b5ae Mon Sep 17 00:00:00 2001 From: Daniel Date: Mon, 26 Oct 2026 11:57:54 +0100 Subject: [PATCH 22/77] test(docs): preserve integrated Linux title bar and remove redundant NOTICE install --- crates/ui-egui/src/panels.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 2e2de02c065..56c19e380b1 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -912,9 +912,8 @@ mod title_tests { #[test] fn without_the_preference_the_mark_stays() { - // An explicit choice to keep the app's title, independent of the platform default. - let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - app.session.edit_prefs(|p| p.interface.system_title_bar = false); + // The default (e.g. the web build or snapshot example): the integrated title bar. + let app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); assert!(!system_title_bar(&app)); } From fe7f48fe2ee7ad5037105899d57d54cb325c84c0 Mon Sep 17 00:00:00 2001 From: Ben Huyck Date: Wed, 21 Oct 2026 11:46:12 +0000 Subject: [PATCH 23/77] 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 24/77] 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 25/77] 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 26/77] 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 27/77] 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 28/77] 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 29/77] 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 30/77] 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 31/77] =?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 32/77] 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 33/77] 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 34/77] 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 35/77] 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 36/77] 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 37/77] 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 38/77] 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 39/77] 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 40/77] =?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 41/77] =?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 42/77] =?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 43/77] 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 44/77] 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 45/77] =?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 46/77] =?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 47/77] =?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 122e55a4a02d8b3aa8db10af818ccd32c4d0ce65 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:49:33 +0100 Subject: [PATCH 48/77] Ask before re-importing a brush or gradient file over its group (#10640) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Importing an .abr or .grd whose name matched an existing group silently deleted that group's user presets (edited or moved-in ones included); the preset libraries are outside document history, so it could not be undone. - brush.presets.importAbr / gradient.presets.importGrd: `replace` now defaults to false; a taken group name imports beside it as "Kit (2)", "Kit (3)"…, and the result's `group` names the one it landed in. - UI: when the group already holds the user's presets, a prompt asks Import as New Group (default) / Replace (can't be undone) / Cancel. Agents drive it with ui.dialog.set {"choice":"replace"} / confirm / cancel. - The status bar names the group the file landed in. Fixes #10640 Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/preset_import_cmds.rs | 83 +++++++++++++++--- crates/ui-egui/examples/perf_scenarios.rs | 2 +- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/dialogs.rs | 19 ++++ .../src/dialogs/preset_group_prompt.rs | 86 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/preset_files_ui.rs | 75 +++++++++++++++- docs/control-protocol.md | 9 ++ 8 files changed, 260 insertions(+), 18 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/preset_group_prompt.rs diff --git a/crates/engine/src/cmd/preset_import_cmds.rs b/crates/engine/src/cmd/preset_import_cmds.rs index 417f5623a10..eb2c632561a 100644 --- a/crates/engine/src/cmd/preset_import_cmds.rs +++ b/crates/engine/src/cmd/preset_import_cmds.rs @@ -117,14 +117,29 @@ fn import_abr(s: &mut Session, p: &Value) -> Result { ) } -fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io::abr_map::AbrImport) -> Result { - // Re-importing a file replaces its group instead of duplicating it. - if p.get("replace").and_then(Value::as_bool).unwrap_or(true) { - s.tools.presets.retain(|x| x.builtin || x.group != group); +/// `name`, or `name (2)`, `name (3)`… when `taken` says it is in use. +fn free_group(name: &str, taken: impl Fn(&str) -> bool) -> String { + if !taken(name) { + return name.to_string(); } + (2..=u32::MAX).map(|i| format!("{name} ({i})")).find(|g| !taken(g)).unwrap_or_else(|| name.to_string()) +} + +fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io::abr_map::AbrImport) -> Result { + // A file whose name matches a group already in the library becomes a new group beside it, as + // in Photoshop, unless `replace` asks to drop that group's own presets first: the group name + // is only the file name, and the library is outside document history (#10640). + let group = if p.get("replace").and_then(Value::as_bool).unwrap_or(false) { + s.tools.presets.retain(|x| x.builtin || x.group != group); + group + } else { + let presets = &s.tools.presets; + free_group(&group, |g| presets.iter().any(|x| x.group == g)) + }; let mut taken = UniqueNames::new(s.tools.presets.iter().map(|x| x.name.as_str())); let mut names = Vec::with_capacity(imp.presets.len()); for mut preset in imp.presets { + preset.group.clone_from(&group); preset.name = taken.unique(&preset.name); names.push(preset.name.clone()); s.tools.presets.push(preset); @@ -243,7 +258,7 @@ pub fn specs() -> Vec { label: "Import Brushes…", menu: &[], shortcut: None, - params: r##"{"path":".abr file"?,"data":base64 bytes?,"group":string?=file name,"replace":bool=true (replace a group of the same name),"select":bool=false (make the first imported preset current)} → {group, imported, count, folders (nested folders kept from the file), version, warnings}"##, + params: r##"{"path":".abr file"?,"data":base64 bytes?,"group":string?=file name,"replace":bool=false (first delete the non-built-in presets of a group of the same name; false imports beside it as (2)),"select":bool=false (make the first imported preset current)} → {group, imported, count, folders (nested folders kept from the file), version, warnings}"##, enabled: always, run: import_abr, journal: true, @@ -263,7 +278,7 @@ pub fn specs() -> Vec { label: "Import Gradients…", menu: &[], shortcut: None, - params: r##"{"path":".grd file"?,"data":base64 bytes?,"group":string?=file name,"replace":bool=true (replace a group of the same name)}"##, + params: r##"{"path":".grd file"?,"data":base64 bytes?,"group":string?=file name,"replace":bool=false (first delete a group of the same name; false imports beside it as (2))} → {group, imported, count, warnings}"##, enabled: always, run: import_grd, journal: true, @@ -362,9 +377,13 @@ fn import_grd(s: &mut Session, p: &Value) -> Result { } let names: Vec = items.iter().map(|g| g.name.clone()).collect(); let st = &mut s.presets; - if p.get("replace").and_then(Value::as_bool).unwrap_or(true) { + // As with brushes: a new group beside one of the same name unless `replace` (#10640). + let group = if p.get("replace").and_then(Value::as_bool).unwrap_or(false) { st.gradients.retain(|g| g.name != group); - } + group + } else { + free_group(&group, |g| st.gradients.iter().any(|x| x.name == g)) + }; st.gradients.push(Group::new(&group, items)); s.presets_changed(); Ok(json!({"group": group, "imported": names, "count": names.len(), "warnings": warnings})) @@ -406,8 +425,8 @@ mod tests { assert_eq!(s.tools.presets.len(), before + 2); assert!(s.tools.presets.iter().filter(|p| p.group == "Legacy").all(|p| !p.builtin)); assert!(matches!(s.tools.brush.tip, photocraft_paint::TipShape::Sampled(_))); - // Re-import replaces the group. - s.execute("brush.presets.importAbr", json!({"data": data, "group": "Legacy"})).unwrap(); + // Re-import with `replace` replaces the group. + s.execute("brush.presets.importAbr", json!({"data": data, "group": "Legacy", "replace": true})).unwrap(); assert_eq!(s.tools.presets.len(), before + 2); // Imported presets paint. s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); @@ -426,6 +445,40 @@ mod tests { std::fs::remove_dir_all(&dir).ok(); } + /// Importing a file named like an existing group keeps that group's brushes, edited or moved + /// in ones included: the new brushes become "Kit (2)", "Kit (3)"… Only `replace` drops them (#10640). + #[test] + fn reimport_keeps_the_groups_brushes_unless_replace() { + let mut s = Session::new(); + let data = photocraft_paint::tile::b64_encode(&abr_v2()); + let builtin = s.tools.presets.iter().filter(|p| p.builtin).count(); + s.execute("brush.presets.importAbr", json!({"data": data, "group": "Kit"})).unwrap(); + // The user's own brush moved into the group. + let mut own = s.tools.presets.iter().find(|p| p.group == "Kit").unwrap().clone(); + own.name = "My Ink".into(); + s.tools.presets.push(own); + let r = s.execute("brush.presets.importAbr", json!({"data": data, "group": "Kit"})).unwrap(); + assert_eq!(r["group"], "Kit (2)"); + let in_group = |s: &Session, g: &str| s.tools.presets.iter().filter(|p| p.group == g).count(); + assert_eq!((in_group(&s, "Kit"), in_group(&s, "Kit (2)")), (3, 2)); + let r = s.execute("brush.presets.importAbr", json!({"data": data, "group": "Kit", "replace": false})).unwrap(); + assert_eq!(r["group"], "Kit (3)"); + assert!(s.tools.presets.iter().any(|p| p.name == "My Ink" && p.group == "Kit")); + // `replace` drops only that group's non-built-in presets. + let r = s.execute("brush.presets.importAbr", json!({"data": data, "group": "Kit", "replace": true})).unwrap(); + assert_eq!(r["group"], "Kit"); + assert_eq!((in_group(&s, "Kit"), in_group(&s, "Kit (2)"), in_group(&s, "Kit (3)")), (2, 2, 2)); + assert!(!s.tools.presets.iter().any(|p| p.name == "My Ink")); + assert_eq!(s.tools.presets.iter().filter(|p| p.builtin).count(), builtin); + } + + #[test] + fn free_group_numbers_past_taken_names() { + let taken = ["Kit", "Kit (2)"]; + assert_eq!(free_group("Set", |g| taken.contains(&g)), "Set"); + assert_eq!(free_group("Kit", |g| taken.contains(&g)), "Kit (3)"); + } + #[test] fn bad_params_fail_gracefully() { let mut s = Session::new(); @@ -472,10 +525,14 @@ mod tests { let g = s.presets.gradients.iter().find(|g| g.name == "Fire").unwrap(); assert_eq!(g.items[0].stops, vec![(0.0, StopColor::Foreground), (1.0, StopColor::Rgb([1.0, 0.0, 0.0]))]); assert_eq!(g.items[0].opacity, vec![(0.0, 1.0), (1.0, 0.0)]); - // Re-import replaces the group. + // Re-import adds a group beside it (#10640); with `replace` it replaces the group. let n = s.presets.gradients.len(); - s.execute("gradient.presets.importGrd", json!({"data": data, "group": "Fire"})).unwrap(); - assert_eq!(s.presets.gradients.len(), n); + let r = s.execute("gradient.presets.importGrd", json!({"data": data, "group": "Fire"})).unwrap(); + assert_eq!(r["group"], "Fire (2)"); + assert_eq!(s.presets.gradients.len(), n + 1); + s.execute("gradient.presets.importGrd", json!({"data": data, "group": "Fire", "replace": true})).unwrap(); + assert_eq!(s.presets.gradients.len(), n + 1); + assert_eq!(s.presets.gradients.iter().filter(|g| g.name == "Fire").count(), 1); for p in [json!({}), json!({"data": "@@"}), json!({"data": photocraft_paint::tile::b64_encode(b"8BGR\0\x03")}), json!({"path": "/nope.grd"})] { assert!(s.execute("gradient.presets.importGrd", p.clone()).is_err(), "{p}"); } diff --git a/crates/ui-egui/examples/perf_scenarios.rs b/crates/ui-egui/examples/perf_scenarios.rs index 9572453c75a..0062d12e639 100644 --- a/crates/ui-egui/examples/perf_scenarios.rs +++ b/crates/ui-egui/examples/perf_scenarios.rs @@ -943,7 +943,7 @@ fn background_job_scenarios(b: &mut Bench, sz: &Sizes) { // The UI thread's work: starting the job, then each frame's poll (the last one // applies the 500 presets). let t = Instant::now(); - let job = start_job(s, "brush.presets.importAbr", json!({"data": data, "group": "Bench"}))?; + let job = start_job(s, "brush.presets.importAbr", json!({"data": data, "group": "Bench", "replace": true}))?; let mut worst = ms(t); let t0 = Instant::now(); loop { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index c1660d75f9a..14038b10de4 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -192,6 +192,7 @@ impl PhotocraftApp { jpeg_options: None, dds_options: None, held_opens: Default::default(), + held_preset_import: None, allow_close: false, stylus: Default::default(), control_click: Default::default(), diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index bc0435806e4..d38a75f1017 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -294,6 +294,7 @@ fn command_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: _ if crate::delete_layer_prompt::owns(fields) => crate::delete_layer_prompt::body(ui, 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::preset_group_prompt::owns(fields) => crate::preset_group_prompt::body(ui, fields), _ if crate::actions::owns_insert_stop(fields) => crate::actions::insert_stop_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), @@ -488,6 +489,17 @@ fn button_row( fields.insert("choice".into(), json!("rasterize")); } hit + } else if crate::preset_group_prompt::owns(fields) { + // Import as New Group / Cancel / Replace (#10640): Enter keeps the group. + let new = DialogButton::new(ButtonRole::Default, tl!("Import as New Group"), 150.0); + let replace = DialogButton::new(ButtonRole::Alternate, tl!("Replace"), 84.0); + let hit = dialog_buttons(ui, &[new, cancel, replace]); + if hit == Some(ButtonRole::Alternate) { + fields.insert("choice".into(), json!("replace")); + } else if hit == Some(ButtonRole::Default) { + fields.insert("choice".into(), json!("new")); + } + hit } else { dialog_buttons(ui, &[ok, cancel]) }; @@ -849,6 +861,7 @@ const ROUTES: &[fn(&Fields) -> bool] = &[ crate::prefs_ui::owns, crate::open_prompt::owns, crate::replace_prompt::owns, + crate::preset_group_prompt::owns, crate::layer_style::color_picker::owns, |f| f.contains_key("__export"), |f| f.contains_key("__smartFilter"), @@ -988,6 +1001,7 @@ fn confirm_command(app: &mut PhotocraftApp, d: Dialog) -> Result _ if crate::delete_layer_prompt::owns(&d.fields) => crate::delete_layer_prompt::confirm(app, &d.fields), _ 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::preset_group_prompt::owns(&d.fields) => crate::preset_group_prompt::confirm(app, &d.fields), _ if crate::actions::owns_insert_stop(&d.fields) => crate::actions::insert_stop_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), @@ -1053,6 +1067,10 @@ pub fn cancel(app: &mut PhotocraftApp, id: u64) -> Result { if crate::replace_prompt::owns(&closed.fields) { crate::replace_prompt::cancel(app)?; } + // Cancel on the group-name question imports nothing. + if crate::preset_group_prompt::owns(&closed.fields) { + crate::preset_group_prompt::cancel(app); + } app.ui.dialogs.retain(|d| !crate::layer_style::color_picker::child_of(&d.fields, id)); app.filter_preview = None; app.color_range = None; @@ -1139,6 +1157,7 @@ pub mod new_layer_ui; pub mod open_prompt; pub mod palette; pub(crate) mod pattern_fill_ui; +pub mod preset_group_prompt; pub mod rasterize_prompt; pub mod replace_prompt; pub(super) mod rgb_histogram; diff --git a/crates/ui-egui/src/dialogs/preset_group_prompt.rs b/crates/ui-egui/src/dialogs/preset_group_prompt.rs new file mode 100644 index 00000000000..55f07d6d4d5 --- /dev/null +++ b/crates/ui-egui/src/dialogs/preset_group_prompt.rs @@ -0,0 +1,86 @@ +//! Importing a brush (`.abr`) or gradient (`.grd`) file asks first when the library already has +//! a group of the file's name with presets of the user's (#10640). The group key is only the file +//! name, so it can be another author's set, or hold brushes the user edited or moved there, and +//! the preset libraries are outside document history. +//! +//! Import as New Group (the default) imports beside it as "Kit (2)"; Replace deletes the group's +//! presets first, which can't be undone; Cancel imports nothing. Without a clash the file imports +//! at once, as before. +//! +//! The prompt is an ordinary dialog in the UI state: `ui.inspect` shows it, `ui.dialog.confirm` +//! imports as a new group, `ui.dialog.set` with `"choice": "replace"` then `ui.dialog.confirm` +//! replaces, and `ui.dialog.cancel` imports nothing. + +use serde_json::{Map, Value, json}; + +use crate::PhotocraftApp; +use crate::state::DialogKind; + +const MARK: &str = "__presetGroupClash"; + +/// An import held back while the prompt is up. +pub struct Held { + pub cmd: &'static str, + pub what: &'static str, + pub stem: String, + pub params: Value, +} + +pub fn owns(fields: &Map) -> bool { + fields.contains_key(MARK) +} + +/// How many of the user's presets a group named `group` holds in the library `cmd` imports to +/// (built-in brushes are never replaced, so they don't count). +fn clashing(app: &PhotocraftApp, cmd: &str, group: &str) -> usize { + match cmd { + "brush.presets.importAbr" => app.session.tools.presets.iter().filter(|x| !x.builtin && x.group == group).count(), + "gradient.presets.importGrd" => app.session.presets.gradients.iter().filter(|g| g.name == group).map(|g| g.items.len()).sum(), + _ => 0, + } +} + +/// Opens the prompt for `held` when its group clashes; otherwise hands `held` back to import now. +pub(crate) fn intercept(app: &mut PhotocraftApp, held: Held) -> Result, String> { + let n = clashing(app, held.cmd, &held.stem); + if n == 0 { + return Ok(Some(held)); + } + if app.ui.dialogs.iter().any(|d| owns(&d.fields)) { + return Err(tl!("Answer the open import question first, then import this file again.").into()); + } + let (label, one, other) = if held.what == "gradients" { + ("Import Gradients", "The gradient group “{group}” already exists ({n} gradient).", "The gradient group “{group}” already exists ({n} gradients).") + } else { + ("Import Brushes", "The brush group “{group}” already has {n} brush of yours.", "The brush group “{group}” already has {n} brushes of yours.") + }; + let message = crate::i18n::fmt(&crate::i18n::trn(crate::i18n::current(), n as u64, one, other), &[("group", &held.stem)]); + let fields = json!({MARK: true, "__label": label, "message": message, "group": held.stem, "kind": held.what, "choice": "new"}); + app.held_preset_import = Some(held); + app.ui.open_dialog(DialogKind::Command, fields.as_object().cloned().unwrap_or_default()); + Ok(None) +} + +pub fn body(ui: &mut egui::Ui, fields: &Map) { + ui.label(fields.get("message").and_then(Value::as_str).unwrap_or_default()); + ui.add_space(6.0); + let group = fields.get("group").and_then(Value::as_str).unwrap_or_default(); + ui.label(crate::i18n::fmt(tl!("Import as New Group keeps “{group}” and adds the file as a new group beside it."), &[("group", group)])); + ui.add_space(4.0); + ui.label(crate::i18n::fmt( + tl!("Replace deletes everything in “{group}” first, including presets you edited or moved there. This can't be undone."), + &[("group", group)], + )); +} + +/// The held import: as a new group, or replacing the group when `choice` is "replace". +pub fn confirm(app: &mut PhotocraftApp, fields: &Map) -> Result { + let Held { cmd, what, stem, mut params } = app.held_preset_import.take().ok_or(tl!("No import is waiting. Import the file again."))?; + params["replace"] = json!(fields.get("choice").and_then(Value::as_str) == Some("replace")); + crate::preset_files_ui::run_import(app, cmd, what, &stem, params).map(|()| Value::Null) +} + +/// Cancel: nothing is imported. +pub fn cancel(app: &mut PhotocraftApp) { + app.held_preset_import = None; +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 50b01746312..e17b2bc80dd 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -165,6 +165,7 @@ pub use dialogs::new_layer_ui; pub use dialogs::open_prompt; pub use dialogs::palette; pub(crate) use dialogs::pattern_fill_ui; +pub use dialogs::preset_group_prompt; pub use dialogs::rasterize_prompt; pub use dialogs::replace_prompt; use dialogs::rgb_histogram; @@ -686,6 +687,8 @@ pub struct PhotocraftApp { /// Files read but not opened yet: the first waits on its profile prompt, the rest behind it /// (see `open_prompt`). pub(crate) held_opens: std::collections::VecDeque, + /// A brush or gradient file waiting on the group-name prompt (see `preset_group_prompt`). + pub(crate) held_preset_import: Option, /// Set once the user has agreed to quit, so the resulting close request goes through. pub(crate) allow_close: bool, /// Pen pressure/tilt from the platform (see `stylus`). diff --git a/crates/ui-egui/src/preset_files_ui.rs b/crates/ui-egui/src/preset_files_ui.rs index 74be08360cf..2407f71e14e 100644 --- a/crates/ui-egui/src/preset_files_ui.rs +++ b/crates/ui-egui/src/preset_files_ui.rs @@ -101,12 +101,26 @@ pub fn open(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Option run_import(app, held.cmd, held.what, &held.stem, held.params), + Ok(None) => Ok(()), + Err(e) => Err(e), + }); + } + Some(run_import(app, cmd, what, &stem, p)) +} + +/// Run the import command for a preset file and report it in the status bar. +pub(crate) fn run_import(app: &mut PhotocraftApp, cmd: &str, what: &str, stem: &str, p: Value) -> Result<(), String> { + app.run(cmd, p).map(|r| { // A background import (#210): `jobs_ui` reports the count when it lands. if r.get("pending").and_then(Value::as_bool) == Some(true) { app.ui.status_error = false; let template = "Importing {what} from {file}…"; - app.ui.status = crate::i18n::fmt(tl!(template), &[("what", tl!(what)), ("file", &stem)]); + app.ui.status = crate::i18n::fmt(tl!(template), &[("what", tl!(what)), ("file", stem)]); return; } let n = r.get("count").and_then(Value::as_u64).unwrap_or(0); @@ -118,7 +132,9 @@ pub fn open(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Option ("Imported {n} pattern from {file}", "Imported {n} patterns from {file}"), _ => ("Imported {n} gradient from {file}", "Imported {n} gradients from {file}"), }; - let imported = crate::i18n::fmt(&crate::i18n::trn(crate::i18n::current(), n, one, other), &[("file", &stem)]); + // The group it landed in: "Kit (2)" beside an existing "Kit" (#10640). + let group = r.get("group").and_then(Value::as_str).unwrap_or(stem); + let imported = crate::i18n::fmt(&crate::i18n::trn(crate::i18n::current(), n, one, other), &[("file", group)]); app.ui.status = match warnings.first() { Some(warning) => { let template = "{message} (notes: {n}; {warning})"; @@ -134,7 +150,7 @@ pub fn open(app: &mut PhotocraftApp, name: &str, bytes: &[u8]) -> Option (2)`, ` (3)`…, and the +result's `group` names the one it landed in. Pass `"replace": true` to delete that group's own +presets first (built-in brushes are kept); the preset libraries are outside document history, so +this can't be undone (#10640). In the app, opening such a file (`app.open`, File › Open, +drag-and-drop, Import Brushes…) shows a prompt instead: `ui.dialog.confirm` imports as a new +group, `ui.dialog.set {"choice":"replace"}` then `ui.dialog.confirm` replaces, and +`ui.dialog.cancel` imports nothing. + Named New Document presets also persist with preferences (`presets.documents`) on desktop and web. File › New › Save Preset… saves the current form; the Saved tab selects a configuration or deletes it. Selection only fills the form: Create still runs `file.new`, and the document name From 2ab2ab2f0d995d1049bac8d558557862b0db33af Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:05:41 +0100 Subject: [PATCH 49/77] Name the source file in the preset import status (#10640) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After a group-name clash the status read "Imported 2 brushes from Kit (2)", naming the destination group as if it were the file. Keep the translated "… from {file}" message and add the group only when it differs: "Imported 2 brushes from Kit into “Kit (2)”". Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/preset_files_ui.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/preset_files_ui.rs b/crates/ui-egui/src/preset_files_ui.rs index 2407f71e14e..0e0ae0ffa49 100644 --- a/crates/ui-egui/src/preset_files_ui.rs +++ b/crates/ui-egui/src/preset_files_ui.rs @@ -132,9 +132,12 @@ pub(crate) fn run_import(app: &mut PhotocraftApp, cmd: &str, what: &str, stem: & "patterns" => ("Imported {n} pattern from {file}", "Imported {n} patterns from {file}"), _ => ("Imported {n} gradient from {file}", "Imported {n} gradients from {file}"), }; - // The group it landed in: "Kit (2)" beside an existing "Kit" (#10640). - let group = r.get("group").and_then(Value::as_str).unwrap_or(stem); - let imported = crate::i18n::fmt(&crate::i18n::trn(crate::i18n::current(), n, one, other), &[("file", group)]); + let imported = crate::i18n::fmt(&crate::i18n::trn(crate::i18n::current(), n, one, other), &[("file", stem)]); + // Name the group too when it isn't the file's: "Kit (2)" beside an existing "Kit" (#10640). + let imported = match r.get("group").and_then(Value::as_str) { + Some(group) if group != stem.trim() => crate::i18n::fmt(tl!("{message} into “{group}”"), &[("message", &imported), ("group", group)]), + _ => imported, + }; app.ui.status = match warnings.first() { Some(warning) => { let template = "{message} (notes: {n}; {warning})"; @@ -187,6 +190,7 @@ mod tests { open(&mut app, "Kit.abr", &abr).unwrap().unwrap(); assert_eq!(in_group(&app, "Kit"), 2); assert!(prompt(&app).is_none(), "a new group imports without asking"); + assert!(app.ui.status.ends_with("brushes from Kit"), "{}", app.ui.status); // The user edits one of its brushes. let edited = app.session.tools.presets.iter_mut().find(|p| p.group == "Kit").unwrap(); edited.brush.size = 77.0; @@ -204,7 +208,8 @@ mod tests { let id = prompt(&app).expect("the prompt is open"); crate::dialogs::confirm(&mut app, id).unwrap(); assert_eq!((in_group(&app, "Kit"), in_group(&app, "Kit (2)")), (2, 2)); - assert!(app.ui.status.contains("Kit (2)"), "{}", app.ui.status); + // The status names the file and the group it landed in. + assert!(app.ui.status.ends_with("from Kit into “Kit (2)”"), "{}", app.ui.status); let size = |app: &PhotocraftApp| app.session.tools.presets.iter().find(|p| p.name == edited).map(|p| p.brush.size); assert_eq!(size(&app), Some(77.0), "the edited brush is kept"); From 586563fc2bc25f1cd2664aef5a436e2339df1191 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:18:24 +0100 Subject: [PATCH 50/77] Address review: one group-name set for clashes, test the .grd prompt (#10640) - free_group's brush check builds the set of group names once instead of scanning every preset for each numbered candidate. - reimporting_a_gradient_file_asks_before_touching_its_group covers the gradient branch of the prompt: no prompt for a new group, Cancel imports nothing, Import as New Group adds "Fire (2)", Replace swaps "Fire" alone. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/preset_import_cmds.rs | 5 +-- crates/ui-egui/src/preset_files_ui.rs | 36 +++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/preset_import_cmds.rs b/crates/engine/src/cmd/preset_import_cmds.rs index eb2c632561a..07f7f50eb02 100644 --- a/crates/engine/src/cmd/preset_import_cmds.rs +++ b/crates/engine/src/cmd/preset_import_cmds.rs @@ -133,8 +133,9 @@ fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io s.tools.presets.retain(|x| x.builtin || x.group != group); group } else { - let presets = &s.tools.presets; - free_group(&group, |g| presets.iter().any(|x| x.group == g)) + // One pass over the library, not one per numbered candidate. + let groups: std::collections::HashSet<&str> = s.tools.presets.iter().map(|x| x.group.as_str()).collect(); + free_group(&group, |g| groups.contains(g)) }; let mut taken = UniqueNames::new(s.tools.presets.iter().map(|x| x.name.as_str())); let mut names = Vec::with_capacity(imp.presets.len()); diff --git a/crates/ui-egui/src/preset_files_ui.rs b/crates/ui-egui/src/preset_files_ui.rs index 0e0ae0ffa49..fa82c7a0931 100644 --- a/crates/ui-egui/src/preset_files_ui.rs +++ b/crates/ui-egui/src/preset_files_ui.rs @@ -225,6 +225,42 @@ mod tests { assert!(prompt(&app).is_none()); } + /// The same prompt guards a gradient group: `Fire.grd` again asks, Cancel imports nothing, + /// Import as New Group adds "Fire (2)", Replace swaps "Fire" alone (#10640). + #[test] + fn reimporting_a_gradient_file_asks_before_touching_its_group() { + use photocraft_psd::grd::{GrdColor, GrdGradient, GrdStop, write}; + let stop = |location: f32, color| GrdStop { location, midpoint: 0.5, color }; + let ember = + GrdGradient { name: "Ember".into(), stops: vec![stop(0.0, GrdColor::Foreground), stop(1.0, GrdColor::Rgb([1.0, 0.0, 0.0]))], ..Default::default() }; + let grd = write(&[ember]); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let groups = |app: &PhotocraftApp, g: &str| app.session.presets.gradients.iter().filter(|x| x.name == g).count(); + let prompt = |app: &PhotocraftApp| app.ui.dialogs.iter().find(|d| crate::preset_group_prompt::owns(&d.fields)).map(|d| d.id); + open(&mut app, "Fire.grd", &grd).unwrap().unwrap(); + assert_eq!(groups(&app, "Fire"), 1); + assert!(prompt(&app).is_none(), "a new group imports without asking"); + + open(&mut app, "Fire.grd", &grd).unwrap().unwrap(); + let id = prompt(&app).expect("the prompt is open"); + crate::dialogs::cancel(&mut app, id).unwrap(); + assert_eq!((groups(&app, "Fire"), groups(&app, "Fire (2)")), (1, 0)); + + open(&mut app, "Fire.grd", &grd).unwrap().unwrap(); + let id = prompt(&app).expect("the prompt is open"); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!((groups(&app, "Fire"), groups(&app, "Fire (2)")), (1, 1)); + assert!(app.ui.status.ends_with("from Fire into “Fire (2)”"), "{}", app.ui.status); + + open(&mut app, "Fire.grd", &grd).unwrap().unwrap(); + let id = prompt(&app).expect("the prompt is open"); + if let Some(d) = app.ui.dialogs.iter_mut().find(|d| d.id == id) { + d.fields.insert("choice".into(), json!("replace")); + } + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!((groups(&app, "Fire"), groups(&app, "Fire (2)"), groups(&app, "Fire (3)")), (1, 1, 0)); + } + /// Import Brushes… with a PNG: the image becomes the current brush's tip (TOOL-213-12). #[test] fn import_brushes_turns_an_image_into_a_brush_tip() { From ef36604c3c396c4c0df0d4f7a88446067f6367d5 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:09:29 +0100 Subject: [PATCH 51/77] Preset panel footers use the Layers footer's glyphs and size (#10656) The shared Swatches / Gradients / Patterns footer drew New Group as `folder-plus` and New as `plus` at 24 pt, while the Layers footer uses `folder` and `square-plus` at 26 pt. Both footers now take shared `icons::FOOTER_*` constants, so they can't drift apart again; a test checks the glyphs are bundled (a misspelt name draws the fallback square). The footer grows from 28 to 30 pt, still under the 32 pt first-frame guess; the #4790 footer-fit test passes. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/icons.rs | 15 +++++++++++++++ crates/ui-egui/src/panels/layers.rs | 7 ++++--- crates/ui-egui/src/panels/preset_panels.rs | 8 ++++---- 3 files changed, 23 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index f1bd354a1ce..0a42a03527e 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -23,6 +23,13 @@ pub fn exists(name: &str) -> bool { white_icons().contains(name) } +/// Panel footer buttons share one glyph per action and one size, so the Layers footer and the +/// Swatches, Gradients and Patterns footers read the same, as in Photoshop (#10656). +pub const FOOTER_SIZE: f32 = 26.0; +pub const FOOTER_NEW: &str = "square-plus"; +pub const FOOTER_NEW_GROUP: &str = "folder"; +pub const FOOTER_DELETE: &str = "trash"; + /// An egui image for an icon, tinted. pub fn image(name: &str, size: f32, tint: Color32) -> egui::Image<'static> { egui::Image::new(white_icons().source(name)).fit_to_exact_size(Vec2::splat(size)).tint(tint) @@ -345,6 +352,14 @@ mod tests { } } + /// #10656: a misspelt footer glyph would silently draw the fallback square. + #[test] + fn footer_glyphs_are_bundled() { + for name in [FOOTER_NEW, FOOTER_NEW_GROUP, FOOTER_DELETE] { + assert!(exists(name), "{name}"); + } + } + #[test] fn shared_catalog_preserves_fallback() { let egui::ImageSource::Bytes { uri, bytes } = white_icons().source("missing-icon") else { panic!("expected SVG bytes") }; diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 681754acccd..176ed271e17 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -380,7 +380,7 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } else { ("layer.delete", "Delete layer") }; - let trash = icons::button(ui, "trash", 26.0, false, tl!(label)); + let trash = icons::button(ui, icons::FOOTER_DELETE, icons::FOOTER_SIZE, false, tl!(label)); // A selected smart filter row is what Delete removes, as in Photoshop (#4751). let picked_filter = crate::smart_ui::selected(&ctx, &doc, active); if trash.clicked() @@ -411,7 +411,8 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // A click follows the selected thumbnail; name that action for screen readers even // though dropping a whole layer row onto the same button always deletes the layer. trash.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(label))); - let new_layer = icons::button(ui, "square-plus", 26.0, false, &crate::shortcuts::tip_label(app, "Create a new layer", "layer.new.layer")); + let new_layer = + icons::button(ui, icons::FOOTER_NEW, icons::FOOTER_SIZE, false, &crate::shortcuts::tip_label(app, "Create a new layer", "layer.new.layer")); if new_layer.clicked() { // A click makes the layer above the selection; ⌥-click asks first (the New Layer // dialog) and ⌘/Ctrl-click adds it below, as in Photoshop. @@ -426,7 +427,7 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { actions.push(("layer.new.layer".into(), params)); } actions.extend(footer_drop(ui, &new_layer, footer_drag, "layer.duplicate")); - let group = icons::button(ui, "folder", 26.0, false, tl!("Create a new group")); + let group = icons::button(ui, icons::FOOTER_NEW_GROUP, icons::FOOTER_SIZE, false, tl!("Create a new group")); if group.clicked() { // Like Photoshop CC 2014 and later, a click with two or more layers selected puts them // in the new group (Layer › Group Layers); with one layer or none it adds an empty diff --git a/crates/ui-egui/src/panels/preset_panels.rs b/crates/ui-egui/src/panels/preset_panels.rs index 2387b2ea9d2..29b5d85a959 100644 --- a/crates/ui-egui/src/panels/preset_panels.rs +++ b/crates/ui-egui/src/panels/preset_panels.rs @@ -599,7 +599,7 @@ pub(crate) fn browser( ev.push(Ev::Drop(key, pos)); } } - // Footer: thumbnail size | New Group, New, Delete. + // Footer: thumbnail size | New Group, New, Delete (same glyphs and size as the Layers footer). let footer_top = ui.min_rect().bottom(); ui.add_space(4.0); ui.horizontal(|ui| { @@ -612,15 +612,15 @@ pub(crate) fn browser( st.sizes.insert(panel.to_string(), s); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if crate::icons::button(ui, "trash", 24.0, false, tl!("Delete")).clicked() + if crate::icons::button(ui, crate::icons::FOOTER_DELETE, crate::icons::FOOTER_SIZE, false, tl!("Delete")).clicked() && let Some(k) = selected.clone() { ev.push(Ev::Delete(k)); } - if crate::icons::button(ui, "plus", 24.0, false, new_tip).clicked() { + if crate::icons::button(ui, crate::icons::FOOTER_NEW, crate::icons::FOOTER_SIZE, false, new_tip).clicked() { ev.push(Ev::New); } - if crate::icons::button(ui, "folder-plus", 24.0, false, tl!("Create new group")).clicked() { + if crate::icons::button(ui, crate::icons::FOOTER_NEW_GROUP, crate::icons::FOOTER_SIZE, false, tl!("Create new group")).clicked() { ev.push(Ev::NewGroup); } }); From 44f356c6de63e0b35cf9ca5e3354b9b63e4a1e18 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:27:19 +0100 Subject: [PATCH 52/77] Paint the marching ants over the guides (#10671) A guide on the same device pixel as a selection edge hid it, at some zoom levels and not others: the ants were painted in paint_canvas and the guides after them in paint_primary_overlays. The ants are still traced in paint_canvas from the frame's snapshot, but returned as shapes and painted right after the grid and guides; a secondary view paints them where it did. Free Transform's carried ants come from transform_tool::selection_ants (was draw_selection), which returns shapes instead of painting. Test: canvas::guide_ants_tests checks the paint order at three display scales and nine zoom levels; it fails without the fix. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 44 ++++++++---- crates/ui-egui/src/canvas/ants.rs | 18 +++-- crates/ui-egui/src/canvas/guide_ants_tests.rs | 69 +++++++++++++++++++ crates/ui-egui/src/canvas/paint.rs | 13 +++- crates/ui-egui/src/tools/transform_tool.rs | 2 +- .../ui-egui/src/tools/transform_tool/draw.rs | 20 +++--- .../ui-egui/src/tools/transform_tool/tests.rs | 6 +- 7 files changed, 141 insertions(+), 31 deletions(-) create mode 100644 crates/ui-egui/src/canvas/guide_ants_tests.rs diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 3196f4951f3..12b4a8a766a 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -87,9 +87,10 @@ use navigator::navigator_waits_for_drag; pub use navigator::{NAVIGATOR_SIDE, navigator_gpu_view, navigator_texture, navigator_waits_for_gpu}; #[cfg(test)] use paint::draw_tool_state; -pub(crate) use paint::{clip_line, marching_ants_lines, marching_ants_mapped}; +pub(crate) use paint::{clip_line, marching_ants_line_shapes, marching_ants_mapped}; use paint::{ - draw_beyond_canvas, draw_drag_preview, marching_ants_segments, paint_cpu_detail, paint_cpu_document, paint_gpu_view, paint_mapped_image_at, pattern_xf, + draw_beyond_canvas, draw_drag_preview, marching_ants_segment_shapes, paint_cpu_detail, paint_cpu_document, paint_gpu_view, paint_mapped_image_at, + pattern_xf, }; use selection::selection_shown_offset; pub use selection::{SelCursor, selection_cursor}; @@ -232,7 +233,11 @@ struct SelectionPaintInput<'a> { idx: usize, } -fn paint_selection_outline(app: &mut PhotocraftApp, input: SelectionPaintInput<'_>) { +/// The marching ants of the selection, traced from this frame's snapshot like the image under +/// them, returned to be painted over the grid and guides (#10671): a guide on the same device +/// pixel as an edge used to hide it, at some zoom levels and not others. +fn paint_selection_outline(app: &mut PhotocraftApp, input: SelectionPaintInput<'_>) -> Vec { + let mut ants = Vec::new(); // Select and Mask outlines its refined selection (on its preview proxy, reduced by `k`) in // the Marching Ants view and hides the ants in the others. let refined = crate::select_mask_view::ants(app, input.idx); @@ -316,15 +321,23 @@ fn paint_selection_outline(app: &mut PhotocraftApp, input: SelectionPaintInput<' shown.center = [input.xf.center[0] - dx as f32, input.xf.center[1] - dy as f32]; } // Under a Free Transform box they are where the box puts them (#5297). - if !(carried && crate::transform_tool::draw_selection(app, input.painter, &input.xf, input.doc.id, segs, time)) { - marching_ants_segments(input.painter, &shown, segs, time); - } + let boxed = carried.then(|| crate::transform_tool::selection_ants(app, input.painter, &input.xf, input.doc.id, segs, time)).flatten(); + ants = boxed.unwrap_or_else(|| marching_ants_segment_shapes(input.painter, &shown, segs, time)); input.ctx.request_repaint_after(std::time::Duration::from_millis(100)); } } + ants } -fn paint_canvas(app: &mut PhotocraftApp, ui: &egui::Ui, view: &View, xf: ViewXform, input: &CanvasPaintInput<'_>) -> (bool, egui::layers::ShapeIdx, Rect) { +/// Paints the document, and returns whether the pixels past the canvas show, the Layer Edges slot, +/// the canvas edge on screen, and the selection's ants still to be painted ([`paint_selection_outline`]). +fn paint_canvas( + app: &mut PhotocraftApp, + ui: &egui::Ui, + view: &View, + xf: ViewXform, + input: &CanvasPaintInput<'_>, +) -> (bool, egui::layers::ShapeIdx, Rect, Vec) { let ctx = input.ctx; let rect = input.rect; let painter = input.painter; @@ -546,9 +559,9 @@ fn paint_canvas(app: &mut PhotocraftApp, ui: &egui::Ui, view: &View, xf: ViewXfo // in (`layer_edges_rect`), so a press that Auto-Selects a layer outlines that layer. let layer_edges = painter.add(egui::Shape::Noop); - paint_selection_outline(app, SelectionPaintInput { ctx, painter, ui, view, xf, rect, doc, idx }); + let ants = paint_selection_outline(app, SelectionPaintInput { ctx, painter, ui, view, xf, rect, doc, idx }); - (beyond, layer_edges, edge_rect) + (beyond, layer_edges, edge_rect, ants) } struct CanvasNavigationInput<'a> { @@ -1246,7 +1259,7 @@ struct CanvasOverlayInput<'a> { zoom_out: &'a dyn Fn(bool) -> bool, } -fn paint_primary_overlays(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, input: &CanvasOverlayInput<'_>) { +fn paint_primary_overlays(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, input: &CanvasOverlayInput<'_>, ants: Vec) { let ctx = input.ctx; let painter = input.painter; let xf = input.xf; @@ -1267,6 +1280,8 @@ fn paint_primary_overlays(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut if app.ui.view.shows(app.ui.view.show.canvas_guides) || crate::guide_layout_ui::preview(app, doc).is_some() { crate::rulers::draw_guides(app, painter, xf, doc); } + // The selection's ants go over the grid and guides, as in Photoshop (#10671). + painter.extend(ants); // The pending crop frame shows on its own document only, not on the other tiles (#1918). let foreign_crop = if app.session.active_index() == Some(idx) { None } else { app.ui.crop_rect.take() }; draw_drag_preview(app, painter, xf); @@ -2015,7 +2030,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: } else { xf }; - let (beyond, layer_edges, edge_rect) = painted.unwrap_or_else(|| paint_canvas(app, ui, &display_view, xf, &paint_input)); + let (beyond, layer_edges, edge_rect, ants) = painted.unwrap_or_else(|| paint_canvas(app, ui, &display_view, xf, &paint_input)); // A Hand drag (the tool, Space or the middle button) keeps every overlay on screen, as in // Photoshop: the Pen path being drawn, paths, guides, grid, transform box (#6592). Only the // tool cursors below give way to the fist. @@ -2036,7 +2051,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: panning, zoom_out: &zoom_out, }; - paint_primary_overlays(app, ui, &mut view, &input); + paint_primary_overlays(app, ui, &mut view, &input, ants); + } else { + painter.extend(ants); } let tail = CanvasTailInput { ctx: &ctx, @@ -2104,6 +2121,9 @@ mod transform_controls_tests; #[cfg(test)] mod layer_edges_tests; +#[cfg(test)] +mod guide_ants_tests; + #[cfg(test)] mod rotation_preview_isolation_tests { use super::*; diff --git a/crates/ui-egui/src/canvas/ants.rs b/crates/ui-egui/src/canvas/ants.rs index 2af2e7bd08b..b74b53b1e1f 100644 --- a/crates/ui-egui/src/canvas/ants.rs +++ b/crates/ui-egui/src/canvas/ants.rs @@ -148,14 +148,20 @@ pub(crate) fn shapes(lines: impl Iterator, clip: Rect, styl (mesh, slanted) } +/// The ants along `lines` (screen points) at frame time `time`, as `painter` would draw them but +/// not yet drawn: the canvas traces them early and paints them over the guides (#10671). +pub(crate) fn shapes_for(painter: &egui::Painter, lines: impl Iterator, time: f64, snap_slanted: bool) -> Vec { + let style = Style::new(painter.pixels_per_point(), time); + let (mesh, mut slanted) = shapes(lines, painter.clip_rect(), style, snap_slanted); + if !mesh.is_empty() { + slanted.push(Shape::mesh(mesh)); + } + slanted +} + /// Draw the ants along `lines` (screen points) at frame time `time`; see [`shapes`]. pub(crate) fn draw(painter: &egui::Painter, lines: impl Iterator, time: f64, snap_slanted: bool) { - let style = Style::new(painter.pixels_per_point(), time); - let (mesh, slanted) = shapes(lines, painter.clip_rect(), style, snap_slanted); - painter.extend(slanted); - if !mesh.is_empty() { - painter.add(Shape::mesh(mesh)); - } + painter.extend(shapes_for(painter, lines, time, snap_slanted)); } /// The segments of the polyline `points`, back to the first when `closed`. diff --git a/crates/ui-egui/src/canvas/guide_ants_tests.rs b/crates/ui-egui/src/canvas/guide_ants_tests.rs new file mode 100644 index 00000000000..c51049c10df --- /dev/null +++ b/crates/ui-egui/src/canvas/guide_ants_tests.rs @@ -0,0 +1,69 @@ +//! #10671: the selection's marching ants are painted over the guides, so a guide on a selection +//! edge doesn't hide it (it did at some zoom levels, where both land on the same device pixel). + +use super::*; +use serde_json::json; + +const GUIDE: Color32 = Color32::from_rgb(0x4a, 0xff, 0xff); + +/// A document with guides on all four edges of a rectangular selection, as in the report. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 600, "height": 400})).unwrap(); + for (orientation, position) in [("vertical", 100), ("vertical", 300), ("horizontal", 100), ("horizontal", 260)] { + app.run("view.newGuide", json!({"orientation": orientation, "position": position})).unwrap(); + } + app.run("select.rect", json!({"x": 100, "y": 100, "width": 200, "height": 160})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::RectMarquee; + app.ui.extras.rulers = false; + app.ui.extras.guides = true; + app +} + +/// The painted shapes' order in one frame: the indices of the guide lines and of the ants' meshes. +fn painted(app: &mut PhotocraftApp, ppp: f32, zoom: f32, primary: bool) -> (Vec, Vec) { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + ctx.set_pixels_per_point(ppp); + let rect = Rect::from_min_size(Pos2::ZERO, vec2(700.0, 500.0)); + let view = View { zoom, center: [300.0, 200.0], doc_size: [600, 400], fit_pending: false, ..Default::default() }; + let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(rect), ..Default::default() }, |ui| { + canvas_view(app, ui, 0, rect, view.clone(), primary); + }); + output.textures_delta.clear(); + let (mut guides, mut ants) = (Vec::new(), Vec::new()); + for (i, s) in output.shapes.iter().enumerate() { + match &s.shape { + egui::Shape::LineSegment { stroke, .. } if stroke.color == GUIDE => guides.push(i), + egui::Shape::Mesh(m) if m.vertices.iter().any(|v| v.color == Color32::BLACK) && m.vertices.iter().any(|v| v.color == Color32::WHITE) => { + ants.push(i) + } + _ => {} + } + } + (guides, ants) +} + +#[test] +fn the_ants_are_painted_over_the_guides_at_every_zoom() { + let mut app = app(); + for ppp in [1.0, 1.25, 2.0] { + for zoom in [0.18, 0.25, 0.3333, 0.5, 0.6667, 1.0, 1.5, 2.0, 3.0] { + let (guides, ants) = painted(&mut app, ppp, zoom, true); + assert_eq!(guides.len(), 4, "@{ppp}x, {zoom}: the four guides are drawn"); + assert!(!ants.is_empty(), "@{ppp}x, {zoom}: the selection has its ants"); + let (last_guide, first_ants) = (guides.iter().max().unwrap(), ants.iter().min().unwrap()); + assert!(first_ants > last_guide, "@{ppp}x, {zoom}: ants at {ants:?} are under the guides at {guides:?}"); + } + } +} + +/// A secondary view (another tile of the document) draws no guides, but still its ants. +#[test] +fn a_secondary_view_still_draws_the_ants() { + let mut app = app(); + let (guides, ants) = painted(&mut app, 1.0, 0.5, false); + assert!(guides.is_empty()); + assert!(!ants.is_empty()); +} diff --git a/crates/ui-egui/src/canvas/paint.rs b/crates/ui-egui/src/canvas/paint.rs index 415bb071a75..0be47adf8de 100644 --- a/crates/ui-egui/src/canvas/paint.rs +++ b/crates/ui-egui/src/canvas/paint.rs @@ -140,7 +140,13 @@ fn paint_mapped_quad(painter: &egui::Painter, xf: &ViewXform, origin: [f32; 2], /// Draw boundary segments as marching ants: white base, black dashes phased along x + y. pub(super) fn marching_ants_segments(painter: &egui::Painter, xf: &ViewXform, segs: &[crate::outline::Segment], time: f64) { - marching_ants_mapped(painter, segs, time, |p| xf.to_screen(p[0] as f32, p[1] as f32)); + painter.extend(marching_ants_segment_shapes(painter, xf, segs, time)); +} + +/// [`marching_ants_segments`] as shapes, not yet drawn (`ants::shapes_for`). +pub(super) fn marching_ants_segment_shapes(painter: &egui::Painter, xf: &ViewXform, segs: &[crate::outline::Segment], time: f64) -> Vec { + let lines = segs.iter().map(|(a, b)| (xf.to_screen(a[0] as f32, a[1] as f32), xf.to_screen(b[0] as f32, b[1] as f32))); + marching_ants_line_shapes(painter, lines, time) } /// [`marching_ants_segments`] with each outline point placed on screen by `to_screen` (a @@ -177,6 +183,11 @@ pub(crate) fn marching_ants_lines(painter: &egui::Painter, lines: impl Iterator< crate::ants::draw(painter, lines, time, true); } +/// [`marching_ants_lines`] as shapes, not yet drawn (`ants::shapes_for`). +pub(crate) fn marching_ants_line_shapes(painter: &egui::Painter, lines: impl Iterator, time: f64) -> Vec { + crate::ants::shapes_for(painter, lines, time, true) +} + /// Photoshop crop overlay: the `shield` outside (`crop_shield::fill`; none when disabled), bright /// frame, the composition `guides` (unit-square polylines, `crop_overlay::guides`), corner and /// edge handles. diff --git a/crates/ui-egui/src/tools/transform_tool.rs b/crates/ui-egui/src/tools/transform_tool.rs index 0db62d77503..bf11ca303e1 100644 --- a/crates/ui-egui/src/tools/transform_tool.rs +++ b/crates/ui-egui/src/tools/transform_tool.rs @@ -48,7 +48,7 @@ pub(crate) use draw::draw_handle_cursor; use draw::scale_values; #[cfg(test)] pub(crate) use draw::{Readout, live_readout, styled_frame}; -pub(crate) use draw::{carries_selection_of, draw_selection}; +pub(crate) use draw::{carries_selection_of, selection_ants}; pub use draw::{draw_content, draw_overlay}; #[cfg(test)] use draw::{front_vertices, handle_anchor}; diff --git a/crates/ui-egui/src/tools/transform_tool/draw.rs b/crates/ui-egui/src/tools/transform_tool/draw.rs index fde7b73cfc7..26807afed62 100644 --- a/crates/ui-egui/src/tools/transform_tool/draw.rs +++ b/crates/ui-egui/src/tools/transform_tool/draw.rs @@ -235,24 +235,25 @@ fn carries_selection(app: &PhotocraftApp, t: &TransformSession) -> bool { } /// A transform of `document` is open that carries its selection along (#5297): the canvas traces -/// the whole outline, not only the part in view where it started, for [`draw_selection`]. +/// the whole outline, not only the part in view where it started, for [`selection_ants`]. pub(crate) fn carries_selection_of(app: &PhotocraftApp, document: DocId) -> bool { matches!((&app.ui.transform, &app.transform_preview), (Some(t), Some(pv)) if pv.doc.id == document && carries_selection(app, t)) } /// The marching ants where the open box puts them (#5297): the selection follows a move, scale, /// rotation, skew, distort, perspective or warp while it is made, to where applying it leaves it. -/// `segs` is the outline of `document`'s selection at rest. False when no open transform carries -/// that selection: the caller draws it where it is. -pub(crate) fn draw_selection( +/// `segs` is the outline of `document`'s selection at rest. The ants are returned as shapes for +/// `painter`, not drawn (the canvas paints them over the guides, #10671). `None` when no open +/// transform carries that selection: the caller draws it where it is. +pub(crate) fn selection_ants( app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, document: DocId, segs: &[crate::outline::Segment], time: f64, -) -> bool { - let Some(t) = app.ui.transform.as_ref().filter(|_| carries_selection_of(app, document)) else { return false }; +) -> Option> { + let t = app.ui.transform.as_ref().filter(|_| carries_selection_of(app, document))?; let scr = |(x, y): (f64, f64)| xf.to_screen(x as f32, y as f32); let doc = |p: [i32; 2]| [f64::from(p[0]), f64::from(p[1])]; let along = |a: [f64; 2], b: [f64; 2], k: f64| [a[0] + (b[0] - a[0]) * k, a[1] + (b[1] - a[1]) * k]; @@ -268,7 +269,7 @@ pub(crate) fn draw_selection( }; (0..n).map(move |i| (at(i), at(i + 1))) }); - crate::canvas::marching_ants_lines(painter, lines, time); + Some(crate::canvas::marching_ants_line_shapes(painter, lines, time)) } else if let Some(h) = Homography::rect_to_quad(t.rect, t.quad) { // Past a Distort's horizon the outline has no place, like the pixels (#4863): a run that // crosses it stops short of it, where its points are still a finite way off. @@ -288,9 +289,10 @@ pub(crate) fn draw_selection( } Some((scr(h.apply(a[0], a[1])), scr(h.apply(b[0], b[1])))) }); - crate::canvas::marching_ants_lines(painter, lines, time); + Some(crate::canvas::marching_ants_line_shapes(painter, lines, time)) + } else { + Some(Vec::new()) } - true } /// What the styled preview of the moving layer is drawn from (transform_fx.rs), at `zoom` screen diff --git a/crates/ui-egui/src/tools/transform_tool/tests.rs b/crates/ui-egui/src/tools/transform_tool/tests.rs index a9716790d93..cdc178e6977 100644 --- a/crates/ui-egui/src/tools/transform_tool/tests.rs +++ b/crates/ui-egui/src/tools/transform_tool/tests.rs @@ -1385,7 +1385,7 @@ fn selecting_another_layer_applies_the_transform_and_the_next_one_follows() { assert_eq!((t.layer, t.rect), (second.0, [40.0, 40.0, 56.0, 60.0]), "the next box is on the selected layer"); } -/// The screen rectangle the marching ants cover as [`draw_selection`] paints them over the +/// The screen rectangle the marching ants cover as [`selection_ants`] places them over the /// active document's selection; `None` when it leaves them to the canvas. fn ants_bounds(app: &PhotocraftApp, xf: &ViewXform) -> Option { let st = app.session.active().unwrap(); @@ -1395,7 +1395,9 @@ fn ants_bounds(app: &PhotocraftApp, xf: &ViewXform) -> Option { let mut drawn = false; let mut output = ctx.run_ui(Default::default(), |ui| { let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("ants-test"))); - drawn = draw_selection(app, &painter, xf, st.doc.id, &segs, 0.0); + let ants = selection_ants(app, &painter, xf, st.doc.id, &segs, 0.0); + drawn = ants.is_some(); + painter.extend(ants.unwrap_or_default()); }); output.textures_delta.clear(); // The ants are a mesh of straight dashes and line shapes for the slanted ones. From 0f85d429d71d16097fdb64f3277ba8a635b1b6f6 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:49:27 +0100 Subject: [PATCH 53/77] Save for Web: keep its size and zoom while the pointer moves (#10675) The dialog grows to fit its contents, and the preview panes were sized in fractional points, so they came out a fraction of a pixel wider than the room given. Every repaint (any pointer move) widened the dialog a little and the fitted zoom followed. The preview area and pane sizes are now floored to whole physical pixels. The new test moves the pointer over the preview at 5 scales x 3 screens x 3 views: 15 of the 45 cases drifted before the fix, none after. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/file_ui/tests.rs | 46 +++++++++++++++++++++ crates/ui-egui/src/dialogs/file_ui/web.rs | 13 ++++-- 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/file_ui/tests.rs b/crates/ui-egui/src/dialogs/file_ui/tests.rs index e01de7b105a..6de4ed340d2 100644 --- a/crates/ui-egui/src/dialogs/file_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/file_ui/tests.rs @@ -543,6 +543,52 @@ fn web_preview_grows_with_resize_and_accepts_zoom_and_pan() { assert_eq!(h.state().ui.dialogs.len(), 1); } +/// #10675: moving the pointer over Save for Web repaints it, and each repaint must lay it out the +/// same way. At a fractional display scale the previews came out a fraction of a pixel wider than +/// the room they were given, so the dialog grew a little on every repaint and the fitted zoom +/// with it. +#[test] +fn web_preview_keeps_its_size_and_zoom_while_the_pointer_moves() { + let mut drifted = Vec::new(); + for ppp in [1.0, 1.25, 1.5, 1.75, 2.25] { + for screen in [egui::vec2(1600.0, 1100.0), egui::vec2(1097.0, 617.0), egui::vec2(1280.0, 720.0)] { + for view in ["2up", "4up", "original"] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 1980, "height": 1200})).unwrap(); + let id = open_web(&mut app); + app.ui.dialog_mut(id).unwrap().fields.insert("__view".into(), json!(view)); + let mut h = egui_kittest::Harness::builder().with_size(screen).with_pixels_per_point(ppp).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("semibold".into()))) { + crate::dialogs::show(app, ui.ctx()); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(8); + let layout = |h: &egui_kittest::Harness<'_, PhotocraftApp>| { + let f = &h.state().ui.dialogs[0].fields; + let rects: Vec = h.ctx.data(|m| m.get_temp(egui::Id::unique("pc-dialog-rects"))).unwrap(); + (rects[0], f["__previewRects"].clone(), f["__effectiveZoom"].clone()) + }; + let before = layout(&h); + let pane = &before.1[0]; + let at = egui::pos2(pane[0].as_f64().unwrap() as f32 + 20.0, pane[1].as_f64().unwrap() as f32 + 20.0); + for i in 0..30 { + h.event(egui::Event::PointerMoved(at + egui::vec2(i as f32 * 3.0, i as f32))); + h.step(); + } + let after = layout(&h); + if after != before { + drifted.push(format!("{view} at {ppp}x on {screen:?}: {before:?} -> {after:?}")); + } + } + } + } + assert!(drifted.is_empty(), "the dialog or its zoom changed while the pointer moved: {drifted:#?}"); +} + #[test] fn palette_draft_survives_navigation_and_resets_when_colors_change() { let (app, _) = app(); diff --git a/crates/ui-egui/src/dialogs/file_ui/web.rs b/crates/ui-egui/src/dialogs/file_ui/web.rs index 62082b4f8d2..0b5ef3cf588 100644 --- a/crates/ui-egui/src/dialogs/file_ui/web.rs +++ b/crates/ui-egui/src/dialogs/file_ui/web.rs @@ -265,7 +265,12 @@ pub(super) fn web_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map web_pane(app, ui, area, Some(&p), f, 1, frame), "2up" => { ui.horizontal(|ui| { - web_pane(app, ui, egui::vec2(area.x / 2.0 - 4.0, area.y), None, f, 0, frame); - web_pane(app, ui, egui::vec2(area.x / 2.0 - 4.0, area.y), Some(&p), f, 1, frame); + web_pane(app, ui, egui::vec2(half_w, area.y), None, f, 0, frame); + web_pane(app, ui, egui::vec2(half_w, area.y), Some(&p), f, 1, frame); }); } _ => { let v = variants(&p); - let cell = egui::vec2(area.x / 2.0 - 4.0, area.y / 2.0 - 4.0); + let cell = egui::vec2(half_w, half_h); ui.horizontal(|ui| { web_pane(app, ui, cell, None, f, 0, frame); web_pane(app, ui, cell, Some(&v[0]), f, 1, frame); From af404cfb9f86d83097f08ca8edb9a980e4f518fb Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 1 Nov 2026 13:14:09 +0000 Subject: [PATCH 54/77] Trim the preset file name like the engine, and list the clash prompt's plural forms for translation (#10640) --- .../src/dialogs/preset_group_prompt.rs | 20 +++++++++++++++---- crates/ui-egui/src/preset_files_ui.rs | 13 +++++++++++- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/preset_group_prompt.rs b/crates/ui-egui/src/dialogs/preset_group_prompt.rs index 55f07d6d4d5..d33c789b8e3 100644 --- a/crates/ui-egui/src/dialogs/preset_group_prompt.rs +++ b/crates/ui-egui/src/dialogs/preset_group_prompt.rs @@ -49,12 +49,24 @@ pub(crate) fn intercept(app: &mut PhotocraftApp, held: Held) -> Result Option return Some(crate::kys_import::open_bytes(app, name, bytes).map(|_| ())), _ => return None, }; - let stem = std::path::Path::new(name).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| tl!("Imported").into()); + // Trimmed like the engine trims `group`, so the clash check sees the name the import uses. + let stem = std::path::Path::new(name) + .file_stem() + .map(|s| s.to_string_lossy().trim().to_string()) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| tl!("Imported").into()); let mut p = source(name, bytes); p["group"] = json!(stem); if what == "brushes" { @@ -203,6 +208,12 @@ mod tests { assert_eq!((in_group(&app, "Kit"), in_group(&app, "Kit (2)")), (2, 0)); assert!(app.held_preset_import.is_none()); + // A file name with a trailing space (`Kit .abr`) names the same group. + open(&mut app, "Kit .abr", &abr).unwrap().unwrap(); + let id = prompt(&app).expect("the prompt is open for the trimmed name"); + crate::dialogs::cancel(&mut app, id).unwrap(); + assert_eq!(in_group(&app, "Kit (2)"), 0); + // The default answer imports beside it. open(&mut app, "Kit.abr", &abr).unwrap().unwrap(); let id = prompt(&app).expect("the prompt is open"); From 4b053e15ae229cff1dce09d048f753ed2a2b7c67 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 14:25:51 +0100 Subject: [PATCH 55/77] 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 56/77] 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 57/77] 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 58/77] 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 59/77] 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 60/77] 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 61/77] 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 62/77] 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 63/77] 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 64/77] 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 65/77] 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 66/77] 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 67/77] 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 209bce8d4671708364842ff0ff5cda76d3153fc3 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Sun, 1 Nov 2026 20:30:21 +0530 Subject: [PATCH 68/77] Budget PSD pattern expansion and bound multichannel conversion (#10541) * Stream PSD user and real masks into tile rows * Correct streamed-mask fixture metadata and test lint issues * Budget PSD pattern expansion and bound multichannel conversion --------- Co-authored-by: FredApps --- crates/io/src/lib.rs | 2 +- crates/io/src/multichannel_map.rs | 89 ++++++++++++++------ crates/io/src/pattern_map.rs | 125 ++++++++++++++++++++++++----- crates/io/src/psd_budget.rs | 21 ++++- crates/io/src/psd_budget/tests.rs | 50 ++++++++++++ crates/io/src/psd_import.rs | 28 +++++-- crates/io/tests/it/multichannel.rs | 28 +++++++ crates/psd/src/patterns.rs | 55 ++++++++++++- docs/development.md | 12 ++- 9 files changed, 355 insertions(+), 55 deletions(-) diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 006d9ac020f..b3135df1ad4 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -349,7 +349,7 @@ pub struct ImportOptions { /// The demosaic method camera raws are developed with. pub demosaic: raw::Demosaic, /// PSD layer/mask/merged pixel allowance, including conversion workspace. May lower the - /// default cap; does not cover metadata, patterns or smart-filter caches. + /// default cap; does not cover metadata or smart-filter caches. pub psd_max_pixel_bytes: u64, } diff --git a/crates/io/src/multichannel_map.rs b/crates/io/src/multichannel_map.rs index 2b6f4b9b54d..64fb6e25627 100644 --- a/crates/io/src/multichannel_map.rs +++ b/crates/io/src/multichannel_map.rs @@ -26,50 +26,70 @@ const ALPHA_IDENTIFIERS: u16 = 1053; const LAYER_ONLY_RESOURCES: [u16; 4] = [ids::LAYER_STATE, ids::LAYER_GROUP_INFO, 1069, 1072]; /// Value of sample `i` of a big-endian plane. -fn decode(plane: &[u8], i: usize, s: SampleType) -> f32 { - match s { - SampleType::U8 => f32::from(plane[i]) / 255.0, - SampleType::U16 => f32::from(u16::from_be_bytes([plane[2 * i], plane[2 * i + 1]])) / 65535.0, - SampleType::F32 => f32::from_be_bytes([plane[4 * i], plane[4 * i + 1], plane[4 * i + 2], plane[4 * i + 3]]), - } +fn decode(plane: &[u8], i: usize, s: SampleType) -> Option { + let start = i.checked_mul(s.bytes())?; + let bytes = plane.get(start..start.checked_add(s.bytes())?)?; + Some(match s { + SampleType::U8 => f32::from(*bytes.first()?) / 255.0, + SampleType::U16 => f32::from(u16::from_be_bytes(bytes.try_into().ok()?)) / 65535.0, + SampleType::F32 => f32::from_be_bytes(bytes.try_into().ok()?), + }) } /// Fills `doc` (already in Multichannel mode at the file depth) from the merged planes `all`. -pub(crate) fn import(file: &PsdFile, all: &[u8], doc: &mut Document, names: &[String], warnings: &mut Vec) { +pub(crate) fn import(file: &PsdFile, all: &[u8], doc: &mut Document, names: &[String], warnings: &mut Vec) -> Result<(), crate::IoError> { let h = &file.header; let depth = doc.depth; let (w, hh) = (h.width as usize, h.height as usize); - let n = w * hh; - let plane = h.row_bytes() * hh; - let canvas = Rect::new(0, 0, h.width as i32, h.height as i32); + let invalid = || crate::IoError::Unsupported("multichannel pixel size overflow".into()); + let plane = h.row_bytes().checked_mul(hh).ok_or_else(invalid)?; + let pixels = w.checked_mul(hh).ok_or_else(invalid)?; + if pixels.checked_mul(depth.bytes()).ok_or_else(invalid)? != plane { + return Err(crate::IoError::Unsupported("multichannel channel depth does not match its pixel layout".into())); + } let fmt = PixelFormat::new(ColorMode::Grayscale, depth, false); for k in 0..usize::from(h.channels) { - let Some(p) = all.get(k * plane..(k + 1) * plane) else { + let start = k.checked_mul(plane).ok_or_else(invalid)?; + let end = start.checked_add(plane).ok_or_else(invalid)?; + if all.get(start..end).is_none() { warnings.push(format!("multichannel: channel {} is missing", k + 1)); break; - }; - let vals: Vec = (0..n).map(|i| 1.0 - decode(p, i, depth)).collect(); - let mut s = Surface::new(fmt); - s.write_region(canvas, &vals); - s.prune(); + } let name = names.get(k).cloned().filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Channel {}", k + 1)); - // Without DisplayInfo the channels print in black, as Photoshop shows them. DisplayInfo - // turns alpha-type channels (selected / masked areas) back into alpha channels. - doc.channels.push(AlphaChannel { spot: Some((Color::BLACK, 0.0)), ..AlphaChannel::new(name, s) }); + doc.channels.push(AlphaChannel { spot: Some((Color::BLACK, 0.0)), ..AlphaChannel::new(name, Surface::new(fmt)) }); } if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO) { crate::channel_map::apply_display_info(&r.data, true, 0, &mut doc.channels); } else if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO_OLD) { crate::channel_map::apply_display_info(&r.data, false, 0, &mut doc.channels); } - // Alpha-type planes are stored as-is, not as ink: undo the inversion for them. - for ch in doc.channels.iter_mut().filter(|c| c.spot.is_none()) { - let vals: Vec = ch.surface.read_region(canvas).chunks_exact(ch.surface.channels()).map(|v| 1.0 - v[0]).collect(); - let mut s = Surface::new(fmt); - s.write_region(canvas, &vals); - s.prune(); - ch.surface = s; + for (k, ch) in doc.channels.iter_mut().enumerate() { + let start = k.checked_mul(plane).ok_or_else(invalid)?; + let p = all.get(start..start.checked_add(plane).ok_or_else(invalid)?).ok_or_else(invalid)?; + // DisplayInfo is known before conversion: alpha channels need no inversion or + // second full-plane readback. One tile row is the only conversion buffer. + for y in (0..hh).step_by(photocraft_geom::TILE_SIZE as usize) { + let bottom = (y + photocraft_geom::TILE_SIZE as usize).min(hh); + let samples = w.checked_mul(bottom - y).ok_or_else(invalid)?; + let len = samples.checked_mul(depth.bytes()).ok_or_else(invalid)?; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(len).map_err(|_| crate::IoError::OutOfMemory("not enough memory for multichannel pixels".into()))?; + for i in y.checked_mul(w).ok_or_else(invalid)?..bottom.checked_mul(w).ok_or_else(invalid)? { + let v = decode(p, i, depth).ok_or_else(invalid)?; + let v = if ch.spot.is_some() { 1.0 - v } else { v }; + match depth { + SampleType::U8 => bytes.push((v.clamp(0.0, 1.0) * 255.0).round() as u8), + SampleType::U16 => bytes.extend_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_ne_bytes()), + SampleType::F32 => bytes.extend_from_slice(&v.to_ne_bytes()), + } + } + ch.surface + .try_write_interleaved(Rect::new(0, y as i32, h.width as i32, bottom as i32), &bytes) + .map_err(|e| crate::IoError::OutOfMemory(format!("multichannel pixel allocation: {e}")))?; + } + ch.surface.prune(); } + Ok(()) } /// Writes a Multichannel document as a mode-7 PSD (no layer section; every channel a plane). @@ -204,3 +224,20 @@ pub(crate) fn layerless_file( crate::psd_export::sign_global_blocks(&mut file); file } + +#[cfg(test)] +mod import_allocation_tests { + use super::*; + + #[test] + fn missing_planes_remain_recoverable_without_reading_past_input() { + let file = photocraft_psd::testgen::merged_only(photocraft_psd::Version::Psd, PsdMode::Multichannel, 8, Compression::Raw, 3, 2); + let mut doc = Document::new("Partial", photocraft_geom::Size::new(3, 2), ColorMode::Multichannel, SampleType::U8); + let mut warnings = Vec::new(); + import(&file, &[0; 6], &mut doc, &[], &mut warnings).unwrap(); + assert_eq!(doc.channels.len(), 1); + assert_eq!(doc.channels[0].surface.read_region(doc.bounds()), vec![1.0; 6]); + assert_eq!(warnings.len(), 1); + assert!(decode(&[], usize::MAX, SampleType::F32).is_none()); + } +} diff --git a/crates/io/src/pattern_map.rs b/crates/io/src/pattern_map.rs index 4f0b5fe54d6..97417b7cc71 100644 --- a/crates/io/src/pattern_map.rs +++ b/crates/io/src/pattern_map.rs @@ -12,7 +12,7 @@ use photocraft_geom::Rect; use photocraft_psd::patterns::{PatternBudget, PsdPattern, block_has_user_mask, block_key, mode_channels, parse_pattern_block_with, write_pattern_block}; use photocraft_raster::Surface; -use crate::pixels::{deinterleave, interleave, max_sample, psd_depth, sample_for_depth, zero_sample}; +use crate::pixels::{deinterleave, max_sample, psd_depth, sample_for_depth, try_interleave, zero_sample}; /// Global block keys holding patterns. pub const PATTERN_KEYS: [[u8; 4]; 3] = [*b"Patt", *b"Pat2", *b"Pat3"]; @@ -26,28 +26,67 @@ fn psd_mode(m: ColorMode) -> u32 { } } -/// A PSD pattern as a document pattern (indexed patterns become RGB through their palette). +/// A PSD pattern as a document pattern (indexed patterns become RGB through their palette). A +/// malformed pattern, or one that can't be allocated, is `None`; [`try_from_psd`] tells them apart. pub fn from_psd(p: &PsdPattern) -> Option { + try_from_psd(p).ok().flatten() +} + +/// [`from_psd`], with `Ok(None)` for a malformed pattern and `Err` for a failed allocation. +pub fn try_from_psd(p: &PsdPattern) -> Result, String> { + let mut oom = None; + let pattern = pattern_from_psd(p, &mut oom); + match oom { + Some(error) => Err(error), + None => Ok(pattern), + } +} + +fn pattern_from_psd(p: &PsdPattern, oom: &mut Option) -> Option { let (w, h) = (p.width as usize, p.height as usize); - if w == 0 || h == 0 { + if w == 0 || h == 0 || w > 30_000 || h > 30_000 || !matches!(p.depth, 1 | 8 | 16 | 32) { return None; } + let n = w.checked_mul(h)?; + let plane_len = w.checked_mul(usize::from(p.depth))?.div_ceil(8).checked_mul(h)?; + if p.channels.iter().chain(p.alpha.iter()).any(|plane| plane.len() != plane_len) { + return None; + } + fn copy_plane(plane: &[u8], oom: &mut Option) -> Option> { + let mut out = Vec::new(); + reserve(&mut out, plane.len(), oom)?; + out.extend_from_slice(plane); + Some(out) + } + fn reserve(out: &mut Vec, n: usize, oom: &mut Option) -> Option<()> { + out.try_reserve_exact(n).map_err(|e| *oom = Some(e.to_string())).ok() + } // 1-bit patterns: expand to 8-bit grey. let (channels, depth): (Vec>, u16) = if p.depth == 1 { let row = w.div_ceil(8); - let expand = |plane: &Vec| -> Vec { - (0..w * h).map(|i| if plane.get((i / w) * row + (i % w) / 8).is_some_and(|b| b & (0x80 >> (i % w % 8)) != 0) { 0 } else { 255 }).collect() + let expand = |plane: &Vec, oom: &mut Option| -> Option> { + let mut out = Vec::new(); + reserve(&mut out, n, oom)?; + out.extend((0..n).map(|i| if plane.get((i / w) * row + (i % w) / 8).is_some_and(|b| b & (0x80 >> (i % w % 8)) != 0) { 0 } else { 255 })); + Some(out) }; - (p.channels.iter().map(expand).collect(), 8) + (p.channels.iter().map(|plane| expand(plane, oom)).collect::>()?, 8) } else { - (p.channels.clone(), p.depth) + (p.channels.iter().map(|plane| copy_plane(plane, oom)).collect::>()?, p.depth) }; let (mode, channels) = match p.mode { 1 | 8 => (ColorMode::Grayscale, channels), 2 => { let pal = p.palette.as_deref()?; let idx = channels.first()?; - let ch: Vec> = (0..3).map(|c| idx.iter().map(|i| pal.get(usize::from(*i) * 3 + c).copied().unwrap_or(0)).collect()).collect(); + let ch: Vec> = (0..3) + .map(|c| { + let mut out = Vec::new(); + reserve(&mut out, idx.len(), oom)?; + out.extend(idx.iter().map(|i| pal.get(usize::from(*i) * 3 + c).copied().unwrap_or(0))); + Some(out) + }) + .collect::>()?; (ColorMode::Rgb, ch) } 4 => (ColorMode::Cmyk, channels), @@ -69,11 +108,22 @@ pub fn from_psd(p: &PsdPattern) -> Option { fill.push(max_sample(s)); invert.push(false); } - let mut bytes = interleave(&refs, &fill, w * h, s, &invert); + let mut bytes = match try_interleave(&refs, &fill, n, s, &invert) { + Ok(bytes) => bytes, + Err(photocraft_psd::PsdError::OutOfMemory(error)) => { + *oom = Some(error.to_string()); + return None; + } + Err(_) => return None, + }; if mode == ColorMode::Lab && s == SampleType::U16 { crate::pixels::lab16_chroma(&mut bytes, refs.len(), true); } - let surface = Surface::from_interleaved(fmt, Rect::new(0, 0, w as i32, h as i32), &bytes); + let mut surface = Surface::new(fmt); + if let Err(error) = surface.try_write_interleaved(Rect::new(0, 0, w as i32, h as i32), &bytes) { + *oom = Some(error.to_string()); + return None; + } Some(Pattern { id: p.id.clone(), name: p.name.clone(), width: p.width, height: p.height, surface }) } @@ -119,15 +169,25 @@ pub fn unpaintable_warnings(patterns: &[Pattern]) -> Vec { /// Patterns decoded from the document's raw pattern blocks (malformed blocks are skipped). All /// blocks share one memory budget, so repeating a block can't multiply it. pub fn from_global_blocks(doc: &Document) -> Vec { + try_from_global_blocks(doc).unwrap_or_default() +} + +/// [`from_global_blocks`], failing with the allocation error instead of dropping the pattern it +/// hit, so an import reports that the file could not be opened in full. +pub fn try_from_global_blocks(doc: &Document) -> Result, String> { let mut budget = PatternBudget::default(); - doc.metadata - .psd_global_blocks - .iter() - .filter(|(_, k, _)| PATTERN_KEYS.contains(k)) - .filter_map(|(_, _, d)| parse_pattern_block_with(d, &mut budget).ok()) - .flatten() - .filter_map(|p| from_psd(&p)) - .collect() + let mut out = Vec::new(); + for (_, _, d) in doc.metadata.psd_global_blocks.iter().filter(|(_, k, _)| PATTERN_KEYS.contains(k)) { + let patterns = match parse_pattern_block_with(d, &mut budget) { + Ok(patterns) => patterns, + Err(photocraft_psd::PsdError::OutOfMemory(error)) => return Err(error.to_string()), + Err(_) => continue, + }; + for p in patterns { + out.extend(try_from_psd(&p)?); + } + } + Ok(out) } /// Global blocks to write: the raw ones while they still match [`Document::patterns`] (see @@ -307,3 +367,32 @@ mod unpaintable_tests { assert!(warnings[0].contains("Huge float") && warnings[0].contains("would paint nothing") && warnings[0].contains("32 bits"), "{warnings:?}"); } } + +#[cfg(test)] +mod allocation_tests { + use super::*; + + #[test] + fn malformed_dimensions_and_planes_fail_before_conversion() { + let mut p = PsdPattern { + mode: 1, + width: 9, + height: 2, + name: "Bits".into(), + id: "bits".into(), + palette: None, + depth: 1, + channels: vec![vec![0x80, 0, 0, 0x80]], + alpha: None, + }; + let converted = from_psd(&p).unwrap(); + assert_eq!(converted.surface.to_interleaved(converted.rect()), [0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0]); + p.channels[0].pop(); + assert!(from_psd(&p).is_none()); + p.width = u32::MAX; + assert!(from_psd(&p).is_none()); + p.width = 9; + p.depth = 7; + assert!(from_psd(&p).is_none()); + } +} diff --git a/crates/io/src/psd_budget.rs b/crates/io/src/psd_budget.rs index 9988ff5fa0b..b3c00ed4ef3 100644 --- a/crates/io/src/psd_budget.rs +++ b/crates/io/src/psd_budget.rs @@ -1,5 +1,5 @@ //! Conservative preflight for the main PSD pixel paths. This bounds decoded layer/mask/ -//! merged pixels, not parser metadata, patterns or smart-filter caches (separate limits). +//! merged and pattern pixels, not parser metadata or smart-filter caches (separate limits). //! //! Reserve the sum of all possible retained tiles and the largest workspace, without credit //! for pruning or tile sharing. Reserving before any worker starts makes scheduling irrelevant. @@ -126,6 +126,25 @@ pub(crate) fn check(file: &PsdFile, limit: u64) -> Result<(), IoError> { let converted = mul(pixels, mul(channels.max(cc + 1), sample * 3 + 12)?)?; budget.scratch(converted.checked_add(inflate_scratch(merged, 1)?).ok_or_else(overflow)?); } + let mut patterns = photocraft_psd::patterns::PatternBudget::default(); + for block in file.global_blocks.iter().filter(|b| crate::pattern_map::PATTERN_KEYS.contains(&b.key)) { + // Earlier records can decode before a malformed later record discards the block. + let items = photocraft_psd::patterns::pattern_block_memory(&block.data, &mut patterns); + for p in items { + let pixels = mul(u64::from(p.width), u64::from(p.height))?; + let sample = u64::from(p.depth.div_ceil(8)); + let color = if p.mode == 2 { 3 } else { photocraft_psd::patterns::mode_channels(p.mode) as u64 }; + let alpha = u64::from(p.planes > photocraft_psd::patterns::mode_channels(p.mode)); + budget.surface(Rect::from_xywh(0, 0, p.width, p.height), color + alpha, sample)?; + // The block parser returns all planes together. Count them as retained so + // previous converted patterns and later blocks cannot reuse this allowance. + budget.retain(p.decoded_bytes)?; + // Channel clones/bitmap expansion, indexed RGB expansion and interleave. + // Include a source plane during padded channel placement as well. + let converted = mul(pixels, mul((p.planes as u64).max(color + alpha) + color + alpha + 3, sample)?)?; + budget.scratch(converted.checked_add(p.decoded_bytes).ok_or_else(overflow)?); + } + } budget.check(limit) } diff --git a/crates/io/src/psd_budget/tests.rs b/crates/io/src/psd_budget/tests.rs index 0f72d5c56b3..3c1a195486b 100644 --- a/crates/io/src/psd_budget/tests.rs +++ b/crates/io/src/psd_budget/tests.rs @@ -124,6 +124,56 @@ fn legacy_conversion_reports_a_rejected_import_instead_of_decoding_it() { assert!(warnings.iter().any(|warning| warning.contains("pixel memory"))); } +fn pattern_block(mode: u32, depth: u16, width: u32, height: u32) -> photocraft_psd::TaggedBlock { + use photocraft_psd::patterns::{PsdPattern, mode_channels, write_pattern_block}; + let len = (width as usize * depth as usize).div_ceil(8) * height as usize; + let p = PsdPattern { + mode, + depth, + width, + height, + name: "Budget pattern".into(), + id: "budget".into(), + palette: (mode == 2).then(|| vec![0; 768]), + channels: vec![vec![0; len]; mode_channels(mode)], + alpha: None, + }; + photocraft_psd::TaggedBlock::new(*b"Patt", write_pattern_block(&[p]).unwrap()) +} + +#[test] +fn pattern_tiles_and_expansion_share_the_import_allowance() { + for (mode, depth) in [(1, 1), (2, 8), (3, 8), (4, 16), (9, 32)] { + let mut file = testgen::small(Version::Psd, Compression::Raw); + let baseline = estimate(&file); + let block = pattern_block(mode, depth, 9, 3); + file.global_blocks.push(block.clone()); + let one = estimate(&file); + assert!(one > baseline); + assert!(check(&file, one).is_ok()); + assert!(matches!(check(&file, one - 1), Err(IoError::PsdImportBudget { .. }))); + let bytes = file.to_bytes().unwrap(); + let opts = crate::ImportOptions { psd_max_pixel_bytes: one - 1, ..Default::default() }; + assert!(matches!(crate::import_with_options("pattern.psd", &bytes, &opts), Err(IoError::PsdImportBudget { .. }))); + assert_eq!(crate::import("pattern.psd", &bytes).unwrap().document.patterns.len(), 1); + file.global_blocks.push(block); + assert!(estimate(&file) > one, "blocks cannot each reuse the allowance"); + } +} + +#[test] +fn malformed_later_pattern_still_counts_earlier_decodes() { + let mut file = testgen::small(Version::Psd, Compression::Raw); + let baseline = estimate(&file); + let mut block = pattern_block(1, 1, 9, 3); + // An invalid second pattern makes the real parser discard the block, after decoding + // its first record. The preflight must still account for that transient allocation. + block.data.extend_from_slice(&4u32.to_be_bytes()); + block.data.extend_from_slice(&99u32.to_be_bytes()); + file.global_blocks.push(block); + assert!(estimate(&file) > baseline); +} + /// An unknown colour mode imports as RGB (`import_format`), layers included, so it must pay /// for them: a layered file can't dodge the allowance by carrying mode 5. #[test] diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 717fd02f6f6..6989941d31a 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -1116,7 +1116,16 @@ pub(crate) fn can_recover_layers(file: &PsdFile) -> bool { import_format(file).1 && !file.layers().is_empty() } -fn read_initial_metadata(file: &PsdFile, global: &[PsdGlobalBlock], doc: &mut Document, layered: bool, multichannel: bool, warnings: &mut Vec) -> bool { +/// Reads the document-level metadata; the second value is the allocation failure that stopped a +/// pattern from being read, which fails the open. +fn read_initial_metadata( + file: &PsdFile, + global: &[PsdGlobalBlock], + doc: &mut Document, + layered: bool, + multichannel: bool, + warnings: &mut Vec, +) -> (bool, Option) { let header = &file.header; for resource in &file.resources { match resource.id { @@ -1174,7 +1183,11 @@ fn read_initial_metadata(file: &PsdFile, global: &[PsdGlobalBlock], doc: &mut Do block.key_str() )); } - doc.patterns = crate::pattern_map::from_global_blocks(doc); + let mut alloc_error = None; + match crate::pattern_map::try_from_global_blocks(doc) { + Ok(patterns) => doc.patterns = patterns, + Err(error) => alloc_error = Some(format!("patterns: {error}")), + } warnings.extend(crate::pattern_map::unpaintable_warnings(&doc.patterns)); doc.notes = crate::annotations_map::notes_from_blocks(doc); if crate::annotations_map::anno_unreadable(doc) { @@ -1184,7 +1197,7 @@ fn read_initial_metadata(file: &PsdFile, global: &[PsdGlobalBlock], doc: &mut Do doc.measurement.scale = scale; } let _ = layered; - damaged + (damaged, alloc_error) } /// [`psd_to_document_with`] with the merged image already decoded (by @@ -1231,7 +1244,7 @@ fn psd_to_document_global( warnings.push(format!("unknown color mode {}; importing as RGB", h.color_mode.as_u16())); } let mut doc = Document::new("Untitled", Size::new(h.width, h.height), mode, depth); - let damaged = read_initial_metadata(file, &global, &mut doc, layered, multichannel, &mut warnings); + let (damaged, pattern_error) = read_initial_metadata(file, &global, &mut doc, layered, multichannel, &mut warnings); let fmt = doc.pixel_format(); let cc = fmt.mode.color_channels(); @@ -1259,6 +1272,9 @@ fn psd_to_document_global( uniform: Default::default(), total: file.layers().len(), }; + if let Some(error) = pattern_error { + cx.allocation_failed(error); + } for (_, key, data) in cx.global.clone().iter().filter(|(_, key, _)| matches!(key, b"FEid" | b"FXid")) { // Smart-filter caches can be large: a cancelled open stops between blocks. if ctl.cancelled() { @@ -1348,7 +1364,9 @@ fn import_decoded_content(import: DecodedImport<'_>, doc: &mut Document, cx: &mu fn import_multichannel(file: &PsdFile, merged: &Option>>, doc: &mut Document, cx: &mut Ctx<'_>) { if let Some(Ok(all)) = merged { let names = file.resource(1045).map(|r| unicode_names(&r.data)).unwrap_or_default(); - crate::multichannel_map::import(file, all, doc, &names, &mut cx.warnings); + if let Err(error) = crate::multichannel_map::import(file, all, doc, &names, &mut cx.warnings) { + cx.fatal_error.get_or_insert(error); + } } if !file.layers().is_empty() { cx.warn(format!("Multichannel documents have no layers: {} layer records were not imported", file.layers().len())); diff --git a/crates/io/tests/it/multichannel.rs b/crates/io/tests/it/multichannel.rs index fd8f8448c31..4e7ffeeb2ec 100644 --- a/crates/io/tests/it/multichannel.rs +++ b/crates/io/tests/it/multichannel.rs @@ -223,3 +223,31 @@ fn corpus_multichannel_round_trip_keeps_channels_and_resources() { let keys = |f: &PsdFile| f.global_blocks.iter().map(|b| b.key).collect::>(); assert_eq!(keys(&back), keys(&f)); } + +#[test] +fn tile_row_conversion_preserves_spot_and_alpha_planes() { + for depth in [8, 16, 32] { + let mut f = testgen::merged_only(Version::Psb, ColorMode::Multichannel, depth, Compression::Rle, 5, 600); + let mut info = 1u32.to_be_bytes().to_vec(); + display_record(&mut info, [0, 0, 0], 0, 2); + display_record(&mut info, [65535, 0, 0], 50, 1); + f.resources.push(ImageResource::new(1077, info)); + let raw = f.decode_merged().unwrap(); + let (doc, _) = psd_to_document(&f); + let sample = usize::from(depth / 8); + let plane = 5 * 600 * sample; + for (k, channel) in doc.channels.iter().enumerate() { + let values = channel.surface.read_region(doc.bounds()); + for (i, value) in values.iter().enumerate() { + let bytes = &raw[k * plane + i * sample..k * plane + (i + 1) * sample]; + let original = match depth { + 8 => f32::from(bytes[0]) / 255.0, + 16 => f32::from(u16::from_be_bytes(bytes.try_into().unwrap())) / 65535.0, + _ => f32::from_be_bytes(bytes.try_into().unwrap()), + }; + let expected = if channel.spot.is_some() { 1.0 - original } else { original }; + assert!((value - expected).abs() < 0.00001, "depth {depth}, channel {k}, pixel {i}"); + } + } + } +} diff --git a/crates/psd/src/patterns.rs b/crates/psd/src/patterns.rs index 21e6de55b5f..fb604f0c02c 100644 --- a/crates/psd/src/patterns.rs +++ b/crates/psd/src/patterns.rs @@ -192,7 +192,28 @@ fn read_vma_body<'a>(r: &mut Rd<'a>) -> Result<&'a [u8]> { r.take(len) } +/// Pixel storage needed by a pattern, inspected without decoding channel data. +#[derive(Debug, Clone)] +pub struct PatternMemory { + /// Pattern width in pixels. + pub width: u32, + /// Pattern height in pixels. + pub height: u32, + /// Bits per sample, including packed bitmap samples. + pub depth: u16, + /// PSD colour mode number. + pub mode: u32, + /// All written planes, including any ignored extra arrays. + pub planes: usize, + /// Sum of full padded channel plane sizes. + pub decoded_bytes: u64, +} + fn read_pattern(r: &mut Rd, budget: &mut PatternBudget) -> Result { + read_pattern_with(r, budget, true, &mut |_| {}) +} + +fn read_pattern_with(r: &mut Rd, budget: &mut PatternBudget, decode: bool, visit: &mut dyn FnMut(PatternMemory)) -> Result { let PatternHeader { mode, name, id, palette } = read_header(r)?; let body = read_vma_body(r)?; let mut v = Rd { b: body, p: 0 }; @@ -289,8 +310,18 @@ fn read_pattern(r: &mut Rd, budget: &mut PatternBudget) -> Result { if channels.len() < nc { return Err(PsdError::invalid("pattern has fewer channels than its colour mode")); } + visit(PatternMemory { + width: w, + height: h, + depth: first_depth.unwrap_or(8), + mode, + planes: channels.len(), + decoded_bytes: channels + .iter() + .try_fold(0u64, |sum, c| sum.checked_add(c.destination.total_bytes()?).ok_or(PsdError::LimitExceeded("pattern memory size overflow")))?, + }); let mut planes = Vec::new(); - for channel in channels { + for channel in channels.into_iter().filter(|_| decode) { let plane = decode_planes(channel.compression, channel.data, &channel.source)?; planes.push(place_channel_plane(plane, &channel.source, channel.x, channel.y, &channel.destination)?); } @@ -472,6 +503,28 @@ pub fn parse_pattern_block_with(data: &[u8], budget: &mut PatternBudget) -> Resu Ok(out) } +/// Inspect a pattern block's dimensions and decoded sizes without allocating pixel planes. +/// Uses the pixel parser’s structural validation and shared decode limits. Returns +/// earlier records even if a later record is malformed, since those can decode first. +pub fn pattern_block_memory(data: &[u8], budget: &mut PatternBudget) -> Vec { + let mut r = Rd { b: data, p: 0 }; + let mut out = Vec::new(); + while r.p + 4 <= data.len() { + let Ok(len) = r.u32() else { break }; + let len = len as usize; + if len == 0 { + break; + } + let Ok(body) = r.take(len) else { break }; + // Earlier patterns may already have decoded when a later record is malformed. + if read_pattern_with(&mut Rd { b: body, p: 0 }, budget, false, &mut |m| out.push(m)).is_err() { + break; + } + r.p = (r.p + (4 - len % 4) % 4).min(data.len()); + } + out +} + /// Whether `Patt` / `Pat2` / `Pat3` block data keeps a pattern's transparency in the user mask /// array, as PhotoCraft wrote it before #8054. Photoshop refuses such a file, so a save must /// rewrite the block rather than keep it. Unreadable data counts as `false`. diff --git a/docs/development.md b/docs/development.md index 1eecf910426..3ecefb9f598 100644 --- a/docs/development.md +++ b/docs/development.md @@ -654,7 +654,7 @@ command: `cargo run --release -p photocraft-engine --example remove_bench`. ## PSD import pixel memory limits -PSD/PSB imports preflight layer, user-mask, merged-image and extra-channel pixel storage +PSD/PSB imports preflight layer, user-mask, merged-image, extra-channel and pattern pixel storage before merged-image validation or decoding. The conservative estimate sums retained tile storage (including padding and negative offsets) and the largest decode/conversion workspace. It does not credit uniform-tile sharing or pruning, so some files that could fit after decoding @@ -674,8 +674,14 @@ in place. Raw and RLE source-backed masks read only the current band (plus the R ZIP still inflates one whole plane before handing out bands. No full-mask interleave copy is needed. A damaged later band discards all previously written bands of that mask. -The #8593 allowance covers the main pixel paths, not total process -RSS: encoded input, parser metadata, patterns, smart-filter caches, embedded smart-object +Pattern block headers are inspected without decoding pixels. The same allowance includes +all decoded pattern planes, padded tiles, bitmap/indexed expansion and conversion copies, +including earlier records in a block that later proves malformed. Pattern conversion reserves +pixel buffers fallibly. Multichannel conversion uses one tile-row buffer and applies alpha/ink +polarity before writing tiles, without a full-plane float buffer or alpha readback. + +The #8593 allowance covers these pixel paths, not total process +RSS: encoded input, parser metadata, smart-filter caches, embedded smart-object contents, generated vector caches, and text preparation are outside it and retain their existing limits. Joining these paths to a shared budget and streaming ZIP inflation are follow-up work. An accepted estimate does not guarantee allocation success on a memory-constrained host. From 5f63b3fe4c4f524e91fd74bdc65378fa04481375 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 17:51:02 +0100 Subject: [PATCH 69/77] 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 cf8e3d352bca48f7d35d2444cbc831d9276435b1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 1 Nov 2026 12:29:54 -0500 Subject: [PATCH 70/77] docs: sync Craft App Suite list with ArtCraft Launcher --- README.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3c4e586f269..b1b453a3180 100644 --- a/README.md +++ b/README.md @@ -396,13 +396,22 @@ stand on its own. | | App | What it's for | Code | Learn more | |:-:|---|---|---|---| -| | **PhotoCraft** | **Image editing: layers, masks, type and real PSD files · you are here** | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) | +| | **PhotoCraft** | Image editing: layers, masks, type and real PSD files | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) | | | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) | | | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) | | | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) | | | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) | | | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) | | | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) | +| | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) | +| | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) | +| | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) | +| | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) | +| | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) | +| | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) | +| | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) | +| | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) | +| | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | | And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control. From 2df9f807702a935184041355a86405380bda8274 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Sun, 1 Nov 2026 13:58:51 -0500 Subject: [PATCH 71/77] Release 0.19.0 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 62 +++++++++++++++++++++++++++--------------------------- Cargo.toml | 2 +- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5c882f28e9f..36ce4a272af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4963,7 +4963,7 @@ dependencies = [ [[package]] name = "photocraft" -version = "0.18.0" +version = "0.19.0" dependencies = [ "arboard", "async-io", @@ -5018,7 +5018,7 @@ dependencies = [ [[package]] name = "photocraft-affinity" -version = "0.18.0" +version = "0.19.0" dependencies = [ "crc32fast", "flate2", @@ -5028,7 +5028,7 @@ dependencies = [ [[package]] name = "photocraft-algo" -version = "0.18.0" +version = "0.19.0" dependencies = [ "criterion", "photocraft-color", @@ -5043,7 +5043,7 @@ dependencies = [ [[package]] name = "photocraft-automation" -version = "0.18.0" +version = "0.19.0" dependencies = [ "base64 0.23.1", "cap-std", @@ -5068,7 +5068,7 @@ dependencies = [ [[package]] name = "photocraft-cli" -version = "0.18.0" +version = "0.19.0" dependencies = [ "clap", "clap_complete", @@ -5087,7 +5087,7 @@ dependencies = [ [[package]] name = "photocraft-cms" -version = "0.18.0" +version = "0.19.0" dependencies = [ "moxcms", "rayon", @@ -5095,7 +5095,7 @@ dependencies = [ [[package]] name = "photocraft-codecs" -version = "0.18.0" +version = "0.19.0" dependencies = [ "craft-jpeg", "exr", @@ -5119,7 +5119,7 @@ dependencies = [ [[package]] name = "photocraft-color" -version = "0.18.0" +version = "0.19.0" dependencies = [ "photocraft-cms", "serde", @@ -5127,7 +5127,7 @@ dependencies = [ [[package]] name = "photocraft-compose" -version = "0.18.0" +version = "0.19.0" dependencies = [ "criterion", "photocraft-cms", @@ -5143,7 +5143,7 @@ dependencies = [ [[package]] name = "photocraft-doc" -version = "0.18.0" +version = "0.19.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5154,7 +5154,7 @@ dependencies = [ [[package]] name = "photocraft-engine" -version = "0.18.0" +version = "0.19.0" dependencies = [ "base64 0.22.1", "blake3", @@ -5196,7 +5196,7 @@ dependencies = [ [[package]] name = "photocraft-format" -version = "0.18.0" +version = "0.19.0" dependencies = [ "blake3", "crc32fast", @@ -5219,14 +5219,14 @@ dependencies = [ [[package]] name = "photocraft-geom" -version = "0.18.0" +version = "0.19.0" dependencies = [ "serde", ] [[package]] name = "photocraft-gpu" -version = "0.18.0" +version = "0.19.0" dependencies = [ "bytemuck", "half", @@ -5246,14 +5246,14 @@ dependencies = [ [[package]] name = "photocraft-heif" -version = "0.18.0" +version = "0.19.0" dependencies = [ "heic-rs", ] [[package]] name = "photocraft-io" -version = "0.18.0" +version = "0.19.0" dependencies = [ "blake3", "craft-docpath", @@ -5289,18 +5289,18 @@ dependencies = [ [[package]] name = "photocraft-ipp" -version = "0.18.0" +version = "0.19.0" [[package]] name = "photocraft-ops" -version = "0.18.0" +version = "0.19.0" dependencies = [ "photocraft-doc", ] [[package]] name = "photocraft-paint" -version = "0.18.0" +version = "0.19.0" dependencies = [ "photocraft-cms", "photocraft-color", @@ -5314,7 +5314,7 @@ dependencies = [ [[package]] name = "photocraft-plugins" -version = "0.18.0" +version = "0.19.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5330,7 +5330,7 @@ dependencies = [ [[package]] name = "photocraft-psd" -version = "0.18.0" +version = "0.19.0" dependencies = [ "flate2", "photocraft-psd", @@ -5341,7 +5341,7 @@ dependencies = [ [[package]] name = "photocraft-raster" -version = "0.18.0" +version = "0.19.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5352,7 +5352,7 @@ dependencies = [ [[package]] name = "photocraft-raw" -version = "0.18.0" +version = "0.19.0" dependencies = [ "flate2", "image", @@ -5367,7 +5367,7 @@ dependencies = [ [[package]] name = "photocraft-tablet" -version = "0.18.0" +version = "0.19.0" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -5379,7 +5379,7 @@ dependencies = [ [[package]] name = "photocraft-testkit" -version = "0.18.0" +version = "0.19.0" dependencies = [ "memory-stats", "serde_json", @@ -5387,7 +5387,7 @@ dependencies = [ [[package]] name = "photocraft-text" -version = "0.18.0" +version = "0.19.0" dependencies = [ "flate2", "parley", @@ -5402,7 +5402,7 @@ dependencies = [ [[package]] name = "photocraft-ui-egui" -version = "0.18.0" +version = "0.19.0" dependencies = [ "base64 0.23.1", "craft-print", @@ -5447,7 +5447,7 @@ dependencies = [ [[package]] name = "photocraft-vector" -version = "0.18.0" +version = "0.19.0" dependencies = [ "photocraft-color", "photocraft-doc", @@ -5458,7 +5458,7 @@ dependencies = [ [[package]] name = "photocraft-web" -version = "0.18.0" +version = "0.19.0" dependencies = [ "eframe", "egui", @@ -5480,7 +5480,7 @@ dependencies = [ [[package]] name = "photocraft-web-boot" -version = "0.18.0" +version = "0.19.0" dependencies = [ "flate2", "js-sys", @@ -9196,7 +9196,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "xtask" -version = "0.18.0" +version = "0.19.0" dependencies = [ "chrono", "serde", diff --git a/Cargo.toml b/Cargo.toml index da26a96405a..558bc520db2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"] [workspace.package] -version = "0.18.0" +version = "0.19.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 02316e552d2b51742c8400451646da6788eadb3b Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 1 Nov 2026 21:20:38 +0100 Subject: [PATCH 72/77] 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 73/77] 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 From 86ddfb72f766be906109bb935c7b17ab74814ea5 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Mon, 2 Nov 2026 13:59:59 +0530 Subject: [PATCH 74/77] Reuse large buffers so returning freed memory to the OS doesn't slow filters (#10479) (#10514) * perf: reuse large buffers so a pinned glibc trim threshold costs no speed (#10479) With MALLOC_TRIM_THRESHOLD_ set (#8743), glibc maps every allocation over 128 KiB fresh, so tiles, compositor bands and filter scratch were page-faulted in on every call: viewport compose 3.6x slower, Gaussian Blur up to 1.8x, .pcraft save 2.4x. - photocraft_raster::scratch: a process-wide, capped pool of large Vec buffers (u8/u16/f32/[f32; 4]). A miss drops the oldest buffers worth its size down to a 256 MiB floor, so peak memory stays near glibc's defaults. The engine releases the pool after any command that closes a document, Headless::close does too, and an idle thread releases it after 2 s unused. - Tiles, compose Buffer/masks/bands, algo Image and the blur paths, engine adjustment/filter scratch, GPU tile upload and io import buffers go through the pool. - .pcraft save reuses one zstd FrameCompressor per worker (byte-identical). - interactive_bench reports minor page faults per run. 36 MP, trim threshold set vs glibc defaults: viewport 5.6 vs 6.1 ms (was 22.7), Blur r4 445 vs 437 ms (was 852), Curves CPU proxy 35.0 vs 35.7 ms (was 50), flatten 146 vs 147 ms (was 237), save .pcraft 251 vs 230 ms (was 545). RSS after closing a 5400x7200 document: 21 MB with trim set. * fix: corpus tests build again; return remaining pooled buffers (#10479 review) - Corpus-gated io tests and the Photoshop-oracle test moved `.px` out of a `Buffer`, which now implements `Drop` (E0509 with `--features corpus`): use `into_px()`. - io: masks, the merged image, extra channels, smart-filter masks, smart-object pixels and patterns give their `interleave` buffers back to the scratch pool after writing them. - compose: recycle the mask values of a pass-through group, `effect_shape` and both `split_parts` callers. - Styled Free Transform preview copies each band out instead of moving it, so the band returns to the pool. - interactive_bench: the fault count covers each whole run, untimed setup included; say so. * fix: recycle the masks of adjustment-atop and shape layers (#10479 review) * fix: recycle effect hiding masks (#10479 review) * fix: recycle knockout, CMYK and GPU shape masks; release the pool when Split/Merge Channels close a document (#10479 review) * fix: release the pool when a closed document's cancelled workers exit; idle-release switch for tests; don't pool PSD planes (#10479 review) * fix: release the pool for workers cancelled before their document closes; take the pool lock for budget and idle-release changes (#10479 review) * fix: idle release rechecks activity under the lock; try_take_exact releases the pool and retries before failing (#10479 review) * test: cover a successful try_take_exact miss; name the failed-reservation test for what it checks (#10479 review) * fix: pool the final GPU effect shape buffer and return it after use (#10479 review) * docs: describe scratch pool lifecycle regression invariants * test: verify polling releases cancelled document scratch buffers * perf: recycle remaining transform selection and PSD scratch buffers * fix: free PSD gather bands before allocating channel planes * test: assert exact scratch take reuses pooled storage --- crates/algo/src/blur.rs | 47 ++- crates/algo/src/blur/tests.rs | 5 +- crates/algo/src/image.rs | 29 +- crates/algo/src/lib.rs | 6 +- crates/algo/src/sharpen/tests.rs | 7 +- crates/algo/src/transform.rs | 1 + crates/automation/src/headless.rs | 2 + crates/compose/src/advanced.rs | 15 +- crates/compose/src/advanced_tests.rs | 8 +- crates/compose/src/cmyk.rs | 4 + crates/compose/src/composite.rs | 36 +- crates/compose/src/content.rs | 63 +-- crates/compose/src/extents.rs | 12 +- crates/compose/src/lib.rs | 27 +- crates/compose/src/render.rs | 5 +- crates/compose/src/soft_shape_tests.rs | 2 +- crates/compose/src/tests.rs | 20 +- crates/compose/tests/buffer_reuse.rs | 27 ++ crates/engine/examples/indexed_color_perf.rs | 2 +- crates/engine/src/cmd/adjust_cmds.rs | 6 +- crates/engine/src/cmd/adjust_cmds/tests.rs | 2 +- crates/engine/src/cmd/face_cmds.rs | 2 +- crates/engine/src/cmd/layer_menu_cmds.rs | 2 +- .../engine/src/cmd/layer_menu_cmds/tests.rs | 8 +- crates/engine/src/cmd/mask_view_cmds/tests.rs | 2 +- crates/engine/src/cmd/mode_cmds.rs | 2 +- crates/engine/src/cmd/mode_cmds/tests.rs | 4 +- crates/engine/src/cmd/select_extra_cmds.rs | 2 +- crates/engine/src/cmd/selection_cmds.rs | 2 +- crates/engine/src/cmd/smart_cmds/rendering.rs | 2 +- crates/engine/src/cmd/smart_cmds/tests.rs | 2 +- crates/engine/src/cmd/smartselect_cmds.rs | 2 +- crates/engine/src/cmd/transform_cmds/tests.rs | 2 +- crates/engine/src/cmd/video_cmds/tests.rs | 2 +- crates/engine/src/color_channels/tone.rs | 2 +- crates/engine/src/doc_path/tests.rs | 6 +- crates/engine/src/filters.rs | 2 + crates/engine/src/jobs.rs | 59 ++- crates/engine/src/pixels.rs | 13 +- crates/engine/src/select_mask_edits.rs | 4 +- crates/engine/src/tests.rs | 4 +- .../tests/it/atn_crystallize_cell_size.rs | 2 +- crates/engine/tests/it/atn_ripple_amount.rs | 2 +- crates/engine/tests/it/atn_selective_color.rs | 2 +- crates/engine/tests/it/atn_stroke_width.rs | 2 +- crates/engine/tests/it/photoshop_oracles.rs | 2 +- crates/engine/tests/scratch_release.rs | 114 ++++++ crates/format/src/store.rs | 133 +++++- crates/gpu/src/convert.rs | 14 +- crates/gpu/src/fx.rs | 12 +- crates/gpu/src/fx_passes.rs | 2 + crates/gpu/tests/it/parity.rs | 2 +- crates/io/examples/oracle_diff.rs | 4 +- crates/io/src/flat.rs | 9 +- crates/io/src/lib.rs | 4 +- crates/io/src/ora.rs | 4 +- crates/io/src/pattern_map.rs | 4 +- crates/io/src/pixels.rs | 7 +- crates/io/src/psd_export.rs | 2 + crates/io/src/psd_import.rs | 8 + crates/io/src/smart_map.rs | 2 + crates/io/tests/it/banded.rs | 2 +- crates/io/tests/it/blend_modes_corpus.rs | 2 +- crates/io/tests/it/cmyk_composite_export.rs | 3 +- crates/io/tests/it/color.rs | 8 +- crates/io/tests/it/composite.rs | 6 +- crates/io/tests/it/corpus.rs | 4 +- crates/io/tests/it/effects_multi.rs | 2 +- crates/io/tests/it/flat.rs | 2 +- crates/io/tests/it/lab16.rs | 4 +- crates/io/tests/it/large_files.rs | 2 +- crates/io/tests/it/multichannel.rs | 4 +- crates/io/tests/it/psd32_export.rs | 4 +- crates/io/tests/it/psd_damaged_merged.rs | 2 +- crates/io/tests/it/psd_type_bounds.rs | 2 +- crates/io/tests/it/tiff_corpus.rs | 4 +- crates/io/tests/it/tiff_layers.rs | 4 +- crates/raster/src/lib.rs | 38 +- crates/raster/src/scratch.rs | 384 ++++++++++++++++++ crates/raster/tests/scratch.rs | 361 ++++++++++++++++ crates/testkit/src/perf.rs | 21 + crates/ui-egui/examples/interactive_bench.rs | 19 +- crates/ui-egui/src/dialogs/color_range_ui.rs | 2 +- crates/ui-egui/src/dialogs/file_ui/web.rs | 2 +- .../src/dialogs/filter_dialog/tests.rs | 2 +- crates/ui-egui/src/dialogs/vp_ui/tests.rs | 8 +- crates/ui-egui/src/tools/transform_fx.rs | 3 +- crates/ui-egui/tests/it/adjust_preview_gpu.rs | 6 +- 88 files changed, 1444 insertions(+), 238 deletions(-) create mode 100644 crates/compose/tests/buffer_reuse.rs create mode 100644 crates/engine/tests/scratch_release.rs create mode 100644 crates/raster/src/scratch.rs create mode 100644 crates/raster/tests/scratch.rs diff --git a/crates/algo/src/blur.rs b/crates/algo/src/blur.rs index 819bf6fa78f..7ca9d34f99c 100644 --- a/crates/algo/src/blur.rs +++ b/crates/algo/src/blur.rs @@ -1,7 +1,7 @@ //! Blurs: Gaussian, box, motion, radial, surface. use photocraft_geom::Rect; -use photocraft_raster::Interrupt; +use photocraft_raster::{Interrupt, scratch}; use crate::image::{Edge, Image, premultiply, unpremultiply}; use crate::photo_util::{par_map, par_rows}; @@ -78,7 +78,7 @@ pub(crate) fn conv_sep(src: &Image, out: Rect, kx: &[f32], ky: &[f32], alpha: bo // Premultiplied copy of the needed source window. let win = Rect::new(out.x0 - rx, out.y0 - ry, out.x1 + rx, out.y1 + ry); let ww = win.width() as usize; - let mut p = vec![0.0f32; ww * win.height() as usize * n]; + let mut p = scratch::Buf::new(ww * win.height() as usize * n, 0.0f32); for y in win.y0..win.y1 { for x in win.x0..win.x1 { let o = ((y - win.y0) as usize * ww + (x - win.x0) as usize) * n; @@ -89,7 +89,7 @@ pub(crate) fn conv_sep(src: &Image, out: Rect, kx: &[f32], ky: &[f32], alpha: bo } premultiply(&mut p, n, alpha); // Horizontal pass: (ow × th). - let mut tmp = vec![0.0f32; ow * th * n]; + let mut tmp = scratch::Buf::new(ow * th * n, 0.0f32); for ty in 0..th { let row = &p[ty * ww * n..(ty + 1) * ww * n]; let dst = &mut tmp[ty * ow * n..(ty + 1) * ow * n]; @@ -113,7 +113,7 @@ pub(crate) fn conv_sep(src: &Image, out: Rect, kx: &[f32], ky: &[f32], alpha: bo } } // Vertical pass. - let mut res = vec![0.0f32; ow * oh * n]; + let mut res = scratch::take(ow * oh * n, 0.0f32); for oy in 0..oh { let d = &mut res[oy * ow * n..(oy + 1) * ow * n]; for (i, kv) in ky.iter().enumerate() { @@ -182,11 +182,27 @@ pub(crate) fn box_widths(params: &FilterParams) -> Option> { } /// Scratch buffers of one worker for [`box_blur`]. -#[derive(Default)] struct Scratch { line: Vec, next: Vec, acc: Vec, + /// The source row being read (horizontal passes only). + row: Vec, +} + +impl Scratch { + /// Buffers with room for lines of `line` floats (and the shorter ones after the first pass). + fn new(line: usize, row: usize) -> Self { + Scratch { line: scratch::take_cap(line), next: scratch::take_cap(line), acc: Vec::new(), row: scratch::take_cap(row) } + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + scratch::give(std::mem::take(&mut self.line)); + scratch::give(std::mem::take(&mut self.next)); + scratch::give(std::mem::take(&mut self.row)); + } } /// One running-sum box pass of radius `r` along a line of elements of `w` floats each (a pixel's @@ -252,7 +268,7 @@ fn box_pass_px(src: &[f32], dst: &mut [f32], r: usize) { /// `dst` unfinished) when `ctl` is cancelled before a pass: a column strip's passes take tens of /// milliseconds on a tall image, too long to finish once cancelled (#6205). fn line_passes(dst: &mut [f32], w: usize, radii: &[usize], s: &mut Scratch, ctl: &Interrupt) { - let Scratch { line, next, acc } = s; + let Scratch { line, next, acc, .. } = s; let Some(len) = dst.len().checked_div(w) else { return }; let mut tail: usize = radii.iter().sum(); for (k, &r) in radii.iter().enumerate() { @@ -306,21 +322,21 @@ pub(crate) fn box_blur( // Horizontal passes over `used`'s rows only (the repeated rows above and below it would just // repeat their results), for the output columns. Each row is extended to the passes' reach by // repeating its end pixels. - let mut h = vec![0.0f32; used.height() as usize * ow * n]; + let mut h = scratch::Buf::new(used.height() as usize * ow * n, 0.0f32); let (left, right) = ((used.x0 - out.x0.saturating_sub(reach)) as usize, (out.x1.saturating_add(reach) - used.x1) as usize); par_rows(&mut h, ow * ROWS_PER_TASK, n, |task, chunk| { - let (mut row, mut s) = (Vec::new(), Scratch::default()); + let mut s = Scratch::new((used.width() as usize + left + right) * n, used.width() as usize * n); for (k, dst) in chunk.chunks_exact_mut(ow * n).enumerate() { if ctl.cancelled() { return; } let y = used.y0 + (task * ROWS_PER_TASK + k) as i32; - read(Rect::new(used.x0, y, used.x1, y + 1), &mut row); - premultiply(&mut row, n, alpha); - let (Some(first), Some(last)) = (row.get(..n), row.get(row.len().saturating_sub(n)..)) else { return }; + read(Rect::new(used.x0, y, used.x1, y + 1), &mut s.row); + premultiply(&mut s.row, n, alpha); + let (Some(first), Some(last)) = (s.row.get(..n), s.row.get(s.row.len().saturating_sub(n)..)) else { return }; s.line.clear(); (0..left).for_each(|_| s.line.extend_from_slice(first)); - s.line.extend_from_slice(&row); + s.line.extend_from_slice(&s.row); (0..right).for_each(|_| s.line.extend_from_slice(last)); line_passes(dst, n, &radii, &mut s, ctl); } @@ -336,11 +352,11 @@ pub(crate) fn box_blur( } let (sx, w) = ((t.x0 - out.x0) as usize * n, t.width() as usize * n); let row = |y: usize| &h[y * stride + sx..y * stride + sx + w]; - let mut s = Scratch::default(); + let mut s = Scratch::new((rows + top + bottom) * w, 0); (0..top).for_each(|_| s.line.extend_from_slice(row(0))); (0..rows).for_each(|y| s.line.extend_from_slice(row(y))); (0..bottom).for_each(|_| s.line.extend_from_slice(row(rows - 1))); - let mut res = vec![0.0f32; oh * w]; + let mut res = scratch::take(oh * w, 0.0f32); line_passes(&mut res, w, &radii, &mut s, ctl); if ctl.cancelled() { return (t, Vec::new()); @@ -367,7 +383,7 @@ fn box_passes(src: &Image, out: Rect, alpha: bool, boxes: &[usize]) -> Vec buf.extend_from_slice(src.row(r)); }; let ow = out.width() as usize * n; - let mut res = vec![0.0f32; ow * out.height() as usize]; + let mut res = scratch::take(ow * out.height() as usize, 0.0f32); if res.is_empty() { return res; } @@ -376,6 +392,7 @@ fn box_passes(src: &Image, out: Rect, alpha: bool, boxes: &[usize]) -> Vec for (dst, s) in res.chunks_exact_mut(ow).zip(data.chunks_exact(w)) { dst[x0..x0 + w].copy_from_slice(s); } + scratch::give(data); } res } diff --git a/crates/algo/src/blur/tests.rs b/crates/algo/src/blur/tests.rs index 028ac65dcc2..74cf7ab20c2 100644 --- a/crates/algo/src/blur/tests.rs +++ b/crates/algo/src/blur/tests.rs @@ -204,7 +204,7 @@ fn direct_boxes(img: &Image, out: Rect, boxes: &[usize], alpha: bool) -> Vec = (0..(len + 2 * reach) * w).map(|i| (i % 7) as f32 + 1.0).collect(); let run = |ctl: &Interrupt| { - let mut s = Scratch { line: line.clone(), ..Scratch::default() }; + let mut s = Scratch::new(0, 0); + s.line.extend_from_slice(&line); let mut dst = vec![0.0f32; len * w]; line_passes(&mut dst, w, &radii, &mut s, ctl); dst diff --git a/crates/algo/src/image.rs b/crates/algo/src/image.rs index 6a17e08b01c..c521f043488 100644 --- a/crates/algo/src/image.rs +++ b/crates/algo/src/image.rs @@ -1,7 +1,7 @@ //! Interleaved `f32` image regions and sampling helpers. use photocraft_geom::Rect; -use photocraft_raster::Surface; +use photocraft_raster::{Surface, scratch}; /// How samples outside an image are read. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -14,8 +14,9 @@ pub enum Edge { Wrap, } -/// A rectangle of interleaved, normalized samples. -#[derive(Clone, Debug, PartialEq)] +/// A rectangle of interleaved, normalized samples. The samples come from, and go back to, the +/// scratch pool. +#[derive(Debug, PartialEq)] pub struct Image { pub rect: Rect, /// Channels per pixel (alpha last when the surface has alpha). @@ -23,6 +24,20 @@ pub struct Image { pub data: Vec, } +impl Clone for Image { + fn clone(&self) -> Self { + let mut data = scratch::take(self.data.len(), 0.0f32); + data.copy_from_slice(&self.data); + Image { rect: self.rect, ch: self.ch, data } + } +} + +impl Drop for Image { + fn drop(&mut self) { + scratch::give(std::mem::take(&mut self.data)); + } +} + impl Image { /// Reads `rect` from a surface. pub fn read(s: &Surface, rect: Rect) -> Self { @@ -53,9 +68,15 @@ impl Image { img } + /// The samples, taken out of the image (it can't be destructured: it returns them to the + /// pool on drop). + pub fn into_data(mut self) -> Vec { + std::mem::take(&mut self.data) + } + /// New zeroed image. pub fn new(rect: Rect, ch: usize) -> Self { - Image { rect, ch, data: vec![0.0; rect.width() as usize * rect.height() as usize * ch] } + Image { rect, ch, data: scratch::take(rect.width() as usize * rect.height() as usize * ch, 0.0) } } #[inline] diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs index 03ffe381447..bda29cb2eae 100644 --- a/crates/algo/src/lib.rs +++ b/crates/algo/src/lib.rs @@ -1269,7 +1269,10 @@ fn apply_tiled_with_impl( } for (t, data) in results { match data { - TileData::Samples(data) => out.write_region(t, &data), + TileData::Samples(data) => { + out.write_region(t, &data); + photocraft_raster::scratch::give(data); + } TileData::Encoded(data) => out.write_interleaved(t, &data), } } @@ -1324,6 +1327,7 @@ fn apply_box_blur( mix_selection(data, *t, sel, &Image::read(surface, *t), fmt.alpha); } s.write_region(*t, data); + photocraft_raster::scratch::give(std::mem::take(data)); } }; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/algo/src/sharpen/tests.rs b/crates/algo/src/sharpen/tests.rs index 4699bb3a101..aef62259a36 100644 --- a/crates/algo/src/sharpen/tests.rs +++ b/crates/algo/src/sharpen/tests.rs @@ -267,7 +267,12 @@ fn malformed_inputs_and_allocations_stop_gracefully() { assert!(crate::apply_in_with(&s, &p, rect, rect, None, rect, &Interrupt::NONE).is_none()); assert_eq!(crate::apply_in(&s, &p, rect, rect, None, rect), s); } - for bad in [Image { ch: 0, ..src.clone() }, Image { data: vec![0.0], ..src.clone() }, Image { rect: Rect::new(5, 0, 0, 2), ..src.clone() }] { + let with = |edit: &dyn Fn(&mut Image)| { + let mut bad = src.clone(); + edit(&mut bad); + bad + }; + for bad in [with(&|i| i.ch = 0), with(&|i| i.data = vec![0.0]), with(&|i| i.rect = Rect::new(5, 0, 0, 2))] { assert!(exact::run(&bad, rect, &ctx, 100.0, 1.0, 0.0, &Interrupt::NONE).is_none()); } for rect in [Rect::new(i32::MIN, 0, i32::MAX, 2), Rect::new(0, 0, 300_000, 300_000), Rect::new(2, 0, 0, 2)] { diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rs index 1ed0ec7c040..b1f7bacaae5 100644 --- a/crates/algo/src/transform.rs +++ b/crates/algo/src/transform.rs @@ -521,6 +521,7 @@ fn warp( outp[o + a] = al as f32; } } + photocraft_raster::scratch::give(px); Ok(any.then_some((*t, outp))) }; // Each tile is written as soon as it is warped, so only the tiles in flight hold their `f32` diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 6722c5c00b7..8b08daa6aab 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -358,6 +358,8 @@ impl Headless { if let Some(d) = self.session.close(i) { self.writers.remove(&d.doc.id.0); } + // The closed document's buffers went to the scratch pool: hand them back to the OS. + photocraft_raster::scratch::release(); Ok(self.session_list()) } diff --git a/crates/compose/src/advanced.rs b/crates/compose/src/advanced.rs index 8ea5a86c6df..7a4068012d9 100644 --- a/crates/compose/src/advanced.rs +++ b/crates/compose/src/advanced.rs @@ -32,6 +32,7 @@ use std::borrow::Cow; use photocraft_doc::{Knockout, Layer, LayerContent}; use photocraft_geom::Rect; +use crate::extents::recycle_mask; use crate::{Buffer, Ctx, composite_atop, composite_layer, effects, mask_vals, render_content}; /// Where a layer stack sits, for knockouts: at the document's top level, and/or inside an @@ -157,6 +158,7 @@ pub(crate) fn knockout(layer: &Layer, backdrop: &mut Buffer, target: &Buffer, cl if target.rect != backdrop.rect || shape.len() != backdrop.px.len() { // Never reached (targets are built over the backdrop's rect); compositing without the // knockout beats a wrong pixel or a panic. + recycle_mask(Some(shape)); draw(backdrop); return; } @@ -172,7 +174,10 @@ pub(crate) fn knockout(layer: &Layer, backdrop: &mut Buffer, target: &Buffer, cl } let knocked = (layer.opacity < 1.0).then(|| backdrop.clone()); draw(backdrop); - let Some(knocked) = knocked else { return }; + let Some(knocked) = knocked else { + recycle_mask(Some(shape)); + return; + }; let rest = 1.0 - layer.opacity.clamp(0.0, 1.0); for (((p, b), k), s) in backdrop.px.iter_mut().zip(&before.px).zip(&knocked.px).zip(&shape) { if *s <= 0.0 { @@ -186,6 +191,7 @@ pub(crate) fn knockout(layer: &Layer, backdrop: &mut Buffer, target: &Buffer, cl let a = pm[3].clamp(0.0, 1.0); *p = if a > 0.0 { [(pm[0] / a).clamp(0.0, 1.0), (pm[1] / a).clamp(0.0, 1.0), (pm[2] / a).clamp(0.0, 1.0), a] } else { [0.0; 4] }; } + recycle_mask(Some(shape)); } /// Composite a clipping group's clipped layers atop `base` (the base's isolated content, Blend @@ -220,7 +226,12 @@ pub(crate) fn composite_clipped_individually(layer: &Layer, clipped: &[Layer], b let op = layer.opacity.clamp(0.0, 1.0); let clip: Vec = match render_content(layer, rect, cx) { Some(b) => b.px.iter().map(|p| p[3] * op).collect(), - None => mask_vals(layer, rect, cx).unwrap_or_else(|| vec![1.0; n]).iter().map(|m| m * op).collect(), + None => { + let mv = mask_vals(layer, rect, cx); + let clip = mv.as_ref().map_or_else(|| vec![op; n], |m| m.iter().map(|m| m * op).collect()); + recycle_mask(mv); + clip + } }; if clip.len() != n { return; diff --git a/crates/compose/src/advanced_tests.rs b/crates/compose/src/advanced_tests.rs index 608c6188e2f..15d3cf2346a 100644 --- a/crates/compose/src/advanced_tests.rs +++ b/crates/compose/src/advanced_tests.rs @@ -395,7 +395,7 @@ fn shapeless_stroke_tile_skips_match_full_region_across_blending_settings() { .unwrap(); let mut band_pixels = Vec::with_capacity(whole.px.len()); for band in bands { - band_pixels.extend(band.px); + band_pixels.extend(band.into_px()); } assert_eq!(whole.px, band_pixels, "banded: {depth:?}, {position:?}, {blend:?}, fill={fill}, blend_if={blend_if}"); } @@ -639,7 +639,7 @@ fn transparency_shapes_off_ignores_masks_and_reaches_groups() { l.mask = Some(LayerMask { surface: photocraft_raster::Surface::with_default(PixelFormat::GRAY8, &[77.0 / 255.0]), ..LayerMask::reveal_all() }); l.advanced.transparency_shapes = tsl; d.layers.push(l); - render(&d, d.bounds()).px + render(&d, d.bounds()).into_px() }; let (off, on) = (render_with(false), render_with(true)); assert!(off.iter().zip(&on).all(|(a, b)| close(*a, *b)), "{mode:?} ({depth:?}): a mask isn't the layer's transparency"); @@ -691,13 +691,13 @@ fn transparency_shapes_off_keeps_the_base_alpha_under_a_clipped_knockout() { base.advanced.transparency_shapes = false; base.vector_mask = Some(photocraft_doc::vector::VectorMask { feather: 1.5, ..photocraft_doc::vector::VectorMask::new(square.clone()) }); d.layers.push(base); - let alone = render(&d, d.bounds()).px; + let alone = render(&d, d.bounds()).into_px(); let mut red = solid(&d, "red", full(&d), [1.0, 0.0, 0.0, 0.5]); red.clipped = true; let mut knock = knocker(&d, k); knock.clipped = true; d.layers.extend([red, knock]); - let got = render(&d, d.bounds()).px; + let got = render(&d, d.bounds()).into_px(); let what = format!("{k:?} ({depth:?})"); for (i, (g, a)) in got.iter().zip(&alone).enumerate() { if i % 12 < 6 { diff --git a/crates/compose/src/cmyk.rs b/crates/compose/src/cmyk.rs index 96a6df0cebf..2f8eaa88616 100644 --- a/crates/compose/src/cmyk.rs +++ b/crates/compose/src/cmyk.rs @@ -27,6 +27,7 @@ use photocraft_doc::adjust::ToneSpace; use photocraft_doc::{Adjustment, Document, Knockout, Layer, LayerContent}; use photocraft_geom::Rect; +use super::extents::recycle_mask; use super::{Ctx, RENDER_TILE, advanced, empty_in, mask_vals, pattern}; #[path = "cmyk_split.rs"] @@ -355,6 +356,7 @@ fn apply_mask(l: &Layer, buf: &mut CmykBuffer, cx: &Ctx) { for (p, k) in buf.px.iter_mut().zip(&m) { p[4] *= clean(*k).max(0.0); } + recycle_mask(Some(m)); } } @@ -425,6 +427,7 @@ fn mix_adjusted(l: &Layer, base: &mut CmykBuffer, adjusted: &CmykBuffer, cx: &Ct *v = if k >= 1.0 { b } else { *v + (b - *v) * k }; } } + recycle_mask(mv); } /// Rounds to the document's levels after an adjustment layer, as the compositor does (on the @@ -534,6 +537,7 @@ fn composite_layer(l: &Layer, clipped: &[Layer], backdrop: &mut CmykBuffer, cx: [0.0; 5] }; } + recycle_mask(mv); } return; } diff --git a/crates/compose/src/composite.rs b/crates/compose/src/composite.rs index 8436ff74285..4ef497672fb 100644 --- a/crates/compose/src/composite.rs +++ b/crates/compose/src/composite.rs @@ -1,6 +1,6 @@ -use super::content::{channel_weights, empty_in, recycle_buffer, render_content, restore_channels, scratch_buffer, surface_to_buffer}; +use super::content::{channel_weights, empty_in, render_content, restore_channels, surface_to_buffer}; use super::ctx::Ctx; -use super::extents::{effects_frame, mask_k, mask_vals, shapeless_stroke_bounds}; +use super::extents::{effects_frame, mask_k, mask_vals, recycle_mask, shapeless_stroke_bounds}; use super::fx_cache::effect_maps; use super::{BlendMode, Buffer, Fill, Layer, LayerContent, Rect, Surface, advanced, blend, effects, psblend, shape_split}; @@ -339,6 +339,7 @@ pub(crate) fn composite_pixel_layer(layer: &Layer, surf: &Surface, backdrop: &mu } blend_span_fill(dst, &row, rect.x0, y, layer.blend, layer.opacity, layer.fill_opacity, gamma); } + recycle_mask(mv); } pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) { @@ -389,6 +390,7 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: [0.0; 4] }; } + recycle_mask(mv); } // A Frame's stroke over the frame's content, at the group's opacity. if let Some(stroke) = shape_split::frame_stroke(layer, cx.canvas, cx.depth) { @@ -425,9 +427,10 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: if let LayerContent::Adjustment(adj) = &layer.content { let mv = mask_vals(layer, rect, cx); if mv.as_ref().is_some_and(|values| values.iter().all(|&value| opacity * value <= 0.0)) { + recycle_mask(mv); return; } - let mut adjusted = scratch_buffer(rect); + let mut adjusted = Buffer::transparent(rect); adjusted.px.copy_from_slice(&backdrop.px); cx.apply_adjustment(adj, &mut adjusted); // Clipped layers onto an adjustment are uncommon; they composite atop the adjusted result. @@ -455,7 +458,7 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: None => blend_back(&mut backdrop.px, &adjusted.px, std::iter::repeat(k), layer.blend, fill), } } - recycle_buffer(adjusted); + recycle_mask(mv); return; } @@ -469,6 +472,7 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: if let (Some(m), Some(b)) = (&hide, &before) { advanced::apply_hiding_mask(backdrop, b, m); } + recycle_mask(hide); return; } if let Some((mut content, stroke, mask)) = shape_parts(layer, clipped, rect, cx) { @@ -478,6 +482,7 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: p[3] *= mask_k(&mask, i); } blend_layer_into(backdrop, &content, layer, cx, 1.0); + recycle_mask(mask); return; } if !matches!(layer.content, LayerContent::Group(_) | LayerContent::Fill(_) | LayerContent::Adjustment(_)) @@ -512,7 +517,6 @@ pub(crate) fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: let Some(mut content) = render_content(layer, rect, cx) else { return }; advanced::composite_clipped(clipped, &mut content, cx); blend_layer_into(backdrop, &content, layer, cx, text_gamma(layer)); - recycle_buffer(content); } /// A layer with effects (and its clipping group) onto `backdrop`. @@ -521,7 +525,7 @@ fn composite_layer_effects(layer: &Layer, clipped: &[Layer], backdrop: &mut Buff // Neighbourhoods are already captured by the full-region effect maps; // content and effect application only need the output rectangle. // A stroked shape's vector stroke stays above its clipped layers and interior effects. - let (mut content, vstroke) = match split_parts(layer, rect, cx) { + let (mut content, parts) = match split_parts(layer, rect, cx) { Some((fill, stroke, mask)) => (fill, Some((stroke, mask))), None => { let Some(content) = render_content(layer, rect, cx) else { return }; @@ -529,9 +533,12 @@ fn composite_layer_effects(layer: &Layer, clipped: &[Layer], backdrop: &mut Buff } }; advanced::composite_clipped(clipped, &mut content, cx); - let vstroke = vstroke.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); + let vstroke = parts.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); let maps = effect_maps(layer, rect, cx); effects::composite_with_effects_prepared(layer, &content, backdrop, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke); + if let Some((_, mask)) = parts { + recycle_mask(mask); + } } /// The coverage-mixing gamma of a layer: the text blending gamma @@ -605,6 +612,7 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) { p[c] += (bl[c] - p[c]) * k; } } + recycle_mask(mv); return; } if effects::has_effects(layer) { @@ -615,21 +623,28 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) { let hide = advanced::hiding_mask(layer, rect, cx); let src = advanced::effects_source(layer); let layer = src.as_ref(); - let (content, vstroke) = match split_parts(layer, rect, cx) { + let (content, parts) = match split_parts(layer, rect, cx) { Some((fill, stroke, mask)) => (fill, Some((stroke, mask))), None => { - let Some(content) = render_content(layer, rect, cx) else { return }; + let Some(content) = render_content(layer, rect, cx) else { + recycle_mask(hide); + return; + }; (content, None) } }; - let vstroke = vstroke.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); + let vstroke = parts.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() }); let mut opaque = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() }; let maps = effect_maps(layer, rect, cx); effects::composite_with_effects_prepared(layer, &content, &mut opaque, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke); + if let Some((_, mask)) = parts { + recycle_mask(mask); + } if let Some(m) = &hide { let plain = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() }; advanced::apply_hiding_mask(&mut opaque, &plain, m); } + recycle_mask(hide); for (p, o) in base.px.iter_mut().zip(&opaque.px) { if p[3] > 0.0 { *p = [o[0], o[1], o[2], p[3]]; @@ -689,6 +704,7 @@ fn blend_layer_into(backdrop: &mut Buffer, src: &Buffer, layer: &Layer, cx: &Ctx let alpha = (s[3] / m).clamp(0.0, 1.0); *b = psblend::composite_fill(mode, *b, [s[0], s[1], s[2], m], opacity, fill * alpha, gamma); } + recycle_mask(mv); } /// [`blend_into_g`] for a layer's own `opacity` and `fill`: Fill is part of the blend for diff --git a/crates/compose/src/content.rs b/crates/compose/src/content.rs index ea868d715e1..1f91c6a942b 100644 --- a/crates/compose/src/content.rs +++ b/crates/compose/src/content.rs @@ -1,63 +1,29 @@ use super::composite::{adjustment_quantum, blend_into, composite_stack}; use super::ctx::Ctx; -use super::extents::{effect_shape, effect_source_bounds, mask_vals, shapeless_stroke_bounds, transparent_outside}; +use super::extents::{effect_shape, effect_source_bounds, mask_vals, recycle_mask, shapeless_stroke_bounds, transparent_outside}; use super::fx_cache::effect_maps; use super::{BlendMode, Buffer, Document, Fill, Layer, LayerContent, Pattern, Rect, Surface, bounds, effects, gradient_fill, pattern, shape_split}; /// Tile size for parallel rendering (tile results are independent). pub const RENDER_TILE: i32 = 256; -// One tile of scratch per worker; nested rendering takes its own buffer. -thread_local! { - static SCRATCH: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; -} - -pub(crate) fn scratch_buffer(rect: Rect) -> Buffer { - if rect.width() as usize * rect.height() as usize > (RENDER_TILE * RENDER_TILE) as usize { - return Buffer::transparent(rect); - } - let mut px = SCRATCH.with(|slot| std::mem::take(&mut *slot.borrow_mut())); - px.resize(rect.width() as usize * rect.height() as usize, [0.0; 4]); - Buffer { rect, px } -} - -pub(crate) fn recycle_buffer(buf: Buffer) { - if buf.px.capacity() <= (RENDER_TILE * RENDER_TILE) as usize { - SCRATCH.with(|slot| { - let mut slot = slot.borrow_mut(); - if slot.capacity() < buf.px.capacity() { - *slot = buf.px; - } - }); - } -} - #[cfg(test)] #[test] -fn scratch_reuse_preserves_pixels_and_bounds_retention() { - SCRATCH.with(|slot| slot.borrow_mut().clear()); - let rect = Rect::new(-2, -3, 18, 11); +fn scratch_reuse_preserves_pixels() { + // 256 × 256 pixels of [f32; 4] (1 MiB): over `MIN_POOLED_BYTES`, so the pool keeps it. + let rect = Rect::new(-2, -3, 254, 253); for fmt in [photocraft_color::PixelFormat::RGBA8, photocraft_color::PixelFormat::RGBA16, photocraft_color::PixelFormat::RGBA32F] { let s = Surface::with_default(fmt, &[0.2, 0.4, 0.6, 0.8]); - let buf = surface_to_scratch(&s, rect); + let mut buf = surface_to_scratch(&s, rect); assert_eq!(buf, surface_to_buffer(&s, rect)); - let ptr = buf.px.as_ptr(); - recycle_buffer(buf); - let reused = surface_to_scratch(&Surface::new(fmt), rect); - assert_eq!(reused.px.as_ptr(), ptr); + buf.px.fill([1.0; 4]); + // A dropped buffer goes back to the pool; the next one must come out cleared. + drop(buf); + let reused = Buffer::transparent(rect); assert!(reused.px.iter().all(|p| p == &[0.0; 4])); - let nested = scratch_buffer(rect); + let nested = Buffer::transparent(rect); assert_ne!(nested.px.as_ptr(), reused.px.as_ptr()); - recycle_buffer(nested); - recycle_buffer(reused); } - let cached = SCRATCH.with(|slot| slot.borrow().as_ptr()); - let huge = scratch_buffer(Rect::new(0, 0, RENDER_TILE + 1, RENDER_TILE)); - recycle_buffer(huge); - SCRATCH.with(|slot| { - assert_eq!(slot.borrow().as_ptr(), cached); - assert!(slot.borrow().capacity() <= (RENDER_TILE * RENDER_TILE) as usize); - }); } /// Render a layer's own content (no blending into the backdrop yet) into an isolated buffer. @@ -93,6 +59,7 @@ pub(crate) fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option Buffer { - let mut px = vec![[0.0f32; 4]; rect.width() as usize * rect.height() as usize]; - s.read_rgba_into(rect, &mut px); - Buffer { rect, px } + let mut buf = Buffer::transparent(rect); + s.read_rgba_into(rect, &mut buf.px); + buf } fn surface_to_scratch(s: &Surface, rect: Rect) -> Buffer { - let mut buf = scratch_buffer(rect); + let mut buf = Buffer::transparent(rect); s.read_rgba_into(rect, &mut buf.px); buf } diff --git a/crates/compose/src/extents.rs b/crates/compose/src/extents.rs index d895f14bc9d..7e4f8d234ea 100644 --- a/crates/compose/src/extents.rs +++ b/crates/compose/src/extents.rs @@ -134,6 +134,7 @@ pub(crate) fn effect_shape(layer: &Layer, rect: Rect, cx: &Ctx) -> Vec { out[i] = v * mask_k(&mv, i); } } + recycle_mask(mv); out } @@ -283,13 +284,13 @@ pub(crate) fn mask_vals(layer: &Layer, rect: Rect, cx: &Ctx) -> Option> if masks::has_feather(layer) && let Some(s) = masks::combined_mask(layer, cx.canvas) { - let mut v = Vec::new(); + let mut v = photocraft_raster::scratch::take_cap(rect.width() as usize * rect.height() as usize); s.read_region_into(rect, &mut v); return Some(v); } let vector = layer.vector_mask.as_ref().map(|vm| cx.vector_masks.values(vm, rect)); let Some(m) = layer.mask.as_ref() else { return vector }; - let mut v = Vec::new(); + let mut v = photocraft_raster::scratch::take_cap(rect.width() as usize * rect.height() as usize); m.values_into(rect, &mut v); if let Some(vm) = vector { for (a, b) in v.iter_mut().zip(vm) { @@ -299,6 +300,13 @@ pub(crate) fn mask_vals(layer: &Layer, rect: Rect, cx: &Ctx) -> Option> Some(v) } +/// Hand a [`mask_vals`] result back to the scratch pool once its tile is done. +pub(crate) fn recycle_mask(m: Option>) { + if let Some(v) = m { + photocraft_raster::scratch::give(v); + } +} + #[inline] pub(crate) fn mask_k(m: &Option>, i: usize) -> f32 { m.as_ref().map_or(1.0, |v| v[i]) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index e5932905719..25dc55984a9 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -84,18 +84,39 @@ pub use render::{ }; /// Straight-alpha RGBA float buffer covering a rectangle. -#[derive(Clone, Debug, PartialEq)] +/// +/// The pixel storage comes from, and goes back to, the scratch pool. +#[derive(Debug, PartialEq)] pub struct Buffer { pub rect: Rect, pub px: Vec<[f32; 4]>, } +impl Clone for Buffer { + fn clone(&self) -> Self { + let mut px = photocraft_raster::scratch::take(self.px.len(), [0.0; 4]); + px.copy_from_slice(&self.px); + Self { rect: self.rect, px } + } +} + +impl Drop for Buffer { + fn drop(&mut self) { + photocraft_raster::scratch::give(std::mem::take(&mut self.px)); + } +} + impl Buffer { pub fn transparent(rect: Rect) -> Self { - Self { rect, px: vec![[0.0; 4]; rect.width() as usize * rect.height() as usize] } + Self::filled(rect, [0.0; 4]) } pub fn filled(rect: Rect, c: [f32; 4]) -> Self { - Self { rect, px: vec![c; rect.width() as usize * rect.height() as usize] } + Self { rect, px: photocraft_raster::scratch::take(rect.width() as usize * rect.height() as usize, c) } + } + /// The pixels, taken out of the buffer (it can't be destructured: it returns them to the + /// pool on drop). + pub fn into_px(mut self) -> Vec<[f32; 4]> { + std::mem::take(&mut self.px) } #[inline] pub fn get(&self, x: i32, y: i32) -> [f32; 4] { diff --git a/crates/compose/src/render.rs b/crates/compose/src/render.rs index b739d3f42a3..250a3ebce1a 100644 --- a/crates/compose/src/render.rs +++ b/crates/compose/src/render.rs @@ -229,14 +229,12 @@ pub fn composite_to_surface(doc: &Document, rect: Rect, fmt: photocraft_color::P let mut s = Surface::new(fmt); let n = fmt.channels(); let empty = s.default_pixel(); - let mut data = Vec::new(); let _ = render_bands(doc, rect, 0, |band| -> Result<(), ()> { let band = match background { Some(bg) => band.over_background(bg), None => band, }; - data.clear(); - data.resize(band.px.len() * n, 0.0); + let mut data = photocraft_raster::scratch::take(band.px.len() * n, 0.0f32); photocraft_color::convert::with_cmyk_space(space.as_ref(), || { for (p, out) in band.px.iter().zip(data.chunks_exact_mut(n)) { if fmt.alpha && (p[3] <= 0.0 || p[3].is_nan()) && empty.len() == n { @@ -247,6 +245,7 @@ pub fn composite_to_surface(doc: &Document, rect: Rect, fmt: photocraft_color::P } }); s.write_region(band.rect, &data); + photocraft_raster::scratch::give(data); Ok(()) }); s.prune(); diff --git a/crates/compose/src/soft_shape_tests.rs b/crates/compose/src/soft_shape_tests.rs index 37575beef5f..9332f31af10 100644 --- a/crates/compose/src/soft_shape_tests.rs +++ b/crates/compose/src/soft_shape_tests.rs @@ -115,7 +115,7 @@ fn soft_shape_matches_an_equal_vector_mask() { fn soft_shape_keeps_its_stroke_crisp() { let stroke = ShapeStroke { width: 4.0, paint: Fill::Solid(Color::rgb(1.0, 0.0, 0.0)), ..ShapeStroke::default() }; let d = shape_doc(SampleType::U8, 0.5, 10.0, Some(stroke)); - let px = render(&d, Rect::new(0, 100, 200, 101)).px; + let px = render(&d, Rect::new(0, 100, 200, 101)).into_px(); // Centred 4 px stroke over x = 48..52: opaque red. for x in [48, 49, 50, 51] { let p = px[x]; diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 917192f44a7..7ea86550994 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -3001,7 +3001,7 @@ fn levels_steps_match_photoshop() { let px = xs.iter().map(|&x| f32::from(x) / 255.0).map(|v| [v, v, v, 1.0]).collect(); let mut b = Buffer { rect: Rect::new(0, 0, xs.len() as i32, 1), px }; adjust::apply_depth(adj, &mut b, adjust::Transfer::Srgb, Some(SampleType::U8)); - b.px + b.into_px() }; let rgb = levels(ch(0.0, 213.0, 1.22, 48.0, 255.0), [ch(0.0, 255.0, 0.47, 0.0, 194.0), id.clone(), ch(61.0, 255.0, 0.47, 0.0, 213.0)]); let xs = [2, 8, 9, 15, 16, 43, 45, 48, 55, 61, 72, 79, 84, 89, 90, 101, 106, 120, 150, 180, 200]; @@ -3364,7 +3364,7 @@ fn render_bands_cover_the_rect_in_order() { render_bands(&d, r, 100, |b| -> Result<(), ()> { assert_eq!((b.rect.x0, b.rect.x1), (r.x0, r.x1)); rows.push((b.rect.y0, b.rect.y1)); - px.extend(b.px); + px.extend(b.into_px()); Ok(()) }) .unwrap(); @@ -4469,13 +4469,13 @@ fn dissolve_adjustment_resolves_opacity_to_binary_coverage() { layer.blend = BlendMode::Dissolve; layer.opacity = 0.5; d.layers.push(layer); - let pixels = render(&d, d.bounds()).px; + let pixels = render(&d, d.bounds()).into_px(); let black = pixels.iter().filter(|p| p[0] < 0.01).count(); let white = pixels.iter().filter(|p| p[0] > 0.99).count(); assert!(black > 0 && white > 0, "Dissolve must select both original and adjusted pixels"); assert_eq!(black + white, pixels.len(), "no intermediate gray pixels"); d.layers.last_mut().unwrap().blend = BlendMode::Normal; - let continuous = render(&d, d.bounds()).px; + let continuous = render(&d, d.bounds()).into_px(); assert!(continuous.iter().all(|p| (p[0] - 0.5).abs() < E), "Normal remains continuously interpolated"); } @@ -4486,14 +4486,14 @@ fn clipped_dissolve_fill_matches_opaque_unclipped_coverage() { fill.blend = BlendMode::Dissolve; fill.opacity = 0.5; d.layers.push(fill); - let control = render(&d, d.bounds()).px; + let control = render(&d, d.bounds()).into_px(); d.layers.last_mut().unwrap().clipped = true; - let clipped = render(&d, d.bounds()).px; + let clipped = render(&d, d.bounds()).into_px(); assert_eq!(clipped, control, "clipping over a fully opaque base must preserve dissolve pixels"); let black = clipped.iter().filter(|p| p[0] < 0.01).count(); assert!(black > 0 && black < clipped.len()); d.layers.last_mut().unwrap().blend = BlendMode::Normal; - let continuous = render(&d, d.bounds()).px; + let continuous = render(&d, d.bounds()).into_px(); assert!(continuous.iter().all(|p| (p[0] - 0.5).abs() < E)); } @@ -4504,17 +4504,17 @@ fn dissolve_color_overlay_preserves_binary_layer_coverage() { layer.blend = BlendMode::Dissolve; layer.opacity = 0.5; d.layers.push(layer); - let control = render(&d, d.bounds()).px; + let control = render(&d, d.bounds()).into_px(); d.layers .last_mut() .unwrap() .effects .items .push(photocraft_doc::Effect::ColorOverlay { common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), color: Color::BLACK }); - let styled = render(&d, d.bounds()).px; + let styled = render(&d, d.bounds()).into_px(); assert_eq!(styled, control, "an identity overlay should not turn dissolve pixels gray"); d.layers.last_mut().unwrap().blend = BlendMode::Normal; - let continuous = render(&d, d.bounds()).px; + let continuous = render(&d, d.bounds()).into_px(); assert!(continuous.iter().all(|p| (p[0] - 0.5).abs() < E)); } diff --git a/crates/compose/tests/buffer_reuse.rs b/crates/compose/tests/buffer_reuse.rs new file mode 100644 index 00000000000..f07bf8b69fb --- /dev/null +++ b/crates/compose/tests/buffer_reuse.rs @@ -0,0 +1,27 @@ +use photocraft_compose::Buffer; +use photocraft_geom::Rect; +use photocraft_raster::scratch; + +/// Restores idle release even when an assertion fails. +struct IdleReleaseOff; +impl Drop for IdleReleaseOff { + fn drop(&mut self) { + scratch::release(); + scratch::set_idle_release(true); + } +} + +/// Runs in its own binary so other compositor tests cannot consume the pooled allocation. +#[test] +fn dropped_buffer_storage_is_reused() { + scratch::set_idle_release(false); + let _idle = IdleReleaseOff; + scratch::release(); + let rect = Rect::from_xywh(0, 0, 256, 256); + let buf = Buffer::transparent(rect); + let ptr = buf.px.as_ptr(); + drop(buf); + let reused = Buffer::transparent(rect); + assert_eq!(reused.px.as_ptr(), ptr); + assert!(reused.px.iter().all(|p| *p == [0.0; 4])); +} diff --git a/crates/engine/examples/indexed_color_perf.rs b/crates/engine/examples/indexed_color_perf.rs index 6dba948ff2a..112f6eb0d9c 100644 --- a/crates/engine/examples/indexed_color_perf.rs +++ b/crates/engine/examples/indexed_color_perf.rs @@ -25,7 +25,7 @@ fn main() -> Result<(), Box> { let path = std::env::args().nth(1).ok_or("provide a local image path")?; let bytes = photocraft_format::read::read_file(std::path::Path::new(&path))?; let doc = photocraft_io::import(&path, &bytes)?.document; - let px = photocraft_compose::flatten(&doc).px; + let px = photocraft_compose::flatten(&doc).into_px(); println!("{}", json!({"width":doc.size.width,"height":doc.size.height,"preview_factor":1})); for count in [8usize, 16, 32, 64, 128, 256] { for run in 0..4 { diff --git a/crates/engine/src/cmd/adjust_cmds.rs b/crates/engine/src/cmd/adjust_cmds.rs index 39ab43c7a62..f5301979dc5 100644 --- a/crates/engine/src/cmd/adjust_cmds.rs +++ b/crates/engine/src/cmd/adjust_cmds.rs @@ -459,9 +459,9 @@ fn stats_pixels(doc: &Document, layer: Option, use_selection: bool) -> Resu let px: Vec<[f32; 4]> = match layer { Some(id) => { let l = doc.layer(photocraft_doc::LayerId(id)).ok_or(EngineError::NoLayer(photocraft_doc::LayerId(id)))?; - photocraft_compose::render_layer(l, area).px + photocraft_compose::render_layer(l, area).into_px() } - None => photocraft_compose::flatten(doc).px, + None => photocraft_compose::flatten(doc).into_px(), }; let mask = doc.selection.as_ref().filter(|_| use_selection).map(|sel| photocraft_algo::selection::mask_from_surface(Some(sel), area)); Ok((px, mask)) @@ -521,7 +521,7 @@ fn hdr_toning(s: &mut Session, p: &Value) -> Result { s.edit("HDR Toning", |doc, active| { let buf = photocraft_compose::flatten(doc).over_background([1.0, 1.0, 1.0]); let (w, hgt) = (buf.rect.width() as usize, buf.rect.height() as usize); - let mut px = buf.px; + let mut px = buf.into_px(); tone::hdr_toning(&mut px, w, hgt, &h); let fmt = doc.pixel_format(); let data: Vec = px.iter().flat_map(|q| photocraft_raster::from_rgba(&fmt, *q)).collect(); diff --git a/crates/engine/src/cmd/adjust_cmds/tests.rs b/crates/engine/src/cmd/adjust_cmds/tests.rs index d60fa26d105..51843ae0226 100644 --- a/crates/engine/src/cmd/adjust_cmds/tests.rs +++ b/crates/engine/src/cmd/adjust_cmds/tests.rs @@ -480,7 +480,7 @@ fn smart_session() -> Session { } fn flatten(s: &Session) -> Vec<[f32; 4]> { - photocraft_compose::flatten(doc(s)).px + photocraft_compose::flatten(doc(s)).into_px() } fn max_diff(a: &[[f32; 4]], b: &[[f32; 4]]) -> f32 { diff --git a/crates/engine/src/cmd/face_cmds.rs b/crates/engine/src/cmd/face_cmds.rs index d48df95b845..0ae0af3d356 100644 --- a/crates/engine/src/cmd/face_cmds.rs +++ b/crates/engine/src/cmd/face_cmds.rs @@ -36,7 +36,7 @@ pub fn faces_in(doc: &Document, active: Option, all_layers: bool, min_s surf.read_rgba_into(area, &mut px); px } - None => photocraft_compose::render(doc, area).px, + None => photocraft_compose::render(doc, area).into_px(), }; let found = detect(&px, w, h, min_score)?; let (x0, y0) = (area.x0 as f32, area.y0 as f32); diff --git a/crates/engine/src/cmd/layer_menu_cmds.rs b/crates/engine/src/cmd/layer_menu_cmds.rs index 34a1f914eec..75701d9ddd8 100644 --- a/crates/engine/src/cmd/layer_menu_cmds.rs +++ b/crates/engine/src/cmd/layer_menu_cmds.rs @@ -230,7 +230,7 @@ fn mask_all_objects(s: &mut Session, p: &Value) -> Result { struct Composite<'a>(&'a Document); impl photocraft_algo::segment::Sampler for Composite<'_> { fn rgba(&self, r: Rect) -> Vec<[f32; 4]> { - photocraft_compose::render(self.0, r).px + photocraft_compose::render(self.0, r).into_px() } } photocraft_algo::segment::subject::select_subject(&Composite(&doc), doc.bounds()) diff --git a/crates/engine/src/cmd/layer_menu_cmds/tests.rs b/crates/engine/src/cmd/layer_menu_cmds/tests.rs index 702d65891bf..62522ccc39b 100644 --- a/crates/engine/src/cmd/layer_menu_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_menu_cmds/tests.rs @@ -757,11 +757,11 @@ fn applying_a_feathered_mask_preserves_its_soft_composite() { Ok(()) }) .unwrap(); - let before = photocraft_compose::flatten(doc(&s)).px; + let before = photocraft_compose::flatten(doc(&s)).into_px(); assert!(before[15 * 40 + 19][3] > 0.0 && before[15 * 40 + 19][3] < 1.0, "mask must start with a soft edge"); s.execute("layer.layerMask.apply", json!({})).unwrap(); assert!(active(&s).mask.is_none(), "Apply removes the pixel mask"); - let after = photocraft_compose::flatten(doc(&s)).px; + let after = photocraft_compose::flatten(doc(&s)).into_px(); for (a, b) in before.iter().zip(&after) { assert!((a[3] - b[3]).abs() <= 1.0 / 255.0 + 1e-5, "depth {depth}: alpha {a:?} became {b:?}"); } @@ -791,13 +791,13 @@ fn from_transparency_preserves_mask_coverage_outside_the_canvas() { for depth in DEPTHS { let mut s = session(depth, "rgb"); paint(&mut s, |_, _| [1.0, 0.0, 0.0, 0.5]); - let before = photocraft_compose::flatten(doc(&s)).px; + let before = photocraft_compose::flatten(doc(&s)).into_px(); s.execute("layer.translate", json!({"dx": 20})).unwrap(); s.execute("layer.layerMask.fromTransparency", json!({})).unwrap(); let mask = active(&s).mask.as_ref().unwrap(); assert!((mask.value(50, 10) - 0.5).abs() < 1.0 / 255.0 + 1e-6, "off-canvas mask at depth {depth}"); s.execute("layer.translate", json!({"dx": -20})).unwrap(); - let after = photocraft_compose::flatten(doc(&s)).px; + let after = photocraft_compose::flatten(doc(&s)).into_px(); for (a, b) in before.iter().zip(&after) { assert!((a[3] - b[3]).abs() <= 1.0 / 255.0 + 1e-6, "alpha changed at depth {depth}: {a:?} -> {b:?}"); } diff --git a/crates/engine/src/cmd/mask_view_cmds/tests.rs b/crates/engine/src/cmd/mask_view_cmds/tests.rs index ce9bffa7446..82179a5456b 100644 --- a/crates/engine/src/cmd/mask_view_cmds/tests.rs +++ b/crates/engine/src/cmd/mask_view_cmds/tests.rs @@ -44,7 +44,7 @@ fn modes_toggle_and_show_in_inspect_without_history() { fn a_mask_view_never_alters_pixels() { let (mut s, masked, _) = session(); let before = s.active().unwrap().doc.clone(); - let px = |s: &Session| photocraft_compose::render(&s.active().unwrap().doc, Rect::new(0, 0, 40, 20)).px; + let px = |s: &Session| photocraft_compose::render(&s.active().unwrap().doc, Rect::new(0, 0, 40, 20)).into_px(); let composite = px(&s); for mode in ["gray", "overlay", "toggleOverlay", "toggleGray", "off"] { s.execute(ID, json!({"layer": masked, "mode": mode})).unwrap(); diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index ac30023d92b..3043f080e6f 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -186,7 +186,7 @@ fn with_released_movement_locks(l: &mut Layer, f: impl FnOnce(&mut Layer) -> /// The flattened image as straight RGBA (over white when `opaque`). fn composite(doc: &Document, opaque: bool) -> Vec<[f32; 4]> { let buf = photocraft_compose::flatten(doc); - if opaque { buf.over_background([1.0, 1.0, 1.0]).px } else { buf.px } + if opaque { buf.over_background([1.0, 1.0, 1.0]).into_px() } else { buf.into_px() } } /// Replace the document's layers by one 8-bit layer holding `px` in `mode`'s storage format. diff --git a/crates/engine/src/cmd/mode_cmds/tests.rs b/crates/engine/src/cmd/mode_cmds/tests.rs index 0d3f9b3cea1..4d3c97b02b6 100644 --- a/crates/engine/src/cmd/mode_cmds/tests.rs +++ b/crates/engine/src/cmd/mode_cmds/tests.rs @@ -568,7 +568,7 @@ fn bitmap_budgets_a_conversion_at_the_document_resolution_too() { /// The Bitmap conversion of `d` the pre-#8477 way, from one full-canvas composite over white. fn bitmap_oracle(d: &Document, method: Option, custom: Option<(&[f32], usize, usize)>) -> Vec { - let px = photocraft_compose::flatten(d).over_background([1.0; 3]).px; + let px = photocraft_compose::flatten(d).over_background([1.0; 3]).into_px(); let mut gray: Vec = px.iter().map(|q| photocraft_color::convert::rgb_to_gray([q[0], q[1], q[2]])).collect(); let w = d.size.width as usize; match (method, custom) { @@ -730,7 +730,7 @@ fn duotone_to_colour_modes_keeps_the_ink_colours() { s.execute("image.mode.duotone", cfg.clone()).unwrap(); let before = s.active().unwrap().doc.clone(); let gray: Vec = (0..16).map(|x| before.layers[0].surface().unwrap().pixel(x, 1)[0]).collect(); - let shown = photocraft_compose::render(&display_document(&before).unwrap(), Rect::from_xywh(0, 1, 16, 1)).px; + let shown = photocraft_compose::render(&display_document(&before).unwrap(), Rect::from_xywh(0, 1, 16, 1)).into_px(); s.execute(&format!("image.mode.{mode}"), json!({})).unwrap(); let d = doc(&s); assert!(d.duotone.is_none(), "{ctx}"); diff --git a/crates/engine/src/cmd/select_extra_cmds.rs b/crates/engine/src/cmd/select_extra_cmds.rs index 8ca012266dd..9fd7b309cc2 100644 --- a/crates/engine/src/cmd/select_extra_cmds.rs +++ b/crates/engine/src/cmd/select_extra_cmds.rs @@ -40,7 +40,7 @@ struct CompositeSampler<'a>(&'a Document); impl Sampler for CompositeSampler<'_> { fn rgba(&self, r: Rect) -> Vec<[f32; 4]> { - photocraft_compose::render(self.0, r).px + photocraft_compose::render(self.0, r).into_px() } } diff --git a/crates/engine/src/cmd/selection_cmds.rs b/crates/engine/src/cmd/selection_cmds.rs index e8d206285e8..024f6b088bd 100644 --- a/crates/engine/src/cmd/selection_cmds.rs +++ b/crates/engine/src/cmd/selection_cmds.rs @@ -70,7 +70,7 @@ fn sample_pixels(s: &Session, all_layers: bool, window: Option) -> Result< surf.read_rgba_into(area, &mut px); Ok((area, px)) } - _ => Ok((area, photocraft_compose::render(&d.doc, area).px)), + _ => Ok((area, photocraft_compose::render(&d.doc, area).into_px())), } } diff --git a/crates/engine/src/cmd/smart_cmds/rendering.rs b/crates/engine/src/cmd/smart_cmds/rendering.rs index 907c7d6947f..ab862d5545f 100644 --- a/crates/engine/src/cmd/smart_cmds/rendering.rs +++ b/crates/engine/src/cmd/smart_cmds/rendering.rs @@ -39,7 +39,7 @@ pub fn stack_image(file_name: &str, bytes: &[u8], fmt: PixelFormat, mode: photoc let mut one = l.clone(); one.blend = BlendMode::Normal; one.clipped = false; - photocraft_compose::render_layer(&one, bounds).px + photocraft_compose::render_layer(&one, bounds).into_px() }) .collect(); if frames.is_empty() { diff --git a/crates/engine/src/cmd/smart_cmds/tests.rs b/crates/engine/src/cmd/smart_cmds/tests.rs index d6306f0d188..6e8ce37f9cd 100644 --- a/crates/engine/src/cmd/smart_cmds/tests.rs +++ b/crates/engine/src/cmd/smart_cmds/tests.rs @@ -110,7 +110,7 @@ fn paint(s: &mut Session) { } fn flat(s: &Session) -> Vec<[f32; 4]> { - photocraft_compose::flatten(&s.active().unwrap().doc).px + photocraft_compose::flatten(&s.active().unwrap().doc).into_px() } fn max_diff(a: &[[f32; 4]], b: &[[f32; 4]]) -> f32 { diff --git a/crates/engine/src/cmd/smartselect_cmds.rs b/crates/engine/src/cmd/smartselect_cmds.rs index c04df742a8e..adbf9b5f467 100644 --- a/crates/engine/src/cmd/smartselect_cmds.rs +++ b/crates/engine/src/cmd/smartselect_cmds.rs @@ -49,7 +49,7 @@ struct CompositeSampler<'a>(&'a Document); impl Sampler for CompositeSampler<'_> { fn rgba(&self, r: Rect) -> Vec<[f32; 4]> { - photocraft_compose::render(self.0, r).px + photocraft_compose::render(self.0, r).into_px() } } diff --git a/crates/engine/src/cmd/transform_cmds/tests.rs b/crates/engine/src/cmd/transform_cmds/tests.rs index e9ed16f2453..7bf247466b7 100644 --- a/crates/engine/src/cmd/transform_cmds/tests.rs +++ b/crates/engine/src/cmd/transform_cmds/tests.rs @@ -366,7 +366,7 @@ fn off_from_fresh(s: &Session) -> f32 { let st = s.active().unwrap(); let mut fresh: Document = (*st.doc).clone(); fresh.layer_mut(st.active_layer.unwrap()).unwrap().fill_cache = None; - let (a, b) = (photocraft_compose::render(&st.doc, st.doc.bounds()).px, photocraft_compose::render(&fresh, fresh.bounds()).px); + let (a, b) = (photocraft_compose::render(&st.doc, st.doc.bounds()).into_px(), photocraft_compose::render(&fresh, fresh.bounds()).into_px()); a.iter().zip(&b).flat_map(|(p, q)| p.iter().zip(q).map(|(x, y)| (x - y).abs())).fold(0.0, f32::max) } diff --git a/crates/engine/src/cmd/video_cmds/tests.rs b/crates/engine/src/cmd/video_cmds/tests.rs index 66566bdb7da..d08135f60e1 100644 --- a/crates/engine/src/cmd/video_cmds/tests.rs +++ b/crates/engine/src/cmd/video_cmds/tests.rs @@ -229,7 +229,7 @@ fn animated_gif_keeps_transparency() { // Each frame has a transparent index and is cleared before the next (disposal 2). let packed: Vec = gif.windows(4).filter(|w| w[..3] == [0x21, 0xF9, 0x04]).map(|w| w[3]).collect(); assert_eq!(packed, [0x09, 0x09]); - let px = photocraft_compose::flatten(&photocraft_io::import("t.gif", &gif).unwrap().document).px; + let px = photocraft_compose::flatten(&photocraft_io::import("t.gif", &gif).unwrap().document).into_px(); assert_eq!(px[0][3], 0.0, "the corner stays transparent"); assert_eq!(px[3 * 8 + 3], [1.0, 0.0, 0.0, 1.0], "the square stays red"); } diff --git a/crates/engine/src/color_channels/tone.rs b/crates/engine/src/color_channels/tone.rs index 97d6e8f7b27..c64b1debba6 100644 --- a/crates/engine/src/color_channels/tone.rs +++ b/crates/engine/src/color_channels/tone.rs @@ -61,7 +61,7 @@ pub(super) fn adjust(surface: &mut Surface, colors: ColorChannels, adjustment: & .collect(), }; adjust::apply_in(&scalar, &mut buf, transfer, depth, mode); - Arc::new(IntegerTable { adjusted: buf.px.into_iter().map(|p| p[0]).collect(), encoded: Vec::new() }) + Arc::new(IntegerTable { adjusted: buf.px.iter().map(|p| p[0]).collect(), encoded: Vec::new() }) }) }); let mut component = Component { index, scalar, table, lab_invert }; diff --git a/crates/engine/src/doc_path/tests.rs b/crates/engine/src/doc_path/tests.rs index 1c9bc888745..049e126a47e 100644 --- a/crates/engine/src/doc_path/tests.rs +++ b/crates/engine/src/doc_path/tests.rs @@ -157,7 +157,7 @@ fn replayed(s: &mut Session, id: LayerId, params: serde_json::Value) -> Vec<[f32 }) .unwrap(); let doc = &s.active().unwrap().doc; - photocraft_compose::render(doc, doc.bounds()).px + photocraft_compose::render(doc, doc.bounds()).into_px() } #[test] @@ -202,12 +202,12 @@ fn smart_displace_keeps_a_relative_map_path() { png(&d.join("map.png"), |_| [255, 255, 255]); let (mut s, id) = document(&d, &d.join("ramp.png")); let path = d.join("map.png").to_string_lossy().into_owned(); - let unfiltered = photocraft_compose::render(&s.active().unwrap().doc, s.active().unwrap().doc.bounds()).px; + let unfiltered = photocraft_compose::render(&s.active().unwrap().doc, s.active().unwrap().doc.bounds()).into_px(); s.execute("filter.distort.displace", json!({"layer": id.0, "mapPath": path, "horizontal": 50, "vertical": 0})).unwrap(); let state = |s: &Session| { let doc = &s.active().unwrap().doc; let Some(LayerContent::Smart(sm)) = doc.layer(id).map(|l| &l.content) else { panic!("a smart object") }; - (sm.smart_filters[0].params.clone(), photocraft_compose::render(doc, doc.bounds()).px) + (sm.smart_filters[0].params.clone(), photocraft_compose::render(doc, doc.bounds()).into_px()) }; let (params, displaced) = state(&s); assert_eq!(params["mapPath"], json!(path)); diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs index aebee03caf8..2bcccb7a5ca 100644 --- a/crates/engine/src/filters.rs +++ b/crates/engine/src/filters.rs @@ -397,6 +397,8 @@ pub(crate) fn keep_alpha(old: &photocraft_raster::Surface, new: &mut photocraft_ } } s.write_region(*r, &v); + photocraft_raster::scratch::give(o); + photocraft_raster::scratch::give(v); true }) .reduce(|| true, |a, b| a && b); diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index ac9e38a7231..5ebe45599c8 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -277,6 +277,16 @@ impl Running { } } +/// A cancelled job's worker that may still be unwinding. +#[cfg(not(target_arch = "wasm32"))] +struct Draining { + handle: std::thread::JoinHandle<()>, + doc: Option, + /// Its document closed: the worker still holds that document's snapshot, so the scratch + /// pool is released again once it exits (the release at close came too early, #10479). + release: bool, +} + /// The session's job table (see the module docs). #[derive(Default)] pub struct Jobs { @@ -292,7 +302,7 @@ pub struct Jobs { recent: Vec, /// Workers of cancelled jobs that may still be unwinding (native). #[cfg(not(target_arch = "wasm32"))] - draining: Vec>, + draining: Vec, /// The context inline job work runs under (see [`Session::set_inline_job_ctx`]). inline: Option, } @@ -673,7 +683,17 @@ impl Session { } } #[cfg(not(target_arch = "wasm32"))] - self.jobs.draining.retain(|h| !h.is_finished()); + { + let mut release = false; + self.jobs.draining.retain(|d| { + let done = d.handle.is_finished(); + release |= done && d.release; + !done + }); + if release { + photocraft_raster::scratch::release(); + } + } std::mem::take(&mut self.jobs.events) } @@ -706,8 +726,8 @@ impl Session { job.ctx.cancel(); self.end_job(&job, JobOutcome::Cancelled); #[cfg(not(target_arch = "wasm32"))] - if let Some(h) = job.handle { - self.jobs.draining.push(h); + if let Some(handle) = job.handle { + self.jobs.draining.push(Draining { handle, doc: job.doc, release: false }); } true } @@ -754,8 +774,15 @@ impl Session { /// cancel latency with it). Native only; returns at once on wasm. pub fn join_cancelled_jobs(&mut self) { #[cfg(not(target_arch = "wasm32"))] - for h in self.jobs.draining.drain(..) { - let _ = h.join(); + { + let mut release = false; + for d in self.jobs.draining.drain(..) { + let _ = d.handle.join(); + release |= d.release; + } + if release { + photocraft_raster::scratch::release(); + } } } @@ -774,6 +801,11 @@ impl Session { for id in ids { self.cancel_job(id); } + // Workers cancelled now, or earlier and still unwinding, hold the closing document. + #[cfg(not(target_arch = "wasm32"))] + for d in self.jobs.draining.iter_mut().filter(|d| d.doc == Some(doc)) { + d.release = true; + } } /// Run the command `id`: inline, or (with `background`) as a job when it is one. @@ -857,6 +889,7 @@ impl Session { // being recorded, nor move the recording mark past the entries it is about to replace. let recording = if spec.journal && crate::actions_cmds::replayable(id) { self.actions.recording.take() } else { None }; let before = self.active().map(|st| st.doc.clone()); + let docs_before: Vec<_> = self.docs.iter().map(|st| st.doc.id).collect(); // Last-resort guard (AGENTS.md, Never crash): a command that panics anyway fails with an // error instead of taking the app down. `edit` only commits a document after its closure // returns, so the documents are unchanged. @@ -876,7 +909,7 @@ impl Session { self.hint_before = None; } let pending = self.jobs.pending.take(); - match (r, pending) { + let out = match (r, pending) { (Err(e), Some(job)) => { job.ctx.cancel(); Err(e) @@ -893,8 +926,8 @@ impl Session { Ok(Started::Job(jid)) } (Ok(v), None) => { - if let Some(before) = before { - self.add_relayout_damage(&before); + if let Some(before) = &before { + self.add_relayout_damage(before); } if let Some((doc_id, layer_id)) = new_fx_target && let Some(st) = self.active_mut() @@ -910,7 +943,15 @@ impl Session { self.after_command(id, params, spec.journal, Some(nested_from), pre_selected.as_deref()); Ok(Started::Done(v)) } + }; + // A closed document's freed buffers went to the scratch pool (`before` kept the active + // one alive until here): hand them back to the OS (#10479). Compared by id, since Split + // and Merge Channels close documents while opening others. + if docs_before.iter().any(|id| !self.docs.iter().any(|st| st.doc.id == *id)) { + drop(before); + photocraft_raster::scratch::release(); } + out } /// Grows the damage a command reported for the pixels it changed by what effects laid out diff --git a/crates/engine/src/pixels.rs b/crates/engine/src/pixels.rs index 906f0b23c62..f95a3feb0dd 100644 --- a/crates/engine/src/pixels.rs +++ b/crates/engine/src/pixels.rs @@ -115,6 +115,7 @@ pub fn adjust_surface(s: &mut Surface, adj: &Adjustment, selection: Option<&Surf let tr = tc.rect().intersect(&r); let out = adjusted(&one, tr, adj, selection, mode); one.write_region(tr, &out); + photocraft_raster::scratch::give(out); one.take_tiles(tc.rect()) }) .collect(); @@ -184,6 +185,7 @@ pub(crate) fn adjust_mask_with_transfer( for t in &tiles { let out = adjusted_with_transfer(s, *t, adj, Some(sel), mode, transfer); s.write_region(*t, &out); + photocraft_raster::scratch::give(out); } if !tiles.is_empty() { s.prune(); @@ -197,7 +199,9 @@ pub(crate) fn adjust_mask_with_transfer( // So only the stored tiles are adjusted, not the (possibly huge) rectangle around them. let stored: Vec = s.tiles().map(|(c, _)| c.rect()).collect(); for r in stored { - out.write_region(r, &adjusted_with_transfer(s, r, adj, None, mode, transfer)); + let data = adjusted_with_transfer(s, r, adj, None, mode, transfer); + out.write_region(r, &data); + photocraft_raster::scratch::give(data); } out.prune(); *s = out; @@ -233,7 +237,10 @@ fn adjusted_with_transfer( } let n = fmt.channels(); let raw = s.read_region(r); - let mut buf = Buffer { rect: r, px: raw.chunks_exact(n).map(|p| to_rgba(&fmt, p)).collect() }; + let mut px = photocraft_raster::scratch::take_cap(raw.len() / n.max(1)); + px.extend(raw.chunks_exact(n).map(|p| to_rgba(&fmt, p))); + photocraft_raster::scratch::give(raw); + let mut buf = Buffer { rect: r, px }; let orig = buf.clone(); // 32-bit documents get the float behaviour of an adjustment layer there (Levels doesn't clip); // integer depths keep the unrounded, clipped curves, except that 16-bit Posterize and @@ -311,7 +318,7 @@ pub(crate) fn mix_through_selection( selection: Option<&Surface>, ) -> Vec { let w = (r.width() as usize).max(1); - let mut out = Vec::with_capacity(orig.len() * fmt.channels()); + let mut out = photocraft_raster::scratch::take_cap(orig.len() * fmt.channels()); // The selection's coverage (channel 0) one row at a time, each of its tiles looked up once // per row rather than once per pixel. let mut coverage = vec![1.0f32; w]; diff --git a/crates/engine/src/select_mask_edits.rs b/crates/engine/src/select_mask_edits.rs index 9fd29a2757d..4285491eb7b 100644 --- a/crates/engine/src/select_mask_edits.rs +++ b/crates/engine/src/select_mask_edits.rs @@ -239,7 +239,9 @@ fn invert(base: Option<&Surface>, canvas: Rect) -> Option { if r.is_empty() { continue; } - let inverted: Vec = b.read_region(r).chunks_exact(ch).map(|px| 1.0 - px.first().copied().unwrap_or(0.0).clamp(0.0, 1.0)).collect(); + let read = b.read_region(r); + let inverted: Vec = read.chunks_exact(ch).map(|px| 1.0 - px.first().copied().unwrap_or(0.0).clamp(0.0, 1.0)).collect(); + photocraft_raster::scratch::give(read); s.write_region(r, &inverted); } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index bae9cf4c92b..30c2e32f599 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -814,7 +814,7 @@ fn fill_layer_pixel_rewrites_refresh_the_effect_maps() { .unwrap(); let render = |s: &Session| { let d = &s.active().unwrap().doc; - photocraft_compose::render(d, d.bounds()).px + photocraft_compose::render(d, d.bounds()).into_px() }; // Give the layer the cached-pixels state a PSD import produces (the cache is what Image // › Transform & friends rewrite in place, without touching the Fill spec). @@ -901,7 +901,7 @@ fn group_effect_maps_follow_child_visibility_and_opacity() { .unwrap(); let render = |s: &Session| { let d = &s.active().unwrap().doc; - photocraft_compose::render(d, d.bounds()).px + photocraft_compose::render(d, d.bounds()).into_px() }; let mut prev = render(&s); // populate the effect-map cache type Edit = (&'static str, fn(&mut photocraft_doc::Layer)); diff --git a/crates/engine/tests/it/atn_crystallize_cell_size.rs b/crates/engine/tests/it/atn_crystallize_cell_size.rs index 7b72a6ff70f..8a015f1497d 100644 --- a/crates/engine/tests/it/atn_crystallize_cell_size.rs +++ b/crates/engine/tests/it/atn_crystallize_cell_size.rs @@ -24,7 +24,7 @@ fn fixture(depth: u32) -> Session { /// Compare the actual flattened document rather than just the imported parameters. fn pixels(s: &Session) -> Vec<[f32; 4]> { - photocraft_compose::flatten(&s.active().unwrap().doc).px + photocraft_compose::flatten(&s.active().unwrap().doc).into_px() } /// Fractions remain valid native edits; strict integer ATN conversion must refuse them. diff --git a/crates/engine/tests/it/atn_ripple_amount.rs b/crates/engine/tests/it/atn_ripple_amount.rs index b6bde88f7a4..0ff38f2036c 100644 --- a/crates/engine/tests/it/atn_ripple_amount.rs +++ b/crates/engine/tests/it/atn_ripple_amount.rs @@ -24,7 +24,7 @@ fn fixture(depth: u32) -> Session { /// Flatten the active document to compare direct, native and ATN playback pixels. fn pixels(s: &Session) -> Vec<[f32; 4]> { - photocraft_compose::flatten(&s.active().unwrap().doc).px + photocraft_compose::flatten(&s.active().unwrap().doc).into_px() } /// Fractions are valid native edits, but the existing integer event cannot carry them. diff --git a/crates/engine/tests/it/atn_selective_color.rs b/crates/engine/tests/it/atn_selective_color.rs index 454846f59e0..92a23aff5e6 100644 --- a/crates/engine/tests/it/atn_selective_color.rs +++ b/crates/engine/tests/it/atn_selective_color.rs @@ -37,7 +37,7 @@ fn doc_bounds() -> photocraft_doc::Rect { } fn pixels(s: &Session) -> Vec<[f32; 4]> { - photocraft_compose::flatten(&s.active().unwrap().doc).px + photocraft_compose::flatten(&s.active().unwrap().doc).into_px() } fn check_cases(id: &str, cases: &[Value], require_effect: bool) { diff --git a/crates/engine/tests/it/atn_stroke_width.rs b/crates/engine/tests/it/atn_stroke_width.rs index 742359cf386..3034fb2f0a4 100644 --- a/crates/engine/tests/it/atn_stroke_width.rs +++ b/crates/engine/tests/it/atn_stroke_width.rs @@ -23,7 +23,7 @@ fn fixture(depth: u32) -> Session { /// Compare the flattened document, including alpha, rather than only imported JSON. fn pixels(s: &Session) -> Vec<[f32; 4]> { - photocraft_compose::flatten(&s.active().unwrap().doc).px + photocraft_compose::flatten(&s.active().unwrap().doc).into_px() } /// Direct execution, native playback and strict binary ATN playback must agree exactly. diff --git a/crates/engine/tests/it/photoshop_oracles.rs b/crates/engine/tests/it/photoshop_oracles.rs index 88e63b67fcd..435bab8cc17 100644 --- a/crates/engine/tests/it/photoshop_oracles.rs +++ b/crates/engine/tests/it/photoshop_oracles.rs @@ -124,7 +124,7 @@ fn photoshop_oracles_rerendered() { } }; let Ok(merged) = photocraft_io::merged_composite(&file) else { continue }; - let ours = photocraft_compose::flatten(&doc).px; + let ours = photocraft_compose::flatten(&doc).into_px(); let (m, bad) = max_diff(&ours, &merged); let group = name.split(['/', '\\']).next().unwrap_or(".").to_string(); let g = groups.entry(group).or_default(); diff --git a/crates/engine/tests/scratch_release.rs b/crates/engine/tests/scratch_release.rs new file mode 100644 index 00000000000..6976f0cb7f0 --- /dev/null +++ b/crates/engine/tests/scratch_release.rs @@ -0,0 +1,114 @@ +//! One integration-test process keeps the process-wide scratch pool isolated from parallel unit +//! tests (#10479). +use photocraft_engine::Session; +use photocraft_engine::jobs::Started; +use photocraft_raster::scratch; +use serde_json::json; +use std::sync::{Mutex, PoisonError}; + +static SERIAL: Mutex<()> = Mutex::new(()); + +/// Holds the test lock with the pool's idle release off, so a slow runner can't empty the pool +/// between a command and the check after it; the release comes back on when dropped. +struct Quiet { + _serial: std::sync::MutexGuard<'static, ()>, +} + +impl Quiet { + /// Locks the test process and disables idle pool release for this guard's lifetime. + fn new() -> Self { + let _serial = SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + scratch::set_idle_release(false); + Quiet { _serial } + } +} + +impl Drop for Quiet { + fn drop(&mut self) { + scratch::set_idle_release(true); + } +} + +#[test] +/// Verifies closing one or all documents releases their scratch buffers. +fn closing_a_document_leaves_none_of_its_buffers_in_the_pool() { + let _q = Quiet::new(); + for close in ["file.close", "file.closeAll"] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1024, "height": 1024})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap(); + s.execute("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap(); + // Dispatch holds the active document across the command; its tiles must not land in + // the pool after the release. + s.execute(close, json!({})).unwrap(); + assert_eq!(scratch::retained_bytes(), 0, "{close}"); + } +} + +#[test] +/// Verifies a command that keeps its document does not release unrelated pooled buffers. +fn commands_that_keep_their_documents_keep_the_pool() { + let _q = Quiet::new(); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1024, "height": 1024})).unwrap(); + scratch::give(vec![0u8; scratch::MIN_POOLED_BYTES]); + s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap(); + assert!(scratch::retained_bytes() > 0); +} + +#[test] +/// Verifies a cancelled worker releases its document buffers after it exits. +fn a_cancelled_job_of_a_closed_document_returns_its_buffers_once_it_exits() { + let _q = Quiet::new(); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 2048, "height": 2048})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap(); + let Started::Job(_) = s.start("filter.blur.gaussianBlur", json!({"radius": 60})).unwrap() else { + panic!("Gaussian Blur runs as a background job"); + }; + // Closing cancels the job, but its worker still holds the document until it exits. + s.close(0); + scratch::give(vec![0u8; scratch::MIN_POOLED_BYTES]); + s.join_cancelled_jobs(); + assert_eq!(scratch::retained_bytes(), 0); +} + +#[test] +/// Verifies cancelling a job before document close still releases its buffers. +fn a_job_cancelled_before_its_document_closes_still_returns_its_buffers() { + let _q = Quiet::new(); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 2048, "height": 2048})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap(); + let Started::Job(id) = s.start("filter.blur.gaussianBlur", json!({"radius": 60})).unwrap() else { + panic!("Gaussian Blur runs as a background job"); + }; + // Cancelled first: the worker is already off the running list when the document closes. + assert!(s.cancel_job(id)); + s.close(0); + scratch::give(vec![0u8; scratch::MIN_POOLED_BYTES]); + s.join_cancelled_jobs(); + assert_eq!(scratch::retained_bytes(), 0); +} + +/// Verifies polling alone releases buffers after a closed document's cancelled worker exits. +#[test] +fn a_cancelled_job_of_a_closed_document_is_released_by_polling() { + let _q = Quiet::new(); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 2048, "height": 2048})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap(); + let Started::Job(_) = s.start("filter.blur.gaussianBlur", json!({"radius": 60})).unwrap() else { + panic!("Gaussian Blur runs as a background job"); + }; + s.close(0); + // Seed after close so the close path cannot satisfy the assertion. + scratch::give(vec![0u8; scratch::MIN_POOLED_BYTES]); + assert!(scratch::retained_bytes() > 0); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while scratch::retained_bytes() > 0 && std::time::Instant::now() < deadline { + s.poll_jobs(); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(scratch::retained_bytes(), 0); +} diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index af6678088b9..67bb8df27bb 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -30,8 +30,87 @@ fn blob_path(h: &str) -> String { format!("blobs/{h}.zst") } -fn compress(data: &[u8]) -> Vec { - ruzstd::encoding::compress_to_vec(data, ruzstd::encoding::CompressionLevel::Fastest) +/// The bytes an [`Object`] stores, owned by (or shared with) the compressor's source so one +/// [`Compressor`] can be reused for objects of any lifetime. +enum Source { + Tile(Arc), + Blob(Arc>), + /// A little-endian copy of a tile (big-endian hosts only). + Owned(Vec), +} + +struct SourceReader { + source: Source, + pos: usize, +} + +impl SourceReader { + fn all(&self) -> &[u8] { + match &self.source { + Source::Tile(t) => t.bytes(), + Source::Blob(b) => b.as_slice(), + Source::Owned(v) => v.as_slice(), + } + } + + fn len(&self) -> usize { + self.all().len() + } +} + +impl Read for SourceReader { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let all = self.all(); + let rest = all.get(self.pos..).unwrap_or(&[]); + let n = rest.len().min(buf.len()); + if let (Some(dst), Some(src)) = (buf.get_mut(..n), rest.get(..n)) { + dst.copy_from_slice(src); + } + self.pos += n; + Ok(n) + } +} + +/// A reusable zstd compressor. `ruzstd` allocates a block buffer, a ~1 MiB suffix table and a +/// block output buffer per frame; keeping the [`FrameCompressor`](ruzstd::encoding::FrameCompressor) +/// between objects reuses the first two (its matcher resets itself on every `compress`). +/// Output is byte-identical to `compress_to_vec` at the same level. +struct Compressor { + inner: ruzstd::encoding::FrameCompressor, ruzstd::encoding::MatchGeneratorDriver>, +} + +impl Compressor { + fn new() -> Self { + Self { inner: ruzstd::encoding::FrameCompressor::new(ruzstd::encoding::CompressionLevel::Fastest) } + } + + fn run(&mut self, source: Source) -> Vec { + let reader = SourceReader { source, pos: 0 }; + // Room for the worst case (raw blocks: 3 bytes per 128 KiB, plus frame header and + // checksum), so the output never regrows; shrunk afterwards to what it used. Untouched + // pages cost nothing. + let len = reader.len(); + let mut drain = Vec::new(); + if drain.try_reserve_exact(len.saturating_add(len / 16384).saturating_add(64)).is_err() { + drain = Vec::new(); + } + self.inner.set_source(reader); + self.inner.set_drain(drain); + self.inner.compress(); + self.inner.take_source(); + let mut out = self.inner.take_drain().unwrap_or_default(); + out.shrink_to_fit(); + out + } + + fn object(&mut self, obj: &Object) -> Vec { + let source = match obj { + Object::Tile(tile, _) if cfg!(target_endian = "little") => Source::Tile(Arc::clone(tile)), + Object::Tile(tile, sample) => Source::Owned(tile_le(tile, *sample).into_owned()), + Object::Blob(blob) => Source::Blob(Arc::clone(blob)), + }; + self.run(source) + } } /// Decodes a zstd frame of at most `max` bytes (`LimitExceeded` beyond). With `exact`, the @@ -528,8 +607,8 @@ enum Object { } impl Object { - fn compressed(&self) -> Vec { - compress(&self.content()) + fn compressed(&self, compressor: &mut Compressor) -> Vec { + compressor.object(self) } /// The bytes this object stores (tiles little-endian). @@ -860,7 +939,8 @@ type Compressed<'a> = (&'a String, Arc>); fn par_compress<'a>(objects: &[(&'a String, &'a Object)]) -> Result>> { let threads = if cfg!(target_arch = "wasm32") { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get()).clamp(1, 32) }; if threads < 2 || objects.len() < 2 { - return Ok(objects.iter().map(|(p, o)| (*p, Arc::new(o.compressed()))).collect()); + let mut compressor = Compressor::new(); + return Ok(objects.iter().map(|(p, o)| (*p, Arc::new(o.compressed(&mut compressor)))).collect()); } let next = std::sync::atomic::AtomicUsize::new(0); std::thread::scope(|sc| { @@ -868,10 +948,11 @@ fn par_compress<'a>(objects: &[(&'a String, &'a Object)]) -> Result = None; for (path, obj) in &p.objects { let (key, data) = match self.compressed.remove_entry(path) { Some((key, data)) => { @@ -989,7 +1071,7 @@ impl PcraftWriter { Object::Tile(..) => stats.tiles_written += 1, Object::Blob(_) => stats.blobs_written += 1, } - (None, fresh.remove(path).unwrap_or_else(|| Arc::new(obj.compressed()))) + (None, fresh.remove(path).unwrap_or_else(|| Arc::new(obj.compressed(compressor.get_or_insert_with(Compressor::new))))) } }; z.add(path, &data)?; @@ -1036,6 +1118,7 @@ impl PcraftWriter { None => 0, }; let recheck = self.rolling_recheck(&p.objects); + let mut compressor: Option = None; for (path, obj) in &p.objects { let object_path = dir.join(path); // bundle_root and list_objects validated the fixed parent directories once. Check @@ -1070,7 +1153,7 @@ impl PcraftWriter { Object::Tile(..) => stats.tiles_written += 1, Object::Blob(_) => stats.blobs_written += 1, } - write_bundle_file(dir, &object_path, &obj.compressed(), fs)?; + write_bundle_file(dir, &object_path, &obj.compressed(compressor.get_or_insert_with(Compressor::new)), fs)?; let written = path_signature(&object_path)?; if let Some(cache) = &mut self.verified_directory { match written { @@ -1421,6 +1504,38 @@ pub(crate) fn write_atomic(path: &Path, data: &[u8]) -> Result<()> { #[cfg(all(test, windows))] mod durability_tests; +#[cfg(test)] +#[test] +fn reused_compressor_matches_compress_to_vec_and_round_trips() { + let mut state = 0x9e37_79b9_u32; + let mut noise = |n: usize| -> Vec { + (0..n) + .map(|_| { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (state >> 24) as u8 + }) + .collect() + }; + let inputs: Vec> = vec![ + Vec::new(), + vec![7], + b"hello hello hello hello hello".to_vec(), + noise(1000), + (0..300_000u32).map(|i| (i / 7 % 251) as u8).collect(), + noise(300_000), + vec![0; 262_144], + // A repeat after a big one proves the matcher state is reset between objects. + b"hello hello hello hello hello".to_vec(), + ]; + let mut compressor = Compressor::new(); + for data in inputs { + let expected = ruzstd::encoding::compress_to_vec(data.as_slice(), ruzstd::encoding::CompressionLevel::Fastest); + let got = compressor.object(&Object::Blob(Arc::new(data.clone()))); + assert_eq!(got, expected, "len {}", data.len()); + assert_eq!(decompress(&got, data.len(), "test").unwrap(), data); + } +} + #[cfg(test)] #[test] fn an_incompressible_blob_at_its_limit_still_loads() { @@ -1442,7 +1557,7 @@ fn an_incompressible_blob_at_its_limit_still_loads() { x as u8 }) .collect(); - let z = compress(&data); + let z = Compressor::new().object(&Object::Blob(Arc::new(data.clone()))); assert!(z.len() > data.len(), "the fixture must not compress"); let hash = hash_bytes(&data); let src = One(blob_path(&hash), z); diff --git a/crates/gpu/src/convert.rs b/crates/gpu/src/convert.rs index 9dbfc818141..19ad1947652 100644 --- a/crates/gpu/src/convert.rs +++ b/crates/gpu/src/convert.rs @@ -1,6 +1,7 @@ use super::batch::write_tile; use super::textures::{Resident, TexKind}; use super::{Arc, F, HashMap, I, PixelFormat, Rect, SampleType, Surface, TILE_SIZE, Tile, TileCoord, U, fx}; +use photocraft_raster::scratch; /// Distinct tiles converted per parallel batch: bounds the converted bytes held at once (64 tiles /// of a 16-bit page are 32 MiB). @@ -141,6 +142,8 @@ pub(crate) fn convert_tiles( _ => put(t, cs, &bytes.concat()), } } + // The texels are on their way to the GPU: the buffers serve the next batch. + parts.into_iter().for_each(scratch::give); } groups.len() } @@ -157,7 +160,9 @@ pub(crate) fn colour_managed(fmt: &PixelFormat, kind: TexKind) -> bool { /// Tile pixels in the texture's format. `tile = None` gives the default pixel everywhere. pub(crate) fn convert_tile(surface: &Surface, tile: Option<&Arc>, kind: TexKind, c: TileCoord) -> Vec { if let (Some(t), TexKind::Rgba8Direct | TexKind::R8Direct) = (tile, kind) { - return t.bytes().to_vec(); + let mut out = scratch::take_cap(t.bytes().len()); + out.extend_from_slice(t.bytes()); + return out; } let fmt = surface.format(); if let (Some(t), TexKind::Rgba16F) = (tile, kind) @@ -179,7 +184,7 @@ fn convert_rows(surface: &Surface, tile: Option<&Arc>, kind: TexKind, rect Some(_) => surface.read_region(rect), None => surface.default_pixel().repeat(n), }; - let mut out = Vec::with_capacity(n * kind.bytes_per_pixel()); + let mut out = scratch::take_cap(n * kind.bytes_per_pixel()); // The previous pixel and its colour. let mut last: Option<(usize, [f32; 4])> = None; for (i, px) in raw.chunks_exact(ch).enumerate() { @@ -209,6 +214,7 @@ fn convert_rows(surface: &Surface, tile: Option<&Arc>, kind: TexKind, rect TexKind::R32F => out.extend(px[0].to_le_bytes()), } } + scratch::give(raw); out } @@ -229,7 +235,7 @@ pub(crate) fn rgb_gray16_to_f16(fmt: &PixelFormat, bytes: &[u8]) -> Option [u8; 2] { let v = px.get(i * 2..i * 2 + 2).map_or(0, |b| u16::from_ne_bytes([b[0], b[1]])); @@ -261,7 +267,7 @@ pub(crate) fn rgb_gray32_to_f16(fmt: &PixelFormat, bytes: &[u8]) -> Option [u8; 2] { let v = px.get(i * 4..i * 4 + 4).map_or(0.0, |b| f32::from_ne_bytes([b[0], b[1], b[2], b[3]])); diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs index ceff6076864..972ccadbea3 100644 --- a/crates/gpu/src/fx.rs +++ b/crates/gpu/src/fx.rs @@ -427,12 +427,20 @@ fn fields_in_windows( }) } -/// The layer's shape (`compose::layer_shape`) over `r`, in parallel bands. +/// The layer's shape (`compose::layer_shape`) over `r`, in parallel bands. Callers hand the +/// result back with `photocraft_raster::scratch::give` once they have read it. pub(crate) fn shape(doc: &photocraft_doc::Document, layer: &Layer, r: Rect) -> Vec { if r.is_empty() { return Vec::new(); } - par_map(bands(r, BAND), |band| photocraft_compose::layer_shape(doc, layer, band)).concat() + let parts = par_map(bands(r, BAND), |band| photocraft_compose::layer_shape(doc, layer, band)); + let mut shape = photocraft_raster::scratch::take_cap(parts.iter().map(Vec::len).sum()); + // A band can be a pooled mask (Transparency Shapes Layer off): hand each back once copied. + for part in parts { + shape.extend_from_slice(&part); + photocraft_raster::scratch::give(part); + } + shape } /// Write `v` (row-major over `r`) into the region-sized `shape`. diff --git a/crates/gpu/src/fx_passes.rs b/crates/gpu/src/fx_passes.rs index f3f5ce6da36..94721410669 100644 --- a/crates/gpu/src/fx_passes.rs +++ b/crates/gpu/src/fx_passes.rs @@ -60,6 +60,7 @@ impl Compositor { e.region = region; rebuild = false; } + photocraft_raster::scratch::give(v); } if rebuild { let shape = Tex::map(device, "pc_fx_shape", region, MAP32); @@ -108,6 +109,7 @@ impl Compositor { fx::paste(&mut e.shape_cpu, region, damage, &v); e.shape.write_r32(queue, region, damage, &v); staged += v.len() as u64 * 4; + photocraft_raster::scratch::give(v); } // Programs, and the distance fields they read (max reach per field). diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index d22a4515d10..e8ab0b91c4f 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -957,7 +957,7 @@ fn hard_stop_gradients_match_cpu_or_fall_back() { Ok(out) => out, Err(e) => { assert!(e.0.contains("coincident gradient stops"), "{e}"); - photocraft_compose::render(&d, d.bounds()).px + photocraft_compose::render(&d, d.bounds()).into_px() } }; let worst = worst_diff(&cpu.px, &out); diff --git a/crates/io/examples/oracle_diff.rs b/crates/io/examples/oracle_diff.rs index cc4b5aa0de8..13977e1a613 100644 --- a/crates/io/examples/oracle_diff.rs +++ b/crates/io/examples/oracle_diff.rs @@ -34,7 +34,7 @@ fn run_file(path: &str) { println!("mode {:?} depth {:?} layers {} warnings {:?} light {:?}", doc.mode, doc.depth, doc.layer_count(), imp.warnings, doc.global_light); print_layer_details(doc); dump_filter_effects(&file); - let ours = photocraft_compose::flatten(doc).px; + let ours = photocraft_compose::flatten(doc).into_px(); let merged = photocraft_io::merged_composite(&file).unwrap(); compare_modes(doc, &ours, &merged); } @@ -487,7 +487,7 @@ fn corpus_summary(root: &std::path::Path) { return (name, None); } let Ok(merged) = photocraft_io::merged_composite(&file) else { return (name, None) }; - let ours = photocraft_compose::flatten(&imp.document).px; + let ours = photocraft_compose::flatten(&imp.document).into_px(); let mut m = 0.0f32; let mut bad = 0usize; for (a, b) in ours.iter().zip(merged) { diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 8e169bd5563..9863bdf9b0c 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -452,9 +452,16 @@ pub(crate) fn image_surface(img: &Image, target_layout: ChannelLayout, csample: let band = (BAND_BYTES / row.max(1)).max(1); for (i, rows) in img.data().chunks(row.max(1) * band).enumerate() { let n = (rows.len() / row.max(1)) as u32; - let part = Image::from_raw(w, n, img.layout(), img.sample_type(), rows.to_vec())?.convert(target_layout, csample); + // Band buffers cycle through the scratch pool: at this size each fresh one is an + // mmap that gets page-faulted in. + let mut src = photocraft_raster::scratch::take_cap::(rows.len()); + src.extend_from_slice(rows); + let src = Image::from_raw(w, n, img.layout(), img.sample_type(), src)?; + let part = src.convert(target_layout, csample); let y0 = (i * band) as i32; s.write_interleaved(Rect::new(0, y0, w as i32, y0 + n as i32), part.data()); + photocraft_raster::scratch::give(src.into_data()); + photocraft_raster::scratch::give(part.into_data()); } } Ok(s) diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index b3135df1ad4..d9bb69af2cd 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -765,14 +765,14 @@ pub fn merged_composite(file: &PsdFile) -> Result, IoError> { let (doc, _) = psd_to_document(&PsdFile { layer_info, ..file.clone() }); // Multichannel documents keep their channels apart (no layer): composite them. if doc.layers.is_empty() && doc.mode == photocraft_color::ColorMode::Multichannel { - return Ok(photocraft_compose::flatten(&doc).px); + return Ok(photocraft_compose::flatten(&doc).into_px()); } let l = doc.layers.first().ok_or_else(|| IoError::Unsupported("no merged image".into()))?; let s = l.surface().ok_or_else(|| IoError::Unsupported("no merged image".into()))?; // CMYK reads through the file's own profile, as the compositor reads its layers, so a tagged // file's merged image and its composite are compared in the same colours. let cmyk = photocraft_compose::cmyk_space(&doc); - Ok(photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || photocraft_compose::surface_to_buffer(s, doc.bounds()).px)) + Ok(photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || photocraft_compose::surface_to_buffer(s, doc.bounds()).into_px())) } #[cfg(test)] diff --git a/crates/io/src/ora.rs b/crates/io/src/ora.rs index fb7968fbcc3..36ebbc7b0a0 100644 --- a/crates/io/src/ora.rs +++ b/crates/io/src/ora.rs @@ -629,7 +629,7 @@ impl Writer<'_> { LayerContent::Raster(s) => { let r = s.content_bounds(); admit_layer(r)?; - (r, photocraft_compose::surface_to_buffer(s, r).px) + (r, photocraft_compose::surface_to_buffer(s, r).into_px()) } _ => { // Rendered as it shows on its own, before the layer's blending options. @@ -643,7 +643,7 @@ impl Writer<'_> { solo.effects = Default::default(); let r = photocraft_compose::composite_bounds(&solo, canvas).unwrap_or(canvas).intersect(&canvas); admit_layer(r)?; - (r, photocraft_compose::render_layer(&solo, r).px) + (r, photocraft_compose::render_layer(&solo, r).into_px()) } }; if let Some(mask) = layer.mask.as_ref().filter(|m| m.enabled) { diff --git a/crates/io/src/pattern_map.rs b/crates/io/src/pattern_map.rs index 97417b7cc71..0b949a4bdf9 100644 --- a/crates/io/src/pattern_map.rs +++ b/crates/io/src/pattern_map.rs @@ -120,7 +120,9 @@ fn pattern_from_psd(p: &PsdPattern, oom: &mut Option) -> Option crate::pixels::lab16_chroma(&mut bytes, refs.len(), true); } let mut surface = Surface::new(fmt); - if let Err(error) = surface.try_write_interleaved(Rect::new(0, 0, w as i32, h as i32), &bytes) { + let result = surface.try_write_interleaved(Rect::new(0, 0, w as i32, h as i32), &bytes); + photocraft_raster::scratch::give(bytes); + if let Err(error) = result { *oom = Some(error.to_string()); return None; } diff --git a/crates/io/src/pixels.rs b/crates/io/src/pixels.rs index 1ac715984fe..63c6742a1cc 100644 --- a/crates/io/src/pixels.rs +++ b/crates/io/src/pixels.rs @@ -47,7 +47,8 @@ fn invert_sample(bytes: &mut [u8], s: SampleType) { /// are filled with `fill[c]` (a native-endian encoded sample). Channels whose /// `invert[c]` is set are inverted (PSD stores CMYK as `max - ink`). pub fn interleave(planes: &[Option<&[u8]>], fill: &[Vec], n: usize, s: SampleType, invert: &[bool]) -> Vec { - let mut out = vec![0u8; n * planes.len() * s.bytes()]; + // Large results come from (and callers may return them to) the scratch pool. + let mut out = photocraft_raster::scratch::take(n * planes.len() * s.bytes(), 0u8); interleave_into(planes, fill, n, s, invert, &mut out); out } @@ -69,9 +70,7 @@ pub fn try_interleave(planes: &[Option<&[u8]>], fill: &[Vec], n: usize, s: S return Err(PsdError::Invalid("interleave fill has the wrong sample size".into())); } } - let mut out = Vec::new(); - out.try_reserve_exact(len).map_err(|_| PsdError::OutOfMemory("not enough memory to interleave PSD pixels"))?; - out.resize(len, 0); + let mut out = photocraft_raster::scratch::try_take_exact(len, 0u8).ok_or(PsdError::OutOfMemory("not enough memory to interleave PSD pixels"))?; interleave_into(planes, fill, n, s, invert, &mut out); Ok(out) } diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 315744b354e..6086aaf6446 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -223,6 +223,8 @@ impl Ex { let mut bytes = Vec::with_capacity(row_len * h_of(r) * s.format().bytes_per_pixel()); for part in parts { bytes.extend_from_slice(&part); + // Free gathered bands before allocating channel planes below; pooling them here + // retains another layer-sized allocation throughout deinterleave. } if self.fmt.mode == ColorMode::Lab && self.fmt.sample == SampleType::U16 { crate::pixels::lab16_chroma(&mut bytes, self.cc + 1, false); diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 6989941d31a..a70577fb6f0 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -328,6 +328,12 @@ impl Ctx<'_> { self.allocation_failed(format!("layer \"{name}\": {error}")); return Surface::new(self.fmt); } + // The interleaved band goes back to the scratch pool for the next band (and the next + // import): it is a fresh page-faulted mmap otherwise. The decoded planes don't: the + // decoder allocates its own, so pooled ones would only sit there. + drop(refs); + photocraft_raster::scratch::give(bytes); + drop(planes); } surf.prune(); // A white background, a solid fill's cache: one tile per value, shared across layers. @@ -1408,6 +1414,7 @@ fn import_layered(import: DecodedImport<'_>, doc: &mut Document, cx: &mut Ctx<'_ if let Err(error) = surface.try_write_interleaved(canvas, &bytes) { return cx.allocation_failed(format!("merged image: {error}")); } + photocraft_raster::scratch::give(bytes); if alpha_idx.is_some() { let white = photocraft_raster::from_rgba(&fmt, [1.0, 1.0, 1.0, 1.0]); let mut vals = Vec::new(); @@ -1547,6 +1554,7 @@ fn import_extra_channels(import: DecodedImport<'_>, doc: &mut Document, cx: &mut if let Err(error) = s.try_write_interleaved(canvas, &raw) { return cx.allocation_failed(format!("extra channel {idx}: {error}")); } + photocraft_raster::scratch::give(raw); s.prune(); let name = names.get(k).cloned().unwrap_or_else(|| format!("Alpha {}", k + 1)); doc.channels.push(AlphaChannel::new(name, s)); diff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rs index 72adbe1291c..cacce2b7cb3 100644 --- a/crates/io/src/smart_map.rs +++ b/crates/io/src/smart_map.rs @@ -173,6 +173,7 @@ pub fn mask_from_item(item: &FilterEffectsItem, sample: SampleType, stack: &Filt let n = w.checked_mul(h).ok_or("the smart filter mask is too large")?; let bytes = crate::pixels::interleave(&[Some(&plane)], &[crate::pixels::zero_sample(sample)], n, sample, &[false]); surface.write_interleaved(GeomRect::new(rect.left, rect.top, rect.right, rect.bottom), &bytes); + photocraft_raster::scratch::give(bytes); surface.prune(); if surface.content_bounds().is_empty() { return Ok(None); @@ -215,6 +216,7 @@ pub fn unfiltered_from_item(item: &FilterEffectsItem, fmt: PixelFormat) -> Optio } let mut surface = Surface::new(fmt); surface.write_interleaved(GeomRect::new(item.rect.left, item.rect.top, item.rect.right, item.rect.bottom), &bytes); + photocraft_raster::scratch::give(bytes); surface.prune(); Some(surface) } diff --git a/crates/io/tests/it/banded.rs b/crates/io/tests/it/banded.rs index eb8e97d6b52..c526b79fdb8 100644 --- a/crates/io/tests/it/banded.rs +++ b/crates/io/tests/it/banded.rs @@ -82,7 +82,7 @@ fn psd_merged_image_matches_composite_and_drops_near_opaque_alpha() { let file = document_to_psd(&d); assert_eq!(file.merged_has_alpha(), alpha < 0.99, "alpha {alpha}"); let merged = merged_composite(&file).unwrap(); - let want = photocraft_compose::flatten(&d).px; + let want = photocraft_compose::flatten(&d).into_px(); let m = merged.iter().zip(&want).flat_map(|(a, b)| (0..4).map(move |i| (a[i] - b[i]).abs())).fold(0.0f32, f32::max); // Un-matting divides the 8-bit rounding error by alpha. assert!(m <= 1.0 / (255.0 * alpha) + 1e-4, "alpha {alpha}: max diff {m}"); diff --git a/crates/io/tests/it/blend_modes_corpus.rs b/crates/io/tests/it/blend_modes_corpus.rs index 296e2e2a507..72980bed5b2 100644 --- a/crates/io/tests/it/blend_modes_corpus.rs +++ b/crates/io/tests/it/blend_modes_corpus.rs @@ -18,7 +18,7 @@ fn cell_error(mode: BlendMode) -> (f32, f32) { let doc = import("rgb-blend-modes.psd", &bytes).expect("opens").document; let file = PsdFile::from_bytes(&bytes).expect("parses"); let merged = merged_composite(&file).expect("merged image"); - let ours = photocraft_compose::flatten(&doc).px; + let ours = photocraft_compose::flatten(&doc).into_px(); let width = doc.size.width as i32; let duck = doc.walk().into_iter().map(|(_, _, l)| l).find(|l| l.name == "rubber_duck_PNG1" && l.blend == mode).expect("the mode's duck"); let surface = duck.surface().expect("duck pixels"); diff --git a/crates/io/tests/it/cmyk_composite_export.rs b/crates/io/tests/it/cmyk_composite_export.rs index 0fea33695db..77f35a62d2e 100644 --- a/crates/io/tests/it/cmyk_composite_export.rs +++ b/crates/io/tests/it/cmyk_composite_export.rs @@ -313,7 +313,8 @@ fn rgb_only_export_uses_direct_composite_not_reseparated_cmyk() { let doc = document(SampleType::U16, 0.5); let rgb = photocraft_compose::flatten(&doc); let expected = - photocraft_codecs::Image::from_normalized(8, 8, ChannelLayout::Rgba, CodecSample::U16, &rgb.px.into_iter().flatten().collect::>()).unwrap(); + photocraft_codecs::Image::from_normalized(8, 8, ChannelLayout::Rgba, CodecSample::U16, &rgb.into_px().into_iter().flatten().collect::>()) + .unwrap(); let result = export(&doc, "png", &ExportOptions::default()).unwrap(); diff --git a/crates/io/tests/it/color.rs b/crates/io/tests/it/color.rs index 15453a25189..5da5df1c7ea 100644 --- a/crates/io/tests/it/color.rs +++ b/crates/io/tests/it/color.rs @@ -116,11 +116,11 @@ fn cmyk_fills_survive_psd_roundtrip_at_every_depth() { let mut doc = Document::new("CMYK fill", photocraft_geom::Size::new(9, 6), ColorMode::Cmyk, depth); doc.icc_profile = profile.clone(); doc.layers.push(Layer::new("Fill", LayerContent::Fill(fill))); - let expected = photocraft_compose::flatten(&doc).px; + let expected = photocraft_compose::flatten(&doc).into_px(); assert!(max_diff(&expected, &photocraft_compose::render_tiled(&doc, doc.bounds(), 3).px) <= 1e-6); let bytes = export(&doc, "x.psd", &ExportOptions::default()).unwrap().bytes; let back = import("x.psd", &bytes).unwrap().document; - let actual = photocraft_compose::flatten(&back).px; + let actual = photocraft_compose::flatten(&back).into_px(); let diff = max_diff(&expected, &actual); assert!(diff <= 1e-6, "{depth:?} {style:?}: round-trip error {diff}"); assert_eq!(back.icc_profile, doc.icc_profile); @@ -144,7 +144,7 @@ fn uncached_cmyk_gradient_corpus_roundtrip() { let bytes = std::fs::read(path).expect("run cargo xtask corpus --all"); let doc = import("x.psd", &bytes).unwrap().document; assert!(doc.layers.iter().any(|l| matches!(l.content, photocraft_doc::LayerContent::Fill(_)) && l.fill_cache.is_none())); - let expected = photocraft_compose::flatten(&doc).px; + let expected = photocraft_compose::flatten(&doc).into_px(); let saved = export(&doc, "x.psd", &ExportOptions::default()).unwrap().bytes; let back = import("x.psd", &saved).unwrap().document; let diff = max_diff(&expected, &photocraft_compose::flatten(&back).px); @@ -305,7 +305,7 @@ fn gradient_maps_with_cmyk_lab_gray_stops_import_and_keep_their_space() { _ => assert_eq!((first, last), ([1.0; 3], [0.0; 3])), } // The layer now renders: the composite differs from the background alone. - let with_map = photocraft_compose::flatten(&back).px; + let with_map = photocraft_compose::flatten(&back).into_px(); let mut hidden = back.clone(); hidden.layers[1].visible = false; assert!(max_diff(&with_map, &photocraft_compose::flatten(&hidden).px) > 0.01, "{mode:?} {depth:?}"); diff --git a/crates/io/tests/it/composite.rs b/crates/io/tests/it/composite.rs index cef80e6a080..74eb0c95f1b 100644 --- a/crates/io/tests/it/composite.rs +++ b/crates/io/tests/it/composite.rs @@ -15,7 +15,7 @@ fn check_export_oracle(d: &photocraft_doc::Document, tol: f32) { let f = PsdFile::from_bytes(&r.bytes).unwrap(); let merged = merged_composite(&f).unwrap(); let d2 = import("x.psd", &r.bytes).unwrap().document; - let mut ours = photocraft_compose::flatten(&d2).px; + let mut ours = photocraft_compose::flatten(&d2).into_px(); if d.mode == ColorMode::Cmyk { // The merged CMYK image is the RGB composite separated through the CMYK profile, which // gamut-maps colours that blend modes push outside CMYK: project ours the same way. @@ -107,7 +107,7 @@ fn builder_oracle(depth: u16, mode: ColorMode) { let f = PsdFile::from_bytes(&bytes).unwrap(); let merged = merged_composite(&f).unwrap(); let d2 = import("b.psd", &bytes).unwrap().document; - let ours = photocraft_compose::flatten(&d2).px; + let ours = photocraft_compose::flatten(&d2).into_px(); let m = max_diff(&ours, &merged); // Density/feather of masks are not written by the builder; the generated // doc uses them only on a disabled mask, so results must match. @@ -157,7 +157,7 @@ fn hidden_and_clipped_affect_composite() { for l in &mut d2.layers { l.visible = true; } - let other = photocraft_compose::flatten(&d2).px; + let other = photocraft_compose::flatten(&d2).into_px(); assert!(max_diff(&other, &merged) > 0.0, "unhiding a layer must change the composite"); } diff --git a/crates/io/tests/it/corpus.rs b/crates/io/tests/it/corpus.rs index 182d60095ac..3c8ca3288ad 100644 --- a/crates/io/tests/it/corpus.rs +++ b/crates/io/tests/it/corpus.rs @@ -316,9 +316,9 @@ fn check_file(name: &str, bytes: &[u8]) -> (Outcome, Option) { return (Outcome::Error, None); } }; - let ours = photocraft_compose::flatten(doc).px; + let ours = photocraft_compose::flatten(doc).into_px(); // Our own export must not change how the document renders. - let again = photocraft_compose::flatten(&reimported).px; + let again = photocraft_compose::flatten(&reimported).into_px(); let rt = if again.len() == ours.len() { common::max_diff(&ours, &again) } else { f32::INFINITY }; let layers = doc.layer_count(); // Oracle choice: the merged image (Photoshop's composite; for files without layers it is the diff --git a/crates/io/tests/it/effects_multi.rs b/crates/io/tests/it/effects_multi.rs index 637e9260854..7cabb04b4c3 100644 --- a/crates/io/tests/it/effects_multi.rs +++ b/crates/io/tests/it/effects_multi.rs @@ -17,7 +17,7 @@ fn roundtrip(doc: &Document) -> Document { } fn max_diff(a: &Document, b: &Document) -> f32 { - let (x, y) = (photocraft_compose::flatten(a).px, photocraft_compose::flatten(b).px); + let (x, y) = (photocraft_compose::flatten(a).into_px(), photocraft_compose::flatten(b).into_px()); assert_eq!(x.len(), y.len()); x.iter().zip(&y).flat_map(|(p, q)| (0..4).map(move |c| (p[c] * p[3] - q[c] * q[3]).abs())).fold(0.0, f32::max) } diff --git a/crates/io/tests/it/flat.rs b/crates/io/tests/it/flat.rs index f6e888eb066..c40c76a12b4 100644 --- a/crates/io/tests/it/flat.rs +++ b/crates/io/tests/it/flat.rs @@ -350,7 +350,7 @@ fn layered_to_png_warns_flatten() { assert!(r.warnings.iter().any(|w| w.contains("flattened")), "{:?}", r.warnings); let back = import("out.png", &r.bytes).unwrap().document; // Composite equals our flatten. - let flat = photocraft_compose::flatten(&d).px; + let flat = photocraft_compose::flatten(&d).into_px(); let s = back.layers[0].surface().unwrap(); let px: Vec<[f32; 4]> = s.read_region(back.bounds()).as_chunks::<4>().0.iter().map(|p| [p[0], p[1], p[2], p[3]]).collect(); assert!(max_diff(&px, &flat) <= 1.0 / 255.0 + 1e-4); diff --git a/crates/io/tests/it/lab16.rs b/crates/io/tests/it/lab16.rs index 0aee2518618..ff0707c11bf 100644 --- a/crates/io/tests/it/lab16.rs +++ b/crates/io/tests/it/lab16.rs @@ -60,8 +60,8 @@ fn lab_round_trips_at_every_depth() { let p = back.layers[0].surface().unwrap().pixel(2, 0); let tol = if depth == SampleType::U8 { 0.5 / 255.0 + 1e-6 } else { 2e-5 }; assert!((p[1] - A).abs() <= tol && (p[2] - B).abs() <= tol, "{depth:?}: {p:?}"); - let a = photocraft_compose::flatten(&doc).px; - let b = photocraft_compose::flatten(&back).px; + let a = photocraft_compose::flatten(&doc).into_px(); + let b = photocraft_compose::flatten(&back).into_px(); for (x, y) in a.iter().zip(&b) { for c in 0..4 { assert!((x[c] - y[c]).abs() <= 1.0 / 255.0, "{depth:?}: {x:?} vs {y:?}"); diff --git a/crates/io/tests/it/large_files.rs b/crates/io/tests/it/large_files.rs index b0a2669480a..be4d5eeab7c 100644 --- a/crates/io/tests/it/large_files.rs +++ b/crates/io/tests/it/large_files.rs @@ -42,7 +42,7 @@ fn check_grid(g: &Grid, doc: &Document, what: &str) { ]; assert_eq!(census(doc), want, "{what}: [raster, groups, masked, with effects, hidden]"); for (x, y) in g.sample_points() { - let px = photocraft_compose::render(doc, Rect::from_xywh(x as i32, y as i32, 1, 1)).px; + let px = photocraft_compose::render(doc, Rect::from_xywh(x as i32, y as i32, 1, 1)).into_px(); let got = px.first().copied().unwrap_or_default(); let want = g.expected(x, y); for c in 0..3 { diff --git a/crates/io/tests/it/multichannel.rs b/crates/io/tests/it/multichannel.rs index 4e7ffeeb2ec..f4f7154d414 100644 --- a/crates/io/tests/it/multichannel.rs +++ b/crates/io/tests/it/multichannel.rs @@ -56,7 +56,7 @@ fn alpha_type_channels_import_as_alpha_and_round_trip() { as_ink.channels[1].surface = s; as_ink.channels[1].spot = Some((photocraft_color::Color::BLACK, 0.0)); // Within f32 rounding: the inverted copy is re-quantised to the channel depth. - let (shown, inked) = (photocraft_compose::flatten(&d).px, photocraft_compose::flatten(&as_ink).px); + let (shown, inked) = (photocraft_compose::flatten(&d).into_px(), photocraft_compose::flatten(&as_ink).into_px()); assert_eq!(shown.len(), inked.len()); for (a, b) in shown.iter().zip(&inked) { assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-5), "{a:?} vs {b:?} ({depth}-bit)"); @@ -115,7 +115,7 @@ fn alpha_type_channels_are_stored_as_is_not_as_ink() { assert_eq!(values(&d.channels[0]), [1.0, 0.0, 1.0, 0.0], "spot channel ({depth}-bit)"); // The composite is what Photoshop shows: the alpha prints as black ink where unselected. - let px = photocraft_compose::flatten(&d).px; + let px = photocraft_compose::flatten(&d).into_px(); assert_eq!(px.iter().map(|p| [p[0], p[1], p[2]]).collect::>(), [[0.0, 1.0, 1.0], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]); // Saved back byte for byte. diff --git a/crates/io/tests/it/psd32_export.rs b/crates/io/tests/it/psd32_export.rs index f9a297a7f6e..428fb7903e1 100644 --- a/crates/io/tests/it/psd32_export.rs +++ b/crates/io/tests/it/psd32_export.rs @@ -118,7 +118,7 @@ fn layered_32bit_export_reimports_render_equal() { for mode in [ColorMode::Rgb, ColorMode::Grayscale] { let doc = common::gen_doc(mode, SampleType::F32, Features::ALL); let back = import("t.psd", &export_psd(&doc)).unwrap().document; - let (a, b) = (photocraft_compose::flatten(&doc).px, photocraft_compose::flatten(&back).px); + let (a, b) = (photocraft_compose::flatten(&doc).into_px(), photocraft_compose::flatten(&back).into_px()); assert_eq!(a.len(), b.len()); let d = common::max_diff(&a, &b); assert!(d <= 1e-4, "{mode:?}: render differs by {d}"); @@ -154,7 +154,7 @@ fn photoshop_32bit_corpus_round_trip() { assert_32bit_layout(&name, &out); let back = import(&name, &out).unwrap().document; assert_eq!(doc.layer_count(), back.layer_count(), "{name}: layer count"); - let (a, b) = (photocraft_compose::flatten(&doc).px, photocraft_compose::flatten(&back).px); + let (a, b) = (photocraft_compose::flatten(&doc).into_px(), photocraft_compose::flatten(&back).into_px()); assert_eq!(a.len(), b.len(), "{name}"); let d = common::max_diff(&a, &b); assert!(d <= 1e-4, "{name}: render differs by {d}"); diff --git a/crates/io/tests/it/psd_damaged_merged.rs b/crates/io/tests/it/psd_damaged_merged.rs index 8e20687bb5d..51121d59b71 100644 --- a/crates/io/tests/it/psd_damaged_merged.rs +++ b/crates/io/tests/it/psd_damaged_merged.rs @@ -32,7 +32,7 @@ fn truncated_merged_image_keeps_layer_pixels_at_every_depth_and_compression() { for compression in Compression::ALL { let mut file = layered_in_mode(mode, depth, extension); let intact = import(extension, &file.to_bytes().unwrap()).unwrap(); - let expected = photocraft_compose::flatten(&intact.document).px; + let expected = photocraft_compose::flatten(&intact.document).into_px(); let pixels = file.decode_merged().unwrap(); file.image_data = photocraft_psd::ImageData::encode(compression, &pixels, &file.header).unwrap(); file.image_data.data.truncate(file.image_data.data.len() / 2); diff --git a/crates/io/tests/it/psd_type_bounds.rs b/crates/io/tests/it/psd_type_bounds.rs index b87d4f4a3a0..43ce38c6745 100644 --- a/crates/io/tests/it/psd_type_bounds.rs +++ b/crates/io/tests/it/psd_type_bounds.rs @@ -283,7 +283,7 @@ fn imported_type_layers_keep_their_full_bounds() { let o = iou(&ours.surface, cache); assert!(o > 0.97, "{}: re-render overlap {o}", c.name); // And the document composite is the file's merged composite. - let px = photocraft_compose::flatten(&doc).px; + let px = photocraft_compose::flatten(&doc).into_px(); let worst = common::max_diff(&px, &merged); assert!(worst <= 2.0 / 255.0, "{}: composite differs from the merged image by {worst}", c.name); } diff --git a/crates/io/tests/it/tiff_corpus.rs b/crates/io/tests/it/tiff_corpus.rs index 697eab6d323..1b3c36a05df 100644 --- a/crates/io/tests/it/tiff_corpus.rs +++ b/crates/io/tests/it/tiff_corpus.rs @@ -124,8 +124,8 @@ fn corpus_round_trips_through_layered_tiff() { } d }; - let x = photocraft_compose::flatten(&expected).px; - let y = photocraft_compose::flatten(&back).px; + let x = photocraft_compose::flatten(&expected).into_px(); + let y = photocraft_compose::flatten(&back).into_px(); let diff = max_diff(&x, &y); if diff > 1.0 / 255.0 + 1e-5 { return Err(format!("render differs by {diff}")); diff --git a/crates/io/tests/it/tiff_layers.rs b/crates/io/tests/it/tiff_layers.rs index f2ccddc92eb..3c7815a37ad 100644 --- a/crates/io/tests/it/tiff_layers.rs +++ b/crates/io/tests/it/tiff_layers.rs @@ -87,8 +87,8 @@ fn tiff_and_psd_open_as_the_same_document() { ) .unwrap() .document; - let a = photocraft_compose::flatten(&d).px; - let b = photocraft_compose::flatten(&flat).px; + let a = photocraft_compose::flatten(&d).into_px(); + let b = photocraft_compose::flatten(&flat).into_px(); assert!(max_diff(&a, &b) <= 2.0 / 255.0, "{mode:?} {depth:?}: composite differs by {}", max_diff(&a, &b)); } } diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 5d0f6fe257e..d949445bcc8 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -9,6 +9,7 @@ mod interrupt; pub use interrupt::{Cancelled, Interrupt}; +pub mod scratch; use std::collections::BTreeMap; use std::fmt; @@ -62,18 +63,30 @@ impl TileInterner { } /// Pixel storage for one tile: `TILE_SIZE² × bytes_per_pixel`, row-major, interleaved channels. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq)] pub struct Tile { data: Box<[u8]>, } +impl Clone for Tile { + fn clone(&self) -> Self { + let mut data = scratch::take_exact(self.data.len(), 0u8); + data.copy_from_slice(&self.data); + Tile { data: data.into_boxed_slice() } + } +} + +impl Drop for Tile { + fn drop(&mut self) { + scratch::give(std::mem::take(&mut self.data).into_vec()); + } +} + impl Tile { fn try_filled(format: &PixelFormat, pixel: &[u8]) -> Result { let n = (TILE_SIZE * TILE_SIZE) as usize; let bytes = n.checked_mul(format.bytes_per_pixel()).ok_or(AllocationError::SizeOverflow)?; - let mut data = Vec::new(); - data.try_reserve_exact(bytes).map_err(|_| AllocationError::NotEnoughMemory { bytes })?; - data.resize(bytes, 0); + let mut data = scratch::try_take_exact(bytes, 0u8).ok_or(AllocationError::NotEnoughMemory { bytes })?; if pixel.iter().any(|&b| b != 0) { for px in data.chunks_exact_mut(pixel.len()) { px.copy_from_slice(pixel); @@ -85,15 +98,14 @@ impl Tile { /// Clone this tile's pixel buffer with a fallible reservation. pub fn try_clone(&self) -> Result { let bytes = self.data.len(); - let mut data = Vec::new(); - data.try_reserve_exact(bytes).map_err(|_| AllocationError::NotEnoughMemory { bytes })?; - data.extend_from_slice(&self.data); + let mut data = scratch::try_take_exact(bytes, 0u8).ok_or(AllocationError::NotEnoughMemory { bytes })?; + data.copy_from_slice(&self.data); Ok(Tile { data: data.into_boxed_slice() }) } fn filled(format: &PixelFormat, pixel: &[u8]) -> Self { let row_len = TILE_SIZE as usize * format.bytes_per_pixel(); - let mut data = vec![0u8; row_len * TILE_SIZE as usize]; + let mut data = scratch::take_exact(row_len * TILE_SIZE as usize, 0u8); if pixel.iter().any(|&b| b != 0) { // One prebuilt row copied per tile row: 256 bulk copies instead of one // copy_from_slice per pixel. @@ -358,9 +370,7 @@ impl Surface { pub fn try_read_region(&self, r: Rect) -> Result, AllocationError> { let len = (r.width() as usize).checked_mul(r.height() as usize).and_then(|n| n.checked_mul(self.channels())).ok_or(AllocationError::SizeOverflow)?; let bytes = len.checked_mul(std::mem::size_of::()).ok_or(AllocationError::SizeOverflow)?; - let mut out = Vec::new(); - out.try_reserve_exact(len).map_err(|_| AllocationError::NotEnoughMemory { bytes })?; - out.resize(len, 0.0); + let mut out = scratch::try_take_exact(len, 0.0f32).ok_or(AllocationError::NotEnoughMemory { bytes })?; self.read_region_into(r, &mut out); Ok(out) } @@ -761,7 +771,7 @@ impl Surface { pub fn read_region(&self, r: Rect) -> Vec { let n = self.channels(); let w = r.width() as usize; - let mut out = vec![0.0f32; w * r.height() as usize * n]; + let mut out = scratch::take(w * r.height() as usize * n, 0.0f32); self.read_samples_into(r, &mut out); out } @@ -935,7 +945,7 @@ impl Surface { pub fn to_interleaved(&self, r: Rect) -> Vec { let bpp = self.format.bytes_per_pixel(); let w = r.width() as usize; - let mut out = vec![0u8; w * r.height() as usize * bpp]; + let mut out = scratch::take(w * r.height() as usize * bpp, 0u8); for tc in r.tiles() { let tr = tc.rect().intersect(&r); let span = tr.width() as usize * bpp; @@ -1022,7 +1032,7 @@ impl Surface { return hit.clone().map(|t| (dc, t)); } - let mut tile = Tile { data: vec![0u8; (TILE_SIZE * TILE_SIZE) as usize * bpp].into_boxed_slice() }; + let mut tile = Tile { data: scratch::take_exact((TILE_SIZE * TILE_SIZE) as usize * bpp, 0u8).into_boxed_slice() }; let (tx0, ty0) = (i64::from(dc.tx) * i64::from(TILE_SIZE), i64::from(dc.ty) * i64::from(TILE_SIZE)); let row_len = TILE_SIZE as usize * bpp; // Per stored row: copy the source span that falls inside the content in as few diff --git a/crates/raster/src/scratch.rs b/crates/raster/src/scratch.rs new file mode 100644 index 00000000000..cb0f898306c --- /dev/null +++ b/crates/raster/src/scratch.rs @@ -0,0 +1,384 @@ +//! Process-wide, capped pool of large scratch buffers. +//! +//! With glibc's mmap threshold pinned (`MALLOC_TRIM_THRESHOLD_`, which is how PhotoCraft returns +//! memory to the OS), every allocation over 128 KiB is a fresh `mmap` that is page-faulted in and +//! `munmap`ed on free. Tiles, compositor bands and filter scratch are all that size, so a single +//! viewport render took 350× the page faults. This pool keeps freed buffers (at least +//! [`MIN_POOLED_BYTES`] of capacity) on per-type free lists and hands them back out, so the +//! steady state allocates nothing. +//! +//! Retention is capped by [`set_budget`] (default [`DEFAULT_BUDGET`]); [`release`] drops +//! everything, which is what returns the memory to the OS. The engine releases when a document +//! closes; off wasm a background thread also releases once the pool has gone unused for +//! [`IDLE_RELEASE_SECS`], so every host (app, CLI, tests) gives memory back the same way. + +use std::collections::{BTreeMap, VecDeque}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Mutex, PoisonError}; + +/// Buffers with less capacity than this are cheap from the heap and are never retained. +pub const MIN_POOLED_BYTES: usize = 64 * 1024; +/// Default cap on the bytes the pool retains: about the working set of a 36 MP filter (tiles, +/// halo images and result bands); a browser's wasm heap never shrinks, so there it is small. +pub const DEFAULT_BUDGET: usize = if cfg!(target_arch = "wasm32") { 256 << 20 } else { 2 << 30 }; + +/// Pooled bytes a miss never evicts. A filter's output tiles are all misses (the old tiles stay +/// in the undo history); evicting every byte they need also dropped the scratch planes the next +/// tile reuses. On a 36 MP Gaussian Blur with the trim threshold set, 256 MiB keeps the timings +/// at glibc's defaults (128 MiB: r 40 ~17% slower) for ~10% more peak memory (0: ~20% slower). +pub const DEFAULT_MISS_FLOOR: usize = if cfg!(target_arch = "wasm32") { 64 << 20 } else { 256 << 20 }; + +static BUDGET: AtomicUsize = AtomicUsize::new(DEFAULT_BUDGET); +static MISS_FLOOR: AtomicUsize = AtomicUsize::new(DEFAULT_MISS_FLOOR); +static RETAINED: AtomicUsize = AtomicUsize::new(0); +static USES: AtomicU64 = AtomicU64::new(0); +static IDLE_RELEASE: AtomicBool = AtomicBool::new(true); + +/// Seconds without a [`take`] or [`give`] after which the idle thread releases the pool. +pub const IDLE_RELEASE_SECS: u64 = 2; + +/// Starts the idle-release thread once (off wasm, where there are threads). If the thread +/// can't be spawned the pool still works; it is then released only by [`release`]. +fn start_idle_release() { + #[cfg(not(target_arch = "wasm32"))] + { + static STARTED: std::sync::Once = std::sync::Once::new(); + STARTED.call_once(|| { + let _ = std::thread::Builder::new().name("scratch-idle".into()).spawn(|| { + let mut seen = uses(); + loop { + std::thread::sleep(std::time::Duration::from_secs(IDLE_RELEASE_SECS)); + let now = uses(); + if now == seen { + // Decided under the lock, so `set_idle_release(false)` can't return + // while a release it should have stopped is about to start. + let old = { + let mut pool = lock(); + // A `give` or `take` since `now` was read means the pool is in use. + (uses() == now && retained_bytes() > 0 && IDLE_RELEASE.load(Ordering::Relaxed)).then(|| empty(&mut pool)) + }; + drop(old); + } + seen = now; + } + }); + }); + } +} + +/// One free list: buffers keyed by capacity (in elements), each with the sequence number it +/// was returned at (oldest first within a capacity). +#[doc(hidden)] +pub type FreeList = BTreeMap)>>; + +/// All the free lists behind one lock, so the oldest buffer of any type can be evicted. +/// `order` maps every pooled buffer's sequence number to its type and capacity, so the oldest +/// is found in O(log n); best-fit lookups are a range query on the capacity key. +#[doc(hidden)] +pub struct Pool { + seq: u64, + order: BTreeMap, + u8s: FreeList, + u16s: FreeList, + f32s: FreeList, + px4: FreeList<[f32; 4]>, +} + +static POOL: Mutex = + Mutex::new(Pool { seq: 0, order: BTreeMap::new(), u8s: BTreeMap::new(), u16s: BTreeMap::new(), f32s: BTreeMap::new(), px4: BTreeMap::new() }); + +/// Which free list a buffer lives on. +#[doc(hidden)] +#[derive(Clone, Copy)] +pub enum Tag { + U8, + U16, + F32, + Px4, +} + +/// A buffer evicted from the pool, dropped by the caller once the lock is released. +#[allow(dead_code)] +enum Evicted { + U8(Vec), + U16(Vec), + F32(Vec), + Px4(Vec<[f32; 4]>), +} + +/// Element types that have a free list. Implemented for the buffers the hot paths use. +pub trait Pooled: Copy + Send + 'static { + #[doc(hidden)] + const TAG: Tag; + #[doc(hidden)] + fn list(pool: &mut Pool) -> &mut FreeList; +} + +macro_rules! pooled { + ($($t:ty => $field:ident, $tag:ident),*) => {$( + impl Pooled for $t { + const TAG: Tag = Tag::$tag; + fn list(pool: &mut Pool) -> &mut FreeList { + &mut pool.$field + } + } + )*}; +} +pooled!(u8 => u8s, U8, u16 => u16s, U16, f32 => f32s, F32, [f32; 4] => px4, Px4); + +fn bytes_of(v: &Vec) -> usize { + v.capacity().saturating_mul(std::mem::size_of::()) +} + +fn lock() -> std::sync::MutexGuard<'static, Pool> { + POOL.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// Remove the oldest buffer of capacity `cap` from `list`. +fn drop_oldest(list: &mut FreeList, cap: usize) -> Option> { + let queue = list.get_mut(&cap)?; + let v = queue.pop_front()?.1; + if queue.is_empty() { + list.remove(&cap); + } + Some(v) +} + +impl Pool { + /// Remove the buffer returned longest ago, of any type. `None` when the pool is empty. + fn evict_oldest(&mut self) -> Option { + let (_, (tag, cap)) = self.order.pop_first()?; + let evicted = match tag { + Tag::U8 => drop_oldest(&mut self.u8s, cap).map(Evicted::U8), + Tag::U16 => drop_oldest(&mut self.u16s, cap).map(Evicted::U16), + Tag::F32 => drop_oldest(&mut self.f32s, cap).map(Evicted::F32), + Tag::Px4 => drop_oldest(&mut self.px4, cap).map(Evicted::Px4), + }; + if let Some(e) = &evicted { + let freed = match e { + Evicted::U8(v) => bytes_of(v), + Evicted::U16(v) => bytes_of(v), + Evicted::F32(v) => bytes_of(v), + Evicted::Px4(v) => bytes_of(v), + }; + RETAINED.fetch_sub(freed, Ordering::Relaxed); + } + evicted + } +} + +/// A `Vec` of `len` copies of `fill`, reusing a pooled buffer when one fits: the one whose +/// capacity equals `len`, else the smallest with capacity in `len..=2*len`. +pub fn take(len: usize, fill: T) -> Vec { + take_with(len, fill, 2) +} + +/// An empty `Vec` with room for at least `cap` elements, reusing a pooled buffer when one fits. +pub fn take_cap(cap: usize) -> Vec { + USES.fetch_add(1, Ordering::Relaxed); + match pop::(cap, 2) { + Some(mut v) => { + v.clear(); + v + } + None => Vec::with_capacity(cap), + } +} + +/// Like [`take`] but only reuses a buffer whose capacity is exactly `len`, so +/// `into_boxed_slice` never reallocates. +pub fn take_exact(len: usize, fill: T) -> Vec { + take_with(len, fill, 1) +} + +/// Pop the best-fitting free buffer: capacity `len`, else the smallest up to `len * slack`. +/// +/// On a miss the caller allocates `len` fresh, so the oldest free buffers of at least that many +/// bytes are dropped first, down to [`set_miss_floor`]: memory the pool can't reuse for this request +/// goes back instead of piling up beside the new buffer, so pool plus live buffers exceed what +/// the program would hold without the pool by at most the floor (#10479). +fn pop(len: usize, slack: usize) -> Option> { + let need = len.saturating_mul(std::mem::size_of::()); + if need < MIN_POOLED_BYTES { + return None; + } + let mut evicted = Vec::new(); + let hit = { + let mut pool = lock(); + let max = len.saturating_mul(slack); + let list = T::list(&mut pool); + let cap = list.range(len..=max).next().map(|(&cap, _)| cap); + // The newest buffer of that capacity is the one most likely still in cache. + let found = cap.and_then(|cap| { + let queue = list.get_mut(&cap)?; + let entry = queue.pop_back(); + if queue.is_empty() { + list.remove(&cap); + } + entry + }); + match found { + Some((seq, v)) => { + pool.order.remove(&seq); + RETAINED.fetch_sub(bytes_of(&v), Ordering::Relaxed); + Some(v) + } + None => { + let target = RETAINED.load(Ordering::Relaxed).saturating_sub(need).max(MISS_FLOOR.load(Ordering::Relaxed)); + while RETAINED.load(Ordering::Relaxed) > target { + match pool.evict_oldest() { + Some(e) => evicted.push(e), + None => break, + } + } + None + } + } + }; + // Freed outside the lock. + drop(evicted); + hit +} + +fn take_with(len: usize, fill: T, slack: usize) -> Vec { + USES.fetch_add(1, Ordering::Relaxed); + if len == 0 { + return Vec::new(); + } + match pop::(len, slack) { + Some(mut v) => { + v.clear(); + v.resize(len, fill); + v + } + None => vec![fill; len], + } +} + +/// Fallible [`take_exact`]: on a pool miss the heap allocation is `try_reserve_exact`, so +/// `None` means the allocation failed rather than aborting. +pub fn try_take_exact(len: usize, fill: T) -> Option> { + USES.fetch_add(1, Ordering::Relaxed); + let mut v = match pop::(len, 1) { + Some(v) => v, + None => { + let mut v = Vec::new(); + if v.try_reserve_exact(len).is_err() { + // The pool may hold up to the miss floor of buffers this request couldn't use: + // give them back, then try once more before failing the caller. + release(); + v.try_reserve_exact(len).ok()?; + } + v + } + }; + v.clear(); + v.resize(len, fill); + Some(v) +} + +/// Return a buffer to the pool. Small buffers, and buffers bigger than the whole budget, are +/// dropped; otherwise the buffers returned longest ago (of any type) make room for it. +pub fn give(v: Vec) { + USES.fetch_add(1, Ordering::Relaxed); + let bytes = bytes_of(&v); + if bytes < MIN_POOLED_BYTES { + return; + } + let mut evicted = Vec::new(); + { + let mut pool = lock(); + // Read under the lock, which `set_budget` also takes, so no insert uses a stale budget. + let budget = BUDGET.load(Ordering::Relaxed); + if bytes > budget { + return; + } + start_idle_release(); + while RETAINED.load(Ordering::Relaxed).saturating_add(bytes) > budget { + match pool.evict_oldest() { + Some(e) => evicted.push(e), + None => break, + } + } + RETAINED.fetch_add(bytes, Ordering::Relaxed); + pool.seq += 1; + let seq = pool.seq; + let cap = v.capacity(); + pool.order.insert(seq, (T::TAG, cap)); + T::list(&mut pool).entry(cap).or_default().push_back((seq, v)); + } + // Freed outside the lock. + drop(evicted); +} + +/// Set the cap on retained bytes (existing entries beyond it go on the next [`give`]). +pub fn set_budget(bytes: usize) { + let _pool = lock(); + BUDGET.store(bytes, Ordering::Relaxed); +} + +/// Set the pooled bytes a miss never evicts (default [`DEFAULT_MISS_FLOOR`]). +pub fn set_miss_floor(bytes: usize) { + MISS_FLOOR.store(bytes, Ordering::Relaxed); +} + +/// Let the idle thread release the pool (the default) or not. Tests that check +/// [`retained_bytes`] turn it off, so a slow runner can't have the pool emptied under them. +pub fn set_idle_release(on: bool) { + // Under the lock: once this returns, the idle thread can't be midway into a release. + let _pool = lock(); + IDLE_RELEASE.store(on, Ordering::Relaxed); +} + +/// Bytes currently held by the pool. +pub fn retained_bytes() -> usize { + RETAINED.load(Ordering::Relaxed) +} + +/// Number of [`take`]/[`give`] calls so far; a changing value means the pool is in use. +pub fn uses() -> u64 { + USES.load(Ordering::Relaxed) +} + +/// Drop every pooled buffer, handing the memory back to the OS. +pub fn release() { + let old = empty(&mut lock()); + // Freed outside the lock. + drop(old); +} + +/// Everything `pool` holds, swapped out of it (to be freed once the lock is dropped). +fn empty(pool: &mut Pool) -> Pool { + RETAINED.store(0, Ordering::Relaxed); + let seq = pool.seq; + std::mem::replace(pool, Pool { seq, order: BTreeMap::new(), u8s: BTreeMap::new(), u16s: BTreeMap::new(), f32s: BTreeMap::new(), px4: BTreeMap::new() }) +} + +/// A pooled buffer that derefs to a slice and returns itself to the pool on drop. +pub struct Buf(Vec); + +impl Buf { + /// `len` copies of `fill` from the pool. + pub fn new(len: usize, fill: T) -> Self { + Buf(take(len, fill)) + } +} + +impl std::ops::Deref for Buf { + type Target = [T]; + fn deref(&self) -> &[T] { + &self.0 + } +} + +impl std::ops::DerefMut for Buf { + fn deref_mut(&mut self) -> &mut [T] { + &mut self.0 + } +} + +impl Drop for Buf { + fn drop(&mut self) { + give(std::mem::take(&mut self.0)); + } +} diff --git a/crates/raster/tests/scratch.rs b/crates/raster/tests/scratch.rs new file mode 100644 index 00000000000..a0f532f1745 --- /dev/null +++ b/crates/raster/tests/scratch.rs @@ -0,0 +1,361 @@ +//! The scratch pool is process-wide, so these tests live in their own binary (nothing else +//! allocates tiles here) and take a lock to run one at a time. + +use photocraft_raster::scratch::*; +use std::sync::{Mutex, PoisonError}; + +static SERIAL: Mutex<()> = Mutex::new(()); + +/// Lets a miss evict every pooled byte for the test's lifetime, so sizes can be counted. +struct NoFloor; +impl NoFloor { + /// Sets the miss floor to zero for this guard's lifetime. + fn new() -> Self { + set_miss_floor(0); + NoFloor + } +} +impl Drop for NoFloor { + fn drop(&mut self) { + set_miss_floor(DEFAULT_MISS_FLOOR); + } +} +/// Locks the process-wide pool tests against concurrent access. +fn lock_serial() -> std::sync::MutexGuard<'static, ()> { + SERIAL.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// Runs a test alone with idle release off, so the idle thread can't empty the pool between a +/// `give` and the checks after it; idle release comes back on when dropped. +struct Serial { + _lock: std::sync::MutexGuard<'static, ()>, +} +impl Drop for Serial { + fn drop(&mut self) { + set_idle_release(true); + } +} +/// Serializes a test and disables idle release until the guard is dropped. +fn serial() -> Serial { + let _lock = lock_serial(); + set_idle_release(false); + Serial { _lock } +} + +#[test] +/// Verifies pooled buffers are reused by pointer, retain capacity, and are refilled to the requested length. +fn reuse_returns_same_capacity_and_refills() { + let _g = serial(); + release(); + let mut v = take(100_000, 0.0f32); + v.iter_mut().for_each(|x| *x = 7.0); + let ptr = v.as_ptr(); + give(v); + assert_eq!(retained_bytes(), 400_000); + let w = take(100_000, 1.5f32); + assert_eq!(w.as_ptr(), ptr); + assert_eq!(w.len(), 100_000); + assert!(w.iter().all(|&x| x == 1.5)); + assert_eq!(retained_bytes(), 0); + // A smaller request within 2x reuses it too, and is sized exactly. + give(w); + let s = take(60_000, 0.0f32); + assert_eq!(s.as_ptr(), ptr); + assert_eq!(s.len(), 60_000); + release(); +} + +#[test] +/// Verifies oversized or non-exact buffers are discarded instead of reused. +fn too_big_a_buffer_is_not_reused() { + let _g = serial(); + release(); + let _floor = NoFloor::new(); + give(vec![0u8; 1_000_000]); + assert_eq!(take_exact(1_000_000, 0u8).len(), 1_000_000); + assert_eq!(retained_bytes(), 0); + give(vec![0u8; 1_000_000]); + // More than 2x (or not exact): allocated fresh, and the miss drops the unusable buffer. + assert_eq!(take(100_000, 0u8).capacity(), 100_000); + assert_eq!(retained_bytes(), 0); + give(vec![0u8; 1_000_000]); + assert_eq!(take_exact(999_999, 0u8).capacity(), 999_999); + assert_eq!(retained_bytes(), 0); + release(); +} + +#[test] +/// Verifies exact try-takes reuse a matching buffer and succeed on a miss. +fn try_take_exact_reuses_and_allocates() { + let _g = serial(); + release(); + let buf = vec![0u8; 200_000]; + let ptr = buf.as_ptr(); + give(buf); + let v = try_take_exact(200_000, 9u8); + assert!(v.as_ref().is_some_and(|v| v.len() == 200_000 && v.iter().all(|&b| b == 9))); + assert_eq!(v.as_ref().map(|v| v.as_ptr()), Some(ptr)); + assert_eq!(retained_bytes(), 0); + assert!(try_take_exact(300_000, 0u8).is_some()); + release(); +} + +#[test] +/// Verifies buffers below the pooling threshold are not retained. +fn small_buffers_are_not_retained() { + let _g = serial(); + release(); + give(vec![0u8; MIN_POOLED_BYTES - 1]); + give(vec![0.0f32; 100]); + assert_eq!(retained_bytes(), 0); + assert_eq!(take(10, 3u8), vec![3u8; 10]); +} + +#[test] +/// Verifies zero-length take and give operations remain empty. +fn zero_length() { + let _g = serial(); + assert!(take(0, 0u8).is_empty()); + give(Vec::::new()); + assert!(take_exact(0, [0.0f32; 4]).is_empty()); +} + +#[test] +/// Verifies the byte budget evicts oldest buffers and rejects buffers larger than the budget. +fn budget_evicts_oldest() { + let _g = serial(); + release(); + set_budget(250_000); + let (a, b) = (vec![0u8; 100_000], vec![0u8; 100_000]); + let pb = b.as_ptr(); + give(a); + give(b); + give(vec![0u8; 100_000]); + assert_eq!(retained_bytes(), 200_000); + // The oldest was evicted; the survivors include b. + let first = take_exact(100_000, 0u8); + let second = take_exact(100_000, 0u8); + assert!(first.as_ptr() == pb || second.as_ptr() == pb); + // Larger than the whole budget: dropped. + give(vec![0u8; 300_000]); + assert_eq!(retained_bytes(), 0); + set_budget(DEFAULT_BUDGET); + release(); +} + +#[test] +/// Verifies release empties pooled buffers of several element types. +fn release_empties() { + let _g = serial(); + give(vec![0u8; 200_000]); + give(vec![0.0f32; 200_000]); + give(vec![[0.0f32; 4]; 100_000]); + assert!(retained_bytes() > 0); + release(); + assert_eq!(retained_bytes(), 0); +} + +#[test] +/// Verifies the usage counter advances for both take and give. +fn uses_counts_calls() { + let _g = serial(); + let before = uses(); + give(take(10, 0u8)); + assert_eq!(uses(), before + 2); +} + +#[test] +/// Verifies dropping a `Buf` returns its storage to the pool. +fn buf_returns_on_drop() { + let _g = serial(); + release(); + { + let mut b = Buf::new(150_000, 0.0f32); + b[3] = 1.0; + assert_eq!(b.len(), 150_000); + } + assert_eq!(retained_bytes(), 600_000); + release(); +} + +#[test] +/// Verifies concurrent take and give operations preserve initialized values and finish cleanly. +fn concurrent_smoke() { + let _g = serial(); + release(); + let handles: Vec<_> = (0..8u8) + .map(|t| { + std::thread::spawn(move || { + for i in 0..200 { + let v = take(70_000 + i % 5, t); + assert!(v.iter().all(|&x| x == t)); + give(v); + } + }) + }) + .collect(); + for h in handles { + assert!(h.join().is_ok()); + } + release(); + assert_eq!(retained_bytes(), 0); +} + +#[test] +/// Verifies budget eviction uses insertion age across different element types. +fn eviction_is_oldest_first_across_types() { + let _g = serial(); + release(); + set_budget(500_000); + give(vec![0u8; 300_000]); + give(vec![0.0f32; 50_000]); + assert_eq!(retained_bytes(), 500_000); + // Needs 200 000 more: the older u8 buffer goes, the f32 one stays. + give(vec![[0.0f32; 4]; 12_500]); + assert_eq!(retained_bytes(), 400_000); + assert_eq!(take_exact(50_000, 1.0f32).len(), 50_000); + assert_eq!(retained_bytes(), 200_000); + set_budget(DEFAULT_BUDGET); + release(); +} + +#[test] +/// Verifies reuse chooses the smallest eligible capacity and exact takes require an exact match. +fn best_fit_picks_the_smallest_fitting_capacity() { + let _g = serial(); + release(); + let _floor = NoFloor::new(); + for n in [180_000usize, 120_000, 150_000, 300_000] { + give(vec![0u8; n]); + } + // Within 2x of 100 000: 120 000 is the tightest fit, then 150 000, then 180 000. + assert_eq!(take(100_000, 0u8).capacity(), 120_000); + assert_eq!(take(100_000, 0u8).capacity(), 150_000); + assert_eq!(take(100_000, 0u8).capacity(), 180_000); + // 300 000 is more than 2x: allocated fresh, and the miss drops the pooled one. + assert_eq!(take(100_000, 0u8).capacity(), 100_000); + assert_eq!(retained_bytes(), 0); + // An exact capacity beats a smaller-slack scan. + give(vec![0u8; 100_000]); + assert_eq!(take_exact(100_000, 0u8).capacity(), 100_000); + assert_eq!(take_exact(250_000, 0u8).capacity(), 250_000); + release(); +} + +#[test] +/// Verifies repeated budget overflow evicts oldest entries across mixed types and capacities. +fn eviction_walks_oldest_first_through_mixed_types_and_capacities() { + let _g = serial(); + release(); + let _floor = NoFloor::new(); + set_budget(700_000); + // Oldest to newest, 100 000 bytes each, interleaved types and two u8 capacities. + give(vec![0u8; 100_000]); + let f = vec![0.0f32; 25_000]; + give(f); + give(vec![0u8; 100_000]); + give(vec![0u16; 50_000]); + let newest = vec![0u8; 150_000]; + let np = newest.as_ptr(); + give(newest); + assert_eq!(retained_bytes(), 550_000); + // 200 000 more overflows by 50 000: the oldest (u8) goes. + give(vec![[0.0f32; 4]; 12_500]); + assert_eq!(retained_bytes(), 650_000); + // 100 000 more: the next oldest (the f32 buffer) goes. + give(vec![0u8; 100_000]); + assert_eq!(retained_bytes(), 650_000); + // 200 000 more: the u8 then the u16 buffer go. + give(vec![0u8; 200_000]); + assert_eq!(retained_bytes(), 650_000); + // The newest u8 buffer of the old batch is still pooled; the f32 one was evicted. + let again = take_exact(150_000, 0u8); + assert_eq!(again.as_ptr(), np); + assert_eq!(retained_bytes(), 500_000); + // The evicted f32 buffer is a miss: the oldest buffers, at least its 100 000 bytes, leave + // (the 200 000-byte [f32; 4] one). + assert_eq!(take_exact(25_000, 0.0f32).len(), 25_000); + assert_eq!(retained_bytes(), 300_000); + set_budget(DEFAULT_BUDGET); + release(); +} + +#[test] +/// Verifies the idle-release worker clears an unused pooled buffer. +fn idle_pool_is_released_by_the_background_thread() { + // Idle release stays on here: it is what this test checks. + let _g = lock_serial(); + release(); + give(vec![0u8; MIN_POOLED_BYTES]); + assert_eq!(retained_bytes(), MIN_POOLED_BYTES); + // Released after one full idle interval without use (at most two from the give). + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3 * IDLE_RELEASE_SECS + 1); + while retained_bytes() > 0 && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(100)); + } + assert_eq!(retained_bytes(), 0); +} + +#[test] +/// Verifies a miss discards pooled bytes in proportion to its allocation and a hit preserves the pool. +fn a_miss_drops_as_many_pooled_bytes_as_it_allocates() { + let _g = serial(); + release(); + let _floor = NoFloor::new(); + // Three 64 KiB f32 buffers a byte request can't use. + for _ in 0..3 { + give(vec![0.0f32; MIN_POOLED_BYTES / 4]); + } + assert_eq!(retained_bytes(), 3 * MIN_POOLED_BYTES); + // A 128 KiB miss drops the two oldest, so pool plus live buffers stay at 192 KiB. + let v = take(2 * MIN_POOLED_BYTES, 0u8); + assert_eq!(retained_bytes(), MIN_POOLED_BYTES); + give(v); + // A hit drops nothing. + let w = take(MIN_POOLED_BYTES / 4, 0.0f32); + assert_eq!(retained_bytes(), 2 * MIN_POOLED_BYTES); + drop(w); + release(); +} + +#[test] +/// Verifies miss eviction stops when the configured retained-byte floor is reached. +fn a_miss_keeps_the_floor() { + let _g = serial(); + release(); + set_miss_floor(2 * MIN_POOLED_BYTES); + for _ in 0..3 { + give(vec![0.0f32; MIN_POOLED_BYTES / 4]); + } + // A 192 KiB miss would drop all three; only one goes, down to the floor. + assert_eq!(take(3 * MIN_POOLED_BYTES, 0u8).len(), 3 * MIN_POOLED_BYTES); + assert_eq!(retained_bytes(), 2 * MIN_POOLED_BYTES); + set_miss_floor(DEFAULT_MISS_FLOOR); + release(); +} + +#[test] +/// Verifies a failed oversized reservation leaves the pool empty. +fn a_failed_reservation_releases_the_pool() { + let _g = serial(); + release(); + // Unmatched buffers under the miss floor stay pooled on a miss. + give(vec![0u8; 4 * MIN_POOLED_BYTES]); + assert!(retained_bytes() > 0); + // No allocator can reserve this: the call fails, but not before the pool was emptied. (The + // retry after the release isn't observable here: it needs an allocator that fails once.) + assert!(try_take_exact(isize::MAX as usize, 0u8).is_none()); + assert_eq!(retained_bytes(), 0); +} + +#[test] +/// Verifies a successful miss preserves unmatched buffers within the miss floor. +fn a_successful_miss_keeps_unmatched_pooled_buffers() { + let _g = serial(); + release(); + give(vec![0u8; 4 * MIN_POOLED_BYTES]); + let v = try_take_exact(2 * MIN_POOLED_BYTES, 0u8); + assert!(v.as_ref().is_some_and(|v| v.len() == 2 * MIN_POOLED_BYTES && v.iter().all(|&b| b == 0))); + assert_eq!(retained_bytes(), 4 * MIN_POOLED_BYTES, "within the miss floor, nothing is dropped"); + release(); +} diff --git a/crates/testkit/src/perf.rs b/crates/testkit/src/perf.rs index 6bdf68ab0a9..38e6a14cb95 100644 --- a/crates/testkit/src/perf.rs +++ b/crates/testkit/src/perf.rs @@ -27,6 +27,19 @@ pub fn process_peak_rss_bytes() -> Option { parse_vm_hwm(&status) } +/// Minor page faults this process has taken so far (`/proc/self/stat` field 10), `None` off +/// Linux. A scenario that maps fresh memory on every run shows up here (#10479). +pub fn minor_faults() -> Option { + let stat = std::fs::read_to_string("/proc/self/stat").ok()?; + parse_minflt(&stat) +} + +fn parse_minflt(stat: &str) -> Option { + // `comm` (field 2) may contain spaces; the fields after its closing `)` start at field 3. + let rest = stat.get(stat.rfind(')')?.checked_add(1)?..)?; + rest.split_whitespace().nth(7)?.parse().ok() +} + fn parse_vm_hwm(status: &str) -> Option { let line = status.lines().find(|l| l.starts_with("VmHWM:"))?; let kb: u64 = line.split_whitespace().nth(1)?.parse().ok()?; @@ -149,6 +162,14 @@ pub fn write_report(path: &str, report: &Value) -> Result<(), String> { mod tests { use super::*; + #[test] + fn minflt_is_field_ten_even_with_spaces_in_comm() { + assert_eq!(parse_minflt("42 (cat) R 1 2 3 0 -1 4194304 122 0 0 0"), Some(122)); + assert_eq!(parse_minflt("42 (a b) c) S 1 2 3 0 -1 0 7 0"), Some(7)); + assert_eq!(parse_minflt("42 (cat) R 1"), None); + assert_eq!(parse_minflt("garbage"), None); + } + #[test] fn summary_nearest_rank() { let v: Vec = (1..=20).map(f64::from).collect(); diff --git a/crates/ui-egui/examples/interactive_bench.rs b/crates/ui-egui/examples/interactive_bench.rs index efeff0927d8..0b4cc5c9522 100644 --- a/crates/ui-egui/examples/interactive_bench.rs +++ b/crates/ui-egui/examples/interactive_bench.rs @@ -83,9 +83,9 @@ struct Bench { /// state later rows need). only: Option, rows: Vec<(String, f64, f64, f64, f64)>, - /// Per row (same order as `rows`): the timed samples and the peak RSS while they ran, for - /// `--json` (`cargo xtask perf`). - extra: Vec<(Vec, Option)>, + /// Per row (same order as `rows`): the timed samples, the peak RSS while they ran and the + /// minor page faults per warm run (all of it, untimed setup included), for `--json` (`cargo xtask perf`). + extra: Vec<(Vec, Option, Option)>, rss: photocraft_testkit::perf::RssSampler, } @@ -127,11 +127,17 @@ impl Bench { } self.rss.reset(); let cold = f(self); + let faults0 = photocraft_testkit::perf::minor_faults(); let mut v: Vec = (0..self.reps).map(|_| f(self)).collect(); - self.extra.push((v.clone(), self.rss.peak())); + // Minor page faults per warm run: memory mapped fresh from the kernel each time (#10479). + // Counted over the whole of `f`, so it includes untimed setup and cleanup (an undo, an + // extra refresh), not only the work the milliseconds measure. + let faults = faults0.zip(photocraft_testkit::perf::minor_faults()).map(|(a, b)| b.saturating_sub(a) / self.reps as u64); + self.extra.push((v.clone(), self.rss.peak(), faults)); v.sort_by(f64::total_cmp); let med = v[v.len() / 2]; - println!("{name:<44} {med:>9.1} ms (min {:>8.1}, max {:>8.1}, cold {:>8.1})", v[0], v[v.len() - 1], cold); + let fl = faults.map_or(String::new(), |f| format!(", {f} faults/run incl. setup")); + println!("{name:<44} {med:>9.1} ms (min {:>8.1}, max {:>8.1}, cold {:>8.1}{fl})", v[0], v[v.len() - 1], cold); self.rows.push((name.to_string(), med, v[0], v[v.len() - 1], cold)); } } @@ -473,11 +479,12 @@ fn main() { .rows .iter() .zip(&b.extra) - .map(|((n, med, min, max, cold), (samples, rss))| { + .map(|((n, med, min, max, cold), (samples, rss, faults))| { let mut r = json!({"name": n, "median_ms": med, "min_ms": min, "max_ms": max, "cold_ms": cold}); // For `cargo xtask perf`: raw samples (it computes p50 / p95) and peak RSS. r["samples_ms"] = json!(samples); r["peak_rss_bytes"] = json!(rss); + r["minor_faults_per_run"] = json!(faults); r }) .collect(); diff --git a/crates/ui-egui/src/dialogs/color_range_ui.rs b/crates/ui-egui/src/dialogs/color_range_ui.rs index 75fe3c67b9c..3b02806d3a5 100644 --- a/crates/ui-egui/src/dialogs/color_range_ui.rs +++ b/crates/ui-egui/src/dialogs/color_range_ui.rs @@ -236,7 +236,7 @@ fn proxy_mask(app: &PhotocraftApp, proxy: &Document, k: u32, params: &Value) -> surf.read_rgba_into(area, &mut px); px } - _ => photocraft_compose::render(proxy, area).px, + _ => photocraft_compose::render(proxy, area).into_px(), }; let invert = params.get("invert").and_then(Value::as_bool).unwrap_or(false); let mut mask: Vec = query diff --git a/crates/ui-egui/src/dialogs/file_ui/web.rs b/crates/ui-egui/src/dialogs/file_ui/web.rs index 0b5ef3cf588..865215d4b5a 100644 --- a/crates/ui-egui/src/dialogs/file_ui/web.rs +++ b/crates/ui-egui/src/dialogs/file_ui/web.rs @@ -119,7 +119,7 @@ fn web_pane(app: &PhotocraftApp, ui: &mut egui::Ui, size: egui::Vec2, p: Option< }; let buf = photocraft_compose::flatten(&wd); let v = ( - Arc::new(buf.px), + Arc::new(buf.into_px()), wd.size.width, wd.size.height, (fw * fh) / (f64::from(wd.size.width) * f64::from(wd.size.height)).max(1.0), diff --git a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs index 92daea25285..8c0ba385e67 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs @@ -628,7 +628,7 @@ fn smart_displace_preview_uses_the_map_document() { applied.add_document((**d).clone(), None); } applied.execute(SMART_FILTER_SET_PARAMS, p.clone()).unwrap(); - let want = photocraft_compose::render(&applied.active().unwrap().doc, doc.bounds()).px; + let want = photocraft_compose::render(&applied.active().unwrap().doc, doc.bounds()).into_px(); let preview = preview_document_for_target( &doc, layer, diff --git a/crates/ui-egui/src/dialogs/vp_ui/tests.rs b/crates/ui-egui/src/dialogs/vp_ui/tests.rs index 19f7786e33b..f45063d35cf 100644 --- a/crates/ui-egui/src/dialogs/vp_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/vp_ui/tests.rs @@ -180,7 +180,7 @@ fn overlapping_stamp_preview_matches_commit_across_batches() { s.strokes[0].points.extend_from_slice(&points[2..]); assert!(s.paint_preview(|| 2)); let (shown, _) = s.shown().unwrap(); - let expected = photocraft_compose::flatten(&shown).px; + let expected = photocraft_compose::flatten(&shown).into_px(); assert_ne!(expected, photocraft_compose::flatten(&app.session.active().unwrap().doc).px); commit(&mut app).unwrap(); assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px, expected, "newLayer={new_layer}"); @@ -217,7 +217,7 @@ fn stamp_preview_paints_over_the_paste_like_ok() { let s = app.distort.vanishing.as_ref().unwrap(); assert!(s.preview_has_paste(), "the preview shows the paste, so the overlay isn't drawn over the strokes"); let (shown, _) = s.shown().unwrap(); - let expected = photocraft_compose::flatten(&shown).px; + let expected = photocraft_compose::flatten(&shown).into_px(); commit(&mut app).unwrap(); assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px, expected, "newLayer={new_layer}"); } @@ -349,7 +349,7 @@ fn ok_paints_the_layer_the_mode_was_opened_on() { app.session.execute("layer.new.layer", json!({"name": "other"})).unwrap(); let other = app.session.active().unwrap().active_layer.unwrap(); sync_preview(&mut app); - let expected = photocraft_compose::flatten(&crate::distort_ui::display_doc(&app, 0).unwrap().0).px; + let expected = photocraft_compose::flatten(&crate::distort_ui::display_doc(&app, 0).unwrap().0).into_px(); commit(&mut app).unwrap(); let d = &app.session.active().unwrap().doc; assert!(d.layer(other).unwrap().surface().unwrap().content_bounds().is_empty(), "newLayer={new_layer}"); @@ -389,7 +389,7 @@ fn an_edit_under_the_mode_shows_on_the_canvas() { let px = shown.layer(layer).unwrap().surface().unwrap(); assert!(px.rgba(210, 30)[1] > 0.9, "the edit shows: {:?}", px.rgba(210, 30)); assert!(px.rgba(120, 80) != st.doc.layer(layer).unwrap().surface().unwrap().rgba(120, 80), "and so does the stroke"); - let expected = photocraft_compose::flatten(&shown).px; + let expected = photocraft_compose::flatten(&shown).into_px(); commit(&mut app).unwrap(); assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px, expected); } diff --git a/crates/ui-egui/src/tools/transform_fx.rs b/crates/ui-egui/src/tools/transform_fx.rs index 60fc45d9938..0ad888536db 100644 --- a/crates/ui-egui/src/tools/transform_fx.rs +++ b/crates/ui-egui/src/tools/transform_fx.rs @@ -256,7 +256,8 @@ pub fn compose(doc: &Document, work: &Layer, plan: &Plan, source: &Source) -> Op let band = Rect::new(shown.x0, y0, shown.x1, y0.saturating_add((px.len() / width.max(1)) as i32)); let mut over = Buffer::transparent(band); effects::composite_with_effects(work, &crop(&content, band), &mut over, &maps, plan.bounds, &doc.patterns); - for (o, p) in px.iter_mut().zip(over.px) { + // Copied, not moved out, so `over` hands its band back to the scratch pool on drop. + for (o, p) in px.iter_mut().zip(over.px.iter().copied()) { *o = p; } }); diff --git a/crates/ui-egui/tests/it/adjust_preview_gpu.rs b/crates/ui-egui/tests/it/adjust_preview_gpu.rs index 2fdae54cbe4..4e8aa8552c7 100644 --- a/crates/ui-egui/tests/it/adjust_preview_gpu.rs +++ b/crates/ui-egui/tests/it/adjust_preview_gpu.rs @@ -152,14 +152,14 @@ fn preview_layer_composites_on_the_gpu_like_the_command() { // may flip a few pixels sitting right at a step (1 % allowed). let skip = if matches!(kind, "threshold" | "posterize") && depth != SampleType::U8 { (b.width() * b.height()) as usize / 100 } else { 0 }; let on_gpu = render_to_vec(&mut comp, &device, &queue, &preview, b).unwrap_or_else(|e| panic!("{what}: {e:?}")); - let on_cpu = photocraft_compose::render(&preview, b).px; + let on_cpu = photocraft_compose::render(&preview, b).into_px(); let d = max_diff(&on_gpu, &on_cpu, skip); assert!(d <= tol_gpu, "{what}: GPU vs CPU {:.2}/255", d * 255.0); let mut s = photocraft_engine::Session::new(); s.add_document(doc.clone(), None); s.select_layer(target).unwrap(); s.execute(&format!("image.adjustments.{kind}"), params.clone()).unwrap(); - let cmd = photocraft_compose::render(&s.active().unwrap().doc, b).px; + let cmd = photocraft_compose::render(&s.active().unwrap().doc, b).into_px(); let d = max_diff(&on_gpu, &cmd, skip); worst = worst.max(d); assert!(d <= tol_cmd, "{what}: GPU preview vs command {:.2}/255", d * 255.0); @@ -184,7 +184,7 @@ fn proxy_preview_composites_on_the_gpu() { for kind in photocraft_ui_egui::adjust_editors::KINDS { let p = proxy_with_settings(&proxy, kind, &sample(kind)).unwrap(); let on_gpu = render_to_vec(&mut comp, &device, &queue, &p, p.bounds()).unwrap(); - let on_cpu = photocraft_compose::render(&p, p.bounds()).px; + let on_cpu = photocraft_compose::render(&p, p.bounds()).into_px(); let d = max_diff(&on_gpu, &on_cpu, 0); assert!(d <= 2.0 / 255.0, "{kind} selection {selection}: {:.2}/255", d * 255.0); } From 5d9c57e60db966382abda2638d0ccbb7489d8ee7 Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Mon, 2 Nov 2026 14:00:46 +0530 Subject: [PATCH 75/77] Linux: return memory of closed documents to the system (#8743) (#10515) * perf: reuse large buffers so a pinned glibc trim threshold costs no speed (#10479) With MALLOC_TRIM_THRESHOLD_ set (#8743), glibc maps every allocation over 128 KiB fresh, so tiles, compositor bands and filter scratch were page-faulted in on every call: viewport compose 3.6x slower, Gaussian Blur up to 1.8x, .pcraft save 2.4x. - photocraft_raster::scratch: a process-wide, capped pool of large Vec buffers (u8/u16/f32/[f32; 4]). A miss drops the oldest buffers worth its size down to a 256 MiB floor, so peak memory stays near glibc's defaults. The engine releases the pool after any command that closes a document, Headless::close does too, and an idle thread releases it after 2 s unused. - Tiles, compose Buffer/masks/bands, algo Image and the blur paths, engine adjustment/filter scratch, GPU tile upload and io import buffers go through the pool. - .pcraft save reuses one zstd FrameCompressor per worker (byte-identical). - interactive_bench reports minor page faults per run. 36 MP, trim threshold set vs glibc defaults: viewport 5.6 vs 6.1 ms (was 22.7), Blur r4 445 vs 437 ms (was 852), Curves CPU proxy 35.0 vs 35.7 ms (was 50), flatten 146 vs 147 ms (was 237), save .pcraft 251 vs 230 ms (was 545). RSS after closing a 5400x7200 document: 21 MB with trim set. * fix(linux): restart once with glibc's trim threshold set so closed documents return memory (#8743) With glibc's default malloc, the memory of a closed document stays with the process: freeing a large buffer raises glibc's dynamic mmap threshold, so later tile buffers land in heap pages glibc keeps. A session that opened and closed a 5400x7200 document held ~450 MiB afterwards. photocraft_engine::malloc_tuning::apply(), called first in both binaries' main, re-executes the binary once with MALLOC_TRIM_THRESHOLD_=131072 on Linux with glibc: same PID, arguments, argv[0] and environment, in safe Rust (CommandExt::exec). A malloc variable or glibc.malloc.* tunable the user or a package already set is left alone, so setting MALLOC_TRIM_THRESHOLD_ opts out. No-op on macOS, Windows, musl and wasm. Depends on the scratch-buffer pool (#10479), without which the pinned threshold slows filters, previews, flatten and .pcraft save by 26-209%. * fix: corpus tests build again; return remaining pooled buffers (#10479 review) - Corpus-gated io tests and the Photoshop-oracle test moved `.px` out of a `Buffer`, which now implements `Drop` (E0509 with `--features corpus`): use `into_px()`. - io: masks, the merged image, extra channels, smart-filter masks, smart-object pixels and patterns give their `interleave` buffers back to the scratch pool after writing them. - compose: recycle the mask values of a pass-through group, `effect_shape` and both `split_parts` callers. - Styled Free Transform preview copies each band out instead of moving it, so the band returns to the pool. - interactive_bench: the fault count covers each whole run, untimed setup included; say so. * fix: corpus tests build again; return remaining pooled buffers (#10479 review) - Corpus-gated io tests and the Photoshop-oracle test moved `.px` out of a `Buffer`, which now implements `Drop` (E0509 with `--features corpus`): use `into_px()`. - io: masks, the merged image, extra channels, smart-filter masks, smart-object pixels and patterns give their `interleave` buffers back to the scratch pool after writing them. - compose: recycle the mask values of a pass-through group, `effect_shape` and both `split_parts` callers. - Styled Free Transform preview copies each band out instead of moving it, so the band returns to the pool. - interactive_bench: the fault count covers each whole run, untimed setup included; say so. * fix: recycle the masks of adjustment-atop and shape layers (#10479 review) * fix: recycle the masks of adjustment-atop and shape layers (#10479 review) * fix: recycle effect hiding masks (#10479 review) * fix: recycle effect hiding masks (#10479 review) * fix: recycle knockout, CMYK and GPU shape masks; release the pool when Split/Merge Channels close a document (#10479 review) * fix: recycle knockout, CMYK and GPU shape masks; release the pool when Split/Merge Channels close a document (#10479 review) * fix: release the pool when a closed document's cancelled workers exit; idle-release switch for tests; don't pool PSD planes (#10479 review) * fix: release the pool when a closed document's cancelled workers exit; idle-release switch for tests; don't pool PSD planes (#10479 review) * fix: release the pool for workers cancelled before their document closes; take the pool lock for budget and idle-release changes (#10479 review) * fix: release the pool for workers cancelled before their document closes; take the pool lock for budget and idle-release changes (#10479 review) * fix: idle release rechecks activity under the lock; try_take_exact releases the pool and retries before failing (#10479 review) * fix: idle release rechecks activity under the lock; try_take_exact releases the pool and retries before failing (#10479 review) * test: cover a successful try_take_exact miss; name the failed-reservation test for what it checks (#10479 review) * test: cover a successful try_take_exact miss; name the failed-reservation test for what it checks (#10479 review) * fix: pool the final GPU effect shape buffer and return it after use (#10479 review) * fix: pool the final GPU effect shape buffer and return it after use (#10479 review) * docs: describe scratch pool lifecycle regression invariants * test: verify polling releases cancelled document scratch buffers * perf: recycle remaining transform selection and PSD scratch buffers * fix: free PSD gather bands before allocating channel planes * test: assert exact scratch take reuses pooled storage --- apps/photocraft-cli/src/main.rs | 2 + apps/photocraft-cli/tests/it/main.rs | 2 + apps/photocraft-cli/tests/it/malloc_tuning.rs | 41 ++++++++++ apps/photocraft/src/main.rs | 5 +- crates/engine/src/lib.rs | 1 + crates/engine/src/malloc_tuning.rs | 81 +++++++++++++++++++ 6 files changed, 131 insertions(+), 1 deletion(-) create mode 100644 apps/photocraft-cli/tests/it/malloc_tuning.rs create mode 100644 crates/engine/src/malloc_tuning.rs diff --git a/apps/photocraft-cli/src/main.rs b/apps/photocraft-cli/src/main.rs index ea5598f99d4..6e21c2ac445 100644 --- a/apps/photocraft-cli/src/main.rs +++ b/apps/photocraft-cli/src/main.rs @@ -1,6 +1,8 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] fn main() { + // May re-execute this process with glibc tuned to return freed document memory (#8743). + photocraft_engine::malloc_tuning::apply(); // `args_os`, not `args`: a non-Unicode argument (a Latin-1 file name on Linux) must reach clap, // not panic before anything is printed (issue #1108). let code = photocraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr()); diff --git a/apps/photocraft-cli/tests/it/main.rs b/apps/photocraft-cli/tests/it/main.rs index 65092cdee41..2729f742516 100644 --- a/apps/photocraft-cli/tests/it/main.rs +++ b/apps/photocraft-cli/tests/it/main.rs @@ -1,6 +1,8 @@ //! The crate's integration tests, linked into one test binary. mod cli; +#[cfg(all(target_os = "linux", target_env = "gnu"))] +mod malloc_tuning; mod man_and_completions; mod orientation; diff --git a/apps/photocraft-cli/tests/it/malloc_tuning.rs b/apps/photocraft-cli/tests/it/malloc_tuning.rs new file mode 100644 index 00000000000..a7513a714a3 --- /dev/null +++ b/apps/photocraft-cli/tests/it/malloc_tuning.rs @@ -0,0 +1,41 @@ +//! The binary re-executes itself with glibc's trim threshold set (#8743), keeping its arguments +//! and a value the user set. + +use std::io::{BufRead, BufReader, Write}; +use std::process::{Command, Stdio}; + +use photocraft_engine::malloc_tuning::{TRIM_THRESHOLD, TRIM_THRESHOLD_VAR}; + +/// The environment of a running `serve` once it answered a request, as `NAME=value` entries. +fn serve_environ(set: Option<&str>) -> Vec { + let mut cmd = Command::new(crate::binary()); + for var in [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX", "GLIBC_TUNABLES"] { + cmd.env_remove(var); + } + if let Some(v) = set { + cmd.env(TRIM_THRESHOLD_VAR, v); + } + let mut child = cmd.arg("serve").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap(); + let mut stdin = child.stdin.take().unwrap(); + writeln!(stdin, r#"{{"id":1,"method":"session.list"}}"#).unwrap(); + let mut reply = String::new(); + BufReader::new(child.stdout.take().unwrap()).read_line(&mut reply).unwrap(); + assert!(reply.contains(r#""id":1"#), "serve answered after the re-exec: {reply}"); + // The same process: `exec` keeps the PID, so this is the re-executed program's environment. + let environ = std::fs::read(format!("/proc/{}/environ", child.id())).unwrap(); + drop(stdin); + child.wait().unwrap(); + environ.split(|&b| b == 0).map(|e| String::from_utf8_lossy(e).into_owned()).collect() +} + +#[test] +fn sets_the_trim_threshold() { + let env = serve_environ(None); + assert!(env.contains(&format!("{TRIM_THRESHOLD_VAR}={TRIM_THRESHOLD}")), "{env:?}"); +} + +#[test] +fn keeps_a_value_the_user_set() { + let env = serve_environ(Some("999999")); + assert!(env.contains(&format!("{TRIM_THRESHOLD_VAR}=999999")), "{env:?}"); +} diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index e19a9d45e82..3738ffc8d12 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -340,7 +340,10 @@ fn write_start_marker(sentinel: &gpu_startup::SharedSentinel, plan: &gpu_startup } fn main() -> eframe::Result { - // First, so the panic hook and every start-up warning are recorded (`logging`). + // Before anything starts a thread: may re-execute this process with glibc tuned to return + // the memory of closed documents (#8743). + photocraft_engine::malloc_tuning::apply(); + // Then, so the panic hook and every start-up warning are recorded (`logging`). let logger = logging::install(); crash_guard::install_hook(); #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5e6cc66ab03..b49675176ee 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -29,6 +29,7 @@ pub mod kys; pub mod layer_place; pub mod layer_style; pub mod link_watch; +pub mod malloc_tuning; pub mod new_layer; mod param_check; mod pixels; diff --git a/crates/engine/src/malloc_tuning.rs b/crates/engine/src/malloc_tuning.rs new file mode 100644 index 00000000000..f9c5947c471 --- /dev/null +++ b/crates/engine/src/malloc_tuning.rs @@ -0,0 +1,81 @@ +//! glibc malloc tuning for the native binaries (#8743). +//! +//! With glibc's defaults, the memory of a closed document stays with the process: freeing a large +//! buffer raises glibc's dynamic mmap threshold (up to 32 MiB), so later tile buffers come from the +//! heap, whose freed pages glibc keeps for reuse instead of giving them back. A session that opened +//! and closed a 5400 × 7200 document held ~540 MiB afterwards; with `MALLOC_TRIM_THRESHOLD_` set it +//! went back to ~20 MiB, and the peak was lower too. Setting the threshold explicitly turns the +//! dynamic adjustment off (mallopt(3)), so large buffers are mapped and unmapped on their own and +//! the heap top is trimmed as it is freed. Mapping fresh pages on every call is slow, so the large +//! short-lived buffers come from `photocraft_raster::scratch` instead, which reuses them and +//! releases them when a document closes or the pool goes idle (#10479). +//! +//! glibc reads its tunables once, when the process starts, and changing the environment from Rust +//! needs `unsafe` (and comes too late), so [`apply`] re-executes the binary with the variable set: +//! the same process (PID), arguments, `argv[0]` and environment, on Linux with glibc only. A value +//! the user or a package already set, for this or another malloc tunable, is left alone, so setting +//! `MALLOC_TRIM_THRESHOLD_` to anything opts out. Programs PhotoCraft starts inherit the variable. + +use std::ffi::OsString; + +/// The glibc environment variable [`apply`] sets. +pub const TRIM_THRESHOLD_VAR: &str = "MALLOC_TRIM_THRESHOLD_"; + +/// Its value: glibc's own default trim threshold (128 KiB), now fixed instead of dynamic. +pub const TRIM_THRESHOLD: &str = "131072"; + +/// glibc malloc variables that mean someone tuned malloc themselves. +const MALLOC_VARS: [&str; 5] = [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX"]; + +/// Whether a start-up should re-execute with [`TRIM_THRESHOLD_VAR`] set, given the environment: +/// only when no malloc variable or `glibc.malloc.*` tunable is set (which also ends the re-exec). +pub fn needs_restart(var: impl Fn(&str) -> Option) -> bool { + if MALLOC_VARS.iter().any(|v| var(v).is_some()) { + return false; + } + !var("GLIBC_TUNABLES").is_some_and(|t| t.to_string_lossy().contains("glibc.malloc.")) +} + +/// Re-execute this binary with [`TRIM_THRESHOLD_VAR`] set when [`needs_restart`] says so. Call it +/// first in `main`, before any thread starts. It returns only when nothing needed to change or the +/// re-exec failed, and then the process carries on with glibc's defaults. +#[cfg(all(target_os = "linux", target_env = "gnu"))] +pub fn apply() { + use std::os::unix::process::CommandExt; + if !needs_restart(|k| std::env::var_os(k)) { + return; + } + let Ok(exe) = std::env::current_exe() else { return }; + let mut args = std::env::args_os(); + let mut cmd = std::process::Command::new(exe); + if let Some(argv0) = args.next() { + cmd.arg0(argv0); + } + // `exec` replaces the process and only returns on failure. + let err = cmd.args(args).env(TRIM_THRESHOLD_VAR, TRIM_THRESHOLD).exec(); + eprintln!("PhotoCraft: could not restart with {TRIM_THRESHOLD_VAR} set ({err}); memory of closed documents may not be returned to the system"); +} + +/// Nothing to tune off glibc. +#[cfg(not(all(target_os = "linux", target_env = "gnu")))] +pub fn apply() {} + +#[cfg(test)] +mod tests { + use super::*; + + fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option + 'a { + move |k| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| OsString::from(v)) + } + + #[test] + fn restarts_only_without_malloc_tuning() { + assert!(needs_restart(env(&[]))); + assert!(needs_restart(env(&[("HOME", "/home/a"), ("GLIBC_TUNABLES", "glibc.cpu.hwcaps=-AVX2")]))); + assert!(!needs_restart(env(&[(TRIM_THRESHOLD_VAR, TRIM_THRESHOLD)])), "the re-executed process stops"); + assert!(!needs_restart(env(&[(TRIM_THRESHOLD_VAR, "")])), "any value opts out"); + assert!(!needs_restart(env(&[("MALLOC_MMAP_THRESHOLD_", "1048576")]))); + assert!(!needs_restart(env(&[("MALLOC_ARENA_MAX", "2")]))); + assert!(!needs_restart(env(&[("GLIBC_TUNABLES", "glibc.malloc.trim_threshold=0")]))); + } +} From 289dd0a874763d6528bab2184a87a1b53771c02a Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Mon, 2 Nov 2026 08:43:46 -0800 Subject: [PATCH 76/77] Format: take the .pcraft envelope from craft-pcraft-format (#10724) * Format: take the .pcraft envelope from craft-pcraft-format The manifest envelope, TileRef, Hash, FORMAT_VERSION, EXTENSION, the entry names, tile_path and blob_path, is_valid_hash, the manifest nesting and item checks and the migration runner now come from craft-libs' craft-pcraft-format. photocraft-format re-exports them, so callers do not change. Manifest is craft_pcraft_format::Manifest. Saved bundles keep the same bytes. A save still checks only the nesting and the item count of its manifest, not its size, and the manifest nesting limit is still computed from photocraft_doc::MAX_GROUP_DEPTH. Tests: a save, load and save again gives the same bytes in every color mode and depth, with and without previews; MAX_GROUP_DEPTH equals craft_pcraft_format::MAX_GROUP_DEPTH. * Format: pin craft-pcraft-format from storytold/craft-libs * Format: read manifests with craft-pcraft-format's read_manifest_with Pins craft-pcraft-format to dca870a0, the head of craft-libs #407. Loading reads the manifest with read_manifest_with, which runs the limit check, the version check, the migration steps and the envelope read in one path; the layers are still decoded one at a time after the rest of the document. A save builds the manifest with Manifest::new and tile references with TileRef::new, and the bundle's directory names and the .zst suffix come from the crate's constants. Saved bytes and error messages are unchanged. * Format: pin craft-pcraft-format to craft-libs #407's head 04dd1bd 04dd1bd changes only the crate's docs and a test, so photocraft-format builds the same code. * Format: pin craft-pcraft-format to craft-libs main at b8f7d93 craft-libs #407 merged as b8f7d93. Its read_manifest also refuses a thumbnail other than thumb.png and a composite other than composite/preview.png, the only names photocraft-format writes. --- Cargo.lock | 11 +++ Cargo.toml | 1 + crates/format/Cargo.toml | 1 + crates/format/src/autosave.rs | 2 +- crates/format/src/convert.rs | 6 +- crates/format/src/lib.rs | 23 ++++- crates/format/src/manifest.rs | 28 +----- crates/format/src/migrate.rs | 44 ++++----- crates/format/src/store.rs | 134 +++++++++------------------- crates/format/tests/it/roundtrip.rs | 23 +++++ 10 files changed, 119 insertions(+), 154 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b22b872d1d8..eb50bad6fdf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1388,6 +1388,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-pcraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b8f7d93b00dfb8f172938f3d2d796ae62dcfe123#b8f7d93b00dfb8f172938f3d2d796ae62dcfe123" +dependencies = [ + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-print" version = "0.1.0" @@ -5199,6 +5209,7 @@ name = "photocraft-format" version = "0.19.0" dependencies = [ "blake3", + "craft-pcraft-format", "crc32fast", "exacl", "flate2", diff --git a/Cargo.toml b/Cargo.toml index ef1f6d5fdb1..4674a55e6fd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,6 +42,7 @@ photocraft-ipp = { path = "crates/ipp" } craft-print = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" } +craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b8f7d93b00dfb8f172938f3d2d796ae62dcfe123" } # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["egui"] } thiserror = "2" diff --git a/crates/format/Cargo.toml b/crates/format/Cargo.toml index 42677466335..a04875e4438 100644 --- a/crates/format/Cargo.toml +++ b/crates/format/Cargo.toml @@ -15,6 +15,7 @@ photocraft-color = { workspace = true } photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-codecs = { workspace = true } +craft-pcraft-format = { workspace = true } serde = { workspace = true } serde_json = { workspace = true, features = ["unbounded_depth", "float_roundtrip"] } thiserror = { workspace = true } diff --git a/crates/format/src/autosave.rs b/crates/format/src/autosave.rs index 7b379451dd5..2ab8676c662 100644 --- a/crates/format/src/autosave.rs +++ b/crates/format/src/autosave.rs @@ -451,7 +451,7 @@ fn sweep_orphans(recovery_dir: &Path, min_age: std::time::Duration) { } // Anything at the sidecar's path (even a broken one) keeps the bundle. let has_sidecar = std::fs::symlink_metadata(recovery_dir.join(format!("{key}.json"))).is_ok(); - let parts = [path.clone(), path.join("tiles"), path.join("blobs")]; + let parts = [path.clone(), path.join(craft_pcraft_format::TILES_DIR), path.join(craft_pcraft_format::BLOBS_DIR)]; // A committed bundle is recoverable work: keep exactly what `list_recovery` lists. if !has_sidecar && sidecarless_entry(recovery_dir, &path).is_none() && parts.iter().all(|p| untouched_for(p, min_age, true)) { let _ = std::fs::remove_dir_all(&path); diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs index b5cfda9ad56..fbe121c1535 100644 --- a/crates/format/src/convert.rs +++ b/crates/format/src/convert.rs @@ -81,9 +81,7 @@ fn key4(s: &str) -> Result<[u8; 4]> { unhex(s)?.try_into().map_err(|_| FormatError::corrupt(format!("bad 4-byte key `{s}`"))) } -pub(crate) fn is_valid_hash(h: &str) -> bool { - h.len() == 64 && h.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) -} +pub(crate) use craft_pcraft_format::is_valid_hash; /// Convert native-endian sample bytes to little-endian in place (and back: /// the swap is an involution). @@ -110,7 +108,7 @@ fn surface_m(s: &Surface, sink: &mut dyn Sink) -> SurfaceM { let mut dp = vec![0u8; f.bytes_per_pixel()]; encode_pixel(&f, &s.default_pixel(), &mut dp); swap_to_le(&mut dp, f.sample); - SurfaceM { format: f, default: hex(&dp), tiles: s.tiles().map(|(c, t)| TileRef { tx: c.tx, ty: c.ty, hash: sink.tile(f, t) }).collect() } + SurfaceM { format: f, default: hex(&dp), tiles: s.tiles().map(|(c, t)| TileRef::new(c.tx, c.ty, sink.tile(f, t))).collect() } } fn opt_blob(b: &Option>>, sink: &mut dyn Sink) -> Option { diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 992e925ae9f..cb1c5eb41d3 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -50,7 +50,7 @@ pub use read::read_file; pub use store::{ByteSource, DEFAULT_REVERIFY_BUDGET, PcraftWriter, SaveStats, read_entry}; /// File extension of the native format. -pub const EXTENSION: &str = "pcraft"; +pub use craft_pcraft_format::EXTENSION; #[derive(Debug, thiserror::Error)] pub enum FormatError { @@ -76,6 +76,20 @@ impl FormatError { } } +impl From for FormatError { + fn from(e: craft_pcraft_format::Error) -> Self { + use craft_pcraft_format::Error; + match e { + Error::Corrupt(m) => FormatError::Corrupt(m), + Error::Unsupported(m) => FormatError::Unsupported(m), + Error::TooNew { found, supported, .. } => FormatError::TooNew { found, supported }, + Error::LimitExceeded(m) => FormatError::LimitExceeded(m), + Error::Json(e) => FormatError::Json(e), + other => FormatError::Corrupt(other.to_string()), + } + } +} + pub type Result = std::result::Result; /// Previews to embed. The format crate cannot render (it sits beside the @@ -119,10 +133,11 @@ pub const MAX_CANVAS_PIXELS: u64 = MAX_CANVAS_SIDE as u64 * MAX_CANVAS_SIDE as u impl Default for LoadOptions { fn default() -> Self { + let limits = craft_pcraft_format::Limits::default(); LoadOptions { - max_manifest_bytes: 256 << 20, - max_blob_bytes: 1 << 30, - max_total_bytes: 16 << 30, + max_manifest_bytes: limits.max_manifest_bytes, + max_blob_bytes: limits.max_blob_bytes, + max_total_bytes: limits.max_total_bytes, preserve_ids: true, max_canvas_side: MAX_CANVAS_SIDE, max_canvas_pixels: MAX_CANVAS_PIXELS, diff --git a/crates/format/src/manifest.rs b/crates/format/src/manifest.rs index 1164bc0a683..dd3a012ad2d 100644 --- a/crates/format/src/manifest.rs +++ b/crates/format/src/manifest.rs @@ -14,24 +14,11 @@ use photocraft_doc::{ use photocraft_geom::{Affine, Size}; use serde::{Deserialize, Serialize}; -/// Current manifest version written by this build. -pub const FORMAT_VERSION: u32 = 1; +pub use craft_pcraft_format::{FORMAT_VERSION, Hash, TileRef}; -/// Hex-encoded BLAKE3 hash (64 chars). -pub type Hash = String; - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct Manifest { - pub format_version: u32, - /// Free-form writer identification, e.g. `photocraft-format 0.1.0`. - pub generator: String, - pub document: DocM, - /// Optional previews present in the bundle. - #[serde(default)] - pub thumbnail: Option, - #[serde(default)] - pub composite: Option, -} +/// The manifest: craft-pcraft-format's envelope (`format_version`, `generator`, the optional +/// `thumbnail` and `composite` previews) around the document [`DocM`]. +pub type Manifest = craft_pcraft_format::Manifest; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct DocM { @@ -154,13 +141,6 @@ pub struct NamedPathM { pub psd_raw: Option, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct TileRef { - pub tx: i32, - pub ty: i32, - pub hash: Hash, -} - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SurfaceM { pub format: PixelFormat, diff --git a/crates/format/src/migrate.rs b/crates/format/src/migrate.rs index d24581275e3..429b5bc281d 100644 --- a/crates/format/src/migrate.rs +++ b/crates/format/src/migrate.rs @@ -1,43 +1,29 @@ //! Manifest migrations. Each step upgrades the raw JSON from version `n` to //! `n + 1`, so old bundles keep loading as the schema evolves. -use serde_json::Value; +use crate::FormatError; -use crate::manifest::FORMAT_VERSION; -use crate::{FormatError, Result}; - -pub(crate) type Step = fn(&mut Value) -> Result<()>; +pub(crate) type Step = craft_pcraft_format::Step; /// `STEPS[i]` upgrades version `i + 1` to `i + 2`. Empty while version 1 is -/// the only version. +/// the only version. `craft_pcraft_format::read_manifest_with` runs them on load. pub(crate) const STEPS: &[Step] = &[]; -/// Upgrade `v` in place to `target` using `steps`. -pub(crate) fn migrate_with(v: &mut Value, steps: &[Step], target: u32) -> Result { - let found = v.get("format_version").and_then(Value::as_u64).ok_or_else(|| FormatError::corrupt("manifest has no format_version"))?; - let found = u32::try_from(found).map_err(|_| FormatError::corrupt("format_version out of range"))?; - if found == 0 { - return Err(FormatError::corrupt("format_version 0 is invalid")); - } - if found > target { - return Err(FormatError::TooNew { found, supported: target }); - } - for ver in found..target { - let step = steps.get(ver as usize - 1).ok_or_else(|| FormatError::Unsupported(format!("no migration from format {ver}")))?; - step(v)?; - v["format_version"] = Value::from(ver + 1); - } - Ok(found) -} - -pub(crate) fn migrate(v: &mut Value) -> Result { - migrate_with(v, STEPS, FORMAT_VERSION) -} - #[cfg(test)] mod tests { use super::*; - use serde_json::json; + use crate::Result; + use crate::manifest::FORMAT_VERSION; + use serde_json::{Value, json}; + + /// Upgrade `v` in place to `target` using `steps`, with craft-pcraft-format's runner. + fn migrate_with(v: &mut Value, steps: &[Step], target: u32) -> Result { + craft_pcraft_format::migrate(v, steps, target) + } + + fn migrate(v: &mut Value) -> Result { + migrate_with(v, STEPS, FORMAT_VERSION) + } fn rename_title(v: &mut Value) -> Result<()> { let t = v["document"]["title"].take(); diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index 67bb8df27bb..5fa9b55425f 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -15,21 +15,12 @@ use crate::manifest::{ContentM, FORMAT_VERSION, Hash, LayerM, Manifest}; use crate::zip::{ZipReader, ZipWriter}; use crate::{FormatError, LoadOptions, Result, SaveOptions}; -pub(crate) const MANIFEST: &str = "manifest.json"; -pub(crate) const THUMB: &str = "thumb.png"; -pub(crate) const COMPOSITE: &str = "composite/preview.png"; -/// The file a directory save holds an exclusive lock on for its whole transaction (#4957). -pub(crate) const SAVE_LOCK: &str = "save.lock"; +use craft_pcraft_format::{BLOBS_DIR, COMPOSITE_DIR, TILES_DIR, blob_path, tile_path}; +// `SAVE_LOCK` is the file a directory save holds an exclusive lock on for its whole transaction (#4957). +pub(crate) use craft_pcraft_format::{COMPOSITE, MANIFEST, SAVE_LOCK, THUMB}; /// How long a directory save waits for another save of the same bundle to finish. const SAVE_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(10); -fn tile_path(h: &str) -> String { - format!("tiles/{h}.zst") -} -fn blob_path(h: &str) -> String { - format!("blobs/{h}.zst") -} - /// The bytes an [`Object`] stores, owned by (or shared with) the compressor's source so one /// [`Compressor`] can be reused for objects of any lifetime. enum Source { @@ -228,64 +219,27 @@ pub fn read_entry(file: &mut impl std::io::Read, len: u64, max: usize, path: &st // Loading // --------------------------------------------------------------------------- -/// Deepest JSON nesting a manifest may have: each group level adds three (the layer object, its -/// content object and the `children` array), with headroom for the document and leaf layer fields. -/// The saver checks the same bound, so every bundle it writes loads again. -const MAX_MANIFEST_DEPTH: usize = 3 * (convert::MAX_GROUP_DEPTH + 1) + 64; - -/// Most JSON items (arrays and objects opened, plus elements and members after a comma) a -/// manifest may hold. Parsing builds a `serde_json::Value` tree of tens of bytes per item, so -/// `[0,0,…]` costs about 16× its size in memory; a typical manifest spends 20 bytes or more per -/// item, so this still admits manifests of about 80 MiB. -const MAX_MANIFEST_ITEMS: usize = 4 << 20; - -/// Rejects JSON nested deeper than [`MAX_MANIFEST_DEPTH`] or holding more than -/// [`MAX_MANIFEST_ITEMS`] items with a linear scan (no recursion), so parsing with serde_json's -/// recursion limit disabled can't exhaust the stack, nor tiny values the memory, on hostile input. -fn check_manifest_depth(json: &[u8]) -> Result<()> { - let (mut depth, mut items, mut in_str, mut escaped) = (0usize, 0usize, false, false); - for &b in json { - if in_str { - match b { - _ if escaped => escaped = false, - b'\\' => escaped = true, - b'"' => in_str = false, - _ => {} - } - continue; - } - match b { - b'"' => in_str = true, - b'[' | b'{' => { - depth += 1; - if depth > MAX_MANIFEST_DEPTH { - return Err(FormatError::LimitExceeded(format!("manifest JSON nested deeper than {MAX_MANIFEST_DEPTH} levels"))); - } - } - b']' | b'}' => depth = depth.saturating_sub(1), - _ => {} - } - if matches!(b, b'[' | b'{' | b',') { - items += 1; - if items > MAX_MANIFEST_ITEMS { - return Err(FormatError::LimitExceeded(format!("manifest JSON holds more than {MAX_MANIFEST_ITEMS} values"))); - } - } - } - Ok(()) +/// The limits a manifest is checked against: craft-pcraft-format's item limit, the JSON nesting +/// of [`convert::MAX_GROUP_DEPTH`] nested groups ([`craft_pcraft_format::manifest_depth`]) and at +/// most `max_manifest_bytes` bytes. The saver checks the same nesting and items, so every bundle +/// it writes loads again. +fn manifest_limits(max_manifest_bytes: usize) -> craft_pcraft_format::Limits { + let mut limits = craft_pcraft_format::Limits::default(); + limits.max_manifest_bytes = max_manifest_bytes; + limits.max_depth = craft_pcraft_format::manifest_depth(convert::MAX_GROUP_DEPTH); + limits } pub(crate) fn read_manifest(src: &dyn ByteSource, opts: &LoadOptions) -> Result { let raw = src.get(MANIFEST, opts.max_manifest_bytes)?; - // serde_json stops at 128 levels (about 40 nested groups); the bounded check replaces that limit. - check_manifest_depth(&raw)?; - let mut de = serde_json::Deserializer::from_slice(&raw); - de.disable_recursion_limit(); - let mut v = ::deserialize(&mut de)?; - de.end()?; - crate::migrate::migrate(&mut v)?; - let layers = take_array(&mut v, "/document/layers"); - let mut m: Manifest = serde_json::from_value(v)?; + // serde_json stops at 128 levels (about 40 nested groups); `read_manifest_with` checks the + // nesting and the items in one pass, then parses without that limit. + let limits = manifest_limits(opts.max_manifest_bytes); + let mut layers = Vec::new(); + let mut m: Manifest = craft_pcraft_format::read_manifest_with(&raw, &limits, crate::migrate::STEPS, FORMAT_VERSION, |mut document| { + layers = take_array(&mut document, "/layers"); + Ok::<_, FormatError>(serde_json::from_value(document)?) + })?; m.document.layers = layers_from_json(layers)?; // A number past f32's range decodes as infinity, which no save could write back (#6862). if let Err(crate::finite::Problem::NonFinite { path }) = crate::finite::check(&m) { @@ -342,11 +296,10 @@ impl LoadFetch<'_> { impl Fetch for LoadFetch<'_> { fn tile(&mut self, hash: &str, len: usize) -> Result> { - if !is_valid_hash(hash) { + let Some(path) = tile_path(hash) else { return Err(FormatError::corrupt(format!("invalid tile hash `{hash}`"))); - } + }; self.account(len)?; - let path = tile_path(hash); let z = self.src.get(&path, len + len / 8 + 4096)?; let data = decompress(&z, len, &path)?; if hash_bytes(&data) != hash { @@ -367,10 +320,9 @@ impl Fetch for LoadFetch<'_> { if let Some(b) = self.blobs.get(hash) { return if b.len() <= limit { Ok(b.clone()) } else { Err(FormatError::LimitExceeded("optional preview blob exceeds its limit".into())) }; } - if !is_valid_hash(hash) { + let Some(path) = blob_path(hash) else { return Err(FormatError::corrupt(format!("invalid blob hash `{hash}`"))); - } - let path = blob_path(hash); + }; // The stored zstd frame of incompressible data is a little larger than the data, so a // blob right at `limit` must still be read; `decompress_bounded` enforces `limit`. let z = self.src.get(&path, limit.saturating_add(limit / 8).saturating_add(4096))?; @@ -686,7 +638,7 @@ fn bundle_root(dir: &Path) -> Result { std::fs::create_dir_all(&dir)?; let root = std::fs::canonicalize(&dir)?; plain_directory_or_missing(&root)?; - for sub in ["tiles", "blobs", "composite"] { + for sub in [TILES_DIR, BLOBS_DIR, COMPOSITE_DIR] { let path = root.join(sub); plain_directory_or_missing(&path)?; if !path.exists() { @@ -706,7 +658,7 @@ fn bundle_root(dir: &Path) -> Result { fn validate_bundle_file(root: &Path, path: &Path) -> Result<()> { let parent = path.parent().ok_or_else(|| unsafe_bundle_entry(path))?; - if parent != root && parent != root.join("tiles") && parent != root.join("blobs") && parent != root.join("composite") { + if parent != root && parent != root.join(TILES_DIR) && parent != root.join(BLOBS_DIR) && parent != root.join(COMPOSITE_DIR) { return Err(unsafe_bundle_entry(path)); } plain_directory_or_missing(parent)?; @@ -863,9 +815,9 @@ impl BundleGc { let flags = gc_directory_flags(); let root = open(root, flags, Mode::empty()).map_err(std::io::Error::from)?; - let tiles = openat(&root, "tiles", flags, Mode::empty()).map_err(std::io::Error::from)?; - let blobs = openat(&root, "blobs", flags, Mode::empty()).map_err(std::io::Error::from)?; - let composite = openat(&root, "composite", flags, Mode::empty()).map_err(std::io::Error::from)?; + let tiles = openat(&root, TILES_DIR, flags, Mode::empty()).map_err(std::io::Error::from)?; + let blobs = openat(&root, BLOBS_DIR, flags, Mode::empty()).map_err(std::io::Error::from)?; + let composite = openat(&root, COMPOSITE_DIR, flags, Mode::empty()).map_err(std::io::Error::from)?; Ok(Self { root, tiles, blobs, composite }) } @@ -875,8 +827,8 @@ impl BundleGc { THUMB => (&self.root, THUMB), COMPOSITE => (&self.composite, "preview.png"), _ => match relative.split_once('/') { - Some(("tiles", name)) if name.strip_suffix(".zst").is_some_and(is_valid_hash) => (&self.tiles, name), - Some(("blobs", name)) if name.strip_suffix(".zst").is_some_and(is_valid_hash) => (&self.blobs, name), + Some((TILES_DIR, name)) if name.strip_suffix(craft_pcraft_format::OBJECT_SUFFIX).is_some_and(is_valid_hash) => (&self.tiles, name), + Some((BLOBS_DIR, name)) if name.strip_suffix(craft_pcraft_format::OBJECT_SUFFIX).is_some_and(is_valid_hash) => (&self.blobs, name), _ => return Err(FormatError::Unsupported(format!("invalid bundle cleanup target: {relative}"))), }, }; @@ -1000,13 +952,9 @@ impl PcraftWriter { convert::check_nesting(&doc.layers)?; let mut c = Collect { hash_cache: Some(&mut self.hash_cache), blob_hash_cache: Some(&mut self.blob_hash_cache), ..Default::default() }; let document = convert::doc_m(doc, &mut c); - let manifest = Manifest { - format_version: FORMAT_VERSION, - generator: format!("photocraft-format {}", env!("CARGO_PKG_VERSION")), - document, - thumbnail: opts.thumbnail.as_ref().map(|_| THUMB.to_owned()), - composite: opts.composite.as_ref().map(|_| COMPOSITE.to_owned()), - }; + let mut manifest = Manifest::new(format!("photocraft-format {}", env!("CARGO_PKG_VERSION")), document); + manifest.thumbnail = opts.thumbnail.as_ref().map(|_| THUMB.to_owned()); + manifest.composite = opts.composite.as_ref().map(|_| COMPOSITE.to_owned()); // serde_json writes NaN and the infinities as `null`, which the manifest's float fields // refuse on load (issue #1101): refuse the save instead, naming the value. crate::finite::check(&manifest).map_err(|e| match e { @@ -1014,14 +962,16 @@ impl PcraftWriter { crate::finite::Problem::Other(m) => FormatError::Unsupported(format!("manifest: {m}")), })?; let manifest = serde_json::to_vec_pretty(&manifest)?; - check_manifest_depth(&manifest)?; + // The nesting and the items only: a save checks no manifest size. + craft_pcraft_format::check_manifest(&manifest, &manifest_limits(usize::MAX))?; let stats = SaveStats { tiles_total: c.tiles.len(), blobs_total: c.blobs.len(), manifest_bytes: manifest.len(), ..Default::default() }; + let invalid = |h: &str| FormatError::corrupt(format!("invalid object hash `{h}`")); let mut objects = BTreeMap::new(); for (h, (t, s)) in c.tiles { - objects.insert(tile_path(&h), Object::Tile(t, s)); + objects.insert(tile_path(&h).ok_or_else(|| invalid(&h))?, Object::Tile(t, s)); } for (h, b) in c.blobs { - objects.insert(blob_path(&h), Object::Blob(b)); + objects.insert(blob_path(&h).ok_or_else(|| invalid(&h))?, Object::Blob(b)); } Ok(Prepared { manifest, objects, stats }) } @@ -1178,12 +1128,12 @@ impl PcraftWriter { // flush. The retry can reuse those valid bytes (including cached ones), so flush // both object directories again before publishing a manifest that references them. // This also persists the fixed subdirectories of a newly created bundle. - for sub in ["tiles", "blobs"] { + for sub in [TILES_DIR, BLOBS_DIR] { fs.sync_dir(&dir.join(sub)).map_err(|e| crate::atomic::publication_error(e, &dir.join(sub)))?; } } #[cfg(not(windows))] - for sub in ["tiles", "blobs"] { + for sub in [TILES_DIR, BLOBS_DIR] { let folder = dir.join(sub); if folder.is_dir() { confirm_flushed(&folder, &folder)?; @@ -1560,7 +1510,7 @@ fn an_incompressible_blob_at_its_limit_still_loads() { let z = Compressor::new().object(&Object::Blob(Arc::new(data.clone()))); assert!(z.len() > data.len(), "the fixture must not compress"); let hash = hash_bytes(&data); - let src = One(blob_path(&hash), z); + let src = One(blob_path(&hash).unwrap(), z); let mut fetch = LoadFetch { src: &src, opts: crate::LoadOptions::default(), total: 0, blobs: HashMap::new() }; assert_eq!(fetch.blob_bounded(&hash, data.len()).unwrap().as_slice(), data.as_slice()); assert!(LoadFetch { src: &src, opts: crate::LoadOptions::default(), total: 0, blobs: HashMap::new() }.blob_bounded(&hash, data.len() - 1).is_err()); diff --git a/crates/format/tests/it/roundtrip.rs b/crates/format/tests/it/roundtrip.rs index 25af8b22a62..be016f0aaf6 100644 --- a/crates/format/tests/it/roundtrip.rs +++ b/crates/format/tests/it/roundtrip.rs @@ -216,6 +216,13 @@ fn nesting_beyond_the_load_limit_is_refused_at_save() { assert!(matches!(e, FormatError::LimitExceeded(_)), "{e}"); } +/// craft-pcraft-format's default manifest nesting limit is computed from its own copy of the +/// group depth, so the two must stay equal. +#[test] +fn group_depth_matches_craft_pcraft_format() { + assert_eq!(MAX_GROUP_DEPTH, craft_pcraft_format::MAX_GROUP_DEPTH); +} + #[test] fn empty_document_roundtrips() { let doc = Document::new("empty", photocraft_doc::Size::new(1, 1), ColorMode::Rgb, SampleType::U8); @@ -524,6 +531,22 @@ fn save_is_deterministic() { assert_eq!(a, b); } +/// A bundle that is read and saved again gives the same bytes, previews included. +#[test] +fn save_load_save_gives_the_same_bytes() { + let mut preview = Rgba8Image::new(4, 3); + preview.pixels.iter_mut().enumerate().for_each(|(i, p)| *p = i as u8); + for opts in [SaveOptions::default(), SaveOptions { thumbnail: Some(preview.clone()), composite: Some(preview.clone()) }] { + for mode in MODES { + for depth in SampleType::ALL { + let first = save_to_bytes(&rich_doc(mode, depth), &opts).unwrap(); + let again = save_to_bytes(&load_from_bytes(&first).unwrap(), &opts).unwrap(); + assert!(first == again, "{mode:?} {depth:?}: the second save differs"); + } + } + } +} + #[test] fn not_pcraft() { assert!(!is_pcraft(b"")); From 9034223c4b6d80fe15a12b9e0d173786ac5f7a4c Mon Sep 17 00:00:00 2001 From: Yuki-init Date: Mon, 2 Nov 2026 18:31:22 +0000 Subject: [PATCH 77/77] TIFF: open YCbCr images as RGB (#10316) (#10319) * TIFF: open YCbCr images as RGB (#10316) Scanners often write JPEG-compressed YCbCr TIFFs with 2x2 chroma subsampling. The tiff crate decodes and upsamples them but returns raw YCbCr samples, which the decoder rejected with "colour type YCbCr(8)". The new tiff/ycbcr.rs converts them to RGB after decoding: JPEG data uses the JFIF full-range BT.601 conversion (as libtiff does), other compressions honour ReferenceBlackWhite and YCbCrCoefficients with the TIFF defaults as fallback. 8 and 16-bit. YCbCr with extra samples, or in other sample formats, fails with a clear unsupported error. Co-Authored-By: Claude Opus 5.5 * Contributors: add Yuki-init's display name Co-Authored-By: Claude Opus 5.5 * TIFF YCbCr: test that YCbCrCoefficients set the luma weights Co-Authored-By: Claude Opus 5.5 * TIFF: YCbCr tags with the wrong value count use the defaults tag_f64s now returns None unless the tag holds exactly n values, so a YCbCrCoefficients or ReferenceBlackWhite tag with extra values falls back to the TIFF defaults instead of being truncated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lrgj5pnShYtsSnrsZq5iRn * TIFF YCbCr: tests for tiled JPEG with ICC, big-endian 16-bit and planar Covers the layouts the review asked for: a tiled 4:2:0 JPEG file with an embedded profile (checked against an independent JPEG decoder), a big-endian 16-bit file, and planar data in both byte orders. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lrgj5pnShYtsSnrsZq5iRn * TIFF YCbCr: cite the formula sources and pin the green-channel choice Documents where the conversion comes from: TIFF 6.0 Section 21 (YCbCrCoefficients, pp. 90-91) and libtiff's tif_color.c (TIFFYCbCrToRGBInit, TIFFYCbCrtoRGB). Red and blue follow the spec; green follows libtiff and adds Y unscaled, which matches the spec only when the luma weights sum to 1. The module doc records this as a deliberate compatibility choice, and a new test pins it: with weights 0.25/0.25/0.25, mid gray stays (128, 128, 128). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lrgj5pnShYtsSnrsZq5iRn * Codecs README: YCbCr TIFFs with three 8- or 16-bit samples decode to RGB Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lrgj5pnShYtsSnrsZq5iRn * Format tiff_ycbcr tests with rustfmt Co-Authored-By: Claude Opus 5.5 * test(tiff): compare grouped YCbCr decoding and update support notes * style(tiff): align grouped decode call with test formatting * style(tiff): apply repository rustfmt to grouped YCbCr regression --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: FredApps --- contributors/people.toml | 4 + crates/codecs/README.md | 6 +- crates/codecs/src/codecs/tiff.rs | 1 + crates/codecs/src/codecs/tiff/decode.rs | 38 +++- crates/codecs/src/codecs/tiff/ycbcr.rs | 222 ++++++++++++++++++++ crates/codecs/src/codecs/tiff_ifd.rs | 25 ++- crates/codecs/tests/it/main.rs | 1 + crates/codecs/tests/it/tiff_ycbcr.rs | 259 ++++++++++++++++++++++++ docs/file-format-parity.md | 5 +- 9 files changed, 547 insertions(+), 14 deletions(-) create mode 100644 crates/codecs/src/codecs/tiff/ycbcr.rs create mode 100644 crates/codecs/tests/it/tiff_ycbcr.rs diff --git a/contributors/people.toml b/contributors/people.toml index e1c91b3049c..f8dece1fdc6 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -291,6 +291,10 @@ sync_github_name = true [people.dylanmtaylor] sync_github_name = true +[people.Yuki-init] +display_name = "DC@yuki.himejima" +sync_github_name = false + [people.sn-o-w] real_name = "Cristian Silaghi" sync_github_name = false diff --git a/crates/codecs/README.md b/crates/codecs/README.md index 43bf4ea361b..ffd7b655b16 100644 --- a/crates/codecs/README.md +++ b/crates/codecs/README.md @@ -254,8 +254,10 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them ms in release). Image data cut off by the end of the file decodes with `DecodeWarning::Truncated`; a file far too small for its declared size (more than any compression could expand) is refused before allocating. - * YCbCr, CIE Lab, signed integers and compressions that the `tiff` crate lacks (CCITT, - JPEG-in-TIFF) return `Unsupported`. + * YCbCr with three 8- or 16-bit samples decodes to RGB. YCbCr with other sample counts or + bit depths returns `Unsupported`. JPEG-compressed YCbCr uses the full-range JFIF conversion. + * 8/16-bit CIELab and ICCLab decode to the Lab channel layout. + * Signed integer samples and unsupported compression methods return `Unsupported`. * **TIFF encode** writes classic TIFF, or BigTIFF when `EncodeOptions::tiff_bigtiff` is set or the file could pass 4 GiB. `Metadata::extra_samples` (up to 16) are written after the colour and alpha samples, with their `kind` in the ExtraSamples tag (a reserved `kind` above 2 is diff --git a/crates/codecs/src/codecs/tiff.rs b/crates/codecs/src/codecs/tiff.rs index a04460ea1a6..8b2d5d4e8f4 100644 --- a/crates/codecs/src/codecs/tiff.rs +++ b/crates/codecs/src/codecs/tiff.rs @@ -168,6 +168,7 @@ mod bands; mod decode; mod encode; mod tags; +mod ycbcr; pub use decode::TiffBands; pub(crate) use decode::{decode, decode_page, orientation}; diff --git a/crates/codecs/src/codecs/tiff/decode.rs b/crates/codecs/src/codecs/tiff/decode.rs index f698f040397..9747b7c2f0b 100644 --- a/crates/codecs/src/codecs/tiff/decode.rs +++ b/crates/codecs/src/codecs/tiff/decode.rs @@ -2,6 +2,7 @@ use std::borrow::Cow; use super::bands::{Tally, convert_ab, decode_bands, extra_sample_indices, refill_zeroed, split_extra_samples, zeroed}; use super::tags::{F, TAG_IMAGE_SOURCE_DATA, TAG_PHOTOSHOP, TAG_XMP, TEXT_TAGS, photoshop_tags}; +use super::ycbcr::YCbCr; use super::{ ChannelLayout, ChunkType, CodecError, DecodeWarning, Decoder, ExifDirs, File, Ifd, Image, Limits, Metadata, Read, SampleType, Seek, SeekFrom, Tag, camera_raw, err, ifd, io, map_err, tiff_exif, @@ -185,6 +186,9 @@ impl<'a> TiffBands<'a> { // Missing chunks leave their rows as they are: they must start empty in every group. buf = refill_zeroed(buf, len)?; tally = tally + decode_bands(p, self.b, &mut buf, band, first, &mut [], 0)?; + if let Some(c) = p.ycbcr { + c.convert(&mut buf, p.lay.out_channels(), p.lay.out); + } if let Some(signed) = p.lab { convert_ab(&mut buf, p.lay.out_channels(), p.lay.out, signed, false); } @@ -520,6 +524,20 @@ fn header_patches( Ok(patches) } +/// Lab and YCbCr are converted after decoding, from 8 or 16-bit samples only: Lab needs at least +/// its three colour samples, YCbCr exactly three. +fn check_converted_model(photometric: u64, spp: u64, bits: u64, src: Src) -> Result<(), CodecError> { + let (name, samples_ok) = match photometric { + 8 | 9 => ("Lab", spp >= 3), + 6 => ("YCbCr", spp == 3), + _ => return Ok(()), + }; + if samples_ok && matches!(src, Src::U8 | Src::U16) { + return Ok(()); + } + Err(CodecError::unsupported(F, format!("{name} image with {spp} samples of {bits} bits"))) +} + /// A directory checked and laid out for decoding, before any pixel is read. pub(super) struct Prepared { w: u32, @@ -531,6 +549,8 @@ pub(super) struct Prepared { tl: tiff::decoder::Limits, /// Lab samples: `Some(true)` for CIELab (a* and b* stored signed), `Some(false)` for ICCLab. lab: Option, + /// YCbCr samples: the conversion to RGB (#10316). + ycbcr: Option, /// The colour samples of a pixel in the file's colour model. color: usize, /// The ExtraSamples tag (0 unspecified, 1 associated alpha, 2 unassociated alpha). @@ -567,6 +587,9 @@ fn decode_ifd(f: &File<'_>, dir: &Ifd, limits: &Limits) -> Result 0 { return Err(err("the image data is missing (cut off or past the end of the file)")); } + if let Some(c) = p.ycbcr { + c.convert(&mut data, p.lay.out_channels(), p.lay.out); + } if let Some(signed) = p.lab { convert_ab(&mut data, p.lay.out_channels(), p.lay.out, signed, false); } @@ -642,15 +665,17 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result 3, + 2 | 6 | 8 | 9 => 3, 5 => 4, _ => 1, }; @@ -686,6 +711,7 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result (ChannelLayout::Rgb, 3), + tiff::ColorType::YCbCr(_) if ycbcr => (ChannelLayout::Rgb, 3), tiff::ColorType::RGBA(_) => (ChannelLayout::Rgba, 4), tiff::ColorType::CMYK(_) => (ChannelLayout::Cmyk, 4), tiff::ColorType::CMYKA(_) => (ChannelLayout::CmykA, 5), @@ -729,8 +755,9 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result 4, 32773 => 130, 4 => cw.clamp(4096, 65_535), @@ -814,6 +841,7 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result +//! - libtiff, `libtiff/tif_color.c`: `TIFFYCbCrToRGBInit` (tables) and `TIFFYCbCrtoRGB` (per pixel). +//! +//! +//! # Green: a compatibility choice +//! +//! Red and blue follow the spec. Green follows libtiff, which rewrites the spec's equation as +//! `G = Y - (LumaRed·(2 - 2·LumaRed) / LumaGreen)·Cr - (LumaBlue·(2 - 2·LumaBlue) / LumaGreen)·Cb`, +//! adding Y unscaled. The two agree only when the weights sum to 1. Every standard set does +//! (the spec's own examples, BT.601 and BT.709), but the spec only calls the weights "the +//! proportions of red, green, and blue respectively in luminance" and does not require the sum. +//! For other weights the spec's equation scales Y in green by `(1 - LumaRed - LumaBlue) / LumaGreen`, +//! which tints neutral grays. +//! +//! PhotoCraft deliberately follows libtiff here (decided in PR #10319, for issue #10316), so such +//! files open as they do in libtiff-based tools (ImageMagick, GIMP) and grays stay neutral. This is +//! a contributor choice, not a requirement of the spec; the test +//! `weights_that_do_not_sum_to_one_keep_grays_neutral` in `tests/it/tiff_ycbcr.rs` pins it. + +use super::{File, Ifd, SampleType}; + +const TAG_YCBCR_COEFFICIENTS: u16 = 529; +const TAG_REFERENCE_BLACK_WHITE: u16 = 532; + +/// BT.601 luma weights: the TIFF default for YCbCrCoefficients. +const BT601: [f64; 3] = [0.299, 0.587, 0.114]; + +/// How one file's YCbCr codes map to RGB. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct YCbCr { + /// Luma weights of red, green and blue. + luma: [f64; 3], + /// Black and white codes of Y, Cb and Cr. + ref_bw: [f64; 6], +} + +impl YCbCr { + /// The conversion for directory `dir`, whose samples have `max` as their largest code + /// (255 or 65535). Missing or unusable tags fall back to the TIFF defaults. + pub(super) fn of(f: &File<'_>, dir: &Ifd, compression: u64, max: f64) -> Self { + let defaults = Self::defaults(max); + if compression == 7 { + return defaults; + } + let luma = f + .tag_f64s(dir, TAG_YCBCR_COEFFICIENTS, 3) + .and_then(|v| <[f64; 3]>::try_from(v).ok()) + .filter(|l| l.iter().all(|c| c.is_finite() && *c > 0.0 && *c < 1.0)) + .unwrap_or(defaults.luma); + let ref_bw = f + .tag_f64s(dir, TAG_REFERENCE_BLACK_WHITE, 6) + .and_then(|v| <[f64; 6]>::try_from(v).ok()) + .filter(|r| r.iter().all(|v| v.is_finite()) && r.as_chunks::<2>().0.iter().all(|[black, white]| (white - black).abs() > f64::EPSILON)) + .unwrap_or(defaults.ref_bw); + YCbCr { luma, ref_bw } + } + + /// TIFF's defaults: BT.601 weights, full-range luma, chroma centred on the middle code. + fn defaults(max: f64) -> Self { + let mid = (max + 1.0) / 2.0; + YCbCr { luma: BT601, ref_bw: [0.0, max, mid, max, mid, max] } + } + + /// Converts interleaved Y, Cb, Cr pixels of `channels` samples (the first three are the + /// colour) to R, G, B in place. Other sample types are left as they are. + pub(super) fn convert(self, data: &mut [u8], channels: usize, sample: SampleType) { + match sample { + SampleType::U8 => { + let t = Tables::new(&self, 255); + for_each_pixel(data, channels, |px| { + if let [y, cb, cr, ..] = px { + let [r, g, b] = t.rgb(usize::from(*y), usize::from(*cb), usize::from(*cr)); + (*y, *cb, *cr) = (r as u8, g as u8, b as u8); + } + }); + } + SampleType::U16 => { + let t = Tables::new(&self, 65535); + for_each_pixel(data, channels * 2, |px| { + if let [y0, y1, b0, b1, r0, r1, ..] = px { + let get = |a: u8, b: u8| usize::from(u16::from_ne_bytes([a, b])); + let [r, g, b] = t.rgb(get(*y0, *y1), get(*b0, *b1), get(*r0, *r1)); + [*y0, *y1] = (r as u16).to_ne_bytes(); + [*b0, *b1] = (g as u16).to_ne_bytes(); + [*r0, *r1] = (b as u16).to_ne_bytes(); + } + }); + } + _ => {} + } + } +} + +/// Runs `f` on every `stride`-byte pixel, in parallel on native targets. +fn for_each_pixel(data: &mut [u8], stride: usize, f: impl Fn(&mut [u8]) + Sync + Send) { + if stride == 0 { + return; + } + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + // Bands of whole pixels, so each task has a useful amount of work. + let band = stride.saturating_mul(1 << 14); + data.par_chunks_mut(band).for_each(|b| b.chunks_exact_mut(stride).for_each(&f)); + } + #[cfg(target_arch = "wasm32")] + data.chunks_exact_mut(stride).for_each(f); +} + +/// Per-code contributions, so a pixel costs a few additions. +struct Tables { + max: f64, + /// Scaled luma of each Y code. + y: Vec, + /// Red and green contributions of each Cr code. + cr_r: Vec, + cr_g: Vec, + /// Green and blue contributions of each Cb code. + cb_g: Vec, + cb_b: Vec, +} + +impl Tables { + fn new(c: &YCbCr, max: u32) -> Self { + let m = f64::from(max); + let [lr, lg, lb] = c.luma; + let [y_black, y_white, cb_black, cb_white, cr_black, cr_white] = c.ref_bw; + // TIFF 6.0: chroma codes span ±(max + 1) / 2 - 1 around the black code; with the + // default ReferenceBlackWhite that is the code minus the middle code. + let half = (m + 1.0) / 2.0 - 1.0; + let codes = || (0..=max).map(f64::from); + let y = codes().map(|v| (v - y_black) * m / (y_white - y_black)).collect(); + let cb: Vec = codes().map(|v| (v - cb_black) * half / (cb_white - cb_black)).collect(); + let cr: Vec = codes().map(|v| (v - cr_black) * half / (cr_white - cr_black)).collect(); + // R = Y + (2 - 2·Lr)·Cr and B = Y + (2 - 2·Lb)·Cb (TIFF 6.0 p. 91); green as libtiff: + // G = Y - (Lr·(2 - 2·Lr) / Lg)·Cr - (Lb·(2 - 2·Lb) / Lg)·Cb (see the module notes). + let (kr, kb) = (2.0 - 2.0 * lr, 2.0 - 2.0 * lb); + Tables { + max: m, + y, + cr_r: cr.iter().map(|v| kr * v).collect(), + cr_g: cr.iter().map(|v| -lr * kr * v / lg).collect(), + cb_g: cb.iter().map(|v| -lb * kb * v / lg).collect(), + cb_b: cb.iter().map(|v| kb * v).collect(), + } + } + + /// R, G and B of one pixel, rounded and clamped to the code range. + fn rgb(&self, y: usize, cb: usize, cr: usize) -> [u32; 3] { + let at = |t: &[f64], i: usize| t.get(i).copied().unwrap_or(0.0); + let yv = at(&self.y, y); + // Green adds Y unscaled, as libtiff does (see "Green: a compatibility choice" above). + let r = yv + at(&self.cr_r, cr); + let g = yv + at(&self.cr_g, cr) + at(&self.cb_g, cb); + let b = yv + at(&self.cb_b, cb); + [r, g, b].map(|v| v.round().clamp(0.0, self.max) as u32) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn convert(c: &YCbCr, px: [u8; 3]) -> [u8; 3] { + let mut d = px.to_vec(); + c.convert(&mut d, 3, SampleType::U8); + [d[0], d[1], d[2]] + } + + #[test] + fn jfif_conversion_matches_known_colours() { + let c = YCbCr::defaults(255.0); + assert_eq!(convert(&c, [0, 128, 128]), [0, 0, 0]); + assert_eq!(convert(&c, [255, 128, 128]), [255, 255, 255]); + assert_eq!(convert(&c, [128, 128, 128]), [128, 128, 128]); + // Pure red, green and blue as JFIF encodes them. + assert_eq!(convert(&c, [76, 85, 255]), [254, 0, 0]); + assert_eq!(convert(&c, [150, 44, 21]), [0, 255, 1]); + assert_eq!(convert(&c, [29, 255, 107]), [0, 0, 254]); + } + + #[test] + fn sixteen_bit_and_extra_samples() { + let c = YCbCr::defaults(65535.0); + let mut d: Vec = [65535u16, 32768, 32768, 1234].iter().flat_map(|v| v.to_ne_bytes()).collect(); + c.convert(&mut d, 4, SampleType::U16); + let v: Vec = d.as_chunks::<2>().0.iter().map(|b| u16::from_ne_bytes(*b)).collect(); + assert_eq!(v, [65535, 65535, 65535, 1234]); + } + + #[test] + fn studio_range_reference_black_white() { + // Y 16–235, chroma 128 ± 112 (ITU-R BT.601 studio range). + let c = YCbCr { luma: BT601, ref_bw: [16.0, 235.0, 128.0, 240.0, 128.0, 240.0] }; + assert_eq!(convert(&c, [16, 128, 128]), [0, 0, 0]); + assert_eq!(convert(&c, [235, 128, 128]), [255, 255, 255]); + } + + #[test] + fn odd_buffers_do_not_panic() { + let c = YCbCr::defaults(255.0); + let mut d = vec![1u8, 2]; + c.convert(&mut d, 3, SampleType::U8); + c.convert(&mut d, 0, SampleType::U8); + c.convert(&mut d, 0, SampleType::U16); + assert_eq!(d, [1, 2]); + } +} diff --git a/crates/codecs/src/codecs/tiff_ifd.rs b/crates/codecs/src/codecs/tiff_ifd.rs index 63b39258cf3..cdaa890ec4d 100644 --- a/crates/codecs/src/codecs/tiff_ifd.rs +++ b/crates/codecs/src/codecs/tiff_ifd.rs @@ -236,18 +236,33 @@ impl<'a> File<'a> { /// The first value of a numeric tag as a float: RATIONAL, FLOAT, DOUBLE or an integer. pub fn tag_f64(&self, ifd: &Ifd, tag: u16) -> Option { + self.float(ifd.get(tag)?, 0) + } + + /// The values of a numeric tag as floats, when it holds exactly `n` (`None` for any other + /// count or an unreadable value). + pub fn tag_f64s(&self, ifd: &Ifd, tag: u16, n: u64) -> Option> { let e = ifd.get(tag)?; - if e.count == 0 { + if e.count != n { return None; } + (0..n).map(|i| self.float(e, i)).collect() + } + + /// Value `i` of a numeric entry as a float: RATIONAL, FLOAT, DOUBLE or an integer. + fn float(&self, e: &Entry, i: u64) -> Option { + if i >= e.count { + return None; + } + let at = e.value_at.checked_add(i.checked_mul(type_size(e.ty)?)?)?; match e.ty { 5 => { - let (n, d) = (self.u32_at(e.value_at)?, self.u32_at(e.value_at.checked_add(4)?)?); + let (n, d) = (self.u32_at(at)?, self.u32_at(at.checked_add(4)?)?); (d != 0).then(|| f64::from(n) / f64::from(d)) } - 11 => Some(f64::from(f32::from_bits(self.u32_at(e.value_at)?))), - 12 => Some(f64::from_bits(self.u64_at(e.value_at)?)), - _ => self.uint(e, 0).map(|v| v as f64), + 11 => Some(f64::from(f32::from_bits(self.u32_at(at)?))), + 12 => Some(f64::from_bits(self.u64_at(at)?)), + _ => self.uint(e, i).map(|v| v as f64), } } diff --git a/crates/codecs/tests/it/main.rs b/crates/codecs/tests/it/main.rs index a2ed94616a2..4293fb4a481 100644 --- a/crates/codecs/tests/it/main.rs +++ b/crates/codecs/tests/it/main.rs @@ -31,6 +31,7 @@ mod tiff_lab; mod tiff_pages; mod tiff_photoshop; mod tiff_regressions; +mod tiff_ycbcr; mod webp_frames; mod webp_lossy; mod xpm; diff --git a/crates/codecs/tests/it/tiff_ycbcr.rs b/crates/codecs/tests/it/tiff_ycbcr.rs new file mode 100644 index 00000000000..94ff9f87e2b --- /dev/null +++ b/crates/codecs/tests/it/tiff_ycbcr.rs @@ -0,0 +1,259 @@ +//! YCbCr TIFFs (PhotometricInterpretation 6), as scanners write them: JPEG-compressed with 2×2 +//! chroma subsampling, and uncompressed with ReferenceBlackWhite and YCbCrCoefficients (#10316). +//! Every file here is hand-built by `common::tiffgen`. + +use crate::common::sample_icc; +use crate::common::tiffgen::*; +use photocraft_codecs::*; + +const COMPRESSION: u16 = 259; +const SUBSAMPLING: u16 = 530; +const YCBCR_COEFFICIENTS: u16 = 529; +const REFERENCE_BLACK_WHITE: u16 = 532; +const ICC_PROFILE: u16 = 34675; + +/// A directory whose Compression is `c`. +fn compressed(mut d: Dir, c: u64) -> Dir { + d.entries.retain(|e| e.0 != COMPRESSION); + d.tag(COMPRESSION, SHORT, &[c]) +} + +/// A little-endian RATIONAL value for `tiffgen`. +fn rational(num: u32, den: u32) -> u64 { + u64::from(num) | (u64::from(den) << 32) +} + +/// The image's pixels as RGB bytes. +fn rgb(img: &Image) -> Vec { + img.to_rgba8().as_chunks::<4>().0.iter().flat_map(|[r, g, b, _]| [*r, *g, *b]).collect() +} + +/// A smooth colour test card, `w`×`h` RGB. +fn card(w: u32, h: u32) -> Vec { + let mut v = Vec::new(); + for y in 0..h { + for x in 0..w { + v.extend([(x * 255 / (w - 1)) as u8, (y * 255 / (h - 1)) as u8, (255 - x * 255 / (w - 1)) as u8]); + } + } + v +} + +/// A 4:2:0 baseline JPEG stream of `rgb`. +fn jpeg(rgb: &[u8], w: u32, h: u32) -> Vec { + let img = Image::from_raw(w, h, ChannelLayout::Rgb, SampleType::U8, rgb.to_vec()).unwrap(); + encode(&img, Format::Jpeg, &EncodeOptions { jpeg_chroma_subsampling: true, ..Default::default() }).unwrap() +} + +#[test] +fn jpeg_compressed_ycbcr_with_subsampled_chroma_reads_as_rgb() { + let (w, h) = (32, 24); + let stream = jpeg(&card(w, h), w, h); + // The stream really is subsampled: the luma component samples 2×2 in the frame header. + let sof = stream.windows(2).position(|m| m == [0xFF, 0xC0]).expect("baseline frame header"); + assert_eq!(stream[sof + 11], 0x22, "luma sampling factors"); + let dir = compressed(strips(w, h, 8, 3, 6, h, &stream), 7).tag(SUBSAMPLING, SHORT, &[2, 2]); + let file = build(true, false, &[dir], &[0]).bytes; + + let img = decode(&file).unwrap(); + assert_eq!((img.width(), img.height(), img.layout(), img.sample_type()), (w, h, ChannelLayout::Rgb, SampleType::U8)); + // The oracle: the same JPEG stream decoded to RGB by an independent decoder. + let want = image::load_from_memory_with_format(&stream, image::ImageFormat::Jpeg).unwrap().to_rgb8().into_raw(); + let worst = rgb(&img).iter().zip(&want).map(|(g, o)| g.abs_diff(*o)).max().unwrap(); + assert!(worst <= 2, "largest difference from the oracle: {worst}"); +} + +#[test] +fn uncompressed_ycbcr_uses_the_default_conversion() { + // Black, white, mid gray and JFIF's pure red, without subsampling. + let px = [0, 128, 128, 255, 128, 128, 128, 128, 128, 76, 85, 255]; + let dir = strips(4, 1, 8, 3, 6, 1, &px).tag(SUBSAMPLING, SHORT, &[1, 1]); + let img = decode(&build(true, false, &[dir], &[0]).bytes).unwrap(); + assert_eq!(img.layout(), ChannelLayout::Rgb); + assert_eq!(rgb(&img), [0, 0, 0, 255, 255, 255, 128, 128, 128, 254, 0, 0]); +} + +#[test] +fn reference_black_white_sets_the_code_range() { + // Studio range: Y 16–235, chroma 128 ± 112. + let rbw = [rational(16, 1), rational(235, 1), rational(128, 1), rational(240, 1), rational(128, 1), rational(240, 1)]; + let dir = strips(2, 1, 8, 3, 6, 1, &[16, 128, 128, 235, 128, 128]).tag(SUBSAMPLING, SHORT, &[1, 1]).tag(REFERENCE_BLACK_WHITE, RATIONAL, &rbw); + let img = decode(&build(true, false, &[dir], &[0]).bytes).unwrap(); + assert_eq!(rgb(&img), [0, 0, 0, 255, 255, 255]); +} + +#[test] +fn weights_that_do_not_sum_to_one_keep_grays_neutral() { + // 0.25 each (sum 0.75): TIFF 6.0's full inverse would scale green's Y by (1 − Lr − Lb) / Lg + // = 2 and give mid gray G 255 (clamped). Like libtiff, green keeps Y, so gray stays gray, and + // the weights still set the chroma terms: R = Y + 1.5·Cr, B = Y + 1.5·Cb. + let weights = [rational(1, 4), rational(1, 4), rational(1, 4)]; + let dir = strips(2, 1, 8, 3, 6, 1, &[128, 128, 128, 128, 64, 192]).tag(SUBSAMPLING, SHORT, &[1, 1]).tag(YCBCR_COEFFICIENTS, RATIONAL, &weights); + let img = decode(&build(true, false, &[dir], &[0]).bytes).unwrap(); + // Green for the second pixel: 128 − (Lb·1.5/Lg)·Cb − (Lr·1.5/Lg)·Cr = 128 + 96 − 96. + assert_eq!(rgb(&img), [128, 128, 128, 224, 128, 32]); +} + +#[test] +fn ycbcr_coefficients_set_the_luma_weights() { + // Weights 0.25, 0.5, 0.25 with Cb −64 and Cr +64: R = Y + 1.5·Cr, B = Y + 1.5·Cb, and G keeps Y + // (BT.601 would give R 218 and B 15). + let weights = [rational(1, 4), rational(1, 2), rational(1, 4)]; + let dir = strips(1, 1, 8, 3, 6, 1, &[128, 64, 192]).tag(SUBSAMPLING, SHORT, &[1, 1]).tag(YCBCR_COEFFICIENTS, RATIONAL, &weights); + let img = decode(&build(true, false, &[dir], &[0]).bytes).unwrap(); + assert_eq!(rgb(&img), [224, 128, 32]); +} + +#[test] +fn ycbcr_tags_with_the_wrong_count_use_the_defaults() { + // Four weights and seven black/white codes: both tags are malformed, so BT.601 and full range + // apply (the weights alone would give 224, 128, 32). + let weights = [rational(1, 4), rational(1, 2), rational(1, 4), rational(1, 4)]; + let rbw = [rational(16, 1), rational(235, 1), rational(128, 1), rational(240, 1), rational(128, 1), rational(240, 1), rational(0, 1)]; + let dir = strips(1, 1, 8, 3, 6, 1, &[128, 64, 192]).tag(SUBSAMPLING, SHORT, &[1, 1]).tag(YCBCR_COEFFICIENTS, RATIONAL, &weights).tag( + REFERENCE_BLACK_WHITE, + RATIONAL, + &rbw, + ); + let img = decode(&build(true, false, &[dir], &[0]).bytes).unwrap(); + assert_eq!(rgb(&img), [218, 104, 15]); +} + +#[test] +fn sixteen_bit_ycbcr_reads_as_rgb() { + let px: Vec = [65535u16, 32768, 32768, 0, 32768, 32768].iter().flat_map(|v| v.to_le_bytes()).collect(); + let dir = strips(2, 1, 16, 3, 6, 1, &px).tag(SUBSAMPLING, SHORT, &[1, 1]); + let img = decode(&build(true, false, &[dir], &[0]).bytes).unwrap(); + assert_eq!((img.layout(), img.sample_type()), (ChannelLayout::Rgb, SampleType::U16)); + let n = img.to_normalized(); + assert!(n[..3].iter().all(|&v| v == 1.0) && n[3..].iter().all(|&v| v == 0.0), "{n:?}"); +} + +#[test] +#[cfg(target_pointer_width = "64")] +fn sixteen_bit_ycbcr_bands_match_whole_decode_with_a_missing_last_strip() { + // On 32-bit targets max_alloc also bounds the whole image, so a small allocation cap + // cannot force these tiny strips into separate output groups there. + let (w, h, rows) = (4u32, 5u32, 2u32); + let pixels = [[0u16, 32768, 32768], [65535, 32768, 32768], [19595, 21710, 65535], [32768, 40960, 24576]]; + let samples: Vec = (0..w * h).flat_map(|i| pixels[i as usize % pixels.len()]).collect(); + let weights = [rational(1, 4), rational(1, 2), rational(1, 4)]; + let icc = sample_icc(512); + for little in [true, false] { + for missing in [false, true] { + let dir = strips(w, h, 16, 3, 6, rows, &u16s(&samples, little)).tag(SUBSAMPLING, SHORT, &[1, 1]).tag(YCBCR_COEFFICIENTS, RATIONAL, &weights).bytes( + ICC_PROFILE, + UNDEFINED, + &icc, + ); + let mut file = build(little, false, &[dir], &[0]); + if missing { + let past = file.bytes.len() as u64 + 4096; + patch_value(&mut file, little, false, 0, 273, 2, past); + } + let want = decode_with(&file.bytes, &DecodeOptions { keep_orientation: true, ..Default::default() }).unwrap(); + let limits = Limits { max_alloc: u64::from(w * rows * 3 * 2), ..Limits::banded() }; + let mut bands = TiffBands::open(&file.bytes, None, &limits).unwrap(); + assert_eq!((bands.dimensions(), bands.layout(), bands.sample_type()), ((w, h), ChannelLayout::Rgb, SampleType::U16)); + let mut got = Image::new(w, h, bands.layout(), bands.sample_type()).unwrap(); + let mut positions = Vec::new(); + bands + .decode(|x, y, group: &Image| -> Result<(), CodecError> { + positions.push((x, y, group.height())); + assert_eq!((x, group.width(), group.layout(), group.sample_type()), (0, w, ChannelLayout::Rgb, SampleType::U16)); + let at = y as usize * w as usize * 3 * 2; + got.data_mut()[at..at + group.data().len()].copy_from_slice(group.data()); + Ok(()) + }) + .unwrap(); + assert_eq!(positions, [(0, 0, 2), (0, 2, 2), (0, 4, 1)], "one output group per strip, including the short last strip"); + assert_eq!(got.data(), want.data(), "little endian: {little}, missing last strip: {missing}"); + assert_eq!(bands.icc, want.icc); + assert_eq!(bands.meta, want.meta); + assert_eq!(bands.warnings, want.warnings); + assert_eq!(bands.warnings.iter().any(|w| matches!(w, DecodeWarning::Truncated { .. })), missing); + } + } +} + +#[test] +fn unsupported_ycbcr_files_fail_cleanly() { + // Four samples (an extra sample next to YCbCr). + let four = strips(1, 1, 8, 4, 6, 1, &[128, 128, 128, 255]).tag(SUBSAMPLING, SHORT, &[1, 1]); + assert!(decode(&build(true, false, &[four], &[0]).bytes).is_err()); + // Subsampled chroma without JPEG compression (the default subsampling is 2×2). + let sub = strips(2, 2, 8, 3, 6, 2, &[128; 12]); + assert!(decode(&build(true, false, &[sub], &[0]).bytes).is_err()); + // A JPEG strip that is not JPEG data. + let junk = compressed(strips(16, 16, 8, 3, 6, 16, &[0x5A; 64]), 7).tag(SUBSAMPLING, SHORT, &[2, 2]); + assert!(decode(&build(true, false, &[junk], &[0]).bytes).is_err()); + // Coefficients and ReferenceBlackWhite that would divide by zero fall back to the defaults. + let bad = strips(1, 1, 8, 3, 6, 1, &[255, 128, 128]) + .tag(SUBSAMPLING, SHORT, &[1, 1]) + .tag(YCBCR_COEFFICIENTS, RATIONAL, &[rational(0, 1), rational(0, 0), rational(5, 1)]) + .tag(REFERENCE_BLACK_WHITE, RATIONAL, &[rational(7, 1); 6]); + let img = decode(&build(true, false, &[bad], &[0]).bytes).unwrap(); + assert_eq!(&img.to_rgba8()[..3], &[255, 255, 255]); +} + +#[test] +fn tiled_jpeg_ycbcr_keeps_its_icc_profile() { + // Two 16×16 tiles, each its own 4:2:0 JPEG stream, and an embedded profile, like a scanner's + // tiled output. + let (w, h, t) = (32u32, 16u32, 16u32); + let px = card(w, h); + let tile = |tx: u32| -> Vec { + (0..t) + .flat_map(|y| { + let at = ((y * w + tx * t) * 3) as usize; + px[at..at + (t * 3) as usize].to_vec() + }) + .collect() + }; + let streams = [jpeg(&tile(0), t, t), jpeg(&tile(1), t, t)]; + let icc = sample_icc(512); + let dir = Dir { entries: base(w, h, 8, 3, 6), chunks: streams.to_vec(), tiled: true }; + let dir = compressed(dir, 7).tag(322, SHORT, &[u64::from(t)]).tag(323, SHORT, &[u64::from(t)]).tag(SUBSAMPLING, SHORT, &[2, 2]).bytes( + ICC_PROFILE, + UNDEFINED, + &icc, + ); + let img = decode(&build(true, false, &[dir], &[0]).bytes).unwrap(); + assert_eq!((img.width(), img.height(), img.layout()), (w, h, ChannelLayout::Rgb)); + assert_eq!(img.icc.as_deref(), Some(icc.as_slice()), "the embedded profile is kept"); + // The oracle: each tile's stream decoded by an independent decoder, placed side by side. + let tiles: Vec> = streams.iter().map(|s| image::load_from_memory_with_format(s, image::ImageFormat::Jpeg).unwrap().to_rgb8().into_raw()).collect(); + let row = (t * 3) as usize; + let want: Vec = (0..t as usize).flat_map(|y| [&tiles[0][y * row..(y + 1) * row], &tiles[1][y * row..(y + 1) * row]].concat()).collect(); + let worst = rgb(&img).iter().zip(&want).map(|(g, o)| g.abs_diff(*o)).max().unwrap(); + assert!(worst <= 2, "largest difference from the oracle: {worst}"); +} + +#[test] +fn big_endian_sixteen_bit_ycbcr_reads_as_rgb() { + // White, black, and red as full-range 16-bit YCbCr (Y 0.299·65535, Cb 32768 − 0.1687·65535, Cr max). + let px = [65535u16, 32768, 32768, 0, 32768, 32768, 19595, 21710, 65535]; + let dir = strips(3, 1, 16, 3, 6, 1, &u16s(&px, false)).tag(SUBSAMPLING, SHORT, &[1, 1]); + let file = build(false, false, &[dir], &[0]).bytes; + assert_eq!(&file[..2], b"MM"); + let img = decode(&file).unwrap(); + assert_eq!((img.layout(), img.sample_type()), (ChannelLayout::Rgb, SampleType::U16)); + let n = img.to_normalized(); + let want = [1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + assert!(n.iter().zip(want).all(|(g, w)| (g - w).abs() < 2.0 / 255.0), "{n:?}"); +} + +#[test] +fn planar_ycbcr_reads_as_rgb_in_both_byte_orders() { + // The pixels of the default-conversion test, one plane per component. + let px = [0u8, 128, 128, 255, 128, 128, 128, 128, 128, 76, 85, 255]; + for little in [true, false] { + let dir = Dir { entries: base(4, 1, 8, 3, 6), chunks: planar_strips(&px, 4, 1, 3, 1, 1), tiled: false }.tag(278, LONG, &[1]).tag(284, SHORT, &[2]).tag( + SUBSAMPLING, + SHORT, + &[1, 1], + ); + let img = decode(&build(little, false, &[dir], &[0]).bytes).unwrap(); + assert_eq!(rgb(&img), [0, 0, 0, 255, 255, 255, 128, 128, 128, 254, 0, 0], "little endian: {little}"); + } +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 5ef09a2e7e3..68cd49bbe9d 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-26 · **Change:** minor (TIFFs up to 300,000 px a side open, decoded a group of rows at a time into the layer, #8169; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); Save for Web writes WebP, lossy or lossless, #6391; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency, #8877; layered TIFF writes the TySh text version and descriptor in PSD big-endian order while the header, matrix, warp and bounds keep container order, #9098; layered TIFF writes Photoshop's 14-byte global layer mask, so Photoshop opens the layers instead of only the composite, #9095; legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding; Amiga IFF write: 24-plane ILBM, Save As `.iff`; PSD stores spot channels as Photoshop does, ink 0 = solid, and numbers them in 1053, #7415 split; TIFF writes and reads alpha and spot channels as extra samples with Photoshop's channel resources, PSD output unchanged, FILE-215-7, FILE-215-17's TIFF part, #7415; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-30 · **Change:** patch (TIFF: YCbCr images open as RGB, including JPEG-compressed scans with subsampled chroma, #10316; TIFFs up to 300,000 px a side open, decoded a group of rows at a time into the layer, #8169; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); Save for Web writes WebP, lossy or lossless, #6391; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency, #8877; layered TIFF writes the TySh text version and descriptor in PSD big-endian order while the header, matrix, warp and bounds keep container order, #9098; layered TIFF writes Photoshop's 14-byte global layer mask, so Photoshop opens the layers instead of only the composite, #9095; legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding; Amiga IFF write: 24-plane ILBM, Save As `.iff`; PSD stores spot channels as Photoshop does, ink 0 = solid, and numbers them in 1053, #7415 split; TIFF writes and reads alpha and spot channels as extra samples with Photoshop's channel resources, PSD output unchanged, FILE-215-7, FILE-215-17's TIFF part, #7415; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency) · **Target:** Adobe Photoshop 2026 **PSD Filter Gallery (#8940, 2026-10-23):** Halftone Pattern maps its size, contrast and dot/circle/line pattern as editable settings on import and export, with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`: `ScrD`/`ScrC`/`ScrL`). PSD/PSB round trips pass at 8/16/32 bits. This does not claim pixel equivalence for the existing renderer. Unknown or malformed settings remain verbatim on import. @@ -26,7 +26,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity. | PSD | R/W | yes | yes | 1/8/16/32-bit; Bitmap, Gray, Indexed, RGB, CMYK, Multichannel, Lab, Duotone; layers, groups, masks, vector masks, adjustment and fill layers, effects, text, shapes, smart objects (SoLd/lnk2 with their warp: the bend presets, a custom mesh and, since #4112, Cylinder; CS2 PlLd/lnkD read with their warp, kept as is or re-saved as SoLd once edited), smart filters (53 mapped, among them Invert, the Distort filters but Shear, Clouds, Difference Clouds, Fibers and Lens Flare, plus Hue/Saturation, Perspective Warp, Filter Gallery with Chrome and a Camera Raw subset, rest verbatim), slices, comps, Advanced Blending, each layer's XMP packet (`layer.xmpMetadata`); alpha and spot channels as Photoshop stores them (spot ink 0 = solid, channel identifiers in 1053), and PSDs with spot channels from PhotoCraft 0.1.0–0.16.0, which stored the ink the other way round, keep their ink. Oracle floors: Photoshop-authored 190/258, io 148/170, psd-tools 249/309; round trip ≥ 169/170, 308/309, 258/258. Known failures: #1281, #2469 (#2374, text layers, closed 2026-10-10; #2465, CS2 `PlLd`-only smart objects, fixed 2026-10-12) | | PSB | R/W | yes | yes | Auto-switches above 2 GB (REL-212-2); generated 20 MP, 150-layer, 2 GB PSD and 4.4 GB PSB fixtures opened, saved and re-opened by io tests/it/large_files.rs (FILE-216-2, 2026-10-13; the 4.4 GB PSB opens on Windows); > 4 GB from the app's File › Open on Windows: #375 | | Cloud PSD (.psdc) | R/W | no | no | Out of scope (Adobe cloud) | -| TIFF | R/W | yes | yes | 8/16/32f, Gray/RGB/CMYK, BigTIFF, every IFD, banded parallel decode; flat pages up to 300,000 px a side open a group of rows at a time into the layer, with no full-size copy, and are refused with an error when the machine lacks the memory (Linux: free RAM and swap, cgroup limits; #8169); layered TIFF both byte orders, including Photoshop mixed-order type blocks on read (#4758/#4771) and TySh text descriptors written in PSD order (#9098) and Photoshop's 14-byte `LMsk` block (#9095); LZW/ZIP for scripted saves by `tiffCompression`; undecodable type keeps saved pixels (FILE-215-7); alpha and spot channels as extra samples (at most 16) with Photoshop's names, ink colours and solidity, spot ink stored 0 = solid (#7415); no Save Transparency choice yet (channels are written as Photoshop does with it off) | +| TIFF | R/W | yes | yes | 8/16/32f, Gray/RGB/CMYK, YCbCr read as RGB (JPEG-compressed with subsampled chroma, or uncompressed without subsampling; #10316), BigTIFF, every IFD, banded parallel decode; flat pages up to 300,000 px a side open a group of rows at a time into the layer, with no full-size copy, and are refused with an error when the machine lacks the memory (Linux: free RAM and swap, cgroup limits; #8169); layered TIFF both byte orders, including Photoshop mixed-order type blocks on read (#4758/#4771) and TySh text descriptors written in PSD order (#9098) and Photoshop's 14-byte `LMsk` block (#9095); LZW/ZIP for scripted saves by `tiffCompression`; undecodable type keeps saved pixels (FILE-215-7); alpha and spot channels as extra samples (at most 16) with Photoshop's names, ink colours and solidity, spot ink stored 0 = solid (#7415); no Save Transparency choice yet (channels are written as Photoshop does with it off) | | JPEG | R/W | yes | yes | 8-bit Gray/RGB/CMYK, ICC/EXIF/XMP; Save keeps the opened file's quality (estimated from its quantisation tables, #2399); File › Save, Save As and Save a Copy ask JPEG Options: Quality 0–12, starting at the opened file's quality or else the Export preference, and Baseline ("Standard") / Baseline Optimized / Progressive; scripts pass `quality`/`jpegFormat`, the CLI `--jpeg-format` (FILE-215-19). Baseline Optimized fits the Huffman tables only at 4:4:4 (Gray, CMYK) or progressive: RGB is written 4:2:0, which zune-jpeg 0.5.15 decodes wrongly with fitted tables, as in Save for Web. No Matte, progressive Scans (3–5) or size preview | | PNG | R/W | yes | yes | 8/16-bit, ICC/text; APNG first frame only; alpha channels on open (#2225); palette PNGs open in Indexed Color mode with their transparent entry (#4804); Save keeps a stereo PNG's `sTER` pairing (#6063) | | GIF | R/W | yes | yes | File › Open keeps the first frame; New Video Layer from File and Video Frames to Layers take every frame, with the timeline rate from the delays (#572). Per-frame delays and keeping the frames in `.pcraft` are not done | @@ -148,6 +148,7 @@ Embedded SVG and PDF-compatible AI/PDF/EPS payloads can use an explicit VectorCr | Date | Change | Summary | |---|---|---| +| 2026-10-30 | patch | TIFF: YCbCr (PhotometricInterpretation 6) opens as RGB instead of failing with "colour type YCbCr(8)": JPEG-compressed with subsampled chroma (as scanners write it) through the JPEG conversion, uncompressed with ReferenceBlackWhite and YCbCrCoefficients; 8 and 16-bit. Uncompressed subsampled YCbCr and YCbCr with extra samples still fail with a clear error (#10316) | | 2026-10-26 | minor | Embedded AI/PDF/EPS save-back retains native format and a separate source-bound display preview; original sources remain undoable. Native Adobe interoperability and standalone EPS/DCS remain unverified; no corpus floor or percentage changed. | | 2026-10-22 | minor | Embedded PSD vectors gain explicit bounded SVG editor/save-back; standalone EPS/DCS and native-format fidelity remain open. | | 2026-10-22 | minor | TIFF: flat pages up to 300,000 px a side open (was 2^30 px, about 32,768²): `codecs::TiffBands` decodes a group of rows at a time into the layer's tiles. The 117,504 × 22,464 px banner from #8456 opens in 3.3 s at 11.45 GB peak for a 10.56 GB layer; 30,000² 6.8 s / 6.43 GB → 1.1 s / 3.86 GB; 36 MP 220 → 52 ms. Layered TIFFs still decode whole (#8169) |