diff --git a/.config/nextest.toml b/.config/nextest.toml index a1e0a2ee0a..ef44bae8b4 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -16,7 +16,7 @@ nextest-version = "0.9.150" gpu = { max-threads = 4 } [[profile.default.overrides]] -filter = 'package(photocraft-gpu) | (package(photocraft-ui-egui) & (kind(test) | test(/canvas|gpu|mip|type_tool|background_redraw::|floating_group_titles|swap_arrow::tests::rendered_glyph/)))' +filter = 'package(photocraft-gpu) | (package(photocraft-ui-egui) & (kind(test) | test(/canvas|gpu|mip|type_tool|background_redraw::|floating_group_titles|swap_arrow::tests::rendered_glyph/))) | (package(photocraft-automation) & test(/^gpu_backend::/))' test-group = 'gpu' # CI (`--profile ci`, .github/workflows/ci.yml). Collect all failures in one integration run diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 385245a033..c44b8ef927 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -68,6 +68,12 @@ concurrency: cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: + # Git dependencies come from github.com/storytold, and Cargo.lock is complete and up to date. + git-sources: + if: github.event.action != 'labeled' || github.event.label.name == 'full-ci' + # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. + uses: storytold/craft-common-actions/.github/workflows/git-sources.yml@main + # Whether the Windows legs and the web build run. main, manual runs and PRs labelled `full-ci` # get both. Other PRs get Windows when they touch code whose behaviour differs by platform: the # app shell, UI, text and fonts, GPU, pen input, native saves, build scripts or the lockfile. @@ -82,41 +88,14 @@ jobs: windows: ${{ steps.pick.outputs.windows }} web: ${{ steps.pick.outputs.web }} steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 persist-credentials: false - - name: Git dependencies come from storytold - run: | - set -euo pipefail - test -f Cargo.lock || { echo "Cargo.lock is missing"; exit 1; } - # Source replacement, patches and path overrides in cargo config never show up - # in Cargo.lock. Parsed rather than grepped: TOML has many spellings of one key. - # Cargo still reads the legacy .cargo/config. - python3 - <<'PY' - import os, sys, tomllib - for path in (".cargo/config", ".cargo/config.toml"): - if not os.path.exists(path): - continue - config = tomllib.load(open(path, "rb")) - replaced = [name for name, source in config.get("source", {}).items() - if isinstance(source, dict) and "replace-with" in source] - if replaced or "patch" in config or "paths" in config: - print(f"{path} replaces, patches or overrides a source") - sys.exit(1) - PY - # Fails when Cargo.lock is out of date with the manifests. - cargo metadata --locked --format-version 1 > /dev/null - python3 - <<'PY' - import sys, tomllib - lock = tomllib.load(open("Cargo.lock", "rb")) - bad = sorted({p["source"] for p in lock.get("package", []) - if p.get("source", "").startswith("git+") - and not p["source"].startswith("git+https://github.com/storytold/")}) - if bad: - print("Git dependencies outside github.com/storytold:", *bad, sep="\n") - sys.exit(1) - PY - id: pick env: EVENT: ${{ github.event_name }} @@ -170,8 +149,8 @@ jobs: # 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 the integration # tests over a third runner (nextest --partition) saved ~2 min of wall time but cost ~7 - # runner-minutes and one more Windows slot per PR. They stay outside the shared gate for sccache, - # which needs its own action step. + # runner-minutes and one more Windows slot per PR. Moving these legs into the shared gate is + # tracked by storytold/craft-common-actions#212. windows: needs: platforms if: needs.platforms.outputs.windows == 'true' @@ -183,6 +162,10 @@ jobs: matrix: part: [unit, integration] env: + # Released sccache expands Cargo's response files and exceeds Windows' rustc spawn limit + # (#13543). Let Cargo handle long commands until a release includes mozilla/sccache#3026. + # The dependency rust-cache below stays enabled; only compiler caching is disabled. + RUSTC_WRAPPER: "" # No debuginfo on Windows: writing PDBs for ~200 test binaries cost 2.2 of ~21 build minutes. # A panic still names its file and line; only backtrace frames lose theirs (Linux keeps # line-tables-only, so a backtrace with lines is one OS away). @@ -197,6 +180,10 @@ jobs: CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts CRAFT_FONTS_REQUIRED: "1" steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false @@ -214,37 +201,20 @@ jobs: - name: Check out craft-i18n uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: + toolchain: stable components: clippy # Only main saves caches; PRs restore main's, so the repo's 10 GB cache budget keeps main's. # A failing test still saves: the cache holds compiled dependencies, not test results. # Both legs share one key (same dependencies); the integration leg saves it, because it also # runs Clippy and so leaves Clippy's dependency metadata in it. - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 with: save-if: ${{ github.ref == 'refs/heads/main' && matrix.part == 'integration' }} cache-on-failure: true - # sccache caches the workspace crates' compiled libraries, which rust-cache leaves out: - # warm, each Windows leg built 4.5 min faster. Like rust-cache, only main writes (PRs read - # main's entries); a full set is ~90 MB, so it barely touches the 10 GB budget (#2688). - # Test executables can't be cached, so a PR still links its tests. - - name: Install sccache - uses: Mozilla-Actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 - with: - version: v0.18.0 - - - name: Use sccache - env: - MAIN: ${{ github.ref == 'refs/heads/main' }} - run: | - echo "SCCACHE_GHA_ENABLED=true" >> "$GITHUB_ENV" - echo "RUSTC_WRAPPER=sccache" >> "$GITHUB_ENV" - if [ "$MAIN" != true ]; then echo "SCCACHE_GHA_RW_MODE=READ_ONLY" >> "$GITHUB_ENV"; fi - shell: bash - - name: Clippy if: matrix.part == 'integration' run: cargo clippy --workspace --all-targets --locked --features heif -- -D warnings @@ -253,7 +223,7 @@ jobs: if: matrix.part == 'integration' run: cargo xtask layers - - uses: taiki-e/install-action@3a3daafd3b7f23b8f65d9f5ba2db203fb59b79e2 # v2.90.2 + - uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32 with: tool: cargo-nextest@0.9.150 @@ -290,6 +260,10 @@ jobs: CARGO_INCREMENTAL: 0 CARGO_NET_RETRY: 10 steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false @@ -306,16 +280,18 @@ jobs: libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev libgtk-3-dev - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + with: + toolchain: stable # gate.yml keys its cache `-rust--gate`. - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 with: prefix-key: v1-rust shared-key: ${{ hashFiles('Cargo.toml') }}-gate save-if: false - - uses: taiki-e/install-action@3a3daafd3b7f23b8f65d9f5ba2db203fb59b79e2 # v2.90.2 + - uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32 with: tool: cargo-nextest@0.9.150 @@ -339,11 +315,17 @@ jobs: CARGO_PROFILE_RELEASE_LTO: "false" CARGO_PROFILE_RELEASE_CODEGEN_UNITS: "16" steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + with: + toolchain: stable + - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 with: key: corpus save-if: ${{ github.ref == 'refs/heads/main' }} @@ -369,6 +351,10 @@ jobs: # Match release.yml so PR results reflect what would actually ship. TRUNK_VERSION: 0.21.14 steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false @@ -378,19 +364,20 @@ jobs: - name: Check out craft-i18n uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: + toolchain: stable targets: wasm32-unknown-unknown - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 with: key: ci-web save-if: ${{ github.ref == 'refs/heads/main' }} cache-on-failure: true + # Checksum-verified, as in release.yml's web build. - name: Install trunk - run: | - curl --proto '=https' -fsSL "https://github.com/trunk-rs/trunk/releases/download/v${TRUNK_VERSION}/trunk-x86_64-unknown-linux-gnu.tar.gz" \ - | tar -xz -C "$HOME/.cargo/bin" trunk - trunk --version + uses: storytold/craft-common-actions/actions/install-trunk@main + with: + trunk-version: ${{ env.TRUNK_VERSION }} # package.sh runs Trunk's release builds, validates relative URLs, cuts the wasm into # parts, checks the 24 MiB per-file limit and exercises the packaging step release.yml uses. - name: Build and verify browser release @@ -446,11 +433,17 @@ jobs: - { crate: affinity, name: import_preview, args: "--features io" } - { crate: format, name: load } steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # nightly - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + with: + toolchain: stable + - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 with: workspaces: crates/${{ matrix.target.crate }}/fuzz - name: Install cargo-fuzz @@ -474,6 +467,10 @@ jobs: env: RAYON_NUM_THREADS: "4" steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false @@ -483,8 +480,10 @@ jobs: packages: >- libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev libgtk-3-dev - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + with: + toolchain: stable + - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 with: key: color-range-perf - name: Compare exact outputs and release timings on 24 MP @@ -504,6 +503,10 @@ jobs: env: RAYON_NUM_THREADS: "4" steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false @@ -513,8 +516,10 @@ jobs: packages: >- libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev libgtk-3-dev - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + with: + toolchain: stable + - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 with: key: selection-morphology-perf - name: Compare exact outputs and release timings on 36 MP @@ -539,11 +544,17 @@ jobs: runs-on: macos-15 timeout-minutes: 60 steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + with: + toolchain: stable + - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 with: key: perf-release - name: Quick performance suite @@ -563,11 +574,17 @@ jobs: env: RAYON_NUM_THREADS: "4" steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + with: + toolchain: stable + - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 with: key: selection-combining-perf - name: Compare exact outputs and release timings on 36 MP @@ -587,6 +604,10 @@ jobs: env: RAYON_NUM_THREADS: "4" steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@v7 with: persist-credentials: false @@ -596,8 +617,10 @@ jobs: persist-credentials: false ref: ${{ inputs.brush_tip_base }} path: before - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + with: + toolchain: stable + - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 with: workspaces: | before -> target @@ -633,6 +656,10 @@ jobs: CARGO_PROFILE_RELEASE_LTO: "false" CARGO_PROFILE_RELEASE_CODEGEN_UNITS: "16" steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 @@ -647,7 +674,9 @@ jobs: git worktree add --detach "$RUNNER_TEMP/photocraft-baseline" "$base" mkdir -p "$RUNNER_TEMP/photocraft-baseline/crates/engine/examples" cp crates/engine/examples/bench_dry_mixer.rs "$RUNNER_TEMP/photocraft-baseline/crates/engine/examples/bench_dry_mixer.rs" - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + with: + toolchain: stable - name: Install Linux build dependencies uses: storytold/craft-common-actions/actions/install-apt-packages@main with: diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index e93efc1018..443638eb73 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -27,13 +27,16 @@ concurrency: jobs: build: - timeout-minutes: 15 name: mdBook build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable - - name: Install mdBook - run: cargo install mdbook --version 0.4.52 --locked - - name: Build documentation - run: mdbook build book + # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + timeout-minutes: 15 + # The book needs mdBook only: no craft-fonts, apt packages, wasm target or nextest. + craft-fonts-ref: "" + targets: "" + free-disk-space: false + # Prebuilt mdBook, the version cargo install built before. + tools: mdbook@0.4.52 + cache-version: v1-docs + command: mdbook build book diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index 86619a3ad6..980c3a2445 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -29,6 +29,10 @@ jobs: name: Verified AppImage inputs runs-on: ubuntu-latest steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - run: bash packaging/linux/verified-download-test.sh @@ -37,6 +41,10 @@ jobs: name: Windows installation policy (no app build) runs-on: windows-latest steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false diff --git a/.github/workflows/perf-nightly.yml b/.github/workflows/perf-nightly.yml index 71afc03e14..488ca56126 100644 --- a/.github/workflows/perf-nightly.yml +++ b/.github/workflows/perf-nightly.yml @@ -43,13 +43,19 @@ jobs: runs-on: macos-15 timeout-minutes: 120 steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@v7 with: persist-credentials: false - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + with: + toolchain: stable - - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + - uses: step-security/rust-cache@8871c8ba063416da7c32246932ea6ae08700453e # v2.9.2 with: key: perf-release diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d1efb21c08..298dd4bf87 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,10 @@ name: Release on: + # A nightly dry run on main: every release build except macOS, nothing signed or released + # (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day. + schedule: + - cron: "28 2 * * *" push: branches: [release] workflow_dispatch: @@ -30,6 +34,7 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: + dry-run: ${{ github.event_name == 'schedule' }} app-name: photocraft app-title: PhotoCraft craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 diff --git a/AGENTS.md b/AGENTS.md index e2b8e229a7..4c0acf5b54 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -118,7 +118,7 @@ People trust PhotoCraft with their work, and a crash loses it. A malformed file, 3. **Clean-room.** We studied Photoshop and other proprietary editors for *behaviour and look only*. Never copy their code, shaders, profiles or assets. Implement from public specs (Adobe PSD spec, ICC, ISO 32000 blend modes, papers) and observation. Third-party assets must be permissively licensed, keep their license file next to them, and get a row in `ATTRIBUTION.md` (path, title, author, source, license) in the same change; so do original assets. The ArtCraft logos in `docs/brand/` are not open source (`docs/brand/LICENSE-brand.txt`). **Never commit font files:** fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts). PhotoCraft uses it through the optional build input `CRAFT_FONTS_DIR=` (read by `crates/text/build.rs`, exposed as `photocraft_text::CRAFT_FONTS`; empty without it, and everything must still work). Build with it: `CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo build`; details in `docs/development.md` › Fonts. 4. **Tests are the gate.** Every change comes with tests. Format crates use round-trip, synthetic-generator, oracle and fuzz tests. Keep the PSD corpus results and the parity floor (`crates/ui-egui/src/parity.rs`) from regressing. 5. **The UI is thin and data-driven.** UI state lives in `ui-egui/src/state.rs` (serde), so the control channel can read and drive it. Colours and radii come from `theme::Tokens`, never hard-coded. -6. **Verify UI changes visually.** Render offscreen with `cargo run -p photocraft-ui-egui --example snapshot` (no window, no focus stealing), or launch with `--control` and take `ui.screenshot`. Look at the PNG. Demo images must be public-domain art, never personal photos. When fetching assets, never put a person's name, email or other personal details in requests (User-Agent, headers, URLs); use a generic `Photocraft-dev` User-Agent. +6. **Verify UI changes visually.** Render offscreen with `cargo run -p photocraft-ui-egui --example snapshot` (no window, no focus stealing), or launch with `--control` and take `ui.screenshot`. Look at the PNG. **Screenshots that show a PR's change (before/after evidence) go in the PR description, never in the repo:** `docs/images/` holds only images the README or a doc displays (a doc's own before/after comparison included), so a PR adds an image there only together with the doc that shows it. Demo images must be public-domain art, never personal photos. When fetching assets, never put a person's name, email or other personal details in requests (User-Agent, headers, URLs); use a generic `Photocraft-dev` User-Agent. 7. **Never break wasm.** L0–L6 must `cargo check --target wasm32-unknown-unknown` (run `cargo xtask wasm`). File-system code is `cfg(not(target_arch = "wasm32"))` or goes through the platform services. 8. **Performance is a feature.** Benchmark heavy operations on a 24–36 MP image in release. Work per tile in parallel (rayon), skip empty tiles, never scan a full surface per frame (cache per revision), and record before/after timings in the dev log. @@ -161,6 +161,8 @@ cargo xtask test-corpus # if you touched psd, io, codecs, compose, gpu, text While iterating, run less and keep the full commands above as the final gate: `cargo test -p --lib --tests` skips the examples and doctests plain `cargo test` builds every time (ui-egui has 11 examples), and `cargo test -p --test ` runs one integration-test file. `cargo nextest run` runs tests in parallel across binaries; see `docs/development.md` › Faster test loops. +**MCP in tests and agent sessions: `photocraft-cli mcp --headless`.** Plain `photocraft-cli mcp` works in the open PhotoCraft window while the ArtCraft Launcher's agents switch is on, and then may start PhotoCraft on the developer's machine when it is closed. Scripts, tests and agents that want a session without a window pass `--headless` (or use `photocraft-cli serve`); a test that runs the CLI also gives it its own settings, launcher and flags folders (`PHOTOCRAFT_CONFIG_DIR`, `CRAFT_MCP_DIR`, `CRAFT_FLAGS_FILE`, as `crate::command()` in `apps/photocraft-cli/tests/it/main.rs` does). To drive the running app on purpose, use `--control` (`docs/development.md`). + **Test corpora.** Real-file corpora live in `corpus/` (gitignored, never committed), fetched at pinned commits and sha256-verified by `cargo xtask corpus --all`: our Photoshop- and GIMP-authored oracles from https://github.com/storytold/photocraft-corpus plus psd-tools, ag-psd and PngSuite from their upstreams. Pins: `xtask/src/corpus_pins.rs`. The corpus tests are opt-in (cargo feature `corpus`): plain `cargo test` skips them, and with the feature on a missing corpus fails ("run `cargo xtask corpus --all`"). `cargo xtask test-corpus` fetches and runs them all. CI always runs them (the `corpus` job, cached by pin). Never commit corpus files; new oracles go to photocraft-corpus (its `AGENTS.md`), then a pin bump here. Details: `docs/development.md` › Test corpora. Commands must **never panic** on bad input (Rule 9): every `run` closure and the code it calls returns `Err`, not a panic, for any params or document state. New commands come with a graceful-failure test (empty/out-of-range/wrong-type params → `Err`, not a crash). diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index ec6ae524ff..11f0e304f4 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -10,13 +10,13 @@ next to them. | Path | Title | Author | Source | License | |---|---|---|---|---| -| `crates/codecs/src/codecs/xpm/x11_colors.rs` | X11 `rgb.txt` color-name lookup table (normalized X.Org RGB values) | X.Org Foundation and X11 contributors | | MIT (X.Org app/rgb) | | Embedded at build time from storytold/craft-i18n `locales//common.tsv` and `locales//photocraft.tsv` (revision in [`craft-i18n.rev`](craft-i18n.rev)) | UI translations (all languages) | craft-i18n and PhotoCraft contributors; per-language credits and provenance in [craft-i18n's ATTRIBUTION.md](https://github.com/storytold/craft-i18n/blob/main/ATTRIBUTION.md) | | MIT OR Apache-2.0; Copyright (c) 2026 ArtCraft Team and the craft-i18n contributors; notice in [NOTICE](NOTICE) | | `epaint_default_fonts::EGUI_ICONS` (build input; deflated into `OUT_DIR/egui_fonts/egui-icons.ttf.deflate`, registered by `crates/ui-egui/src/text/egui_fonts.rs`) | egui-icons, five-glyph subset of emoji-icon-font | John Slegers | [egui fork at 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [original](https://github.com/jslegers/emoji-icon-font); egui subset, unmodified here | MIT; Copyright (c) 2014 John Slegers; full upstream notice in [NOTICE](NOTICE) | | `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) | | `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) | -| `assets/icons/*.svg` except `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `history-brush.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg`, `path-op-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg`, `crop-overlay-*.svg`, `vertical-align-*.svg`, `spirit-level.svg` (116 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | -| `assets/icons/{check,chevron-down,chevron-left,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | +| `assets/icons/*.svg` except `vector-shape.svg`, `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `history-brush.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg`, `path-op-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg`, `crop-overlay-*.svg`, `vertical-align-*.svg`, `spirit-level.svg` (117 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | +| `assets/icons/{check,chevron-down,chevron-left,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in,zoom-out}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | +| `assets/icons/vector-shape.svg` | Vector path shape-layer glyph with four anchor points | @superplay2021 | Original work for PhotoCraft | MIT OR Apache-2.0 | | `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/slice-select.svg` | Slice Select tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/crop-overlay-*.svg` | Crop overlay glyphs: Rule of Thirds, Grid, Diagonal, Triangle, Golden Ratio and Golden Spiral inside the crop-mark frame | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | @@ -80,14 +80,12 @@ The other built-in ICC profiles and the generated LUT looks are produced by code |---|---|---|---|---| | `docs/brand/` (all files) | ArtCraft name, wordmark and mark | ArtCraft Team | getartcraft.com | Not open source; trademarks of the ArtCraft Team, [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt) | | `docs/images/photocraft-*.jpg` | PhotoCraft screenshots | PhotoCraft contributors (UI) | Rendered offscreen with the `snapshot` example | MIT OR Apache-2.0 (UI); the artwork in each is public domain, listed below | -| `docs/images/preferences-apply-*.png` | Preferences before and after adding Apply (no artwork) | PhotoCraft contributors | PhotoCraft control-channel capture and offscreen `snapshot` example | MIT OR Apache-2.0 | -| `docs/images/guide-position-*-tab.png` | New Guide before and after focusing Position with Tab (no artwork) | PhotoCraft contributors | Offscreen `snapshot` example with `ui.key Tab` | MIT OR Apache-2.0 | | `docs/images/embedded-vector-editor-en.png` | Embedded AI/PDF/EPS conversion warning and editor chooser (no artwork) | Don Omondi | Offscreen `smart_svg_ui::tests::capture_embedded_vector_conversion_prompt` with authored bytes and mock services | MIT OR Apache-2.0 | | `docs/images/embedded-vector-tabs-linux.png` | Shared VectorCraft window after a portal editor save and ordinary document launch | Don Omondi | Local Linux GUI acceptance with authored orange rectangle/blue circle SVGs; no private artwork | MIT OR Apache-2.0 | -| `docs/images/gradient-overlay-method-*.png` | Gradient Overlay Method selector, before and after (synthetic gradient) | @oRE-o | Rendered offscreen with the `snapshot` example; no external artwork | MIT OR Apache-2.0 | | `docs/images/preset-invalid-choice-before.png` | Gradient preset import before validation, with the collision dialog closed | @yoriswind | Offscreen PhotoCraft capture with the synthetic `Fire.grd` gradient fixture | MIT OR Apache-2.0 | | `docs/images/preset-invalid-choice-after.png` | Gradient preset import after validation, with the collision dialog still open | @yoriswind | Offscreen PhotoCraft capture with the synthetic `Fire.grd` gradient fixture | MIT OR Apache-2.0 | | `docs/images/cpu-pixel-alignment/*.png` | CPU canvas pixel alignment, before and after #8321 | PhotoCraft contributors | Original synthetic noise rendered with the offscreen `snapshot` example; see the adjacent README | MIT OR Apache-2.0, adjacent `LICENSE-MIT` and `LICENSE-APACHE` | +| `docs/images/clone-source/*.png` | Clone source opacity/flow, cross-document and source-edge previews, and offset readouts | PhotoCraft contributors | Original synthetic red shapes rendered offscreen with the `snapshot` example; adjacent capture scripts and README | MIT OR Apache-2.0 | | `docs/images/multi-channel-editing/{curves,curves-choices,levels,drawing,mask-view-before,mask-view-after}.png` | Selected colour channel editing (synthetic gradient) | @hidoba | Original synthetic gradient rendered with the offscreen `snapshot` example; adjacent JSON scripts | MIT OR Apache-2.0, adjacent `LICENSE-MIT` and `LICENSE-APACHE` | | `docs/images/multi-channel-editing/great-wave.jpg`, `rgb.png`, `cmyk.png`, `lab.png`, `gallery-channel-preview-{before,after}.png` | *The Great Wave off Kanagawa*, c. 1830–1832, and PhotoCraft channel-selection captures | Katsushika Hokusai (artwork); PhotoCraft contributors (UI) | [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Tsunami_by_hokusai_19th_century.jpg), Metropolitan Museum reproduction; adjacent JSON capture scripts | Public domain artwork (PD-Art), adjacent `LICENSE-PUBLIC-DOMAIN.txt`; UI/scripts MIT OR Apache-2.0 | @@ -133,7 +131,7 @@ Files copied into `corpus/` by hand (tiff, exr, raw) must be MIT, BSD or CC0. | Path | Title | Author | Source | License | |---|---|---|---|---| -| `crates/psd/tests/fixtures/atn/*.atn` | Independently encoded ATN version-16 and version-12 parser fixtures | PhotoCraft contributors (version-12 files: @yoriswind) | Original synthetic test data; wire layout documented in `crates/psd/src/atn.rs`; provenance in the adjacent README | MIT OR Apache-2.0 | +| `crates/engine/tests/fixtures/atn/v12-commands.atn` | Independently encoded ATN version-12 parser fixture (Gaussian Blur, Levels, Select All, Make Layer; 404 bytes, sha256 `451958b686da9aab45e65ae902c86333b7149d72021c21904e3aae8e39eb77cb`), copied from the PSD crate's fixtures, which now live in craft-libs' `craft-psd` | PhotoCraft contributors (@yoriswind) | Original synthetic test data | MIT OR Apache-2.0 | ## Embedded-vector editor source diff --git a/Cargo.lock b/Cargo.lock index f16fc58341..50ee8419e8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 4 [[package]] name = "accesskit" -version = "0.25.1" +version = "0.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932" +checksum = "4e883d1d28c5fd5568c79ed2d2bd48d9f2fd3945c8974ed0f53690ceddb051be" dependencies = [ "enumn", "serde", @@ -15,9 +15,9 @@ dependencies = [ [[package]] name = "accesskit_atspi_common" -version = "0.21.0" +version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52c182f9c282ac9c5638d876d551d15e5f7d397ec263349a0c6a2b61595dd5e4" +checksum = "24f5baf62e34a4a6c30e3d697e4782f821a7337049c44c3b40576a27dfbb580d" dependencies = [ "accesskit", "accesskit_consumer", @@ -29,9 +29,9 @@ dependencies = [ [[package]] name = "accesskit_consumer" -version = "0.39.1" +version = "0.39.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a45e2bb300bea6d5f33a82c3e051c3ddc6f41c209750f68a0acbe991a284344" +checksum = "f3da8f27636015191b2264ee1df681503170a632cafd832fdc1edfdd4e3a2fd3" dependencies = [ "accesskit", "hashbrown 0.17.1", @@ -39,37 +39,37 @@ dependencies = [ [[package]] name = "accesskit_ios" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28e539d64b27fd4c14de8f78ada8f7c944c092f52f7e49fb63316507a57f6937" +checksum = "a5280724673bbfa8b30a838c013500b719392989be3b97c5a9964062c252c232" dependencies = [ "accesskit", "accesskit_consumer", "hashbrown 0.17.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", "objc2-ui-kit 0.2.2", ] [[package]] name = "accesskit_macos" -version = "0.27.1" +version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5701624bf6a11efb6d4c8e922bf44126ed96250e5faa9a7a0468c979635839a4" +checksum = "123828ceeec755b05255e3976cb0852993202de98a0626c97dd8d34246991f84" dependencies = [ "accesskit", "accesskit_consumer", "hashbrown 0.17.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-app-kit 0.2.2", "objc2-foundation 0.2.2", ] [[package]] name = "accesskit_unix" -version = "0.24.0" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "202f24df034a7476d07b7f74284de84f6d62aabd858dbe7ee9cad3b7ad6f8f9d" +checksum = "30d5192871228c54f1b0fb4a85cef000e11a3804f25d2165f14afa0daa67f3f6" dependencies = [ "accesskit", "accesskit_atspi_common", @@ -85,9 +85,9 @@ dependencies = [ [[package]] name = "accesskit_windows" -version = "0.35.1" +version = "0.35.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce63f35d6bdcf59f26b76b3379063f738e6412cef46999cc772d46aa3de35adb" +checksum = "498668b90da9995302a0055aaecad4756932333da2ddef6baee1c00844c430fc" dependencies = [ "accesskit", "accesskit_consumer", @@ -99,9 +99,9 @@ dependencies = [ [[package]] name = "accesskit_winit" -version = "0.34.1" +version = "0.34.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee96dd150375c05912d8a473f98c2fb155fb3234fac88292d396548a2460fa77" +checksum = "cd4ab4437b520ff03088fbe48676a11e7d44a929535e64b31432c1073e48dbcc" dependencies = [ "accesskit", "accesskit_ios", @@ -314,9 +314,9 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "arbitrary" -version = "1.4.2" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" [[package]] name = "arboard" @@ -412,9 +412,9 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.14.0" +version = "1.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" dependencies = [ "async-task", "concurrent-queue", @@ -444,9 +444,9 @@ dependencies = [ [[package]] name = "async-lock" -version = "3.4.2" +version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" dependencies = [ "event-listener", "event-listener-strategy", @@ -473,13 +473,13 @@ dependencies = [ [[package]] name = "async-recursion" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.10", ] [[package]] @@ -514,7 +514,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -611,9 +611,9 @@ dependencies = [ [[package]] name = "aws-lc-rs" -version = "1.18.2" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" dependencies = [ "aws-lc-sys", "untrusted 0.7.1", @@ -622,9 +622,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.46.0" +version = "0.47.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" dependencies = [ "cc", "cmake", @@ -685,7 +685,7 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" dependencies = [ - "bit-vec 0.10.1", + "bit-vec 0.10.2", ] [[package]] @@ -696,9 +696,9 @@ checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" [[package]] name = "bit-vec" -version = "0.10.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5727b15fa97d4f4fee0a3b7c3d550ed0269f54329207b86388de918604e31269" +checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0" dependencies = [ "borsh", "serde", @@ -706,9 +706,9 @@ dependencies = [ [[package]] name = "bit_field" -version = "0.10.3" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6" +checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1" [[package]] name = "bitflags" @@ -743,7 +743,7 @@ dependencies = [ "arrayvec", "cc", "cfg-if", - "constant_time_eq", + "constant_time_eq 0.4.2", "cpufeatures 0.3.1", ] @@ -762,6 +762,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block-padding" version = "0.3.3" @@ -777,7 +786,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" dependencies = [ - "objc2 0.5.2", + "objc2 0.5.3", ] [[package]] @@ -823,7 +832,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -882,7 +891,7 @@ checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -913,14 +922,13 @@ dependencies = [ [[package]] name = "calloop" -version = "0.14.4" +version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dbf9978365bac10f54d1d4b04f7ce4427e51f71d61f2fe15e3fed5166474df7" +checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" dependencies = [ "bitflags 2.13.2", "polling", "rustix 1.1.5", - "slab", "tracing", ] @@ -942,7 +950,7 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" dependencies = [ - "calloop 0.14.4", + "calloop 0.14.5", "rustix 1.1.5", "wayland-backend", "wayland-client", @@ -995,9 +1003,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.5.1" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" dependencies = [ "find-msvc-tools", "jobserver", @@ -1103,7 +1111,7 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "crypto-common", + "crypto-common 0.1.7", "inout", ] @@ -1158,7 +1166,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -1179,9 +1187,9 @@ dependencies = [ [[package]] name = "clipboard-win" -version = "5.4.1" +version = "5.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" dependencies = [ "error-code", ] @@ -1213,7 +1221,7 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der", "spki", "x509-cert", @@ -1272,9 +1280,9 @@ dependencies = [ [[package]] name = "combine" -version = "4.6.8" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" dependencies = [ "bytes", "memchr", @@ -1295,12 +1303,27 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "constant_time_eq" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" +[[package]] +name = "constant_time_eq" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +dependencies = [ + "rustversion", +] + [[package]] name = "cookie-factory" version = "0.3.3" @@ -1403,15 +1426,64 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-ai-agents" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=35e0352666a117407d62230a6c6c2366f3e21a3b#35e0352666a117407d62230a6c6c2366f3e21a3b" +dependencies = [ + "dirs", + "serde", + "serde_json", +] + +[[package]] +name = "craft-atomic" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97#86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97" +dependencies = [ + "rustix 1.1.5", +] + [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" + +[[package]] +name = "craft-dpx" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=09dcbc225b95232998498a40ca56e24716571d53#09dcbc225b95232998498a40ca56e24716571d53" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-exr" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=09dcbc225b95232998498a40ca56e24716571d53#09dcbc225b95232998498a40ca56e24716571d53" +dependencies = [ + "serde_json", +] + +[[package]] +name = "craft-flags" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97#86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97" +dependencies = [ + "craft-atomic", + "dirs", + "toml_edit", +] [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" + +[[package]] +name = "craft-gif" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=09dcbc225b95232998498a40ca56e24716571d53#09dcbc225b95232998498a40ca56e24716571d53" [[package]] name = "craft-heif" @@ -1425,7 +1497,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1448,7 +1520,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "thiserror 2.0.21", ] @@ -1466,7 +1538,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "bytemuck", "hayro", @@ -1478,21 +1550,49 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "craft-winprint-gdi", "log", "miniz_oxide 0.9.1", - "roxmltree 0.21.1", + "roxmltree 0.21.2", "tempfile", "winprint", "winsafe", ] +[[package]] +name = "craft-psd" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=09dcbc225b95232998498a40ca56e24716571d53#09dcbc225b95232998498a40ca56e24716571d53" +dependencies = [ + "encoding_rs", + "flate2", + "rayon", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-raster-codecs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=09dcbc225b95232998498a40ca56e24716571d53#09dcbc225b95232998498a40ca56e24716571d53" +dependencies = [ + "rayon", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-tga" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=09dcbc225b95232998498a40ca56e24716571d53#09dcbc225b95232998498a40ca56e24716571d53" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1513,7 +1613,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "chrono", "dunce", @@ -1523,10 +1623,11 @@ dependencies = [ "image", "log", "plist", + "rustix 1.1.5", "semver", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "tar", "tempfile", "ureq", @@ -1546,9 +1647,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.5.3" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" dependencies = [ "cfg-if", ] @@ -1648,6 +1749,15 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -1674,7 +1784,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -1685,7 +1795,7 @@ checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" dependencies = [ "darling_core", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -1700,7 +1810,7 @@ version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der_derive", "flagset", "pem-rfc7468", @@ -1743,11 +1853,43 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", "subtle", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.3", + "crypto-common 0.2.2", +] + +[[package]] +name = "dirs" +version = "7.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.59.0", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -1774,7 +1916,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -2045,9 +2187,9 @@ dependencies = [ [[package]] name = "either" -version = "1.18.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" @@ -2060,9 +2202,9 @@ dependencies = [ [[package]] name = "encoding_rs" -version = "0.8.42" +version = "0.8.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" dependencies = [ "cfg-if", "core_detect", @@ -2095,7 +2237,7 @@ checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -2140,7 +2282,7 @@ dependencies = [ "ecolor", "emath", "epaint_default_fonts", - "font-types 0.12.5", + "font-types 0.12.7", "harfrust", "log", "nohash-hasher", @@ -2184,9 +2326,9 @@ dependencies = [ [[package]] name = "equivalent" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "errno" @@ -2247,16 +2389,15 @@ dependencies = [ [[package]] name = "exr" -version = "1.74.2" +version = "1.74.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "711fe42c9964295e01ee3fba3f9fe0e1d24b98886950d68efe81b1c76e21adf3" +checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6" dependencies = [ "bit_field", "half", "lebe", "miniz_oxide 0.8.9", - "num-complex", - "pulp", + "multiversion", "rayon-core", "smallvec", "zune-inflate", @@ -2270,23 +2411,9 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] name = "fax" -version = "0.2.6" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f05de7d48f37cd6730705cbca900770cab77a89f413d23e100ad7fad7795a0ab" -dependencies = [ - "fax_derive", -] - -[[package]] -name = "fax_derive" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0aca10fb742cb43f9e7bb8467c91aa9bcb8e3ffbc6a6f7389bb93ffc920577d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" [[package]] name = "fdeflate" @@ -2315,9 +2442,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.14" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "fixed_decimal" @@ -2332,9 +2459,9 @@ dependencies = [ [[package]] name = "fixedbitset" -version = "0.5.7" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" +checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175" [[package]] name = "flagset" @@ -2344,9 +2471,9 @@ checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" [[package]] name = "flate2" -version = "1.1.10" +version = "1.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" dependencies = [ "crc32fast", "miniz_oxide 0.9.1", @@ -2421,9 +2548,9 @@ dependencies = [ [[package]] name = "font-types" -version = "0.12.5" +version = "0.12.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8eb065f3251655b3c90e22e5e363f310fc5332fb3402e37bbc94752283248f6" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" dependencies = [ "bytemuck", "serde", @@ -2466,7 +2593,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parlance", "read-fonts 0.41.0", - "roxmltree 0.21.1", + "roxmltree 0.21.2", "smallvec", "windows", "windows-core", @@ -2491,7 +2618,7 @@ checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -2595,7 +2722,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -2974,7 +3101,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "bytemuck", "hayro-interpret", @@ -3004,7 +3131,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -3022,7 +3149,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -3046,7 +3173,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "flate2", "hayro-ccitt", @@ -3092,7 +3219,7 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" dependencies = [ - "digest", + "digest 0.10.7", ] [[package]] @@ -3134,6 +3261,15 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.12.0" @@ -3333,9 +3469,9 @@ checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" [[package]] name = "icu_pattern" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b3db611446bd92c246b03e4aa0bafa71ddb194af431ddbb42b9d70e4bfce1a0" +checksum = "bc43ce0e76ee8cb0482dc6e2dbb9b76278e8038f45daabf2a2877577e2ceb18f" dependencies = [ "displaydoc", "either", @@ -3552,7 +3688,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f" dependencies = [ "io-lifetimes 3.0.1", - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] @@ -3627,9 +3763,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] name = "jni" @@ -3707,9 +3843,9 @@ checksum = "b454d911ac55068f53495488d8ccd0646eaa540c033a28ee15b07838afafb01f" [[package]] name = "js-sys" -version = "0.3.106" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", @@ -3956,9 +4092,9 @@ dependencies = [ [[package]] name = "lazy_static" -version = "1.5.0" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" [[package]] name = "leb128fmt" @@ -4013,7 +4149,7 @@ dependencies = [ "bitflags 2.13.2", "libc", "plain", - "redox_syscall 0.9.4", + "redox_syscall 0.9.5", ] [[package]] @@ -4099,9 +4235,9 @@ dependencies = [ [[package]] name = "litrs" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" [[package]] name = "lock_api" @@ -4114,9 +4250,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.34" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "loop9" @@ -4148,7 +4284,7 @@ dependencies = [ "nom_locate", "rand 0.9.5", "rangemap", - "sha2", + "sha2 0.10.9", "stringprep", "thiserror 2.0.21", "ttf-parser", @@ -4189,7 +4325,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" dependencies = [ "cfg-if", - "digest", + "digest 0.10.7", ] [[package]] @@ -4200,9 +4336,9 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "memmap2" -version = "0.9.11" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" dependencies = [ "libc", ] @@ -4228,9 +4364,9 @@ dependencies = [ [[package]] name = "mime" -version = "0.3.17" +version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" [[package]] name = "minimal-lexical" @@ -4260,9 +4396,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.3" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "wasi", @@ -4297,6 +4433,28 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multiversion" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076" +dependencies = [ + "multiversion-macros", + "target-features", +] + +[[package]] +name = "multiversion-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "target-features", +] + [[package]] name = "multiversion_no_op" version = "1.0.0" @@ -4465,7 +4623,6 @@ version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" dependencies = [ - "bytemuck", "num-traits", ] @@ -4546,9 +4703,9 @@ checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" [[package]] name = "objc2" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804" +checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b" dependencies = [ "objc-sys", "objc2-encode", @@ -4572,7 +4729,7 @@ dependencies = [ "bitflags 2.13.2", "block2 0.5.1", "libc", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-core-data 0.2.2", "objc2-core-image 0.2.2", "objc2-foundation 0.2.2", @@ -4640,7 +4797,7 @@ checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" dependencies = [ "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-core-location", "objc2-foundation 0.2.2", ] @@ -4663,7 +4820,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" dependencies = [ "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", ] @@ -4697,7 +4854,7 @@ checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" dependencies = [ "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", ] @@ -4748,7 +4905,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" dependencies = [ "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", "objc2-metal 0.2.2", ] @@ -4770,7 +4927,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" dependencies = [ "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-contacts", "objc2-foundation 0.2.2", ] @@ -4834,7 +4991,7 @@ dependencies = [ "block2 0.5.1", "dispatch", "libc", - "objc2 0.5.2", + "objc2 0.5.3", ] [[package]] @@ -4889,7 +5046,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" dependencies = [ "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-app-kit 0.2.2", "objc2-foundation 0.2.2", ] @@ -4914,7 +5071,7 @@ checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" dependencies = [ "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", ] @@ -4938,7 +5095,7 @@ checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" dependencies = [ "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", "objc2-metal 0.2.2", ] @@ -4963,7 +5120,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" dependencies = [ - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", ] @@ -4975,7 +5132,7 @@ checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" dependencies = [ "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-cloud-kit 0.2.2", "objc2-core-data 0.2.2", "objc2-core-image 0.2.2", @@ -5007,7 +5164,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" dependencies = [ "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", ] @@ -5019,7 +5176,7 @@ checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" dependencies = [ "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-core-location", "objc2-foundation 0.2.2", ] @@ -5054,9 +5211,15 @@ dependencies = [ [[package]] name = "openssl-probe" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" [[package]] name = "orbclient" @@ -5070,9 +5233,9 @@ dependencies = [ [[package]] name = "ordered-float" -version = "5.5.0" +version = "5.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0" +checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" dependencies = [ "num-traits", ] @@ -5138,9 +5301,9 @@ dependencies = [ [[package]] name = "parlance" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b6937eda350acc1a5d05872c3cbf99fe78619c269096e2be3d4a350058639d5" +checksum = "73072a9470554c8e794778acece2312661218aaabb635600957d952cf01c716e" [[package]] name = "parley" @@ -5323,7 +5486,7 @@ dependencies = [ [[package]] name = "photocraft" -version = "0.20.1" +version = "0.23.1" dependencies = [ "arboard", "async-io", @@ -5332,6 +5495,7 @@ dependencies = [ "chrono", "clap", "core-graphics2", + "craft-flags", "craft-update", "dispatch2", "eframe", @@ -5361,7 +5525,7 @@ dependencies = [ "resvg", "rfd", "ron", - "roxmltree 0.21.1", + "roxmltree 0.21.2", "rustix 1.1.5", "serde", "serde_json", @@ -5378,7 +5542,7 @@ dependencies = [ [[package]] name = "photocraft-affinity" -version = "0.20.1" +version = "0.23.1" dependencies = [ "crc32fast", "flate2", @@ -5388,7 +5552,7 @@ dependencies = [ [[package]] name = "photocraft-algo" -version = "0.20.1" +version = "0.23.1" dependencies = [ "criterion", "photocraft-color", @@ -5403,11 +5567,14 @@ dependencies = [ [[package]] name = "photocraft-automation" -version = "0.20.1" +version = "0.23.1" dependencies = [ "base64 0.23.1", "cap-std", "clap", + "craft-ai-agents", + "craft-flags", + "craft-psd", "getrandom 0.3.4", "hmac", "photocraft-codecs", @@ -5419,7 +5586,6 @@ dependencies = [ "photocraft-geom", "photocraft-gpu", "photocraft-io", - "photocraft-psd", "photocraft-raster", "photocraft-raw", "pollster 1.0.1", @@ -5428,7 +5594,7 @@ dependencies = [ "schemars", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror 2.0.21", "tokio", "wgpu", @@ -5436,11 +5602,12 @@ dependencies = [ [[package]] name = "photocraft-cli" -version = "0.20.1" +version = "0.23.1" dependencies = [ "clap", "clap_complete", "clap_mangen", + "craft-psd", "photocraft-automation", "photocraft-cms", "photocraft-codecs", @@ -5448,7 +5615,6 @@ dependencies = [ "photocraft-engine", "photocraft-format", "photocraft-io", - "photocraft-psd", "photocraft-raster", "photocraft-raw", "serde", @@ -5462,7 +5628,7 @@ dependencies = [ [[package]] name = "photocraft-cms" -version = "0.20.1" +version = "0.23.1" dependencies = [ "moxcms", "rayon", @@ -5470,10 +5636,15 @@ dependencies = [ [[package]] name = "photocraft-codecs" -version = "0.20.1" +version = "0.23.1" dependencies = [ + "craft-dpx", + "craft-exr", + "craft-gif", "craft-heif", "craft-jpeg", + "craft-raster-codecs", + "craft-tga", "exr", "flate2", "half", @@ -5494,7 +5665,7 @@ dependencies = [ [[package]] name = "photocraft-color" -version = "0.20.1" +version = "0.23.1" dependencies = [ "photocraft-cms", "serde", @@ -5502,7 +5673,7 @@ dependencies = [ [[package]] name = "photocraft-compose" -version = "0.20.1" +version = "0.23.1" dependencies = [ "criterion", "photocraft-cms", @@ -5518,7 +5689,7 @@ dependencies = [ [[package]] name = "photocraft-doc" -version = "0.20.1" +version = "0.23.1" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5529,12 +5700,13 @@ dependencies = [ [[package]] name = "photocraft-engine" -version = "0.20.1" +version = "0.23.1" dependencies = [ "base64 0.22.1", "blake3", "chrono", "craft-print", + "craft-psd", "exr", "flate2", "photocraft-affinity", @@ -5551,14 +5723,13 @@ dependencies = [ "photocraft-ops", "photocraft-paint", "photocraft-plugins", - "photocraft-psd", "photocraft-raster", "photocraft-raw", "photocraft-testkit", "photocraft-text", "photocraft-vector", "rayon", - "roxmltree 0.21.1", + "roxmltree 0.21.2", "same-file", "semver", "serde", @@ -5572,7 +5743,7 @@ dependencies = [ [[package]] name = "photocraft-format" -version = "0.20.1" +version = "0.23.1" dependencies = [ "blake3", "craft-pcraft-format", @@ -5596,14 +5767,14 @@ dependencies = [ [[package]] name = "photocraft-geom" -version = "0.20.1" +version = "0.23.1" dependencies = [ "serde", ] [[package]] name = "photocraft-gpu" -version = "0.20.1" +version = "0.23.1" dependencies = [ "bytemuck", "half", @@ -5624,11 +5795,12 @@ dependencies = [ [[package]] name = "photocraft-io" -version = "0.20.1" +version = "0.23.1" dependencies = [ "blake3", "craft-docpath", "craft-pdf", + "craft-psd", "crc32fast", "flate2", "imagesize", @@ -5645,7 +5817,6 @@ dependencies = [ "photocraft-format", "photocraft-geom", "photocraft-paint", - "photocraft-psd", "photocraft-raster", "photocraft-raw", "photocraft-testkit", @@ -5653,7 +5824,7 @@ dependencies = [ "photocraft-vector", "proptest", "resvg", - "roxmltree 0.21.1", + "roxmltree 0.21.2", "serde_json", "thiserror 2.0.21", "tiff", @@ -5664,18 +5835,18 @@ dependencies = [ [[package]] name = "photocraft-ipp" -version = "0.20.1" +version = "0.23.1" [[package]] name = "photocraft-ops" -version = "0.20.1" +version = "0.23.1" dependencies = [ "photocraft-doc", ] [[package]] name = "photocraft-paint" -version = "0.20.1" +version = "0.23.1" dependencies = [ "photocraft-cms", "photocraft-color", @@ -5689,7 +5860,7 @@ dependencies = [ [[package]] name = "photocraft-plugins" -version = "0.20.1" +version = "0.23.1" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5703,21 +5874,9 @@ dependencies = [ "wat", ] -[[package]] -name = "photocraft-psd" -version = "0.20.1" -dependencies = [ - "encoding_rs", - "flate2", - "photocraft-psd", - "proptest", - "serde", - "thiserror 2.0.21", -] - [[package]] name = "photocraft-raster" -version = "0.20.1" +version = "0.23.1" dependencies = [ "crc32fast", "lz4_flex", @@ -5733,7 +5892,7 @@ dependencies = [ [[package]] name = "photocraft-raw" -version = "0.20.1" +version = "0.23.1" dependencies = [ "flate2", "image", @@ -5748,7 +5907,7 @@ dependencies = [ [[package]] name = "photocraft-tablet" -version = "0.20.1" +version = "0.23.1" dependencies = [ "block2 0.6.2", "log", @@ -5763,7 +5922,7 @@ dependencies = [ [[package]] name = "photocraft-testkit" -version = "0.20.1" +version = "0.23.1" dependencies = [ "memory-stats", "serde_json", @@ -5771,14 +5930,14 @@ dependencies = [ [[package]] name = "photocraft-text" -version = "0.20.1" +version = "0.23.1" dependencies = [ + "craft-psd", "flate2", "parley", "photocraft-color", "photocraft-doc", "photocraft-geom", - "photocraft-psd", "photocraft-raster", "rayon", "skrifa 0.47.0", @@ -5786,12 +5945,13 @@ dependencies = [ [[package]] name = "photocraft-ui-egui" -version = "0.20.1" +version = "0.23.1" dependencies = [ "base64 0.23.1", "chrono", "craft-i18n", "craft-print", + "craft-psd", "craft-ui", "craft-update", "eframe", @@ -5816,7 +5976,6 @@ dependencies = [ "photocraft-io", "photocraft-paint", "photocraft-plugins", - "photocraft-psd", "photocraft-raster", "photocraft-raw", "photocraft-testkit", @@ -5835,7 +5994,7 @@ dependencies = [ [[package]] name = "photocraft-vector" -version = "0.20.1" +version = "0.23.1" dependencies = [ "photocraft-color", "photocraft-doc", @@ -5846,8 +6005,9 @@ dependencies = [ [[package]] name = "photocraft-web" -version = "0.20.1" +version = "0.23.1" dependencies = [ + "craft-psd", "eframe", "egui", "js-sys", @@ -5857,7 +6017,6 @@ dependencies = [ "photocraft-engine", "photocraft-io", "photocraft-paint", - "photocraft-psd", "photocraft-raster", "photocraft-ui-egui", "rfd", @@ -5869,7 +6028,7 @@ dependencies = [ [[package]] name = "photocraft-web-boot" -version = "0.20.1" +version = "0.23.1" dependencies = [ "flate2", "js-sys", @@ -6176,7 +6335,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" dependencies = [ "bit-set 0.11.1", - "bit-vec 0.10.1", + "bit-vec 0.10.2", "bitflags 2.13.2", "chacha20", "core_detect", @@ -6189,29 +6348,6 @@ dependencies = [ "unarray", ] -[[package]] -name = "pulp" -version = "0.22.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a" -dependencies = [ - "bytemuck", - "cfg-if", - "libm", - "num-complex", - "paste", - "pulp-wasm-simd-flag", - "raw-cpuid", - "reborrow", - "version_check", -] - -[[package]] -name = "pulp-wasm-simd-flag" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740" - [[package]] name = "pxfm" version = "0.1.30" @@ -6466,15 +6602,6 @@ dependencies = [ "rgb", ] -[[package]] -name = "raw-cpuid" -version = "11.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" -dependencies = [ - "bitflags 2.13.2", -] - [[package]] name = "raw-window-handle" version = "0.6.2" @@ -6530,7 +6657,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" dependencies = [ "bytemuck", - "font-types 0.12.5", + "font-types 0.12.7", "once_cell", ] @@ -6541,16 +6668,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8" dependencies = [ "bytemuck", - "font-types 0.12.5", + "font-types 0.12.7", "once_cell", ] -[[package]] -name = "reborrow" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430" - [[package]] name = "redox_syscall" version = "0.4.1" @@ -6571,13 +6692,23 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.9.4" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "737970939a87c6fa31e7acad13307bccbb017a073b695b6089a2c484f929e20e" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", +] + [[package]] name = "ref-cast" version = "1.0.27" @@ -6595,7 +6726,7 @@ checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -6745,9 +6876,9 @@ dependencies = [ [[package]] name = "rmcp" -version = "3.6.0" +version = "3.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ceb42e9e47443cd83a834dea57b5816d35481417bae72ade5dc5615c59122e26" +checksum = "d24a7e92f4bcaa36b97fa93c4fa7ca8f3e669eced949345b3462dba333c7f909" dependencies = [ "chrono", "futures", @@ -6759,6 +6890,7 @@ dependencies = [ "schemars", "serde", "serde_json", + "sha2 0.11.1", "thiserror 2.0.21", "tokio", "tokio-stream", @@ -6769,15 +6901,15 @@ dependencies = [ [[package]] name = "rmcp-macros" -version = "3.7.0" +version = "3.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "967fa7f7935d7d6217d593df0e8e5c9307bcaf256974a5a9ee64476c97735389" +checksum = "b3140f24a766f80f9ec1607bde85680959a69b83d46fa9ce87dadab7e67ab029" dependencies = [ "darling", "proc-macro2", "quote", "serde_json", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -6788,12 +6920,11 @@ checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189" [[package]] name = "ron" -version = "0.12.2" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81116b9531d61eabc41aeb228e4b6b2435bcca3233b98cf3b3077d4e6e9debb3" +checksum = "97b3fe97c18ff24299ea56f802c5693eb34266fb0bc8317f4e101debc8a3ceaf" dependencies = [ "bitflags 2.13.2", - "once_cell", "serde", "serde_derive", "typeid", @@ -6808,9 +6939,9 @@ checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" [[package]] name = "roxmltree" -version = "0.21.1" +version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" dependencies = [ "memchr", ] @@ -6904,9 +7035,9 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" dependencies = [ "openssl-probe", "rustls-pki-types", @@ -6916,9 +7047,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.15.1" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" dependencies = [ "web-time", "zeroize", @@ -6953,9 +7084,9 @@ checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "aws-lc-rs", "ring", @@ -7031,9 +7162,9 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.29" +version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" dependencies = [ "windows-sys 0.61.2", ] @@ -7061,7 +7192,7 @@ dependencies = [ "proc-macro2", "quote", "serde_derive_internals", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -7159,7 +7290,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -7170,7 +7301,7 @@ checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -7205,14 +7336,14 @@ checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] name = "serde_spanned" -version = "1.1.1" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" dependencies = [ "serde_core", ] @@ -7237,7 +7368,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", ] [[package]] @@ -7248,7 +7379,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -7308,12 +7450,12 @@ checksum = "da90c3d9af638898a5fdc347479b18f950bb0dde11ecf2244f94cd28135da53b" dependencies = [ "aws-lc-rs", "base64 0.22.1", - "const-oid", + "const-oid 0.9.6", "der", - "digest", + "digest 0.10.7", "pem", "rand_core 0.10.1", - "sha2", + "sha2 0.10.9", "signature", "sigstore-types", "spki", @@ -7382,7 +7524,7 @@ dependencies = [ "chrono", "cmpv2", "cms", - "const-oid", + "const-oid 0.9.6", "der", "hex", "rand 0.10.3", @@ -7421,7 +7563,7 @@ dependencies = [ "base64 0.22.1", "chrono", "cms", - "const-oid", + "const-oid 0.9.6", "hex", "pem", "rustls-pki-types", @@ -7535,9 +7677,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.16.2" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" dependencies = [ "serde", ] @@ -7574,7 +7716,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0512da38f5e2b31201a93524adb8d3136276fa4fe4aafab4e1f727a82b534cc0" dependencies = [ "bitflags 2.13.2", - "calloop 0.14.4", + "calloop 0.14.5", "calloop-wayland-source 0.4.1", "cursor-icon", "libc", @@ -7763,9 +7905,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.6" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -7789,7 +7931,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -7863,6 +8005,12 @@ dependencies = [ "xattr", ] +[[package]] +name = "target-features" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" + [[package]] name = "target-lexicon" version = "0.13.5" @@ -7928,7 +8076,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -8003,9 +8151,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", "serde_core", @@ -8072,7 +8220,7 @@ checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] @@ -8098,9 +8246,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.19" +version = "0.7.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" dependencies = [ "bytes", "futures-core", @@ -8112,9 +8260,9 @@ dependencies = [ [[package]] name = "toml" -version = "1.1.6+spec-1.1.0" +version = "1.2.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a" +checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" dependencies = [ "indexmap", "serde_core", @@ -8127,39 +8275,40 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.1.1+spec-1.1.0" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" dependencies = [ "serde_core", ] [[package]] name = "toml_edit" -version = "0.25.15+spec-1.1.0" +version = "0.25.19+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" dependencies = [ "indexmap", "toml_datetime", "toml_parser", + "toml_writer", "winnow", ] [[package]] name = "toml_parser" -version = "1.1.3+spec-1.1.0" +version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" dependencies = [ "winnow", ] [[package]] name = "toml_writer" -version = "1.1.2+spec-1.1.0" +version = "1.2.0+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" [[package]] name = "tower" @@ -8276,9 +8425,9 @@ dependencies = [ [[package]] name = "twox-hash" -version = "2.1.4" +version = "2.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5283634e518fe9e82c7b20520bb4bc209009fd16c82077c802f8111ecbb0117a" +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" [[package]] name = "type-map" @@ -8350,9 +8499,9 @@ checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" [[package]] name = "unicode-ident" -version = "1.0.26" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-normalization" @@ -8365,15 +8514,15 @@ dependencies = [ [[package]] name = "unicode-properties" -version = "0.1.4" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" [[package]] name = "unicode-script" -version = "0.5.8" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee" +checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf" [[package]] name = "unicode-segmentation" @@ -8389,9 +8538,9 @@ checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" [[package]] name = "unicode-width" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" [[package]] name = "untrusted" @@ -8407,9 +8556,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "ureq" -version = "3.5.0" +version = "3.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" +checksum = "e7be76686bdf7198002062423ca0d8cf9b75a27c8e1de804513b97e97b555d9d" dependencies = [ "base64 0.23.1", "flate2", @@ -8424,9 +8573,9 @@ dependencies = [ [[package]] name = "ureq-proto" -version = "0.6.5" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" dependencies = [ "base64 0.23.1", "http", @@ -8475,9 +8624,12 @@ dependencies = [ [[package]] name = "utf16_iter" -version = "1.0.5" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" +checksum = "1c7de35d9d8757dbc1f5125dc8b51438c68b4430546a735c3a9b91aaaaf9a18a" +dependencies = [ + "utf_types", +] [[package]] name = "utf8-zero" @@ -8487,9 +8639,12 @@ checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" [[package]] name = "utf8_iter" -version = "1.0.4" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] [[package]] name = "utf8parse" @@ -8498,10 +8653,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] -name = "uuid" -version = "1.26.1" +name = "utf_types" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.29.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c" dependencies = [ "getrandom 0.4.3", "js-sys", @@ -8596,9 +8757,9 @@ dependencies = [ [[package]] name = "verifysign" -version = "1.0.1" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6acfcc42a8d44f340d001193d97ef56bf33210b51ad760ae8308c97d5241ca51" +checksum = "a6efd25aadc22c756a9012267fae0b130278d335d6ceb512ec02ce82029b5ca9" dependencies = [ "core-foundation 0.10.1", "windows-sys 0.61.2", @@ -8661,12 +8822,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -8674,9 +8834,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.79" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", "tokio", @@ -8685,9 +8845,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -8695,34 +8855,34 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] [[package]] name = "wasm-encoder" -version = "0.262.0" +version = "0.263.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +checksum = "0b883a26aea02eaabe2d2c3fba7eb039ef5cdcb5d5201ae5551e73d5e251a81f" dependencies = [ "leb128fmt", - "wasmparser 0.262.0", + "wasmparser 0.263.0", ] [[package]] @@ -8777,9 +8937,9 @@ dependencies = [ [[package]] name = "wasmparser" -version = "0.262.0" +version = "0.263.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +checksum = "4f5fa0a054ae153606df820eb0a84213e28cda41bbe04ba2628e71b6ba100fcb" dependencies = [ "bitflags 2.13.2", "indexmap", @@ -8788,9 +8948,9 @@ dependencies = [ [[package]] name = "wast" -version = "262.0.0" +version = "263.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30612a0c29249b5f185888a107e8a519d920226b7d07f9d351fd094e9f75eb23" +checksum = "69d90bcf581b501aa1c358bc5dc0faa979cd375796908860ebcb6d1d70b907c7" dependencies = [ "bumpalo", "leb128fmt", @@ -8801,9 +8961,9 @@ dependencies = [ [[package]] name = "wat" -version = "1.262.0" +version = "1.263.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e228027f2b07bbaf946980ebbe2437fca73be6f54c40c2a8d4f42f277075f8d1" +checksum = "bbc9c5aca783b3f1838be89f3f9937c528b90ec5faa6fb62d809726c16a7d8f7" dependencies = [ "wast", ] @@ -8960,9 +9120,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.106" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -8980,9 +9140,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.9" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" dependencies = [ "rustls-pki-types", ] @@ -9331,7 +9491,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -9340,7 +9500,16 @@ version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", ] [[package]] @@ -9358,14 +9527,31 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", ] [[package]] @@ -9383,48 +9569,96 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + [[package]] name = "winit" version = "0.30.13" @@ -9447,7 +9681,7 @@ dependencies = [ "libc", "memmap2", "ndk", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-app-kit 0.2.2", "objc2-foundation 0.2.2", "objc2-ui-kit 0.2.2", @@ -9478,9 +9712,9 @@ dependencies = [ [[package]] name = "winnow" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" dependencies = [ "memchr", ] @@ -9488,7 +9722,7 @@ dependencies = [ [[package]] name = "winprint" version = "0.2.1" -source = "git+https://github.com/storytold/winprint.rs?rev=51934db382f225454cf152a8657eb03789be63c4#51934db382f225454cf152a8657eb03789be63c4" +source = "git+https://github.com/storytold/winprint.rs?rev=bc06a7c48b768eb27a828c7986f6d2868b245ee0#bc06a7c48b768eb27a828c7986f6d2868b245ee0" dependencies = [ "flate2", "fmt-derive", @@ -9503,6 +9737,7 @@ dependencies = [ "windows", "windows-core", "windows-implement", + "windows-numerics", "xml", ] @@ -9638,7 +9873,7 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" dependencies = [ - "const-oid", + "const-oid 0.9.6", "der", "sha1", "signature", @@ -9754,7 +9989,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "xtask" -version = "0.20.1" +version = "0.23.1" dependencies = [ "chrono", "craft-i18n", @@ -9783,9 +10018,9 @@ dependencies = [ [[package]] name = "yoke" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -9794,13 +10029,13 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", "synstructure", ] @@ -9872,7 +10107,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", "zbus_names", "zvariant", "zvariant_utils", @@ -9880,9 +10115,9 @@ dependencies = [ [[package]] name = "zbus_names" -version = "4.3.4" +version = "4.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" dependencies = [ "serde", "winnow", @@ -9903,27 +10138,27 @@ dependencies = [ [[package]] name = "zcheapstr" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" +checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920" dependencies = [ "serde", ] [[package]] name = "zerocopy" -version = "0.8.59" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.59" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", @@ -9947,7 +10182,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", "synstructure", ] @@ -9987,9 +10222,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.8" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ "serde", "yoke", @@ -9999,29 +10234,32 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", ] [[package]] name = "zip" -version = "9.1.0" +version = "9.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2886b00003a72c4ccee3f42cfc34908d33b2508a74d827dc2a4244706475c704" +checksum = "e3476fd497ac8af5b1ec7b51acab7bef380f7e8dd8e0487595bafd839417a302" dependencies = [ + "constant_time_eq 0.6.1", "crc32fast", "flate2", "getrandom 0.4.3", "indexmap", + "libc", "memchr", "nix", "typed-path", "windows-sys 0.61.2", + "zeroize", ] [[package]] @@ -10086,9 +10324,9 @@ dependencies = [ [[package]] name = "zvariant" -version = "5.15.0" +version = "5.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1d34c27cc6cdd1f458427519dd6b8612f7b7e3f7b9a0b2355d041dda9869147" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" dependencies = [ "endi", "enumflags2", @@ -10101,14 +10339,14 @@ dependencies = [ [[package]] name = "zvariant_derive" -version = "5.15.0" +version = "5.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "864155e69b4352db0c7f374917bf45d1e0c8d17659c8b3dbf9795f3673f8c497" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.10", "zvariant_utils", ] @@ -10121,7 +10359,7 @@ dependencies = [ "proc-macro2", "quote", "serde", - "syn 3.0.6", + "syn 3.0.10", "winnow", ] diff --git a/Cargo.toml b/Cargo.toml index 3a4bfceeb4..779273168c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,13 +4,19 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"] [workspace.package] -version = "0.20.1" +version = "0.23.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" [workspace.dependencies] -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["serde"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] } +# Feature flags shared with the launcher and the other Craft apps (craft-libs#1118, #1119). +craft-flags = { git = "https://github.com/storytold/craft-libs", rev = "86d6e8c5b05a4dadc35ff1c8e5d2f992c687ee97" } +# The ArtCraft Launcher's agents switch and app list, shared with the launcher, the MCP gateway and +# every Craft app (storytold/craft-ai-integrations#195). Pinned to the head of +# storytold/craft-ai-integrations#197 until it merges. +craft-ai-agents = { git = "https://github.com/storytold/craft-ai-integrations", rev = "35e0352666a117407d62230a6c6c2366f3e21a3b" } # internal photocraft-geom = { path = "crates/geom" } photocraft-color = { path = "crates/color" } @@ -18,7 +24,8 @@ photocraft-cms = { path = "crates/cms" } photocraft-raster = { path = "crates/raster" } photocraft-doc = { path = "crates/doc" } photocraft-ops = { path = "crates/ops" } -photocraft-psd = { path = "crates/psd" } +# PSD/PSB and the Photoshop resource files (ABR, ASL, ACO, ATN, ...): the shared reader and writer (craft-libs#875). +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "09dcbc225b95232998498a40ca56e24716571d53" } photocraft-codecs = { path = "crates/codecs" } photocraft-raw = { path = "crates/raw" } photocraft-affinity = { path = "crates/affinity" } @@ -39,19 +46,29 @@ photocraft-tablet = { path = "crates/tablet" } photocraft-ipp = { path = "crates/ipp" } # external -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +# DDS, DICOM, FITS, IFF/ILBM, PCX, PNM and XPM: the shared decoders and encoders (craft-libs#880). +# DPX and Cineon frames (craft-libs#887); the mapping onto images stays in crates/codecs. +craft-dpx = { git = "https://github.com/storytold/craft-libs", rev = "09dcbc225b95232998498a40ca56e24716571d53" } +# The Targa writer (craft-libs#892). +craft-tga = { git = "https://github.com/storytold/craft-libs", rev = "09dcbc225b95232998498a40ca56e24716571d53" } +# GIF blocks without decoding: the first frame's colour table, the frame walk (craft-libs#939). +craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "09dcbc225b95232998498a40ca56e24716571d53" } +# OpenEXR channel naming and Cryptomatte IDs, manifests and streams (craft-libs#929). +craft-exr = { git = "https://github.com/storytold/craft-libs", rev = "09dcbc225b95232998498a40ca56e24716571d53" } +craft-raster-codecs = { git = "https://github.com/storytold/craft-libs", rev = "09dcbc225b95232998498a40ca56e24716571d53" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } # HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784). craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "081078bb1b44aeedfa5bef3d4f13d978dc77510a" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["raster"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["raster"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "b8f7d93b00dfb8f172938f3d2d796ae62dcfe123" } # Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n # catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at # the commit in `craft-i18n.rev`). Already in the tree through craft-ui. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } # 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 = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" @@ -151,7 +168,7 @@ opt-level = "s" # (runs when a pipeline is created). "z" keeps the wasm well under the size gate. [profile.wasm-release.package.photocraft-doc] opt-level = "z" -[profile.wasm-release.package.photocraft-psd] +[profile.wasm-release.package.craft-psd] opt-level = "z" [profile.wasm-release.package.photocraft-format] opt-level = "z" @@ -211,7 +228,7 @@ egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc7 egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # craft-pdf's vendored Hayro trees: consumers patch the same craft-libs revision (crates/pdf README). -hayro = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } diff --git a/README.md b/README.md index c1789ab7d2..4e2b8ac8fb 100644 --- a/README.md +++ b/README.md @@ -221,7 +221,7 @@ Every screenshot here is the real app at work on public-domain art, rendered off PhotoCraft's PSD support is a standalone crate written from Adobe's public specification and tested against a corpus of real-world files. -- **Faithful round trips:** opening and re-saving a document renders the same for 307 of the 309 files in the psd-tools test set and 169 of 170 in our mixed ag-psd/psd-tools set (`crates/io/tests/it/corpus.rs`; fetch the psd-tools set with `cargo xtask corpus --psd-tools`), and anything we don't model yet (raw blocks, descriptors, extras) is carried over instead of being dropped. A re-saved file is not byte-identical to its source: PhotoCraft rewrites image resources, layer records and the composite. Only the standalone `photocraft-psd` crate, parsing and writing a file without the document model, reproduces every parseable corpus file byte for byte (`crates/psd/tests/it/corpus.rs`). +- **Faithful round trips:** opening and re-saving a document renders the same for 307 of the 309 files in the psd-tools test set and 169 of 170 in our mixed ag-psd/psd-tools set (`crates/io/tests/it/corpus.rs`; fetch the psd-tools set with `cargo xtask corpus --psd-tools`), and anything we don't model yet (raw blocks, descriptors, extras) is carried over instead of being dropped. A re-saved file is not byte-identical to its source: PhotoCraft rewrites image resources, layer records and the composite. Only the standalone `craft-psd` crate, parsing and writing a file without the document model, reproduces every parseable corpus file byte for byte (`crates/psd/tests/it/corpus.rs`). - **Pixels that match:** a composite oracle compares our render with Photoshop's own merged image, covering gradient interpolation (Classic, Perceptual and Linear), layer effects, shape strokes, clipping and fill opacity. - **Large documents:** PSB, 16 and 32-bit files, and CMYK and Lab documents open natively. @@ -242,10 +242,14 @@ photocraft-cli batch --actions grade.json --in ./raw --out ./graded # Every subcommand explains itself photocraft-cli batch --help -# Let an agent drive it over MCP (headless, or bridged to the running app) +# Let an agent drive it over MCP: the open window while agents are allowed, otherwise headless photocraft-cli mcp +# Always without a window (scripts, tests) +photocraft-cli mcp --headless ``` +To let Claude or another AI app drive the open PhotoCraft window without a terminal, turn on **ArtCraft Launcher › Settings › AI agents** and click **Add** next to the AI app (one entry for every Craft app). See [`docs/mcp.md`](docs/mcp.md). These settings are behind the Craft suite's `AI-MCP` feature flag: set `AI-MCP = true` in `ArtCraft/flags.toml`, or start PhotoCraft with `CRAFT_FLAGS=AI-MCP`. + The desktop app also offers an authenticated, loopback-only control channel (`photocraft --control`) for inspecting UI state, driving tools with pointer events, and taking offscreen screenshots. Every image in this README was rendered that way. See [`docs/control-protocol.md`](docs/control-protocol.md). ## Under the hood diff --git a/apps/photocraft-cli/Cargo.toml b/apps/photocraft-cli/Cargo.toml index 059e53eb39..35af450c4f 100644 --- a/apps/photocraft-cli/Cargo.toml +++ b/apps/photocraft-cli/Cargo.toml @@ -46,7 +46,7 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros"] } serde = { workspace = true } tempfile = "3" # Reading back a saved PSD's merged-image flag (#8064). -photocraft-psd = { workspace = true } +craft-psd = { workspace = true } # A real ICC profile for the --metadata test (#9466). photocraft-cms = { workspace = true } # Synthetic camera raws (#7789). diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index ae1e3f8f8f..429fcb4547 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -270,13 +270,24 @@ pub(crate) struct CommandsArgs { pub(crate) filter: Option, } -/// Run the MCP server on stdio (headless engine, or bridge to a running `photocraft --control `) +/// Run the MCP server on stdio: in the open PhotoCraft window when the person lets agents use it +/// (ArtCraft Launcher › Settings › AI agents), otherwise headless /// -/// Headless: each automation root grants that direction of file access; an omitted root denies it. -/// Prefer absolute root paths in MCP client configurations. Bridge: set the roots on the desktop -/// app; root flags are refused. The token flags require --bridge (or PHOTOCRAFT_CONTROL_PORT). +/// The open window is found again on every call, with no port or token to configure. Without +/// the person's consent, or with --headless, it runs headless: each automation root grants that +/// direction of file access; an omitted root denies it. Prefer absolute root paths in MCP client +/// configurations. Bridge (--bridge or PHOTOCRAFT_CONTROL_PORT): a running `photocraft --control +/// `; set the roots on the desktop app, root flags are refused, and the token flags require +/// it. #[derive(Args)] pub(crate) struct McpArgs { + /// Always work headless, without the open window + #[arg(long, conflicts_with = "when_closed")] + pub(crate) headless: bool, + /// While agents may use PhotoCraft but it is closed: start it, serve a headless session, or + /// fail (default: the app's When PhotoCraft Is Closed setting) + #[arg(long, value_name = "launch|headless|error", value_parser = when_closed)] + pub(crate) when_closed: Option, /// Bridge to the PhotoCraft app listening here instead of a headless engine; a bare port means /// 127.0.0.1: #[arg(long, value_name = "127.0.0.1:PORT", env = "PHOTOCRAFT_CONTROL_PORT", value_parser = bridge)] @@ -337,6 +348,8 @@ enum ValueError { /// Why a `--bridge` value, or a PHOTOCRAFT_CONTROL_PORT value for `mcp`, is refused. #[error("expected a port, 0-65535 (--bridge also takes 127.0.0.1:)")] Bridge, + #[error("expected launch, headless or error")] + WhenClosed, } /// Why `parse` refuses `mcp` or `serve` options clap accepted: clap prints it as a usage error @@ -360,13 +373,19 @@ enum ServerOptionError { /// A token flag without the bridge or port that reads it would be ignored (#8035). #[error("{flag} requires {transport}")] NeedsTransport { flag: &'static str, transport: &'static str }, + /// `--headless` never reaches an app. + #[error("--headless works without the app; {0} is for --bridge")] + HeadlessBridge(&'static str), + /// `--when-closed` is about the open app, which a bridge names itself. + #[error("--when-closed is for the open window; --bridge names the app itself")] + BridgeWhenClosed, } impl ServerOptionError { fn into_clap(self, cmd: &mut clap::Command) -> clap::Error { let kind = match self { Self::BridgeVar(_) | Self::GpuVar(_) => ErrorKind::ValueValidation, - Self::BridgeRoots | Self::BridgeGpu => ErrorKind::ArgumentConflict, + Self::BridgeRoots | Self::BridgeGpu | Self::HeadlessBridge(_) | Self::BridgeWhenClosed => ErrorKind::ArgumentConflict, Self::NeedsTransport { .. } => ErrorKind::MissingRequiredArgument, }; cmd.error(kind, self) @@ -394,6 +413,10 @@ fn tiff_compression(s: &str) -> Result { } } +fn when_closed(s: &str) -> Result { + photocraft_engine::prefs::WhenAppClosed::parse(s).ok_or(ValueError::WhenClosed) +} + fn on_off(s: &str) -> Result { match s { "on" => Ok(true), @@ -474,6 +497,11 @@ fn steps(m: &ArgMatches) -> Vec { /// stray.psd --help`): clap reports the mistake first. pub(crate) fn parse(args: &[OsString]) -> Result { let mut cmd = Cli::command().mut_subcommands(|sub| sub.mut_args(blank_env_is_unset)); + // `mcp --headless` reaches no app: a PHOTOCRAFT_CONTROL_PORT exported for another tool is not + // read, so a value it couldn't use anyway doesn't stop it. + if args.first().is_some_and(|a| a == "mcp") && args.iter().take_while(|a| *a != "--").any(|a| a == "--headless") { + cmd = cmd.mut_subcommand("mcp", |sub| sub.mut_arg("bridge", |arg| arg.env(None::<&str>))); + } let argv = std::iter::once(OsString::from("photocraft-cli")).chain(args.iter().cloned()); let matches = match cmd.try_get_matches_from_mut(argv) { Err(e) if args.iter().take_while(|a| *a != "--").any(|a| *a == "--help" || *a == "-h") => { @@ -490,6 +518,21 @@ pub(crate) fn parse(args: &[OsString]) -> Result { check_gpu_env(&mut cmd, m)?; } (Command::Mcp(a), Some((name, m))) => { + if a.headless { + // `--headless` reaches no app. Given on the command line, the bridge's flags + // conflict; exported for another tool, they are left alone. + for (id, flag) in [("bridge", "--bridge"), ("control_token", "--control-token"), ("control_token_file", "--control-token-file")] { + if m.value_source(id) == Some(ValueSource::CommandLine) { + if let Some(sub) = cmd.find_subcommand_mut(name) { + return Err(ServerOptionError::HeadlessBridge(flag).into_clap(sub)); + } + return Err(ServerOptionError::HeadlessBridge(flag).into_clap(&mut cmd)); + } + } + a.bridge = None; + check_gpu_env(&mut cmd, m)?; + return Ok(cli); + } a.bridge_from_env = from_env(m, "bridge"); if a.bridge_from_env && let Some(Bridge::Addr(v)) = &a.bridge @@ -516,6 +559,9 @@ pub(crate) fn parse(args: &[OsString]) -> Result { return Err(ServerOptionError::BridgeGpu.into_clap(sub)); } check_server(sub, m, a.bridge.is_some(), "--bridge")?; + if a.bridge.is_some() && a.when_closed.is_some() { + return Err(ServerOptionError::BridgeWhenClosed.into_clap(sub)); + } } if a.bridge.is_none() { check_gpu_env(&mut cmd, m)?; diff --git a/apps/photocraft-cli/src/automation.rs b/apps/photocraft-cli/src/automation.rs index 34dbd1ce8a..39dd9ce374 100644 --- a/apps/photocraft-cli/src/automation.rs +++ b/apps/photocraft-cli/src/automation.rs @@ -68,8 +68,12 @@ pub(crate) fn serve(a: &ServeArgs, err: &mut dyn Write) -> Result { } } +/// `mcp`: with the suite's `AI-MCP` flag, the open window when agents may use it, otherwise +/// headless (`mcp_live`); without the flag headless, as before it; `--headless` always headless; +/// `--bridge` (or PHOTOCRAFT_CONTROL_PORT) a `photocraft --control` app. pub(crate) fn mcp(a: &McpArgs, err: &mut dyn Write) -> Result { let server = match &a.bridge { + None if !a.headless && photocraft_automation::agent_link::mcp_flag() => PhotocraftMcp::live(live_config(a)?), Some(addr) => { if a.bridge_from_env { // Name the mode switch, as `serve` does: the way back to headless is to unset it. @@ -94,3 +98,30 @@ pub(crate) fn mcp(a: &McpArgs, err: &mut dyn Write) -> Result { let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build()?; Ok(rt.block_on(server.serve_stdio())?) } + +/// `mcp`: the app's settings folder, the closed-app override, the app launcher, and the headless +/// session's roots and rendering for when it works without the window. +fn live_config(a: &McpArgs) -> Result { + let other = |m: &str| crate::CliError::Other(m.to_string()); + let dir = photocraft_automation::app_dirs::from_env() + .dir + .ok_or_else(|| other("can't find PhotoCraft's settings folder (no home folder; set PHOTOCRAFT_CONFIG_DIR)"))?; + let mut config = photocraft_automation::live::LiveConfig::new(dir); + config.when_closed = a.when_closed; + // As a headless `mcp` always did: folders that can't be opened stop the start, before the + // server answers anything, rather than at the first call that would fall back to them. + a.automation.workspace()?; + config.read_roots.clone_from(&a.automation.automation_read_root); + config.write_root = a.automation.automation_write_root.clone(); + config.launch = std::env::current_exe().ok().and_then(|exe| photocraft_automation::live::launcher(&exe)); + let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(crate::CliError::Other)?; + config.prepare_headless = Some(Box::new(move |h| { + policy.apply_to_headless(h); + // stdout carries the protocol; the warnings a headless start has go to stderr. + let mut err = std::io::stderr(); + for d in h.drain_diagnostics() { + let _ = writeln!(err, "warning: {d}"); + } + })); + Ok(config) +} diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index d99c405eda..b14e2e61a3 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; /// The binary, without the variables `mcp` and `serve` fall back to: a test that wants one sets it. fn bin() -> Command { - let mut cmd = Command::new(crate::binary()); + let mut cmd = crate::command(); for var in ENV_VARS { cmd.env_remove(var); } @@ -879,7 +879,7 @@ fn no_maximize_compatibility_writes_the_psd_placeholder() { { let out = d.join(format!("a.{ext}")); ok(bin().arg("run").arg(&a).args(["--cmd", "layer.new.layer"]).arg("--out").arg(&out).args(args)); - let psd = photocraft_psd::PsdFile::from_bytes(&std::fs::read(&out).unwrap()).unwrap(); + let psd = craft_psd::PsdFile::from_bytes(&std::fs::read(&out).unwrap()).unwrap(); assert_eq!(psd.has_real_merged_data(), Some(real), "{args:?} {ext}"); } std::fs::remove_dir_all(d).unwrap(); @@ -1442,7 +1442,7 @@ fn batch_plays_a_photoshop_actions_file() { fn extensionless_version_12_actions_file_is_read_as_atn() { let d = tmp("atn-v12"); let path = d.join("Legacy Actions"); - std::fs::write(&path, include_bytes!("../../../../crates/psd/tests/fixtures/atn/v12-commands.atn")).unwrap(); + std::fs::write(&path, include_bytes!("../../../../crates/engine/tests/fixtures/atn/v12-commands.atn")).unwrap(); let (steps, set, warnings) = photocraft_cli::load_actions_file(&path, None).unwrap(); assert_eq!(set.len(), 1); assert_eq!(steps, vec![("actions.play".to_string(), json!({"action": set[0].name}))]); @@ -2029,3 +2029,95 @@ fn info_detail_adds_text_runs_and_antialiasing() { assert!(text["runs"].as_array().is_some_and(|r| !r.is_empty()), "{text}"); let _ = std::fs::remove_dir_all(&dir); } + +/// Flags that don't go together are usage errors before anything starts. Adding PhotoCraft to an +/// MCP client is the ArtCraft Launcher's job, so there is no `mcp install`, and plain `mcp` does +/// what `--live` did, so there is no `--live` either. +#[test] +fn mcp_rejects_mismatched_flags() { + for (args, needle) in [ + (&["mcp", "install"][..], "install"), + (&["mcp", "--live"], "--live"), + (&["mcp", "--client", "json"], "--client"), + (&["mcp", "--headless", "--bridge", "127.0.0.1:1"], "--bridge"), + (&["mcp", "--headless", "--control-token-file", "t"], "--control-token-file"), + (&["mcp", "--headless", "--when-closed", "launch"], "--when-closed"), + (&["mcp", "--when-closed", "sometimes"], "sometimes"), + (&["mcp", "--bridge", "127.0.0.1:1", "--when-closed", "error"], "--when-closed"), + ] { + let o = bin().args(args).stdin(Stdio::null()).output().unwrap(); + let err = String::from_utf8_lossy(&o.stderr); + assert_eq!(o.status.code(), Some(2), "{args:?}: {err}"); + assert!(err.contains(needle), "{args:?}: {err}"); + } +} + +/// One MCP exchange with `photocraft-cli mcp `: initialize, then each tool call; returns the +/// tool results. +fn mcp_session(args: &[&str], env: &[(&str, &std::ffi::OsStr)], calls: &[(&str, Value)]) -> Vec { + let mut cmd = bin(); + cmd.args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()); + for (k, v) in env { + cmd.env(k, v); + } + let mut child = cmd.spawn().unwrap(); + let mut stdin = child.stdin.take().unwrap(); + let mut stdout = BufReader::new(child.stdout.take().unwrap()); + let mut send = |v: Value| { + writeln!(stdin, "{v}").unwrap(); + stdin.flush().unwrap(); + }; + let mut recv = |id: u64| -> Value { + loop { + let mut line = String::new(); + assert!(stdout.read_line(&mut line).unwrap() > 0, "server closed"); + let v: Value = serde_json::from_str(&line).unwrap(); + if v["id"] == id { + return v; + } + } + }; + send(json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{ + "protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}})); + recv(1); + send(json!({"jsonrpc":"2.0","method":"notifications/initialized"})); + let mut out = Vec::new(); + for (i, (name, arguments)) in calls.iter().enumerate() { + let id = 2 + i as u64; + send(json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":{"name":name,"arguments":arguments}})); + out.push(recv(id)["result"].clone()); + } + drop(stdin); + let _ = child.kill(); + let _ = child.wait(); + out +} + +/// Plain `mcp` without the person's consent works headless, as it always did: commands run, UI +/// tools say they need the open app. `--headless` too, and it doesn't read a PHOTOCRAFT_CONTROL_PORT +/// exported for another tool (here not even a port). +#[test] +fn mcp_without_consent_works_headless() { + let dir = tmp("mcp-plain"); + let empty = tmp("mcp-plain-launcher"); + // `crate::command()` keeps the machine's launcher and flags out already; this test names its + // own settings and an empty launcher folder as well, to say what it relies on. + let env = [("PHOTOCRAFT_CONFIG_DIR", dir.as_os_str()), ("CRAFT_MCP_DIR", empty.as_os_str())]; + let calls = [("command_list", json!({})), ("ui_inspect", json!({}))]; + let r = mcp_session(&["mcp", "--when-closed", "error"], &env, &calls); + assert_ne!(r[0]["isError"], true, "headless commands run: {}", r[0]); + assert_eq!(r[1]["isError"], true, "{}", r[1]); + assert!(r[1]["content"][0]["text"].as_str().unwrap().contains("bridge"), "{}", r[1]); + let mut env = env.to_vec(); + env.push(("PHOTOCRAFT_CONTROL_PORT", std::ffi::OsStr::new("not-a-port"))); + let r = mcp_session(&["mcp", "--headless"], &env, &calls[..1]); + assert_ne!(r[0]["isError"], true, "{}", r[0]); + // Without the `AI-MCP` flag a Control Port saved before the agents switch (which the app + // reads as "agents may connect") still leaves plain `mcp` headless: it neither looks for + // the app nor applies When PhotoCraft Is Closed ("error" would fail this call). + std::fs::write(dir.join("preferences.json"), r#"{"integrations": {"controlPort": 7878}}"#).unwrap(); + let r = mcp_session(&["mcp", "--when-closed", "error"], &env[..2], &calls[..1]); + assert_ne!(r[0]["isError"], true, "without the flag plain mcp stays headless: {}", r[0]); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_dir_all(&empty); +} diff --git a/apps/photocraft-cli/tests/it/gpu.rs b/apps/photocraft-cli/tests/it/gpu.rs index eeb3faa8db..471e5a486f 100644 --- a/apps/photocraft-cli/tests/it/gpu.rs +++ b/apps/photocraft-cli/tests/it/gpu.rs @@ -6,7 +6,7 @@ use std::process::Command; use serde_json::Value; fn bin() -> Command { - let mut cmd = Command::new(crate::binary()); + let mut cmd = crate::command(); cmd.env_remove("PHOTOCRAFT_CONTROL_PORT"); cmd.env_remove("PHOTOCRAFT_CONTROL_TOKEN"); cmd.env_remove("PHOTOCRAFT_CONTROL_TOKEN_FILE"); diff --git a/apps/photocraft-cli/tests/it/main.rs b/apps/photocraft-cli/tests/it/main.rs index 411791d94c..280d98616d 100644 --- a/apps/photocraft-cli/tests/it/main.rs +++ b/apps/photocraft-cli/tests/it/main.rs @@ -13,3 +13,19 @@ mod psd_write_oracle; fn binary() -> std::ffi::OsString { std::env::var_os("NEXTEST_BIN_EXE_photocraft_cli").unwrap_or_else(|| env!("CARGO_BIN_EXE_photocraft-cli").into()) } + +/// The CLI, kept away from this machine's own PhotoCraft settings, ArtCraft Launcher and feature +/// flags: plain `mcp` works in the open app when the launcher's switch lets agents use it, and +/// would otherwise find (or start) the developer's own PhotoCraft. A test that needs a settings +/// folder of its own sets `PHOTOCRAFT_CONFIG_DIR` again; the last value wins. +fn command() -> std::process::Command { + let base = std::env::temp_dir().join(format!("pc-cli-it-isolated-{}", std::process::id())); + let settings = base.join("settings"); + let _ = std::fs::create_dir_all(&settings); + let mut cmd = std::process::Command::new(binary()); + cmd.env("PHOTOCRAFT_CONFIG_DIR", &settings) + .env("CRAFT_MCP_DIR", base.join("launcher")) + .env("CRAFT_FLAGS_FILE", base.join("flags.toml")) + .env_remove("CRAFT_FLAGS"); + cmd +} diff --git a/apps/photocraft-cli/tests/it/malloc_tuning.rs b/apps/photocraft-cli/tests/it/malloc_tuning.rs index a7513a714a..068b4d2205 100644 --- a/apps/photocraft-cli/tests/it/malloc_tuning.rs +++ b/apps/photocraft-cli/tests/it/malloc_tuning.rs @@ -2,13 +2,13 @@ //! and a value the user set. use std::io::{BufRead, BufReader, Write}; -use std::process::{Command, Stdio}; +use std::process::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()); + let mut cmd = crate::command(); for var in [TRIM_THRESHOLD_VAR, "MALLOC_MMAP_THRESHOLD_", "MALLOC_TOP_PAD_", "MALLOC_MMAP_MAX_", "MALLOC_ARENA_MAX", "GLIBC_TUNABLES"] { cmd.env_remove(var); } diff --git a/apps/photocraft-cli/tests/it/orientation.rs b/apps/photocraft-cli/tests/it/orientation.rs index 8e8da558c7..e29549e3a7 100644 --- a/apps/photocraft-cli/tests/it/orientation.rs +++ b/apps/photocraft-cli/tests/it/orientation.rs @@ -10,7 +10,7 @@ use photocraft_codecs::{ChannelLayout, DecodeOptions, EncodeOptions, Format, Ima use serde_json::Value; fn bin() -> Command { - Command::new(crate::binary()) + crate::command() } fn tmp(name: &str) -> PathBuf { diff --git a/apps/photocraft-web/Cargo.toml b/apps/photocraft-web/Cargo.toml index 7054d67bf9..075b734d3e 100644 --- a/apps/photocraft-web/Cargo.toml +++ b/apps/photocraft-web/Cargo.toml @@ -40,4 +40,4 @@ web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlE [dev-dependencies] serde_json = { workspace = true } photocraft-paint = { workspace = true } -photocraft-psd = { workspace = true } +craft-psd = { workspace = true } diff --git a/apps/photocraft-web/src/preset_bridge.rs b/apps/photocraft-web/src/preset_bridge.rs index a39fdfb4b4..4b79130493 100644 --- a/apps/photocraft-web/src/preset_bridge.rs +++ b/apps/photocraft-web/src/preset_bridge.rs @@ -181,7 +181,7 @@ impl PresetBackend for Bridge { #[cfg(test)] mod tests { use super::*; - use photocraft_psd::abr::{AbrSample, LegacyBrush, LegacyTip, write_v12}; + use craft_psd::abr::{AbrSample, LegacyBrush, LegacyTip, write_v12}; use serde_json::json; fn import(s: &mut Session) { @@ -367,7 +367,7 @@ mod tests { } #[test] fn indexed_brush_store_coexists_with_imported_gradient_preferences() { - use photocraft_psd::grd::{GrdColor, GrdGradient, GrdStop, write}; + use craft_psd::grd::{GrdColor, GrdGradient, GrdStop, write}; let b = Bridge::default(); let (mut s, _) = session(b.clone()); import(&mut s); diff --git a/apps/photocraft/Cargo.toml b/apps/photocraft/Cargo.toml index 413002248a..a9a11046b9 100644 --- a/apps/photocraft/Cargo.toml +++ b/apps/photocraft/Cargo.toml @@ -27,6 +27,7 @@ photocraft-io = { workspace = true } photocraft-format = { workspace = true } photocraft-automation = { workspace = true } photocraft-ui-egui = { workspace = true } +craft-flags = { workspace = true } # Pen tablet pressure/tilt on macOS and X11 (the workspace's one isolated unsafe helper crate). photocraft-tablet = { workspace = true } eframe = { workspace = true, features = ["wgpu", "accesskit", "wayland", "x11", "persistence", "clipboard"] } diff --git a/apps/photocraft/src/agent_link.rs b/apps/photocraft/src/agent_link.rs new file mode 100644 index 0000000000..26fc0756a3 --- /dev/null +++ b/apps/photocraft/src/agent_link.rs @@ -0,0 +1,281 @@ +//! Agents in the open desktop app: while the person lets them in (ArtCraft Launcher › Settings › +//! AI agents; without the `AI-MCP` flag, a Control Port saved before), the app serves the control +//! protocol by itself (no `--control`) and publishes the connection file `photocraft-cli mcp` +//! finds it by ([`photocraft_automation::agent_link`]). Turning it on or off, or changing the +//! port or folders in Preferences › AI Integrations, applies at once. The token stays in the settings +//! folder across launches (`agent-control.token`, as `--control-token-file` would keep it; delete +//! it for a new one). Agent requests get the policy and the folders chosen there, exactly as with +//! `--control` and the automation roots. +//! +//! Launch flags win: started with `--control`, the app doesn't install this service and the +//! dialog says the launch options manage the connection. + +use std::path::{Path, PathBuf}; +use std::sync::mpsc::Receiver; + +use photocraft_automation::agent_link::{self, Connection}; +use photocraft_automation::security; +use photocraft_engine::prefs::Integrations; +use photocraft_ui_egui::{AgentLink, AgentLinkFn, ControlRequest}; + +use crate::control_server; + +/// The connection while it runs; dropping it stops the server and removes the connection file. +struct Running { + server: control_server::Listening, + dir: PathBuf, + /// The `controlPort` preference it was started for (0 = any). + port_pref: u32, +} + +impl Drop for Running { + fn drop(&mut self) { + agent_link::remove_connection(&self.dir, std::process::id()); + log::info!("agent connection on 127.0.0.1:{} stopped", self.server.port); + } +} + +/// Start serving agents on `port` (0 = any free port): the token from the settings folder +/// (created `0600` when missing), then the connection file. Returns the connection and the +/// channel its requests arrive on. A token file that can't be written leaves the connection off +/// (no server, so no token to leak) and says why. +fn start(dir: &Path, port: u16, ctx: &egui::Context, port_pref: u32) -> Result<(Running, Receiver), String> { + let token_file = dir.join(agent_link::TOKEN_FILE); + let token = security::server_token(None, Some(&token_file)).map_err(|e| format!("Agents can't connect: the token file could not be written: {e}"))?; + let (requests, server) = control_server::listen(port, token, ctx.clone()).map_err(|e| format!("Couldn't listen on 127.0.0.1:{port}: {e}"))?; + let running = Running { server, dir: dir.to_path_buf(), port_pref }; + agent_link::write_connection(dir, &Connection::new(running.server.port, token_file)).map_err(|e| format!("Couldn't publish the agent connection: {e}"))?; + log::info!("agents can connect on 127.0.0.1:{}", running.server.port); + Ok((running, requests)) +} + +/// The agent connection service (`settings_dir`: where the connection file and token go). +pub fn service(settings_dir: Option) -> AgentLinkFn { + let mut running: Option = None; + Box::new(move |integrations: &Integrations, ctx: &egui::Context| apply(&mut running, settings_dir.as_deref(), integrations, ctx)) +} + +/// Bring the connection in line with `integrations`: start, restart on another port, stop, or only +/// change the folders agents may use. +fn apply(running: &mut Option, dir: Option<&Path>, integrations: &Integrations, ctx: &egui::Context) -> AgentLink { + let mut out = AgentLink::default(); + if !integrations.connect_agents { + out.stopped = running.take().is_some(); + return out; + } + // Allow Agent Control off refuses every control server, this one as `--control`. + if !integrations.allow_agent_control { + out.stopped = running.take().is_some(); + out.status.error = Some("Agents can't connect: Allow Agent Control is off in the preferences file.".into()); + return out; + } + let Some(dir) = dir else { + out.stopped = running.take().is_some(); + out.status.error = Some("Agents can't connect: PhotoCraft has no settings folder (no home folder).".into()); + return out; + }; + if running.as_ref().is_none_or(|r| r.port_pref != integrations.control_port) { + out.stopped = running.take().is_some(); + // The preference's range is 0..=65535; anything else picks a free port. + let port = u16::try_from(integrations.control_port).unwrap_or(0); + match start(dir, port, ctx, integrations.control_port) { + Ok((r, requests)) => { + out.requests = Some(requests); + *running = Some(r); + } + Err(e) => { + log::warn!("{e}"); + out.status.error = Some(e); + return out; + } + } + } + out.status.port = running.as_ref().map(|r| r.server.port); + // Agent requests always go through the automation policy; without folders they get no file + // access at all (as `--control` without automation roots). A folder that can't be opened, or + // isn't an absolute path, is left out (that direction fails closed) and named, as at launch. + let no_flags = photocraft_automation::args::AutomationArgs { automation_read_root: Vec::new(), automation_write_root: None }; + let workspace = match crate::automation_workspace(&no_flags, integrations) { + Ok((workspace, warning)) => { + if let Some(w) = warning { + out.status.error = Some(format!("Agents can connect, but without file access there: {w}")); + } + workspace + } + Err(e) => { + out.status.error = Some(format!("Agents can connect, but without file access: {e}")); + photocraft_automation::AuthorizedWorkspace::default() + } + }; + out.automation = crate::services::automation(Some(workspace)); + out +} + +/// How often [`launcher_watch`] looks at the ArtCraft Launcher's files. +const LAUNCHER_POLL: std::time::Duration = std::time::Duration::from_secs(2); + +/// Whether the ArtCraft Launcher turned agents on for every Craft app +/// ([`agent_link::launcher_allows_agents`]), watched on its own thread so the UI can ask every +/// frame without touching the disk. A change wakes the UI, which then starts or stops the +/// connection. Without a thread (one couldn't be started) the answer stays what it was at launch. +pub fn launcher_watch(ctx: &egui::Context) -> Box bool> { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + let on = Arc::new(AtomicBool::new(agent_link::launcher_allows_agents())); + let (seen, ctx) = (on.clone(), ctx.clone()); + let started = std::thread::Builder::new().name("launcher-agents".into()).spawn(move || { + loop { + std::thread::sleep(LAUNCHER_POLL); + let now = agent_link::launcher_allows_agents(); + if seen.swap(now, Ordering::Relaxed) != now { + log::info!("ArtCraft Launcher: agents {}", if now { "on" } else { "off" }); + ctx.request_repaint(); + } + } + }); + if let Err(e) = started { + log::warn!("couldn't watch the ArtCraft Launcher's agents switch: {e}"); + } + Box::new(move || on.load(Ordering::Relaxed)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn temp() -> PathBuf { + static N: AtomicUsize = AtomicUsize::new(0); + let d = std::env::temp_dir().join(format!("photocraft-agent-service-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + fn on(port: u32) -> Integrations { + Integrations { connect_agents: true, control_port: port, ..Default::default() } + } + + #[test] + fn turning_agents_on_publishes_a_reachable_connection_and_off_removes_it() { + let dir = temp(); + let ctx = egui::Context::default(); + let mut link = service(Some(dir.clone())); + // Off (the default): nothing listens, nothing is published. + let off = link(&Integrations::default(), &ctx); + assert!(off.requests.is_none() && !off.stopped && off.status.port.is_none()); + assert!(off.automation.command.is_none(), "no agent policy without a connection"); + assert_eq!(agent_link::read_connection(&dir).unwrap(), None); + + let started = link(&on(0), &ctx); + let port = started.status.port.unwrap(); + assert!(started.requests.is_some()); + assert!(started.automation.command.is_some() && started.automation.authorize.is_some(), "agent requests go through the policy"); + assert!(started.automation.read.is_some(), "the workspace answers (and refuses: no folder chosen)"); + let c = agent_link::read_connection(&dir).unwrap().unwrap(); + assert_eq!((c.port, c.pid), (port, std::process::id())); + assert!(agent_link::probe(port, agent_link::PROBE_TIMEOUT)); + let token = security::client_token(None, Some(&c.token_file)).unwrap(); + + // Folder changes keep the server and its token. + let folders = Integrations { read_root: dir.to_string_lossy().into_owned(), ..on(0) }; + let changed = link(&folders, &ctx); + assert!(changed.requests.is_none() && !changed.stopped); + assert_eq!(changed.status.port, Some(port)); + assert!(changed.status.error.is_none(), "{:?}", changed.status.error); + assert_eq!(security::client_token(None, Some(&c.token_file)).unwrap(), token); + + // A missing folder still connects, without file access, and says why. + let missing = Integrations { write_root: dir.join("nope").to_string_lossy().into_owned(), ..on(0) }; + let partial = link(&missing, &ctx); + assert_eq!(partial.status.port, Some(port)); + assert!(partial.status.error.as_deref().is_some_and(|e| e.contains("without file access")), "{:?}", partial.status.error); + assert!(partial.automation.command.is_some()); + + let stopped = link(&Integrations::default(), &ctx); + assert!(stopped.stopped && stopped.status.port.is_none()); + assert_eq!(agent_link::read_connection(&dir).unwrap(), None, "the connection file goes with the server"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while agent_link::probe(port, agent_link::PROBE_TIMEOUT) { + assert!(std::time::Instant::now() < deadline, "port {port} still open"); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_new_port_restarts_with_the_same_token_and_a_taken_port_is_reported() { + let dir = temp(); + let ctx = egui::Context::default(); + let mut link = service(Some(dir.clone())); + let first = link(&on(0), &ctx); + let first_port = first.status.port.unwrap(); + let token_file = dir.join(agent_link::TOKEN_FILE); + let first_token = std::fs::read_to_string(&token_file).unwrap(); + // A taken port: the error names it and nothing is published for it. + let taken = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let taken_port = taken.local_addr().unwrap().port(); + let failed = link(&on(u32::from(taken_port)), &ctx); + assert!(failed.stopped && failed.requests.is_none() && failed.status.port.is_none()); + assert!(failed.status.error.as_deref().is_some_and(|e| e.contains(&taken_port.to_string())), "{:?}", failed.status.error); + assert_eq!(agent_link::read_connection(&dir).unwrap(), None); + drop(taken); + // Back to any port: the token in the settings folder is kept, so a client holding it + // (a `--bridge` setup reading the token file) needn't be set up again. + let again = link(&on(0), &ctx); + assert!(again.requests.is_some()); + assert!(again.status.port.is_some_and(|p| p != 0)); + assert_eq!(std::fs::read_to_string(&token_file).unwrap(), first_token); + let _ = first_port; + drop(link); + assert_eq!(agent_link::read_connection(&dir).unwrap(), None, "quitting removes the connection file"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A token file that can't be written (here the "settings folder" is a file) leaves the + /// connection off with the reason shown, and its port free. + #[test] + fn a_token_file_that_cannot_be_written_leaves_agents_off() { + let dir = temp(); + let settings = dir.join("not-a-folder"); + std::fs::write(&settings, b"").unwrap(); + let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + let mut link = service(Some(settings)); + let r = link(&on(u32::from(port)), &egui::Context::default()); + assert!(r.requests.is_none() && r.status.port.is_none()); + assert!(r.status.error.as_deref().is_some_and(|e| e.contains("token file")), "{:?}", r.status.error); + std::net::TcpListener::bind(("127.0.0.1", port)).expect("the port was let go"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A relative folder would depend on the folder the app was started from: left out and named. + #[test] + fn a_relative_folder_is_left_out_with_a_reason() { + let dir = temp(); + let mut link = service(Some(dir.clone())); + let r = link(&Integrations { read_root: ".".into(), ..on(0) }, &egui::Context::default()); + assert!(r.status.port.is_some()); + assert!(r.status.error.as_deref().is_some_and(|e| e.contains("not an absolute path")), "{:?}", r.status.error); + drop(link); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Allow Agent Control off (in the file; the dialog doesn't show it) refuses this server too. + #[test] + fn allow_agent_control_off_keeps_agents_out() { + let dir = temp(); + let mut link = service(Some(dir.clone())); + let r = link(&Integrations { allow_agent_control: false, ..on(0) }, &egui::Context::default()); + assert!(r.requests.is_none() && r.status.port.is_none() && r.automation.command.is_none()); + assert!(r.status.error.as_deref().is_some_and(|e| e.contains("Allow Agent Control")), "{:?}", r.status.error); + assert_eq!(agent_link::read_connection(&dir).unwrap(), None); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn no_settings_folder_is_an_error_not_a_panic() { + let mut link = service(None); + let r = link(&on(0), &egui::Context::default()); + assert!(r.requests.is_none() && r.status.error.is_some()); + } +} diff --git a/apps/photocraft/src/app_dirs.rs b/apps/photocraft/src/app_dirs.rs index 4d5330d58c..f1c20cfa6a 100644 --- a/apps/photocraft/src/app_dirs.rs +++ b/apps/photocraft/src/app_dirs.rs @@ -10,6 +10,9 @@ //! 3. The platform convention: macOS `~/Library/Application Support/Photocraft`, Windows //! `%APPDATA%\Photocraft`, Linux `$XDG_CONFIG_HOME/photocraft` or `~/.config/photocraft`. //! +//! The rules live in [`photocraft_automation::app_dirs`], so `photocraft-cli` resolves the same +//! folder; this module resolves it once for the app and logs the outcome. +//! //! One exception: the platform convention keeps crash-recovery autosaves out of what is synced //! with the settings: the Windows roaming profile and the Linux config folder ([`recovery_dir`]). @@ -17,31 +20,11 @@ use std::ffi::OsString; use std::path::{Path, PathBuf}; use std::sync::OnceLock; -/// Files beside the executable that switch on portable mode (either one; contents are ignored). -pub const PORTABLE_MARKERS: [&str; 2] = ["portable.txt", "PhotoCraft.portable"]; -/// The data folder created beside the executable in portable mode. -pub const PORTABLE_DATA_DIR: &str = "PhotoCraftData"; - -/// How [`DataDir::dir`] was chosen. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Mode { - /// `PHOTOCRAFT_CONFIG_DIR`. - Override, - /// `/PhotoCraftData`. - Portable, - /// The platform's per-user config directory. - Platform, -} - -/// The resolved data directory. -#[derive(Clone, Debug)] -pub struct DataDir { - /// `None` only when no platform directory is known either (no `HOME`/`APPDATA`). - pub dir: Option, - pub mode: Mode, - /// Set when a portable marker was found but its data folder isn't writable. - pub warning: Option, -} +pub use photocraft_automation::app_dirs::{DataDir, Mode, resolve}; +// The tests below exercise the shared resolver too; some of them run on Unix only. +#[cfg(test)] +#[allow(unused_imports)] +use photocraft_automation::app_dirs::{PORTABLE_DATA_DIR, PORTABLE_MARKERS, WRITE_PROBE_ATTEMPTS, ensure_writable, platform_dir, portable_marker}; /// The data directory for this process, resolved once (the portable check probes the disk). pub fn current() -> &'static DataDir { @@ -453,70 +436,5 @@ fn copy_file(from: &Path, to: &Path) -> std::io::Result<()> { dst.sync_all() } -/// Resolve the data directory from the environment (`env`) and the executable's folder. -pub fn resolve(env: impl Fn(&str) -> Option, exe_dir: Option<&Path>) -> DataDir { - if let Some(d) = env("PHOTOCRAFT_CONFIG_DIR").filter(|d| !d.is_empty()) { - return DataDir { dir: Some(PathBuf::from(d)), mode: Mode::Override, warning: None }; - } - let platform = platform_dir(&env); - let Some((exe_dir, marker)) = exe_dir.and_then(|d| portable_marker(d).map(|m| (d, m))) else { - return DataDir { dir: platform, mode: Mode::Platform, warning: None }; - }; - let data = exe_dir.join(PORTABLE_DATA_DIR); - match ensure_writable(&data) { - Ok(()) => DataDir { dir: Some(data), mode: Mode::Portable, warning: None }, - Err(e) => { - let fallback = platform.as_ref().map_or_else(|| "nowhere (no user folder found)".to_string(), |p| p.display().to_string()); - let warning = - format!("portable mode ({} found) but {} isn't writable ({e}); settings are kept in {fallback} instead", marker.display(), data.display()); - DataDir { dir: platform, mode: Mode::Platform, warning: Some(warning) } - } - } -} - -/// The platform convention, from `env` (so tests can fake `HOME`/`APPDATA`/`XDG_CONFIG_HOME`). -pub fn platform_dir(env: &impl Fn(&str) -> Option) -> Option { - let home = env("HOME").filter(|h| !h.is_empty()).map(PathBuf::from); - if cfg!(target_os = "macos") { - return home.map(|h| h.join("Library/Application Support/Photocraft")); - } - if cfg!(windows) { - return env("APPDATA").filter(|a| !a.is_empty()).map(|a| PathBuf::from(a).join("Photocraft")); - } - env("XDG_CONFIG_HOME").filter(|x| !x.is_empty()).map(PathBuf::from).or_else(|| home.map(|h| h.join(".config"))).map(|c| c.join("photocraft")) -} - -/// The first portable marker file in `exe_dir`, if any. -pub fn portable_marker(exe_dir: &Path) -> Option { - PORTABLE_MARKERS.iter().map(|m| exe_dir.join(m)).find(|p| p.is_file()) -} - -/// Probe names tried before giving up on a portable data folder. -const WRITE_PROBE_ATTEMPTS: u32 = 64; - -/// Create `dir` and prove a file can be written in it (a folder can exist yet be read-only). -/// -/// The probe is created exclusively (`create_new`), so an entry already at its name (a link -/// someone else placed there, say) is never opened, written through or removed: the next name -/// is tried instead. Only a probe this call created is removed. -fn ensure_writable(dir: &Path) -> std::io::Result<()> { - std::fs::create_dir_all(dir)?; - let pid = std::process::id(); - for attempt in 0..WRITE_PROBE_ATTEMPTS { - let probe = dir.join(format!(".write-test-{pid}-{attempt}")); - match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) { - Ok(file) => { - drop(file); - // A leftover probe is harmless; don't fail portable mode over it. - let _ = std::fs::remove_file(&probe); - return Ok(()); - } - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(e) => return Err(e), - } - } - Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "every write-test name is already taken")) -} - #[cfg(test)] mod tests; diff --git a/apps/photocraft/src/control_server.rs b/apps/photocraft/src/control_server.rs index ae7fa8a32e..004a85463e 100644 --- a/apps/photocraft/src/control_server.rs +++ b/apps/photocraft/src/control_server.rs @@ -1,9 +1,13 @@ //! Localhost JSON-lines control server (one request per line, one reply per line). //! Loopback only. This is the transport the MCP server will wrap. +//! +//! `--control` starts it for the whole run ([`start`]); Preferences › AI Integrations starts and +//! stops it while the app runs ([`listen`], see `agent_link`). use std::io::{BufReader, Write}; use std::net::{TcpListener, TcpStream}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, Sender, channel}; use std::time::{Duration, Instant}; @@ -16,32 +20,74 @@ use photocraft_ui_egui::ControlRequest; use photocraft_ui_egui::control::REPLY_DEADLINE; use serde_json::{Value, json}; -/// Start serving a listener already bound during startup, before a window is opened. +/// Start serving a listener already bound during startup, before a window is opened. It serves +/// for the whole run. pub fn start(listener: TcpListener, token: String, ctx: egui::Context) -> Receiver { let (tx, rx) = channel::(); let port = listener.local_addr().map_or(0, |a| a.port()); eprintln!("photocraft: control server listening on {}", listening_addr(&listener, port)); - std::thread::spawn(move || { - let limiter = ConnectionLimiter::new(MAX_CONNECTIONS); - let token = Arc::new(token); - for mut stream in listener.incoming().flatten() { - let Some(permit) = limiter.try_acquire() else { - let _ = configure_stream(&stream); - let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "connection limit reached"})); - continue; - }; - let tx = tx.clone(); - let ctx = ctx.clone(); - let token = Arc::clone(&token); - std::thread::spawn(move || { - let _permit = permit; - serve(stream, &token, tx, ctx); - }); - } - }); + std::thread::spawn(move || accept(listener, token, tx, ctx, None)); rx } +/// A control server started by [`listen`]. Dropping it stops accepting connections; connections +/// already open end at their next request, once the app drops the request channel. +pub struct Listening { + /// The bound port (the one the system picked for port 0). + pub port: u16, + stop: Arc, + accept: Option>, +} + +impl Drop for Listening { + fn drop(&mut self) { + self.stop.store(true, Ordering::Release); + // Wake the accept loop so it sees the flag and closes the listener, and wait for that, so + // the port is free when this returns (a restart on the same port binds it again at once). + // Without a wake-up the loop would block in `accept`: then don't wait. + let woke = TcpStream::connect_timeout(&std::net::SocketAddr::from(([127, 0, 0, 1], self.port)), Duration::from_millis(500)).is_ok(); + if woke && let Some(accept) = self.accept.take() { + let _ = accept.join(); + } + } +} + +/// Serve the control protocol on `127.0.0.1:port` (0 = any free port) until the returned +/// [`Listening`] is dropped. +pub fn listen(port: u16, token: String, ctx: egui::Context) -> std::io::Result<(Receiver, Listening)> { + let (tx, rx) = channel::(); + let listener = TcpListener::bind(("127.0.0.1", port))?; + let port = listener.local_addr()?.port(); + let stop = Arc::new(AtomicBool::new(false)); + let stopped = stop.clone(); + let accept = std::thread::Builder::new().name("control server".into()).spawn(move || accept(listener, token, tx, ctx, Some(stopped)))?; + Ok((rx, Listening { port, stop, accept: Some(accept) })) +} + +/// Accept connections on `listener` and serve each on its own thread, until `stop` is set (never, +/// without one). +fn accept(listener: TcpListener, token: String, tx: Sender, ctx: egui::Context, stop: Option>) { + let limiter = ConnectionLimiter::new(MAX_CONNECTIONS); + let token = Arc::new(token); + for mut stream in listener.incoming().flatten() { + if stop.as_ref().is_some_and(|s| s.load(Ordering::Acquire)) { + break; + } + let Some(permit) = limiter.try_acquire() else { + let _ = configure_stream(&stream); + let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "connection limit reached"})); + continue; + }; + let tx = tx.clone(); + let ctx = ctx.clone(); + let token = Arc::clone(&token); + std::thread::spawn(move || { + let _permit = permit; + serve(stream, &token, tx, ctx); + }); + } +} + /// The address `listener` is bound to: with `--control 0` the OS picks the port, and a client /// needs that one, not the requested 0 (#6427). Falls back to the requested port if the OS /// can't report it. @@ -138,6 +184,34 @@ mod tests { use std::io::BufRead; /// #6427: with port 0 the log names the port the OS bound, which a client can connect to. + + #[test] + fn a_listening_server_picks_a_port_and_stops_when_dropped() { + const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + let (rx, server) = listen(0, TOKEN.into(), egui::Context::default()).unwrap(); + let port = server.port; + assert_ne!(port, 0); + let handler = std::thread::spawn(move || { + let req = rx.recv_timeout(Duration::from_secs(5)).unwrap(); + assert_eq!(req.method, "test.ping"); + req.reply.send(json!({"ok": true, "result": "pong"})).unwrap(); + }); + let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut line = String::new(); + writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).unwrap(); + reader.read_line(&mut line).unwrap(); + assert_eq!(serde_json::from_str::(&line).unwrap()["ok"], true); + writeln!(stream, "{}", json!({"id": 2, "method": "test.ping"})).unwrap(); + line.clear(); + reader.read_line(&mut line).unwrap(); + assert_eq!(serde_json::from_str::(&line).unwrap()["result"], "pong"); + handler.join().unwrap(); + drop(server); + // The listener is closed when the drop returns: the same port binds again at once. + TcpListener::bind(("127.0.0.1", port)).expect("the port is free after the drop"); + } #[test] fn port_zero_logs_the_bound_port() { let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); diff --git a/apps/photocraft/src/external_svg.rs b/apps/photocraft/src/external_svg.rs index 1d4f552573..c34dd88bd0 100644 --- a/apps/photocraft/src/external_svg.rs +++ b/apps/photocraft/src/external_svg.rs @@ -627,17 +627,14 @@ mod native { /// True for a symlink, or on Windows any reparse point, whose target could be swapped. /// Expects `symlink_metadata`, which describes the link itself rather than its target. fn is_redirect(metadata: &Metadata) -> bool { - if metadata.file_type().is_symlink() { - return true; - } #[cfg(windows)] { use std::os::windows::fs::MetadataExt; - metadata.file_attributes() & 0x0000_0400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT + metadata.file_type().is_symlink() || metadata.file_attributes() & 0x0000_0400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT } #[cfg(not(windows))] { - false + metadata.file_type().is_symlink() } } diff --git a/apps/photocraft/src/logging.rs b/apps/photocraft/src/logging.rs index f5f014a3c1..e525197a27 100644 --- a/apps/photocraft/src/logging.rs +++ b/apps/photocraft/src/logging.rs @@ -244,6 +244,17 @@ pub struct LogFile { /// One formatted log line: ` [] : \n`. pub fn format_line(ts: &str, level: log::Level, thread: &str, target: &str, message: &str) -> String { let message = message.strip_suffix('\n').unwrap_or(message); + // A message cannot forge a record or inject terminal controls: continuation lines are + // indented (a record starts with a timestamp) and other control characters are escaped. + let message: String = message + .chars() + .flat_map(|c| match c { + '\n' => "\n ".chars().collect::>(), + '\r' => vec!['\\', 'r'], + c if c.is_control() && c != '\t' => c.escape_default().collect(), + c => vec![c], + }) + .collect(); format!("{ts} {level:<5} [{thread}] {target}: {message}\n") } @@ -560,8 +571,10 @@ mod tests { format_line("2026-10-08T07:59:17.728Z", log::Level::Warn, "main", "photocraft::gpu_startup", "GPU startup marker: denied"), "2026-10-08T07:59:17.728Z WARN [main] photocraft::gpu_startup: GPU startup marker: denied\n" ); - // A multi-line message (a panic with a backtrace) keeps its lines; the record still ends in one newline. - assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n")); + // A multi-line message (a panic with a backtrace) keeps its lines, indented; the record still ends in one newline. + assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\n b\n")); + let forged = format_line("t", log::Level::Error, "w", "x", "a\r\n2026 INFO forged\x1b[2J"); + assert!(forged.lines().all(|l| !l.starts_with("2026")) && !forged.contains('\x1b') && !forged.contains('\r')); } #[test] diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index b7622e2979..dbde20d44a 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -29,6 +29,7 @@ #![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod agent_link; mod app_dirs; mod app_icon; mod appearance; @@ -94,51 +95,77 @@ fn custom_titlebar(prefs_file: Option<&std::path::Path>) -> bool { CUSTOM_TITLEBAR && !prefs.interface.system_title_bar } -/// Preferences › Integrations, read before the window opens the way [`custom_titlebar`] is: -/// whether agents may drive this launch at all, and the port to listen on when no `--control` -/// was given (0 = only with `--control`). A missing or unreadable file keeps the defaults. +/// Preferences › AI Integrations, read before the window opens the way [`custom_titlebar`] is: +/// whether agents may drive this launch at all, the port to listen on when no `--control` +/// was given (0 = only with `--control`) and the automation folders used when no +/// `--automation-read-root` / `--automation-write-root` was given. A missing or unreadable file +/// keeps the defaults. /// /// The section is read on its own, and when it doesn't read as a whole each value on its own, /// as the app's lenient load reads them (#6611): a wrong-typed value elsewhere in the file, or /// in the other field, must not turn Allow Agent Control back on while the dialog shows it off. fn integrations(prefs_file: Option<&std::path::Path>) -> photocraft_engine::prefs::Integrations { - use serde_json::Value; - let mut out = photocraft_engine::prefs::Preferences::default().integrations; - let file: Option = prefs_file.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()); - let Some(section) = file.as_ref().and_then(|v| v.get("integrations")) else { - return out; - }; - if let Ok(whole) = serde_json::from_value(section.clone()) { - return whole; + let file: Option = prefs_file.and_then(|p| std::fs::read_to_string(p).ok()).and_then(|t| serde_json::from_str(&t).ok()); + file.as_ref() + .and_then(|v| v.get("integrations")) + .cloned() + .map(photocraft_engine::prefs::read_integrations_section) + .unwrap_or_else(|| photocraft_engine::prefs::Preferences::default().integrations) +} + +/// The automation roots: `--automation-read-root` / `--automation-write-root` (or their +/// variables) win; a direction without one takes Preferences › AI Integrations' folder. A flag's +/// root that can't be opened stops the launch (exit status 2) as before. A preference's root that +/// can't be opened, or isn't an absolute path (it would depend on the folder the app was started +/// from), is left out, so that direction fails closed, and the warning says why: a folder moved +/// since it was chosen must not stop the app from starting. Each folder is opened once, so one +/// that goes away during the launch can't turn into an error, and the same folder for reading +/// and writing shares one capability, as it does when given by flags. +fn automation_workspace( + flags: &photocraft_automation::args::AutomationArgs, + prefs: &photocraft_engine::prefs::Integrations, +) -> Result<(photocraft_automation::workspace::AuthorizedWorkspace, Option), photocraft_automation::AutomationError> { + use photocraft_automation::agent_link::folder; + let mut workspace = flags.workspace()?; + let mut warnings = Vec::new(); + for read in [true, false] { + let given = if read { !flags.automation_read_root.is_empty() } else { flags.automation_write_root.is_some() }; + let Some(root) = folder(if read { &prefs.read_root } else { &prefs.write_root }).filter(|_| !given) else { + continue; + }; + let opened = if !root.is_absolute() { + Err(format!("`{}` is not an absolute path", root.display())) + } else if read { + workspace.with_read_root(&root).map_err(|e| e.to_string()) + } else { + workspace.with_write_root(&root).map_err(|e| e.to_string()) + }; + match opened { + Ok(w) => workspace = w, + Err(e) => { + let which = if read { "Automation Read Folder" } else { "Automation Write Folder" }; + warnings.push(format!("Preferences › AI Integrations › {which} is not used: {e}")); + } + } } - if let Some(allow) = section.get("allowAgentControl").and_then(Value::as_bool) { - out.allow_agent_control = allow; - } - if let Some(port) = section.get("controlPort").and_then(Value::as_u64).and_then(|p| u32::try_from(p).ok()) { - out.control_port = port; - } - out + Ok((workspace, (!warnings.is_empty()).then(|| warnings.join("\n")))) } /// The control port this launch listens on, and the warning to print when a request was refused. -/// `--control` (or `PHOTOCRAFT_CONTROL_PORT`) wins over the preference; Allow Agent Control off -/// refuses both, and says so rather than ignoring the flag silently. A preferred port outside -/// 1..=65535 is refused the same way. +/// Only `--control` (or `PHOTOCRAFT_CONTROL_PORT`) opens one at launch: Preferences › AI +/// Integrations' connection starts and stops while the app runs (`agent_link`). Allow Agent +/// Control off refuses the flag too, and says so rather than ignoring it silently. fn control_port_for(cli: Option, prefs: &photocraft_engine::prefs::Integrations) -> (Option, Option) { if !prefs.allow_agent_control { - let warning = cli.map(|p| format!("photocraft: Preferences › Integrations › Allow Agent Control is off: not listening on port {p}\n")); + let warning = cli.map(|p| { + format!( + "photocraft: Preferences › AI Integrations › Allow Agent Control is off: not listening on port {p} +" + ) + }); return (None, warning); } - if let Some(port) = cli { - return (Some(port), None); - } - match prefs.control_port { - 0 => (None, None), - p => match u16::try_from(p).ok().filter(|p| *p != 0) { - Some(port) => (Some(port), None), - None => (None, Some(format!("photocraft: Preferences › Integrations › Control Port {p} is not a usable port: not listening\n"))), - }, - } + (cli, None) } /// The main window: 1440 × 900 (shrunk to fit the monitor, and maximized on the first frame @@ -282,17 +309,54 @@ fn linux_display_session() -> linux_libs::DisplaySession { session } -/// The control server's port, token and workspace, when it is on (exits 2 on a bad configuration). +/// The control server: its listener, token and workspace. +type Control = (std::net::TcpListener, String, photocraft_automation::workspace::AuthorizedWorkspace); + +/// What [`control_setup`] set up: the control server when it is on, and a notice for the window +/// (a preference's automation folder that wasn't used). +struct ControlSetup { + control: Option, + warning: Option, +} + +/// A notice for the window about the control server: a Dock launch has no console. +struct ControlNotice { + title: &'static str, + lines: Vec, +} + +/// The `--control` server's port, token and workspace, when it is on (exits 2 on a bad +/// configuration). Preferences › AI Integrations' folders stand in for automation roots no flag +/// names. The server the agents switch starts is `agent_link`'s, not this. fn control_setup( cli_port: Option, auth: photocraft_automation::args::ControlArgs, automation: &photocraft_automation::args::AutomationArgs, -) -> Option<(std::net::TcpListener, String, photocraft_automation::workspace::AuthorizedWorkspace)> { - let (port, warning) = control_port_for(cli_port, &integrations(services::prefs_file().as_deref())); +) -> ControlSetup { + control_setup_in(services::config_dir(), &integrations(services::prefs_file().as_deref()), cli_port, auth, automation) +} + +/// [`control_setup`] with the settings folder and Preferences › AI Integrations given. +fn control_setup_in( + settings: Option, + prefs: &photocraft_engine::prefs::Integrations, + cli_port: Option, + auth: photocraft_automation::args::ControlArgs, + automation: &photocraft_automation::args::AutomationArgs, +) -> ControlSetup { + use photocraft_automation::agent_link; + let (port, warning) = control_port_for(cli_port, prefs); if let Some(warning) = &warning { eprint!("{warning}"); } - let port = port?; + // A file a crashed (or, on macOS, quit) launch left behind names a port nothing serves. Before + // binding, so this launch's own listener doesn't keep it. + if let Some(dir) = &settings { + agent_link::remove_stale_connection(dir); + } + let Some(port) = port else { + return ControlSetup { control: None, warning: None }; + }; let listener = match std::net::TcpListener::bind(("127.0.0.1", port)) { Ok(listener) => listener, Err(error) => { @@ -308,21 +372,26 @@ fn control_setup( std::process::exit(2); } }; - if let Some(path) = token_file { + if let Some(path) = &token_file { eprintln!("photocraft: control token file: {}", path.display()); } else if supplied.is_none() { eprintln!("photocraft: control token: {token}"); } else { eprintln!("photocraft: using supplied control token"); } - let workspace = match automation.workspace() { + let (workspace, warning) = match automation_workspace(automation, prefs) { Ok(workspace) => workspace, Err(error) => { eprintln!("photocraft: cannot configure automation workspace: {error}"); std::process::exit(2); } }; - Some((listener, token, workspace)) + if let Some(warning) = &warning { + eprintln!("photocraft: {warning}"); + log::warn!("{warning}"); + } + let warning = warning.map(|w| ControlNotice { title: "Automation folder not used", lines: w.lines().map(str::to_owned).collect() }); + ControlSetup { control: Some((listener, token, workspace)), warning } } /// Record this start's backend in the GPU startup marker, if the marker is locked. @@ -398,7 +467,7 @@ fn main() -> eframe::Result { let _ = (new_instance, &launch_options); // Bind and authenticate the authorized control listener before display/GPU initialization. - let control = control_setup(control_port, auth, &automation); + let ControlSetup { control, warning: control_warning } = control_setup(control_port, auth, &automation); #[cfg(target_os = "linux")] let native_session = linux_libs::session_from_env(|name| std::env::var(name).ok()); @@ -618,9 +687,24 @@ fn main() -> eframe::Result { log::warn!("couldn't remember GPU backend {}: {e}", b.name()); } }); + // Agents in the open window, unless the launch flags (`--control`) manage the + // connection. Behind the suite's AI-MCP feature flag, the ArtCraft Launcher's switch + // (Settings › AI agents) is the one consent; without it, as before, a Control Port. + let flags = craft_flags::load(); + for problem in &flags.problems { + log::warn!("feature flags: {problem}"); + } + app.agent_link.mcp_flag = flags.enabled(&craft_flags::AI_MCP); + if app.agent_link.mcp_flag { + app.services.launcher_agents = Some(agent_link::launcher_watch(&cc.egui_ctx)); + } if let Some((listener, token, _)) = control { + app.agent_link.launch_flags = true; + app.agent_link.port = listener.local_addr().ok().map(|a| a.port()); let rx = control_server::start(listener, token, cc.egui_ctx.clone()); app = app.with_control(rx); + } else { + app.services.agent_link = Some(agent_link::service(services::config_dir())); } #[cfg(target_os = "macos")] { @@ -695,6 +779,11 @@ fn main() -> eframe::Result { if let Some(w) = &app_dirs::current().warning { photocraft_ui_egui::notices::post(&mut app, "Portable mode is off", vec![w.clone()], false, None); } + // A preference's automation folder that couldn't be opened, or a token file it couldn't + // write: a Dock launch has no console. + if let Some(ControlNotice { title, lines }) = control_warning { + photocraft_ui_egui::notices::post(&mut app, title, lines, false, None); + } Ok(Box::new(app)) }), ); @@ -977,16 +1066,17 @@ mod tests { #[test] fn integrations_preferences_decide_the_control_port() { use photocraft_engine::prefs::Integrations; - let off = Integrations { allow_agent_control: false, control_port: 0 }; - let on = Integrations { allow_agent_control: true, control_port: 0 }; - let preferred = Integrations { allow_agent_control: true, control_port: 7878 }; + let off = Integrations { allow_agent_control: false, control_port: 0, ..Default::default() }; + let on = Integrations { allow_agent_control: true, control_port: 0, ..Default::default() }; + let preferred = Integrations { allow_agent_control: true, control_port: 7878, ..Default::default() }; // Nothing asked for, nothing listening. assert_eq!(super::control_port_for(None, &on), (None, None)); // --control wins over the preference. assert_eq!(super::control_port_for(Some(9000), &preferred), (Some(9000), None)); - // The preference opens the port when --control is absent. - assert_eq!(super::control_port_for(None, &preferred), (Some(7878), None)); + // The preference alone opens nothing at launch: the agent connection starts it while + // the app runs (`agent_link`). + assert_eq!(super::control_port_for(None, &preferred), (None, None)); // Allow Agent Control off refuses both, and says so when --control asked for one // rather than ignoring the flag. @@ -994,14 +1084,8 @@ mod tests { let (port, warning) = super::control_port_for(Some(9000), &off); assert_eq!(port, None); assert!(warning.is_some_and(|w| w.contains("Allow Agent Control") && w.contains("9000")), "the refusal names the port"); - let off_with_port = Integrations { allow_agent_control: false, control_port: 7878 }; + let off_with_port = Integrations { allow_agent_control: false, control_port: 7878, ..Default::default() }; assert_eq!(super::control_port_for(None, &off_with_port), (None, None), "off beats a preferred port"); - - // A port a hand-edited file could hold, outside 1..=65535, is refused and named. - let huge = Integrations { allow_agent_control: true, control_port: 70_000 }; - let (port, warning) = super::control_port_for(None, &huge); - assert_eq!(port, None); - assert!(warning.is_some_and(|w| w.contains("70000")), "the refusal names the value"); } #[test] @@ -1049,13 +1133,108 @@ mod tests { assert_eq!(r.control_port, 0, "the bad port alone takes its default"); // A bad Allow Agent Control alone takes its default. let r = read(r#"{"integrations":{"allowAgentControl":"no","controlPort":7878}}"#); - assert_eq!(r, photocraft_engine::prefs::Integrations { allow_agent_control: true, control_port: 7878 }); + // (A saved port from before the agents switch turns it on, in both reads.) + assert_eq!(r, photocraft_engine::prefs::Integrations { allow_agent_control: true, control_port: 7878, connect_agents: true, ..Default::default() }); read(r#"{"integrations":{"allowAgentControl":false,"controlPort":-1}}"#); read(r#"{"integrations":{"allowAgentControl":false,"controlPort":4294967296}}"#); read(r#"{"integrations":"off"}"#); // serde reads a struct from a list too; the app does. assert!(!read(r#"{"integrations":[false]}"#).allow_agent_control, "a list"); assert_eq!(read(r#"{"integrations":[false,7878]}"#).control_port, 7878); + // The automation folders: a bad one takes its default alone, too. + let r = read(r#"{"integrations":{"allowAgentControl":false,"readRoot":5,"writeRoot":"/w"}}"#); + assert!(!r.allow_agent_control, "a bad folder"); + assert_eq!((r.read_root.as_str(), r.write_root.as_str()), ("", "/w")); + let _ = std::fs::remove_dir_all(&dir); + } + + fn temp_dir(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("pc-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn flags(read: Option<&std::path::Path>, write: Option<&std::path::Path>) -> photocraft_automation::args::AutomationArgs { + photocraft_automation::args::AutomationArgs { + automation_read_root: read.map(Into::into).into_iter().collect(), + automation_write_root: write.map(Into::into), + } + } + + fn roots(read: &std::path::Path, write: &std::path::Path) -> photocraft_engine::prefs::Integrations { + photocraft_engine::prefs::Integrations { + read_root: read.to_string_lossy().into_owned(), + write_root: write.to_string_lossy().into_owned(), + ..Default::default() + } + } + + /// Preferences › AI Integrations' folders are the automation roots when no flag names one, and + /// a flag wins over its preference, direction by direction. + #[test] + fn automation_folders_come_from_the_preferences_unless_a_flag_names_one() { + let dir = temp_dir("automation-roots"); + let (pref, flag) = (dir.join("pref"), dir.join("flag")); + std::fs::create_dir_all(&pref).unwrap(); + std::fs::create_dir_all(&flag).unwrap(); + + // No flags: both directions from the preferences. + let (ws, warning) = super::automation_workspace(&flags(None, None), &roots(&pref, &pref)).unwrap(); + assert_eq!(warning, None); + ws.write("a.txt", b"pref").unwrap(); + assert_eq!(std::fs::read(pref.join("a.txt")).unwrap(), b"pref"); + assert_eq!(ws.read("a.txt").unwrap(), b"pref"); + // One folder for both shares one capability, as the flags do: an implicit save is allowed. + assert_eq!(ws.read_with_save_path("a.txt").unwrap().1.as_deref(), Some("a.txt")); + + // A write flag wins over the write folder; reads still come from the preference. + let (ws, _) = super::automation_workspace(&flags(None, Some(&flag)), &roots(&pref, &pref)).unwrap(); + ws.write("b.txt", b"flag").unwrap(); + assert!(flag.join("b.txt").is_file() && !pref.join("b.txt").exists(), "the flag's folder takes the write"); + assert_eq!(ws.read("a.txt").unwrap(), b"pref"); + assert_eq!(ws.read_with_save_path("a.txt").unwrap().1, None, "read and write folders differ: no implicit save"); + + // A read folder spelled like the write flag shares the flag's capability. + let (ws, _) = super::automation_workspace(&flags(None, Some(&flag)), &roots(&flag, &pref)).unwrap(); + assert_eq!(ws.read_with_save_path("b.txt").unwrap().1.as_deref(), Some("b.txt")); + + // Empty preferences grant nothing, as no flags do. + let (ws, warning) = super::automation_workspace(&flags(None, None), &photocraft_engine::prefs::Integrations::default()).unwrap(); + assert_eq!(warning, None); + assert!(ws.read("a.txt").is_err() && ws.write("c.txt", b"x").is_err()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A preference's folder that can't be opened is left out (that direction fails closed) and + /// named in the warning; the app still starts. A flag's still stops the launch. + #[test] + fn a_missing_preference_folder_is_left_out_and_a_missing_flag_root_is_an_error() { + let dir = temp_dir("automation-roots-missing"); + let missing = dir.join("gone"); + let (ws, warning) = super::automation_workspace(&flags(None, None), &roots(&dir, &missing)).unwrap(); + let warning = warning.expect("the missing write folder is named"); + assert!(warning.contains("Automation Write Folder") && !warning.contains("Read Folder"), "{warning}"); + std::fs::write(dir.join("in.txt"), b"x").unwrap(); + assert_eq!(ws.read("in.txt").unwrap(), b"x", "the read folder still applies"); + assert!(ws.write("out.txt", b"x").is_err(), "no write access without its folder"); + + assert!(super::automation_workspace(&flags(Some(&missing), None), &roots(&dir, &dir)).is_err(), "a flag's root must open"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A relative folder preference would depend on the folder the app was started from: left + /// out with a warning, like a missing one. + #[test] + fn a_relative_preference_folder_is_left_out() { + let dir = temp_dir("automation-roots-relative"); + let relative = photocraft_engine::prefs::Integrations { read_root: ".".into(), ..roots(&dir, &dir) }; + let (ws, warning) = super::automation_workspace(&flags(None, None), &relative).unwrap(); + let warning = warning.expect("the relative read folder is named"); + assert!(warning.contains("Automation Read Folder") && warning.contains("not an absolute path"), "{warning}"); + assert!(ws.read("anything").is_err(), "no read access from a relative folder"); + ws.write("out.txt", b"x").unwrap(); + assert!(dir.join("out.txt").is_file(), "the absolute write folder still applies"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index dc6d39d7f6..352321d294 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -721,38 +721,45 @@ fn shell_word(s: &str) -> String { if s.bytes().all(|b| b.is_ascii_alphanumeric() || b"/._-+:,@".contains(&b)) { s.to_string() } else { format!("'{}'", s.replace('\'', r"'\''")) } } -pub fn native(automation: Option) -> Services { - let clip: Rc>> = Rc::default(); - let clip_unreadable: Rc> = Rc::default(); - let automation_read = automation.clone().map(|workspace| { +/// What control and MCP requests may read, write and run, through `workspace` (`None`: no +/// automation, as without `--control` or an agent connection). +pub fn automation(workspace: Option) -> photocraft_ui_egui::AutomationServices { + let read = workspace.clone().map(|workspace| { Box::new(move |path: &str| { let (bytes, save_path) = workspace.read_with_save_path(path).map_err(|error| error.to_string())?; let name = Path::new(path).file_name().and_then(|name| name.to_str()).unwrap_or(path).to_string(); Ok(photocraft_ui_egui::AutomationReadResult { name, bytes, save_path }) }) as photocraft_ui_egui::AutomationReadFn }); - let automation_write = automation.clone().map(|workspace| { + let write = workspace.clone().map(|workspace| { Box::new(move |path: &str, bytes: &[u8]| workspace.write(path, bytes).map_err(|error| error.to_string())) as photocraft_ui_egui::AutomationWriteFn }); - let automation_open_pcraft = automation.clone().map(|workspace| { + let open_pcraft = workspace.clone().map(|workspace| { Box::new(move |path: &str| { let name = Path::new(path).file_name().and_then(|name| name.to_str()).unwrap_or(path).to_string(); let opened = crate::crash_guard::guard("Open", || workspace.open_pcraft(path).map_err(|e| e.to_string()))?; Ok(opened.map(|doc| (name, doc))) }) as photocraft_ui_egui::AutomationOpenPcraftFn }); - let automation_save = automation.clone().map(|workspace| { + let save = workspace.clone().map(|workspace| { std::sync::Arc::new(move |doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings, ctl: &photocraft_ui_egui::jobs_ui::SaveCtl| { save_through(doc, path, settings, ctl, |p, encoded, _| workspace.write_stream(p, &mut |w| encoded.write_to(w)).map_err(|e| e.to_string())) }) as photocraft_ui_egui::SaveFileFn }); - let step: fn(&str, &serde_json::Value) -> photocraft_engine::Result<()> = photocraft_automation::workspace::authorize_desktop_engine_step; - let automation_authorize = automation.is_some().then_some(step); - let automation_command = automation.map(|_| { + let step: photocraft_ui_egui::AutomationAuthorizeFn = photocraft_automation::workspace::authorize_desktop_engine_step; + let authorize = workspace.is_some().then_some(step); + let command = workspace.map(|_| { Box::new(|id: &str, params: &serde_json::Value| { photocraft_automation::workspace::authorize_desktop_engine_command(id, params).map_err(|error| error.to_string()) }) as photocraft_ui_egui::AutomationCommandFn }); + photocraft_ui_egui::AutomationServices { read, write, open_pcraft, save, command, authorize } +} + +pub fn native(automation: Option) -> Services { + let clip: Rc>> = Rc::default(); + let clip_unreadable: Rc> = Rc::default(); + let automation = self::automation(automation); Services { import: Some(Box::new(|name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions| { crate::crash_guard::guard("Open", || { @@ -772,12 +779,12 @@ pub fn native(automation: Option) -> Some(photocraft_ui_egui::FileStamp { len: meta.len(), modified: meta.modified().ok() }) })), same_file: Some(Box::new(|a: &str, b: &str| same_entry(Path::new(a), Path::new(b), same_file))), - automation_read, - automation_write, - automation_open_pcraft, - automation_save, - automation_command, - automation_authorize, + automation_read: automation.read, + automation_write: automation.write, + automation_open_pcraft: automation.open_pcraft, + automation_save: automation.save, + automation_command: automation.command, + automation_authorize: automation.authorize, encode_png: Some(Box::new(|w, h, rgba| { let img = Image::from_u8(w, h, ChannelLayout::Rgba, rgba.to_vec()).map_err(|e| e.to_string())?; photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &EncodeOptions::default()).map_err(|e| e.to_string()) diff --git a/assets/icons/vector-shape.svg b/assets/icons/vector-shape.svg new file mode 100644 index 0000000000..e05c3b8c1d --- /dev/null +++ b/assets/icons/vector-shape.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/icons/zoom-out.svg b/assets/icons/zoom-out.svg new file mode 100644 index 0000000000..70abec44b4 --- /dev/null +++ b/assets/icons/zoom-out.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/book/src/automation/mcp.md b/book/src/automation/mcp.md index 511f5f8850..36d5e6be5e 100644 --- a/book/src/automation/mcp.md +++ b/book/src/automation/mcp.md @@ -1,17 +1,21 @@ # MCP -`photocraft-automation` implements an MCP server over stdio with two backends: +`photocraft-automation` implements an MCP server over stdio with three backends: - **Headless:** an in-process `Headless` session owns the engine and performs file I/O. - **Bridge:** `BridgeClient` forwards tools to a desktop application started with `photocraft --control `. +- **The open window:** plain `photocraft-cli mcp` finds the desktop application through the connection file it publishes while the person lets agents use it (ArtCraft Launcher › Settings › AI agents), before every tool call; while the app is closed it starts it, serves a headless session, or reports an error, as chosen in Preferences › AI Integrations. Without that consent, or with `--headless`, it is the headless session above. + +The simplest setup needs no terminal: turn on ArtCraft Launcher › Settings › AI agents and click *Add* next to the AI app; that one entry reaches every Craft app. See [`docs/mcp.md`](../../../docs/mcp.md#connecting-the-desktop-app-no-terminal). For a source checkout, first [install the CLI on PATH and register the server](../../../docs/mcp.md#install-and-register). The installed binary survives `cargo clean`; a symlink into `target/release` does not. -Start the headless server with: +Start the headless server with (without `--headless`, `mcp` works in the open PhotoCraft window +while the ArtCraft Launcher's agents switch is on): ```sh -photocraft-cli mcp --automation-read-root /work/project --automation-write-root /work/project +photocraft-cli mcp --headless --automation-read-root /work/project --automation-write-root /work/project ``` Bridge to a running desktop application with the same private token file used by the app: @@ -56,6 +60,12 @@ explicitly granted at launch; omitting a root omits that authority. Bridge mode loopback control connection with a bearer token before invoking any control method and uses the roots configured on the desktop process. +The launcher's switch (off by default) opens the same loopback, token-authenticated control +listener as `--control`, with a token the app keeps in its settings folder (`agent-control.token`, +user-only on Unix; delete it for a new one). The folders chosen in Preferences › AI Integrations +are the desktop process's roots, and the roots of a `mcp` headless session only when agents may +use the app and *When PhotoCraft is closed* is set to work without a window. + The current server does not issue scoped sessions or distinguish trusted tools from high-impact tools. Authentication proves possession of the token; it does not restrict an authenticated client to document-only access. Do not expose either transport through an untrusted broker, shell, proxy, or remote service without adding an external policy boundary. Filesystem capabilities are implemented. General tool and method capabilities remain diff --git a/book/src/formats/overview.md b/book/src/formats/overview.md index 0f066983cb..18c94c2f67 100644 --- a/book/src/formats/overview.md +++ b/book/src/formats/overview.md @@ -2,7 +2,7 @@ External bytes enter PhotoCraft through four main paths: -- `photocraft-psd` parses and writes PSD and PSB structures. +- `craft-psd` parses and writes PSD and PSB structures. - `photocraft-codecs` decodes and encodes flat raster formats. - `photocraft-format` loads and saves the native `.pcraft` bundle. - `photocraft-affinity` reads native Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`): layers, artboards, vectors, text, images and masks; it does not write them. diff --git a/book/src/formats/psd-psb.md b/book/src/formats/psd-psb.md index d0f4e6b734..c82fc8a135 100644 --- a/book/src/formats/psd-psb.md +++ b/book/src/formats/psd-psb.md @@ -1,6 +1,6 @@ # PSD and PSB -`photocraft-psd` is a standalone clean-room reader and writer based on Adobe's public PSD specification. It supports PSD version 1 and PSB version 2, preserves unknown blocks for round-trip fidelity, and decodes channel data lazily. +`craft-psd` is a standalone clean-room reader and writer based on Adobe's public PSD specification. It supports PSD version 1 and PSB version 2, preserves unknown blocks for round-trip fidelity, and decodes channel data lazily. The parser accepts all four PSD compression methods handled by the crate and represents format-level structures before `photocraft-io` maps them to `photocraft-doc`. The current public API and fidelity behavior are documented in [`crates/psd/README.md`](https://github.com/storytold/photocraft/blob/main/crates/psd/README.md). diff --git a/book/src/formats/raster-formats.md b/book/src/formats/raster-formats.md index 8182c97cab..5e8d870de1 100644 --- a/book/src/formats/raster-formats.md +++ b/book/src/formats/raster-formats.md @@ -4,7 +4,7 @@ ## Layered TIFF -A TIFF saved by Photoshop with its layers carries them in two private tags: 37724 (`ImageSourceData`, the same layer section a PSD has, preceded by the string `Adobe Photoshop Document Data Block`) and 34377 (the PSD image resources). `photocraft-codecs` passes both through as opaque bytes on `Metadata`; `photocraft-io` rebuilds a PSD model from them plus the TIFF's pixels and hands it to the PSD importer, so groups, masks, layer styles, type, shapes, smart objects and adjustment layers open from a TIFF exactly as from a PSD, and are written back the same way. In Intel-order (`II`) files Photoshop stores the whole block structure byte-swapped (reversed keys such as `MIB8` and `ryaL`, little-endian integers and doubles) while pixel samples stay big-endian; `photocraft-psd`'s `tiff` module converts between the two orders field by field, and drops, with a warning, any block whose layout it does not know rather than pass byte-swapped data to other readers. Limits: up to sixteen extra samples (spot colours and alpha channels, plus a Quick Mask) are written in the IFD and round-trip, with Photoshop image resources for the channel name, ink colour and solidity; Lab documents are saved flat, with their extra samples. Save As asks "Including layers will increase file size" (with "Discard Layers and Save a Copy") while *Ask Before Saving Layered TIFF Files* is on in Preferences › File Handling. Scripted and agent saves write a flat TIFF unless they ask for layers: `--tiff-layers` for `photocraft-cli convert`, `run` and `batch`, and `"tiffLayers": true` in the save, batch and export commands and MCP `doc_save`. +A TIFF saved by Photoshop with its layers carries them in two private tags: 37724 (`ImageSourceData`, the same layer section a PSD has, preceded by the string `Adobe Photoshop Document Data Block`) and 34377 (the PSD image resources). `photocraft-codecs` passes both through as opaque bytes on `Metadata`; `photocraft-io` rebuilds a PSD model from them plus the TIFF's pixels and hands it to the PSD importer, so groups, masks, layer styles, type, shapes, smart objects and adjustment layers open from a TIFF exactly as from a PSD, and are written back the same way. In Intel-order (`II`) files Photoshop stores the whole block structure byte-swapped (reversed keys such as `MIB8` and `ryaL`, little-endian integers and doubles) while pixel samples stay big-endian; `craft-psd`'s `tiff` module converts between the two orders field by field, and drops, with a warning, any block whose layout it does not know rather than pass byte-swapped data to other readers. Limits: up to sixteen extra samples (spot colours and alpha channels, plus a Quick Mask) are written in the IFD and round-trip, with Photoshop image resources for the channel name, ink colour and solidity; Lab documents are saved flat, with their extra samples. Save As asks "Including layers will increase file size" (with "Discard Layers and Save a Copy") while *Ask Before Saving Layered TIFF Files* is on in Preferences › File Handling. Scripted and agent saves write a flat TIFF unless they ask for layers: `--tiff-layers` for `photocraft-cli convert`, `run` and `batch`, and `"tiffLayers": true` in the save, batch and export commands and MCP `doc_save`. ## JPEG XL @@ -31,7 +31,7 @@ Every route that writes a document to a flat format (Save As, the CLI, MCP `doc_ - Formats without transparency (JPEG, Radiance HDR) get the image composited over white, as Export As and Quick Export do; in CMYK, white is no ink. - Formats that can't embed an ICC profile (GIF, BMP, TGA, QOI, ICO, Netpbm/PFM) get RGB documents in another profile (linear light, Display P3, …) converted to sRGB through the colour engine (perceptual intent), since an untagged file is read as sRGB. OpenEXR and Radiance HDR get linear sRGB instead (linear gray for a grayscale OpenEXR), which is how they are tagged when opened. - TGA, as Photoshop's Targa: an RGB Targa is 24 or 32 bits per pixel. Save As and Save a Copy ask (Targa Options, starting at 32 with an alpha channel, else 24); Export As has a Resolution choice (Auto, 24 or 32 bits/pixel); scripts pass `tgaBits` (`--tga-bits` on the CLI). At 32 bits the document's alpha channel is the file's alpha when it has exactly one (spot channels don't count; with several, none is used), and the colours are written exactly, never premultiplied or cleared where the alpha is 0, so a game texture's mask and its colours both survive. Without a usable alpha channel the layers' transparency is the alpha (opaque without any). 24 bits write no alpha, compositing transparency over white. Without a choice: 32 with an alpha channel or transparency, else 24. A 32-bit Targa opens as an opaque Background with its alpha as "Alpha 1", so it round-trips. Grayscale Targas are 8-bit. -- JPEG, as Photoshop's JPEG Options: File › Save, Save As and Save a Copy ask for the Quality on Photoshop's 0–12 scale (with its Low, Medium, High and Maximum presets) and a Format Option: Baseline ("Standard"), Baseline Optimized (Huffman tables fitted to the image) or Progressive. The quality starts at the opened JPEG's own quality, else at the Export preference's JPEG quality; left there, an opened JPEG is written at exactly its own quality. Scripts pass `"quality": 0..12` and `"jpegFormat": "baseline" | "optimized" | "progressive"` (on the CLI, `--quality` on the encoder's 1–100 scale and `--jpeg-format`) and aren't asked; recorded actions replay the answer. The scale maps onto the encoder's 1–100 as `round(q / 12 × 99 + 1)`. RGB JPEGs are written 4:2:0, where Baseline Optimized keeps the standard tables for now (Gray and CMYK, written 4:4:4, get fitted ones). Matte, the progressive scan count (Scans 3–5) and the file-size preview aren't offered. +- JPEG, as Photoshop's JPEG Options: File › Save, Save As and Save a Copy ask for the Quality on Photoshop's 0–12 scale (with its Low, Medium, High and Maximum presets) and a Format Option: Baseline ("Standard"), Baseline Optimized (Huffman tables fitted to the image) or Progressive. The quality starts at the opened JPEG's own quality, else at the Export preference's JPEG quality; left there, an opened JPEG is written at exactly its own quality. Scripts pass `"quality": 0..12` and `"jpegFormat": "baseline" | "optimized" | "progressive"` (on the CLI, `--quality` on the encoder's 1–100 scale and `--jpeg-format`) and aren't asked; recorded actions replay the answer. The scale maps onto the encoder's 1–100 as `round(q / 12 × 99 + 1)`. RGB JPEGs are written 4:2:0, where Baseline Optimized keeps the standard tables for now (Gray and CMYK, written 4:4:4, get fitted ones). Below the Format Options the dialog shows how big the file will be ("152.3K", "1.5M"), so the quality can be chosen with the size in view; it is worked out as the options change, in the background in the desktop app and within the frame in the web build, for documents up to 40 megapixels (4 on the web), and reads "—" for larger ones. Matte and the progressive scan count (Scans 3–5) aren't offered. - DDS, for game and 3D textures: Save As and Save a Copy ask (DDS Options) for the compression (None, uncompressed and lossless; BC1/DXT1, whose alpha is on or off; BC2/DXT3; BC3/DXT5) and whether to generate mipmaps (the full chain down to 1×1, each level a box filter of the one above). Scripts pass `ddsCompression` (`none`, `bc1`, `bc2`, `bc3`) and `ddsMipmaps` (`--dds-compression`, `--dds-mipmaps` on the CLI). Opening one reads its top mip level. Flat TIFF and JPEG exports of composited CMYK documents convert the RGB composite back through diff --git a/book/src/security/automation-security.md b/book/src/security/automation-security.md index 12a7679558..cc65c7dc81 100644 --- a/book/src/security/automation-security.md +++ b/book/src/security/automation-security.md @@ -29,6 +29,14 @@ Automation is a privilege boundary because requests can cause filesystem access, Screenshots are decoded under separate dimension, pixel, and allocation ceilings before downscaling; the 5 MiB PNG limit applies to the returned image. - MCP normally uses stdio and can optionally bridge to loopback control TCP. +- ArtCraft Launcher › Settings › AI agents (off by default; one switch for every Craft app) opens that loopback + listener without launch flags. Its token is kept in a user-only file in the settings folder + (`agent-control.token`) and stays the same across restarts and port changes: restarting does + not revoke it. To revoke an exposed token, delete that file; the next start creates a new one. + The published `agent-connection.json` holds the port and the token file's path, never the + token. `photocraft-cli mcp` authenticates with the challenge handshake, so the token + itself is never sent: the listener must first prove it holds the token, and a stale file whose + port another program took fails that check before the client reveals anything. - The bridge and UI request paths use timeouts. - Engine commands are expected to reject invalid parameters without panicking. - Remote filesystem methods use separately granted read and write directory capabilities. diff --git a/book/src/security/parser-hardening.md b/book/src/security/parser-hardening.md index 7eedf0e039..3f7ea7153b 100644 --- a/book/src/security/parser-hardening.md +++ b/book/src/security/parser-hardening.md @@ -6,7 +6,7 @@ Parser safety is broader than “does not crash.” A parser must also bound mem ### PSD/PSB -`photocraft-psd` enforces maximum document dimensions and channel counts, bounds decoded channel data, limits ActionDescriptor nesting and pattern edges, and uses checked arithmetic for key decoded-size calculations. Tests cover malformed headers, truncation, property-generated inputs, and dedicated fuzz targets. +`craft-psd` enforces maximum document dimensions and channel counts, bounds decoded channel data, limits ActionDescriptor nesting and pattern edges, and uses checked arithmetic for key decoded-size calculations. Tests cover malformed headers, truncation, property-generated inputs, and dedicated fuzz targets. ### Raster codecs diff --git a/contributors/people.toml b/contributors/people.toml index b1ec09e98e..9b7ed5a52e 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -20,6 +20,9 @@ sync_github_name = true [people.brianblakely] sync_github_name = true +[people.mlo0352] +sync_github_name = true + [people.abdul-karim-mia] real_name = "Abdul karim mia" sync_github_name = false @@ -32,6 +35,9 @@ sync_github_name = false display_name = "Skyfuller" sync_github_name = true +[people.JohnXu28] +display_name = "JohnXu" + [people.AlanRockefeller] sync_github_name = true @@ -326,6 +332,9 @@ sync_github_name = true [people.Luis-0508] sync_github_name = true +[people.ashokram-si] +real_name = "Ashok Ram" + [people.Kaedo17] sync_github_name = true @@ -341,5 +350,8 @@ sync_github_name = false display_name = "Tsieg" sync_github_name = true +[people.slafebre] +real_name = "Sven Lafebre" + [people.kirubhakaran12] sync_github_name = true diff --git a/crates/affinity/README.md b/crates/affinity/README.md index 1be7fd954e..c82911d939 100644 --- a/crates/affinity/README.md +++ b/crates/affinity/README.md @@ -71,7 +71,7 @@ are rejected. The I/O adapter decodes it with a 128 MiB allocation limit. Affinity has no published file-format specification, so this reader is built only from a public description of the format and from public files, never from Affinity itself. This is how -PhotoCraft already treats formats that are only partly documented: `photocraft-psd` fills the gaps +PhotoCraft already treats formats that are only partly documented: `craft-psd` fills the gaps in Adobe's specification from the MIT-licensed psd-tools and ag-psd, and `photocraft-raw` recovered Nikon's compression tables by black-box analysis of CC0 sample files (see their READMEs). diff --git a/crates/algo/src/artistic_fx.rs b/crates/algo/src/artistic_fx.rs index a2c98e3c39..9a15d55b25 100644 --- a/crates/algo/src/artistic_fx.rs +++ b/crates/algo/src/artistic_fx.rs @@ -447,7 +447,7 @@ pub(crate) fn effect_reach(e: &GalleryEffect) -> i32 { F::Plaster => gs(0.5 + g("smoothness") * 0.8) + gs(1.5) + 2, F::Stamp => gs(0.3 + g("smoothness") * 0.3), F::TornEdges => gs(1.0), - F::WaterPaper => 2 * (g("fiberLength") / 6.0) as i32 + 2, + F::WaterPaper => 2 * (fiber_length(e) / 6.0) as i32 + 2, F::GlowingEdges => gs(0.3 + g("smoothness") * 0.25) + gs(g("edgeWidth") * 0.4) + 2, F::Craquelure => 0, F::Patchwork => patch_size(e).ceil() as i32 + 2, @@ -518,6 +518,12 @@ fn plastic_sigma(e: &GalleryEffect) -> f32 { fn watercolor_radius(e: &GalleryEffect) -> usize { 1 + ((15.0 - e.get("brushDetail")) / 2.5) as usize } +/// Water Paper's fiber length within its parameter range (3..=50): raw gallery values bypass the +/// setter's clamp, and the reach estimate and the blur radius must agree on one bounded value. +fn fiber_length(e: &GalleryEffect) -> f32 { + e.get("fiberLength").clamp(3.0, 50.0) +} + fn basrelief_sigma(e: &GalleryEffect) -> f32 { 0.3 + e.get("smoothness") * 0.5 + (15.0 - e.get("detail")) * 0.12 } @@ -1178,7 +1184,7 @@ fn apply_sketch(e: &GalleryEffect, win: &mut Win, ctx: &Ctx) -> bool { } } F::WaterPaper => { - let fl = g("fiberLength"); + let fl = fiber_length(e); let (br, co) = (g("brightness") / 100.0, g("contrast") / 100.0); let r = (fl / 6.0) as usize; line_blur3(&mut win.c, w, h, (1, 0), r); @@ -1360,6 +1366,17 @@ mod tests { s } + #[test] + fn gallery_window_budget_counts_working_temporaries() { + // A 6300 px square RGBA window is 159 M samples for the source read alone, 476 M with the old + // 3x factor, and over the 512 Mi-sample budget once the working window and temporaries count. + // The check runs before any window is read, so nothing that large is allocated. + let s = pattern(SampleType::F32); + let big = Rect::new(0, 0, 6300, 6300); + let fp = FilterParams::FilterGallery { effects: vec![GalleryEffect::new(crate::GalleryFilter::ALL[0])] }; + assert!(crate::apply_tiled_with(&s, &fp, big, big, None, 6300, None, &photocraft_raster::Interrupt::NONE).is_none()); + } + #[test] fn every_effect_changes_pixels_and_is_tile_independent() { let b = Rect::new(0, 0, 56, 40); diff --git a/crates/algo/src/blur.rs b/crates/algo/src/blur.rs index 7ca9d34f99..e9e64aff9b 100644 --- a/crates/algo/src/blur.rs +++ b/crates/algo/src/blur.rs @@ -168,13 +168,18 @@ fn boxes_for_gauss(sigma: f32, n: usize) -> Vec { (0..n).map(|i| if i < m { wl as usize } else { wu as usize }).collect() } +/// Largest box-blur radius run (far beyond any real use). +const MAX_BOX_RADIUS: f32 = 16384.0; + /// The box widths (odd) a blur runs as running-sum passes along each axis, or `None` when it uses a /// direct kernel (small radii, where the kernel is quicker). pub(crate) fn box_widths(params: &FilterParams) -> Option> { match *params { FilterParams::GaussianBlur { radius } if radius > 4.0 => Some(boxes_for_gauss(radius, 3)), FilterParams::BoxBlur { radius } => { - let r = radius.max(0.0).round() as usize; + // Capped: the line scratch grows with the radius, and `2 * r + 1` must not overflow + // (Photoshop's largest Box Blur radius is 999). + let r = radius.clamp(0.0, MAX_BOX_RADIUS).round() as usize; (r > 4).then(|| vec![2 * r + 1]) } _ => None, diff --git a/crates/algo/src/camera_raw.rs b/crates/algo/src/camera_raw.rs index 1a16612cc1..b783f39a54 100644 --- a/crates/algo/src/camera_raw.rs +++ b/crates/algo/src/camera_raw.rs @@ -1029,23 +1029,25 @@ fn dehaze(px: &mut [[f32; 4]], w: usize, h: usize, d: &Dehaze) { } fn detail(px: &mut [[f32; 4]], w: usize, h: usize, p: &CameraRaw, ps: f32) { + // The controls' documented 0..=100 range: raw values drive the filter radii below. + let [nl, nld, nc, ncd] = [p.noise_luminance, p.noise_luminance_detail, p.noise_color, p.noise_color_detail].map(|v| v.clamp(0.0, 100.0)); // Work in Y + chroma (BT.709 luma, B−Y, R−Y). let mut y: Vec = px.iter().map(|q| luma([q[0], q[1], q[2]])).collect(); let mut cb: Vec = px.iter().zip(&y).map(|(q, l)| q[2] - l).collect(); let mut cr: Vec = px.iter().zip(&y).map(|(q, l)| q[0] - l).collect(); - if p.noise_luminance > 0.0 { - let n = p.noise_luminance / 100.0; + if nl > 0.0 { + let n = nl / 100.0; let r = ((1.0 + 3.0 * n) * ps).round().max(1.0) as usize; let smooth = guided(&y, &y, w, h, r, (n * 0.06).powi(2) + 1e-6); - let keep = p.noise_luminance_detail / 100.0 * 0.5; + let keep = nld / 100.0 * 0.5; for i in 0..w * h { y[i] = smooth[i] + (y[i] - smooth[i]) * keep; } } - if p.noise_color > 0.0 { - let sigma = (p.noise_color / 100.0 * 6.0 * ps).max(0.3); + if nc > 0.0 { + let sigma = (nc / 100.0 * 6.0 * ps).max(0.3); let (bcb, bcr) = (gauss(&cb, w, h, sigma), gauss(&cr, w, h, sigma)); - let keep = p.noise_color_detail / 100.0 * 0.3; + let keep = ncd / 100.0 * 0.3; for i in 0..w * h { cb[i] = bcb[i] + (cb[i] - bcb[i]) * keep; cr[i] = bcr[i] + (cr[i] - bcr[i]) * keep; @@ -1306,6 +1308,12 @@ mod tests { let mut nr = noisy.clone(); develop(&mut nr, w, h, &CameraRaw { noise_luminance: 80.0, ..Default::default() }, false); assert!(var(&nr) < var(&noisy) * 0.5); + // Out-of-range noise settings are held to their 0..=100 range, not turned into huge radii. + let mut wild = noisy.clone(); + let hostile = + CameraRaw { noise_luminance: 1.0e30, noise_color: 1.0e30, noise_luminance_detail: 1.0e30, noise_color_detail: 1.0e30, ..Default::default() }; + develop(&mut wild, w, h, &hostile, false); + assert!(wild.iter().all(|q| q[0].is_finite())); let mut sh = noisy.clone(); develop(&mut sh, w, h, &CameraRaw { sharpen_amount: 100.0, ..Default::default() }, false); assert!(var(&sh) > var(&noisy)); diff --git a/crates/algo/src/exif.rs b/crates/algo/src/exif.rs index 15c81fbe9c..2508897a31 100644 --- a/crates/algo/src/exif.rs +++ b/crates/algo/src/exif.rs @@ -30,9 +30,14 @@ impl CameraInfo { } } +/// Text bytes decoded per EXIF read (real Make/Model/Lens/Date strings are a few dozen bytes). +const MAX_TEXT_BYTES: usize = 1 << 20; + struct Tiff<'a> { b: &'a [u8], le: bool, + /// Text bytes this read may still decode: duplicate tags can share one large blank value. + text_left: std::cell::Cell, } impl Tiff<'_> { @@ -93,7 +98,9 @@ impl Tiff<'_> { return None; } let at = self.data_at(typ, count, field)?; - let s = self.b.get(at..at.checked_add(usize::try_from(count).ok()?)?)?; + let n = usize::try_from(count).ok()?; + self.text_left.set(self.text_left.get().checked_sub(n)?); + let s = self.b.get(at..at.checked_add(n)?)?; let s = String::from_utf8_lossy(s).trim_end_matches('\0').trim().to_string(); (!s.is_empty()).then_some(s) } @@ -111,7 +118,7 @@ pub fn read(exif: &[u8]) -> CameraInfo { Some([b'M', b'M', 0, 42]) => false, _ => return info, }; - let t = Tiff { b, le }; + let t = Tiff { b, le, text_left: std::cell::Cell::new(MAX_TEXT_BYTES) }; let Some(ifd0) = t.u32(4) else { return info }; let mut queue = vec![ifd0 as usize]; let mut seen = Vec::new(); @@ -259,6 +266,31 @@ mod tests { /// Hostile payloads: huge counts, offsets near `u32::MAX`, self-referencing IFDs and random /// bytes read as `None` fields instead of panicking or overflowing (usize is 32 bits on wasm). + #[test] + fn blank_duplicate_text_tags_share_one_decode_budget() { + // Blank values never fill `make`, so every duplicate would decode the same 1 MiB again; + // the per-read budget stops after the first, so the later real value is not reached. + let blank = MAX_TEXT_BYTES; + let entry = |count: u32, off: u32| { + let mut e = Vec::new(); + e.extend_from_slice(&0x010Fu16.to_le_bytes()); + e.extend_from_slice(&2u16.to_le_bytes()); + e.extend_from_slice(&count.to_le_bytes()); + e.extend_from_slice(&off.to_le_bytes()); + e + }; + let mut b = b"II*\0".to_vec(); + b.extend_from_slice(&8u32.to_le_bytes()); + b.extend_from_slice(&3u16.to_le_bytes()); + b.extend(entry(blank as u32, 50)); + b.extend(entry(blank as u32, 50)); + b.extend(entry(2, u32::from_le_bytes(*b"M\0\0\0"))); + b.extend_from_slice(&0u32.to_le_bytes()); + assert_eq!(b.len(), 50); + b.extend(std::iter::repeat_n(b' ', blank)); + assert_eq!(read(&b).make, None); + } + #[test] fn duplicate_text_tags_keep_the_first_value_without_copying_large_duplicates() { let value = vec![b'X'; 2 * 1024 * 1024]; diff --git a/crates/algo/src/inpaint.rs b/crates/algo/src/inpaint.rs index c781140ac3..54b6fe3a76 100644 --- a/crates/algo/src/inpaint.rs +++ b/crates/algo/src/inpaint.rs @@ -115,7 +115,7 @@ pub fn complete_with( p: &CompleteParams, ctl: &photocraft_raster::Interrupt, ) -> Result>, photocraft_raster::Cancelled> { - assert_eq!(hole.len(), w * h); + assert_eq!(w.checked_mul(h), Some(hole.len())); let px: Vec = hole.iter().map(|h| if *h { Px::Hole } else { Px::Source }).collect(); complete_masked(w, h, ch, img, &px, p, ctl) } @@ -159,8 +159,13 @@ fn complete_cow<'a>( p: &CompleteParams, ctl: &photocraft_raster::Interrupt, ) -> Result, Cow<'a, [f32]>>, photocraft_raster::Cancelled> { - assert_eq!(img.len(), w * h * ch); - assert_eq!(px.len(), w * h); + // Checked: wrapped products must not let tiny buffers pass for a huge `h`. + assert_eq!(w.checked_mul(h), Some(px.len())); + assert_eq!(w.checked_mul(h).and_then(|n| n.checked_mul(ch)), Some(img.len())); + if w == 0 || h == 0 { + // Nothing to fill; no per-row tables for a zero-width image of any height. + return Ok(Ok(img.into_owned())); + } let Some(hb0) = hole_bounds(w, h, px) else { return Ok(Ok(img.into_owned())) }; if ch == 0 { return Ok(Ok(Vec::new())); diff --git a/crates/algo/src/inpaint/synthesis.rs b/crates/algo/src/inpaint/synthesis.rs index cd0452ab4c..c47e7eb079 100644 --- a/crates/algo/src/inpaint/synthesis.rs +++ b/crates/algo/src/inpaint/synthesis.rs @@ -261,7 +261,8 @@ pub fn best_offset(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], ri pub fn synthesize(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], block: usize, seed: u64) -> Vec { let mut out = img.to_vec(); let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, hole) else { return out }; - let b = block.max(4) as i32; + // A block larger than the image fits no candidate either way: the clamp keeps the i32 math in range. + let b = block.clamp(4, w.max(h).max(4)) as i32; let ov = (b / 3).max(1); let hs = integral(w, h, hole); // Candidate block origins: whole block (with overlap) inside the grid and outside the hole. diff --git a/crates/algo/src/inpaint/tests.rs b/crates/algo/src/inpaint/tests.rs index 45690fac01..747e9c36cd 100644 --- a/crates/algo/src/inpaint/tests.rs +++ b/crates/algo/src/inpaint/tests.rs @@ -23,6 +23,24 @@ fn zero_width_images_complete_without_sizing_by_height() { assert_eq!(complete(1 << 40, 0, 3, &[], &[], &p), Some(Vec::new())); } +/// Dimensions whose product wraps must be refused, not matched against tiny buffers. +#[test] +#[should_panic] +fn wrapping_dimension_products_are_refused() { + let _ = complete(1 << 40, 1 << 40, 1, &[], &[], &CompleteParams::default()); +} + +/// A block size beyond `i32` falls back to the membrane fill instead of looping on a zero step. +#[test] +fn a_huge_synthesis_block_does_not_hang() { + let (w, h) = (8, 8); + let img = vec![0.5f32; w * h]; + let mut hole = vec![false; w * h]; + hole[27] = true; + let out = synthesize(w, h, 1, &img, &hole, usize::MAX, 1); + assert_eq!(out.len(), w * h); +} + /// Smooth gradient plus deterministic fine noise. fn texture(w: usize, h: usize) -> Vec { let mut rng = Rng::new(7); diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs index a673c15b69..bbf039a653 100644 --- a/crates/algo/src/lib.rs +++ b/crates/algo/src/lib.rs @@ -1317,6 +1317,15 @@ fn coverage_operation(params: &FilterParams) -> Option> } } +/// Working-copy samples per pixel a Filter Gallery stack holds beside the source read: none for an +/// empty stack, which returns the cropped source. +fn gallery_working_samples(params: &FilterParams) -> usize { + match params { + FilterParams::FilterGallery { effects } if !effects.is_empty() => 12, + _ => 0, + } +} + #[allow(clippy::too_many_arguments)] /// Dispatch checked whole-domain filters or bounded native tiles, publishing a result only after successful processing /// and cancellation checks. @@ -1390,7 +1399,12 @@ fn apply_tiled_with_impl( // caller-supplied, so a short parameter set can ask for a huge source window per tile. if let Halo::Radius(reach) = halo { let (w, h) = (area.width().min(tile as u32) as usize, area.height().min(tile as u32) as usize); - let read_samples = w.checked_add(2 * reach as usize)?.checked_mul(h.checked_add(2 * reach as usize)?)?.checked_mul(fmt.channels())?; + // A Filter Gallery applies every effect to one working window. Beside the source read (`channels` + // samples per pixel) one effect holds the three-channel window plus its worst temporaries: two more + // three-channel copies and a plane or gradient set, 12 samples per pixel however many effects there + // are. An empty stack makes no working window (it returns the cropped source), so it is not charged. + let per_pixel = fmt.channels().checked_add(gallery_working_samples(params))?; + let read_samples = w.checked_add(2 * reach as usize)?.checked_mul(h.checked_add(2 * reach as usize)?)?.checked_mul(per_pixel)?; let tile_count = u64::from(area.width()).div_ceil(tile as u64).checked_mul(u64::from(area.height()).div_ceil(tile as u64))?; // Reject hostile source-window sizes before Image::read allocates them. // Ordinary filter parameters and automatic tiles fit these bounds. @@ -1771,3 +1785,6 @@ mod selected_alpha_tests { } } } + +#[cfg(test)] +mod paint_bucket_transparent_seed_tests; diff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rs index a7f57c337d..186cd3edeb 100644 --- a/crates/algo/src/paint.rs +++ b/crates/algo/src/paint.rs @@ -63,7 +63,11 @@ pub fn sample_stops(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] { } } -/// Composites `color(i)` over `area` of the surface with per-pixel coverage. +/// Composites `color(i)` over `area` of the surface with per-pixel coverage. Where the coverage is +/// zero, `rim(x, y)` (when given) is the strength of a bucket's transparent-seed fringe there: the +/// pixel takes the fill at coverage `rim × (1 − α)`, its own transparency (#11354 review; see +/// [`bucket_fill_inks`]). Lock Transparent Pixels and Clear ignore it. +#[allow(clippy::too_many_arguments)] fn composite_area( s: &mut Surface, area: Rect, @@ -72,6 +76,7 @@ fn composite_area( color: impl Fn(i32, i32) -> [f32; 4] + Sync, lock_transparency: bool, inks: Option<[f32; 4]>, + rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)>, ) { // Composite tile by tile (in parallel on native); tiles with zero coverage are left untouched, // so their copy-on-write storage (and GPU residency) survives. @@ -86,8 +91,12 @@ fn composite_area( let mut enc = [0.0f32; 8]; for y in r.y0..r.y1 { for x in r.x0..r.x1 { - let k = coverage(x, y); - if k <= 0.0 { + let mut k = coverage(x, y); + let on_rim = match rim { + Some(rim) if k <= 0.0 && !lock_transparency && matches!(mode, FillMode::Blend(_)) => rim(x, y), + _ => 0.0, + }; + if k <= 0.0 && on_rim <= 0.0 { continue; } if !any { @@ -97,6 +106,13 @@ fn composite_area( let i = ((y - r.y0) as usize * w + (x - r.x0) as usize) * n; let px = &mut region[i..i + n]; let d = photocraft_raster::to_rgba(&fmt, px); + if k <= 0.0 { + // A rim pixel: only its transparency takes the fill, so opaque art stays as it is. + k = on_rim * (1.0 - d[3].clamp(0.0, 1.0)); + if k.is_nan() || k <= 0.0 { + continue; + } + } let o = match mode { FillMode::Blend(m) if lock_transparency => blend::composite_atop(m, d, color(x, y), k), FillMode::Blend(m) => blend::composite(m, d, color(x, y), k), @@ -166,6 +182,7 @@ pub fn paint_gradient( }, lock_transparency, None, + None, ); } @@ -227,9 +244,21 @@ pub fn bucket_fill_inks( return false; } let img = crate::selection::rgba8_image(s, area); - let Some(region) = crate::selection::wand_region(&img, area, seed, tolerance, contiguous, anti_alias) else { return false }; + let Some(region) = crate::selection::wand_region_bucket(&img, area, seed, tolerance, contiguous, anti_alias) else { return false }; + // Clicked on transparency with Anti-alias on: the wand's fringe gives the partly transparent + // pixels around the flood no coverage (their alpha is measured against the seed's 0), but the + // reference application fills each pixel 8-adjacent to the flood at coverage `1 − α`, so the + // soft rim a cleared selection leaves rises partly (α 187 → 205, 56 → 211, 3 → 252; the + // reference gives 204, 211, 253) and a black edge pixel of alpha 40 filled green becomes + // (0, 248, 0, 221) (#11311, #12528, #11354 review). Pixels further out stay as they are; with + // Anti-alias off nothing outside the flood changes. + let at_seed = usize::try_from(seed.1 - area.y0) + .ok() + .and_then(|y| y.checked_mul(area.width() as usize)) + .and_then(|row| row.checked_add(usize::try_from(seed.0 - area.x0).ok()?)); + let empty_seed = anti_alias && at_seed.and_then(|i| img.get(i)).is_some_and(|p| p[3] == 0); drop(img); - bucket_fill_region_inks(s, ®ion, opacity, selection, lock_transparency, src, inks, mode); + fill_region(s, ®ion, opacity, selection, lock_transparency, src, inks, mode, empty_seed); true } @@ -258,9 +287,55 @@ pub fn bucket_fill_region_inks( inks: Option<[f32; 4]>, mode: FillMode, ) { - // Composite only over the filled region's box. + fill_region(s, region, opacity, selection, lock_transparency, src, inks, mode, false); +} + +/// [`bucket_fill_region_inks`]; with `rim`, the pixels 8-adjacent to the region's fully covered +/// pixels that the region itself leaves uncovered take the fill at coverage `1 − α` (see +/// [`composite_area`]). Fully covered pixels and pixels further out are filled as without it. +#[allow(clippy::too_many_arguments)] +fn fill_region( + s: &mut Surface, + region: &crate::selection::Region, + opacity: f32, + selection: Option<&Surface>, + lock_transparency: bool, + src: impl Fn(i32, i32) -> [f32; 4] + Sync, + inks: Option<[f32; 4]>, + mode: FillMode, + rim: bool, +) { + // Composite only over the filled region's box (with Anti-alias on it already holds the + // one-pixel ring around the flood). let b = region.bbox; - composite_area(s, b, mode, |x, y| region.at(x, y) * opacity * selection.map_or(1.0, |m| m.sample_channel(x, y, 0)), src, lock_transparency, inks); + let strength = |x: i32, y: i32| opacity * selection.map_or(1.0, |m| m.sample_channel(x, y, 0)); + // The ring is only ever read for an unlocked Blend fill (see composite_area), and it is + // empty when the region covers every pixel, so do not build it in those cases: on a large + // canvas it is a bool per pixel plus a full scan of the mask. + let use_rim = rim && !lock_transparency && matches!(mode, FillMode::Blend(_)) && region.mask.contains(&0); + let ring = if use_rim { rim_ring(region) } else { Vec::new() }; + let on_ring = |x: i32, y: i32| { + let at = usize::try_from(y - b.y0).ok().zip(usize::try_from(x - b.x0).ok()).filter(|_| b.contains(x, y)); + let hit = at.and_then(|(yy, xx)| yy.checked_mul(b.width() as usize)?.checked_add(xx)).and_then(|i| ring.get(i)); + if hit == Some(&true) { strength(x, y) } else { 0.0 } + }; + let rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)> = if use_rim { Some(&on_ring) } else { None }; + composite_area(s, b, mode, |x, y| region.at(x, y) * strength(x, y), src, lock_transparency, inks, rim); +} + +/// Over `region.bbox` (row-major): the pixels the region leaves uncovered that touch one of its +/// fully covered pixels, diagonals included. +fn rim_ring(region: &crate::selection::Region) -> Vec { + let (w, h) = (region.bbox.width() as usize, region.bbox.height() as usize); + let full = |x: usize, y: usize| y.checked_mul(w).and_then(|r| r.checked_add(x)).and_then(|i| region.mask.get(i)) == Some(&255); + let n = w.saturating_mul(h).min(region.mask.len()); + (0..n) + .map(|i| { + let (x, y) = (i % w, i / w); + region.mask.get(i) == Some(&0) + && (y.saturating_sub(1)..=(y + 1).min(h - 1)).any(|ny| (x.saturating_sub(1)..=(x + 1).min(w - 1)).any(|nx| (nx, ny) != (x, y) && full(nx, ny))) + }) + .collect() } #[cfg(test)] @@ -349,6 +424,174 @@ mod tests { assert_eq!(s.rgba(-4, 4), [0.0; 4], "outside the region"); } + /// #11311: flooding transparency with anti-aliasing fills the empty part of the region's edge + /// pixels at the fill's opacity, so the edge is no semi-transparent ring; opaque pixels the + /// anti-aliasing reaches blend exactly as before. + #[test] + fn bucket_on_transparency_fills_the_edge_pixels_in_full() { + let a = Rect::new(0, 0, 8, 1); + let white = |_, _| [1.0, 1.0, 1.0, 1.0]; + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { + for (opaque, opacity) in [([1.0, 1.0, 1.0, 1.0], 1.0), ([1.0, 1.0, 1.0, 1.0], 0.5), ([1.0, 0.0, 0.0, 1.0], 1.0)] { + let mut s = Surface::new(fmt); + s.fill_rect(Rect::new(4, 0, 8, 1), &opaque); + // The same region filled without the rule: what the bucket used to do. + let mut before = s.clone(); + let img = crate::selection::rgba8_image(&before, a); + let region = crate::selection::wand_region(&img, a, (1, 0), 0.0, true, true).unwrap(); + bucket_fill_region_inks(&mut before, ®ion, opacity, None, false, white, None, FillMode::Blend(BlendMode::Normal)); + + assert!(bucket_fill_inks(&mut s, a, (1, 0), 0.0, true, true, opacity, None, false, white, None, FillMode::Blend(BlendMode::Normal))); + for x in 0..4 { + let p = s.rgba(x, 0); + assert!(p[..3].iter().all(|c| (c - 1.0).abs() < 1e-3) && (p[3] - opacity).abs() < 3e-3, "{fmt:?} {opaque:?} at {x}: {p:?}"); + } + for x in 4..8 { + assert_eq!(s.rgba(x, 0), before.rgba(x, 0), "{fmt:?} {opaque:?} at {x}: opaque pixels blend as before"); + } + assert!(s.rgba(4, 0)[3] > 0.999); + } + } + } + + /// #11354 review: on a CMYK target, the edge pixels a transparent-seed bucket makes + /// opaque take the picked inks like the fully covered interior — their colour is the + /// fill alone. A partially transparent destination the fill touches keeps the blended + /// colour it already had, so its inks stay the conversion of that blend. + #[test] + fn bucket_on_transparency_writes_the_picked_cmyk_inks_at_the_edge() { + let a = Rect::new(0, 0, 8, 1); + let inks = [1.0f32, 0.0, 0.0, 0.0]; + let rgb = photocraft_color::convert::cmyk_to_rgb(inks).map(|c| c.clamp(0.0, 1.0)); + let src = |_, _| [rgb[0], rgb[1], rgb[2], 1.0]; + let raw = |s: &Surface, x: i32| -> Vec { s.read_region(Rect::new(x, 0, x + 1, 1)).into_iter().take(4).collect() }; + let is_inks = |got: &[f32]| got.iter().zip(inks).all(|(a, b)| (a - b).abs() < 0.02); + + // Transparent run against opaque white: x=3 is the anti-aliased edge (coverage < 1). + let mut s = Surface::new(PixelFormat::CMYKA8); + s.fill_rect(Rect::new(4, 0, 8, 1), &[0.0, 0.0, 0.0, 0.0, 1.0]); + assert!(bucket_fill_inks(&mut s, a, (1, 0), 0.0, true, true, 1.0, None, false, src, Some(inks), FillMode::Blend(BlendMode::Normal))); + assert!(is_inks(&raw(&s, 1)), "fully covered: {:?}", raw(&s, 1)); + assert!(is_inks(&raw(&s, 3)), "the made-opaque edge takes the picked inks: {:?}", raw(&s, 3)); + + // The edge pixel holds white at half alpha instead: the fill raises its alpha, + // but the colour is a blend, so the picked inks do not replace it. + let mut s = Surface::new(PixelFormat::CMYKA8); + s.fill_rect(Rect::new(3, 0, 4, 1), &[0.0, 0.0, 0.0, 0.0, 0.5]); + s.fill_rect(Rect::new(4, 0, 8, 1), &[0.0, 0.0, 0.0, 0.0, 1.0]); + assert!(bucket_fill_inks(&mut s, a, (1, 0), 0.0, true, true, 1.0, None, false, src, Some(inks), FillMode::Blend(BlendMode::Normal))); + let edge = s.rgba(3, 0); + assert!(edge[3] > 0.5, "the fill raised the partial pixel's alpha: {edge:?}"); + assert!(!is_inks(&raw(&s, 3)), "a blended destination keeps its own encoding: {:?}", raw(&s, 3)); + } + + /// #11354 review: the soft rim a Clear leaves rises only partly. The reference application + /// takes rim alphas 187, 56 and 3 to 204, 211 and 253; the rule here, `α + (1 − α)²`, gives + /// 205, 211 and 252, each within one level of it (fit in PR #11354's review round). The rim pixel + /// sits on the bucket's anti-aliased fringe; the hole beside it fills in full and the opaque + /// art behind it is untouched by the rule. + #[test] + fn bucket_on_transparency_raises_the_cleared_rim_partly() { + let a = Rect::new(0, 0, 8, 1); + let white = |_, _| [1.0, 1.0, 1.0, 1.0]; + let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32; + // (rim alpha after the Clear, the reference application's result, ours) + for (rim, reference, ours) in [(187, 204, 205), (56, 211, 211), (3, 253, 252)] { + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { + let mut s = Surface::new(fmt); + // The cleared hole is [0, 0, 0, 0] (Clear zeroes its RGB), the rim straight white. + s.fill_rect(Rect::new(4, 0, 5, 1), &[1.0, 1.0, 1.0, rim as f32 / 255.0]); + s.fill_rect(Rect::new(5, 0, 8, 1), &[1.0, 1.0, 1.0, 1.0]); + let before = s.clone(); + assert!(bucket_fill_inks(&mut s, a, (1, 0), 32.0, true, true, 1.0, None, false, white, None, FillMode::Blend(BlendMode::Normal))); + let p = s.rgba(4, 0); + assert_eq!(level(p[3]), ours, "{fmt:?}: rim {rim} -> {p:?}"); + assert!((ours - reference).abs() <= 1, "rim {rim}: ours {ours}, reference {reference}"); + assert!(p[..3].iter().all(|c| (c - 1.0).abs() < 1e-3), "{fmt:?}: the rim stays white: {p:?}"); + for x in 0..4 { + assert_eq!(level(s.rgba(x, 0)[3]), 255, "{fmt:?} rim {rim}: the hole and its edge fill in full at {x}"); + } + for x in 5..8 { + assert_eq!(s.rgba(x, 0), before.rgba(x, 0), "{fmt:?} rim {rim}: opaque art at {x}"); + } + } + } + } + + /// The rule is for a click on transparency only: from an opaque seed the fill is exactly the + /// wand region's own fill, fringe included. + #[test] + fn bucket_on_opaque_pixels_keeps_neighbouring_transparency() { + let a = Rect::new(0, 0, 8, 1); + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(Rect::new(0, 0, 4, 1), &[1.0, 1.0, 1.0, 0.5]); + s.fill_rect(Rect::new(4, 0, 8, 1), &[1.0, 1.0, 1.0, 1.0]); + let mut plain = s.clone(); + let img = crate::selection::rgba8_image(&plain, a); + let region = crate::selection::wand_region(&img, a, (6, 0), 0.0, true, true).unwrap(); + bucket_fill_region_inks(&mut plain, ®ion, 1.0, None, false, |_, _| [1.0; 4], None, FillMode::Blend(BlendMode::Normal)); + assert!(bucket_fill_inks(&mut s, a, (6, 0), 0.0, true, true, 1.0, None, false, |_, _| [1.0; 4], None, FillMode::Blend(BlendMode::Normal))); + for x in 0..8 { + assert_eq!(s.rgba(x, 0), plain.rgba(x, 0), "at {x}"); + } + assert!((s.rgba(1, 0)[3] - 0.5).abs() < 0.01, "outside the region"); + } + + /// #12528 (reference application, transparent seed, Tolerance 32, Anti-alias on): a black + /// edge pixel bordering the filled area takes the green fill at coverage `1 − α`, so its + /// colour as well as its alpha follow the reference within two levels; with Anti-alias off it + /// stays as it was. + #[test] + fn bucket_on_transparency_blends_into_the_edge_at_its_transparency() { + let a = Rect::new(0, 0, 8, 1); + let green = |_, _| [0.0, 1.0, 0.0, 1.0]; + let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32; + // (edge alpha, the reference application's result) + for (alpha, reference) in [(40, [0, 248, 0, 221]), (112, [0, 190, 0, 192]), (197, [0, 70, 0, 210]), (253, [0, 2, 0, 253])] { + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { + for anti_alias in [true, false] { + let mut s = Surface::new(fmt); + s.fill_rect(Rect::new(4, 0, 5, 1), &[0.0, 0.0, 0.0, alpha as f32 / 255.0]); + s.fill_rect(Rect::new(5, 0, 8, 1), &[0.0, 0.0, 0.0, 1.0]); + let before = s.clone(); + assert!(bucket_fill_inks(&mut s, a, (1, 0), 32.0, true, anti_alias, 1.0, None, false, green, None, FillMode::Blend(BlendMode::Normal))); + let got = s.rgba(4, 0).map(level); + if anti_alias { + assert!(got.iter().zip(reference).all(|(g, r)| (g - r).abs() <= 2), "{fmt:?} alpha {alpha}: {got:?}, reference {reference:?}"); + } else { + assert_eq!(s.rgba(4, 0), before.rgba(4, 0), "{fmt:?} alpha {alpha}: Anti-alias off leaves the edge"); + } + for x in 5..8 { + assert_eq!(s.rgba(x, 0), before.rgba(x, 0), "{fmt:?} alpha {alpha}: opaque art at {x}"); + } + } + } + } + } + + /// #11354 review (measured in the reference application with a 4 px feathered rim): only the + /// one-pixel ring 8-adjacent to the flood rises, diagonals included; pixels further out keep + /// their alpha exactly. + #[test] + fn bucket_on_transparency_raises_only_the_ring_next_to_the_flood() { + let a = Rect::new(0, 0, 7, 7); + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(a, &[1.0, 1.0, 1.0, 100.0 / 255.0]); + s.fill_rect(Rect::new(3, 3, 4, 4), &[0.0; 4]); + let before = s.clone(); + assert!(bucket_fill_inks(&mut s, a, (3, 3), 32.0, true, true, 1.0, None, false, |_, _| [1.0; 4], None, FillMode::Blend(BlendMode::Normal))); + for y in 0..7 { + for x in 0..7 { + let (p, was) = (s.rgba(x, y), before.rgba(x, y)); + match ((x - 3).abs(), (y - 3).abs()) { + (0, 0) => assert!(p[3] > 0.999, "the flood at ({x},{y}): {p:?}"), + (dx, dy) if dx <= 1 && dy <= 1 => assert!(p[3] > was[3] + 0.1, "the ring at ({x},{y}) rises: {p:?}"), + _ => assert_eq!(p, was, "beyond the ring at ({x},{y})"), + } + } + } + } + /// The Paint Bucket's Mode: Multiply darkens what's there, Clear erases it (half at 50 %). #[test] fn bucket_mode_blends_or_clears() { diff --git a/crates/algo/src/paint_bucket_transparent_seed_tests.rs b/crates/algo/src/paint_bucket_transparent_seed_tests.rs new file mode 100644 index 0000000000..a47c26f888 --- /dev/null +++ b/crates/algo/src/paint_bucket_transparent_seed_tests.rs @@ -0,0 +1,185 @@ +//! Paint Bucket match rule for transparent and semi-transparent seeds (#12529), Anti-alias off. +//! +//! The issue's document is 800 x 600 with a red square, a grey ramp and an anti-aliased black +//! disc on a transparent layer. These tests shrink the geometry (see `NOTES.md`) but keep every +//! measured relationship: the ramp is its own 256 x 1 strip so seeds 127 / 128 and the tolerances +//! 0 / 1 / 32 / 100 give the issue's exact grey ranges. + +use photocraft_color::{PixelFormat, blend::BlendMode}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; + +use crate::paint::{FillMode, bucket_fill_inks}; +use crate::selection::{rgba8_image, wand_region}; + +const W: i32 = 100; +const H: i32 = 80; +const AREA: Rect = Rect { x0: 0, y0: 0, x1: W, y1: H }; +const GREEN: [u8; 4] = [0, 255, 0, 255]; +/// Row of the black disc's edge; x 10..14 hold alpha 40, 112, 197, 253 like (690..700, 400). +const EDGE_Y: i32 = 70; +/// Alphas of the edge row from x = 10: the 40 / 112 / 197 / 253 ladder, then solid 253 inside. +const LADDER: [u8; 4] = [40, 112, 197, 253]; + +fn idx(x: i32, y: i32) -> usize { + (y * W + x) as usize +} + +/// Red square (40..60 x 10..30), grey ramp strip (value = x, x 0..64, y 40..43), and a black +/// edge row at `EDGE_Y` (x 10..14 the alpha ladder, x 14..30 alpha 253); the rest transparent. +fn document() -> Vec<[u8; 4]> { + let mut img = vec![[0u8; 4]; (W * H) as usize]; + for y in 10..30 { + for x in 40..60 { + img[idx(x, y)] = [220, 30, 30, 255]; + } + } + for y in 40..43 { + for x in 0..64 { + img[idx(x, y)] = [x as u8, x as u8, x as u8, 255]; + } + } + for (i, a) in LADDER.iter().enumerate() { + img[idx(10 + i as i32, EDGE_Y)] = [0, 0, 0, *a]; + } + for x in 14..30 { + img[idx(x, EDGE_Y)] = [0, 0, 0, 253]; + } + img +} + +fn surface(img: &[[u8; 4]], area: Rect) -> Surface { + let bytes: Vec = img.iter().flatten().copied().collect(); + Surface::from_interleaved(PixelFormat::RGBA8, area, &bytes) +} + +/// Bucket-fills green at `seed` and returns the layer afterwards. +fn fill(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tol: f32, contiguous: bool) -> Vec<[u8; 4]> { + let mut s = surface(img, area); + let green = |_, _| [0.0, 1.0, 0.0, 1.0]; + assert!(bucket_fill_inks(&mut s, area, seed, tol, contiguous, false, 1.0, None, false, green, None, FillMode::Blend(BlendMode::Normal))); + rgba8_image(&s, area) +} + +/// Pixels the fill changed, as indices. +fn changed(before: &[[u8; 4]], after: &[[u8; 4]]) -> Vec { + (0..before.len()).filter(|&i| before[i] != after[i]).collect() +} + +fn assert_only_alpha_zero_filled(before: &[[u8; 4]], after: &[[u8; 4]], label: &str) { + for (i, (b, a)) in before.iter().zip(after).enumerate() { + if b[3] == 0 { + assert_eq!(*a, GREEN, "{label}: transparent pixel {i} should fill"); + } else { + assert_eq!(a, b, "{label}: pixel {i} with alpha {} must not change", b[3]); + } + } +} + +#[test] +fn transparent_seed_fills_only_alpha_zero_at_any_tolerance() { + let img = document(); + for tol in [0.0, 32.0, 255.0] { + let after = fill(&img, AREA, (49, 49), tol, true); + // The transparent background is one connected region here, so contiguous reaches all of it. + assert_only_alpha_zero_filled(&img, &after, &format!("tolerance {tol}")); + for (i, a) in LADDER.iter().enumerate() { + assert_eq!(after[idx(10 + i as i32, EDGE_Y)], [0, 0, 0, *a], "edge alpha {a} survives at tolerance {tol}"); + } + assert_eq!(after[idx(9, EDGE_Y)], GREEN, "transparent pixel next to the edge fills"); + assert_eq!(after[idx(50, 20)], [220, 30, 30, 255], "red square untouched at tolerance {tol}"); + assert_eq!(after[idx(30, 41)], [30, 30, 30, 255], "ramp untouched at tolerance {tol}"); + } +} + +#[test] +fn transparent_seed_not_contiguous_fills_every_alpha_zero_pixel_only() { + let mut img = document(); + // An enclosed transparent hole that contiguous fill cannot reach. + for y in 12..16 { + for x in 44..48 { + img[idx(x, y)] = [0, 0, 0, 0]; + } + } + for tol in [0.0, 255.0] { + let after = fill(&img, AREA, (49, 49), tol, false); + assert_only_alpha_zero_filled(&img, &after, &format!("global, tolerance {tol}")); + assert_eq!(after[idx(45, 13)], GREEN, "the enclosed transparent hole fills"); + assert_eq!(after[idx(13, EDGE_Y)], [0, 0, 0, 253]); + } +} + +#[test] +fn semi_transparent_seed_takes_same_colour_pixels_of_any_nonzero_alpha() { + let img = document(); + let after = fill(&img, AREA, (10, EDGE_Y), 32.0, true); + // The 40 / 112 / 197 / 253 ladder and the solid 253 run all fill: no alpha band applies. + for x in 10..30 { + assert_eq!(after[idx(x, EDGE_Y)], GREEN, "black alpha pixel at x {x} fills"); + } + assert_eq!(after[idx(9, EDGE_Y)], [0, 0, 0, 0], "the transparent neighbour is never taken"); + let n = changed(&img, &after).len(); + assert_eq!(n, 20, "only the black edge row changes"); +} + +#[test] +fn semi_transparent_seed_respects_colour_tolerance() { + let mut img = document(); + img[idx(12, EDGE_Y)] = [100, 100, 100, 112]; + let after = fill(&img, AREA, (10, EDGE_Y), 32.0, true); + assert_eq!(after[idx(11, EDGE_Y)], GREEN); + assert_eq!(after[idx(12, EDGE_Y)], [100, 100, 100, 112], "a colour outside Tolerance stays"); + assert_eq!(after[idx(13, EDGE_Y)], [0, 0, 0, 253], "and it cuts the contiguous run"); +} + +fn ramp_strip() -> Vec<[u8; 4]> { + (0..=255u8).map(|v| [v, v, v, 255]).collect() +} + +fn filled_range(after: &[[u8; 4]]) -> Option<(usize, usize)> { + let hits: Vec = (0..after.len()).filter(|&i| after[i] == GREEN).collect(); + Some((*hits.first()?, *hits.last()?)) +} + +#[test] +fn opaque_seed_keeps_todays_ranges() { + let img = ramp_strip(); + let area = Rect::new(0, 0, 256, 1); + for (seed, tol, contiguous, lo, hi) in + [(127, 0.0, true, 127, 127), (127, 1.0, true, 126, 128), (127, 32.0, true, 95, 159), (127, 100.0, true, 27, 227), (128, 32.0, false, 96, 160)] + { + let after = fill(&img, area, (seed, 0), tol, contiguous); + assert_eq!(filled_range(&after), Some((lo, hi)), "seed {seed} tolerance {tol} contiguous {contiguous}"); + let count = after.iter().filter(|p| **p == GREEN).count(); + assert_eq!(count, hi - lo + 1, "the filled range is solid"); + } +} + +/// The wand rule did not move: a transparent seed at Tolerance 255 still matches every pixel +/// (alpha within 255 of 0), which is what the Magic Wand and Magic Eraser keep. +#[test] +fn wand_region_still_uses_the_alpha_band() { + let img = document(); + let r = wand_region(&img, AREA, (49, 49), 255.0, true, false).expect("seed is inside"); + assert_eq!(r.at(50, 20), 1.0, "red square is inside the wand region"); + assert_eq!(r.at(30, 41), 1.0, "ramp is inside the wand region"); + assert_eq!(r.at(13, EDGE_Y), 1.0, "disc edge is inside the wand region"); + let r32 = wand_region(&img, AREA, (49, 49), 32.0, true, false).expect("seed is inside"); + assert_eq!(r32.at(10, EDGE_Y), 0.0, "alpha 40 is outside a Tolerance 32 alpha band"); + assert_eq!(r32.at(9, EDGE_Y), 1.0, "alpha 0 is inside it"); +} + +/// The measured semi-transparent case is one colour at several alphas; a pixel of another +/// colour keeps the alpha band the shared rule always had (the issue leaves unmeasured +/// cases at today's behaviour). Seed [0, 0, 0, 40] at x = 1: x = 0 is the same-colour +/// control [0, 0, 0, 253]; x = 2 is [20, 20, 20, 197] — its RGB distance of 20 passes +/// Tolerance 32, but its alpha sits 157 from the seed's, so it is not filled. +#[test] +fn semi_transparent_seed_keeps_the_alpha_band_for_other_colours() { + let img: Vec<[u8; 4]> = vec![[0, 0, 0, 253], [0, 0, 0, 40], [20, 20, 20, 197]]; + let area = Rect::new(0, 0, 3, 1); + let after = fill(&img, area, (1, 0), 32.0, true); + let ch = changed(&img, &after); + assert!(ch.contains(&0), "same-colour pixel of alpha 253 fills"); + assert!(!ch.contains(&2), "different-colour pixel of alpha 197 keeps the alpha band"); +} diff --git a/crates/algo/src/panorama.rs b/crates/algo/src/panorama.rs index 86e3faea08..a965a9dde3 100644 --- a/crates/algo/src/panorama.rs +++ b/crates/algo/src/panorama.rs @@ -896,6 +896,16 @@ mod tests { assert!(pv.vignette[0].abs() < 0.1, "{pv:?}"); } + #[test] + fn an_oversized_level_count_is_clamped() { + let (w, h) = (4, 4); + let img = RoiImage { x0: 0, y0: 0, w, h, ch: 1, px: vec![0.5; w * h], alpha: vec![1.0; w * h] }; + let (out, cov) = multiband(w, h, &[img], &[vec![1.0; w * h]], usize::MAX).unwrap(); + assert_eq!(out.len(), w * h); + assert!(out.iter().all(|v| (v - 0.5).abs() < 1e-5), "{out:?}"); + assert!(cov.iter().all(|c| *c == 1.0), "{cov:?}"); + } + #[test] fn seams_avoid_disagreement_and_multiband_is_seamless() { // Two images over a 120×40 strip, overlapping in 40..80; the second has a bright diff --git a/crates/algo/src/panorama/blend.rs b/crates/algo/src/panorama/blend.rs index 9b4be0262c..4aa545209f 100644 --- a/crates/algo/src/panorama/blend.rs +++ b/crates/algo/src/panorama/blend.rs @@ -555,7 +555,8 @@ pub fn try_multiband_batched( max_band_budget: Option, ) -> Result<(Vec, Vec), AllocationError> { let ch = imgs.first().map_or(1, |i| i.ch); - let levels = levels.max(1); + // Levels past 1x1 add nothing; 16 (real use is at most 7) keeps the shifts below in range. + let levels = levels.clamp(1, 16); let cost = |im: &RoiImage| band_cost(im, w, h, ch, levels); if let Some(limit) = max_band_budget { for im in imgs { diff --git a/crates/algo/src/photo_util.rs b/crates/algo/src/photo_util.rs index 96c6f7b434..8f1e436d53 100644 --- a/crates/algo/src/photo_util.rs +++ b/crates/algo/src/photo_util.rs @@ -167,8 +167,8 @@ impl BandChol { let n = a.diag.len(); let mut p = 0; for i in 0..n { - for k in a.rows[i]..a.rows[i + 1] { - p = p.max(i.abs_diff(a.cols[k])); + for &j in &a.cols[a.rows[i]..a.rows[i + 1]] { + p = p.max(i.abs_diff(j)); } } if n.saturating_mul(p + 1) > 40_000_000 { diff --git a/crates/algo/src/resample.rs b/crates/algo/src/resample.rs index 635a5a3079..d153b78cb0 100644 --- a/crates/algo/src/resample.rs +++ b/crates/algo/src/resample.rs @@ -233,6 +233,10 @@ fn weights(o: i32, scale: f64, kernel: Kernel, edge: Option<(i32, i32)>, content let sum: f64 = w.iter().sum(); (lo, w.into_iter().map(|v| v / sum).collect()) } + // Past a 4096x reduction Lanczos would build a weight per covered source sample (tens of + // thousands per output sample); the box average that folds the beyond-edge weights is + // indistinguishable at that scale. + Kernel::Lanczos if scale < 1.0 / 4096.0 => weights(o, scale, Kernel::Bilinear, edge, content), Kernel::Lanczos => { let stretch = if scale < 1.0 { 1.0 / scale } else { 1.0 }; let u = (o as f64 + 0.5) / scale - 0.5; diff --git a/crates/algo/src/resample/tests.rs b/crates/algo/src/resample/tests.rs index 6e410f1c5d..f4406da0d2 100644 --- a/crates/algo/src/resample/tests.rs +++ b/crates/algo/src/resample/tests.rs @@ -401,6 +401,18 @@ fn nearest_neighbor_reduction_does_not_average() { } } +/// A reduction beyond 4096x by Lanczos must not build a weight per covered source sample. +#[test] +fn a_tiny_lanczos_scale_keeps_its_weights_small() { + let scale = 1.0e-7; + for o in [0, 1] { + let (_, w) = weights(o, scale, Kernel::Lanczos, None, (0, 63)); + assert!(w.len() < 1024, "{} weights", w.len()); + let sum: f64 = w.iter().sum(); + assert!((sum - 1.0).abs() < 1e-6, "{sum}"); + } +} + /// #9212: a bicubic shrink of both axes stores the image between its passes with one axis at the /// old size, larger than the result; single-pass filters and growing axes store nothing larger. #[test] diff --git a/crates/algo/src/retouch.rs b/crates/algo/src/retouch.rs index 78b588f787..08a2e63769 100644 --- a/crates/algo/src/retouch.rs +++ b/crates/algo/src/retouch.rs @@ -194,10 +194,22 @@ pub fn local_blur(data: &[f32], w: usize, h: usize, ch: usize, alpha: Option 0 && x + 1 < w && y > 0 && y + 1 < h { - let w_ch = w * ch; - [i - w_ch - ch, i - w_ch, i - w_ch + ch, i - ch, i + ch, i + w_ch - ch, i + w_ch, i + w_ch + ch] - } else { - let get_n_idx = |dx: i32, dy: i32| -> usize { - let nx = (x as i32 + dx).clamp(0, w as i32 - 1) as usize; - let ny = (y as i32 + dy).clamp(0, h as i32 - 1) as usize; - (ny * w + nx) * ch - }; - [ - get_n_idx(-1, -1), - get_n_idx(0, -1), - get_n_idx(1, -1), - get_n_idx(-1, 0), - get_n_idx(1, 0), - get_n_idx(-1, 1), - get_n_idx(0, 1), - get_n_idx(1, 1), - ] - } - } else { - [0; 8] - }; - + let i = (y * w + x0 + ox) * ch; for c in 0..ch { let v = data[i + c]; if Some(c) == alpha { dst[o + c] = v; continue; } - let mut s = v + amount * (v - blur_row[o + c]); - if protect_detail { - let (mut lo, mut hi) = (v, v); - for &n_idx in &offsets { - let nv = data[n_idx + c]; - lo = lo.min(nv); - hi = hi.max(nv); - } - s = s.clamp(lo, hi); - } - dst[o + c] = s; + let d = v - blur_row[o + c]; + // `PROTECT_DETAIL_LIMIT + |d|` is never zero, so this can't divide by zero. + let d = if protect_detail { d * PROTECT_DETAIL_LIMIT / (PROTECT_DETAIL_LIMIT + d.abs()) } else { d }; + dst[o + c] = v + amount * d; } } }; @@ -287,6 +264,10 @@ pub fn local_sharpen( out } +#[cfg(test)] +#[path = "retouch_sharpen_protect_detail_tests.rs"] +mod sharpen_protect_detail_tests; + #[cfg(test)] mod tests { use super::*; @@ -353,10 +334,10 @@ mod tests { let s = local_sharpen(&smooth, w, h, ch, None, win, 1.0, false); let so: Vec = (4..12).flat_map(|y| (4..12).map(move |x| (x, y))).map(|(x, y)| smooth[y * w + x]).collect(); assert!(var(&s) > var(&so)); - // Protect detail never exceeds the local range. + // Protect Detail sharpens too, but moves no pixel by more than its limit per unit of amount. let sp = local_sharpen(&smooth, w, h, ch, None, win, 4.0, true); - let hi = smooth.iter().cloned().fold(0.0, f32::max); - assert!(sp.iter().all(|v| *v <= hi + 1e-6)); + assert!(var(&sp) > var(&so)); + assert!(sp.iter().zip(&so).all(|(a, b)| (a - b).abs() < 4.0 * PROTECT_DETAIL_LIMIT)); } #[test] diff --git a/crates/algo/src/retouch_sharpen_protect_detail_tests.rs b/crates/algo/src/retouch_sharpen_protect_detail_tests.rs new file mode 100644 index 0000000000..efb9871c95 --- /dev/null +++ b/crates/algo/src/retouch_sharpen_protect_detail_tests.rs @@ -0,0 +1,125 @@ +//! Protect Detail in [`local_sharpen`] sharpens gently instead of changing nothing (#12938). +//! +//! The issue's test document, in RGBA like the Sharpen tool's dabs: a grey 96 | grey 160 step and +//! a lone grey-160 pixel in grey 96. A hard 40 px tip covers each test image, so one click is one +//! pass that moves every pixel by `strength · (sharpened − original)`, rounded to 8 bits. The +//! expected values are the reference application's, with the issue's tolerances. + +use super::*; + +const W: usize = 60; +const H: usize = 21; +/// x of the first grey-160 column of the step: x 400 in the issue's document. +const EDGE: usize = 30; + +fn grey(levels: impl Fn(usize, usize) -> f32, w: usize, h: usize) -> Vec { + (0..w * h) + .flat_map(|i| { + let g = levels(i % w, i / w) / 255.0; + [g, g, g, 1.0] + }) + .collect() +} + +fn step() -> Vec { + grey(|x, _| if x < EDGE { 96.0 } else { 160.0 }, W, H) +} + +/// One pass of the tool at `strength` (0–1) over the whole image. +fn pass(data: &[f32], w: usize, h: usize, strength: f32, protect: bool) -> Vec { + let out = local_sharpen(data, w, h, 4, Some(3), (0, 0, w, h), 1.0, protect); + data.iter().zip(&out).map(|(v, s)| v + (s - v) * strength).collect() +} + +/// Red channel of each pixel in 8-bit levels. +fn levels(data: &[f32]) -> Vec { + data.as_chunks::<4>().0.iter().map(|p| (p[0].clamp(0.0, 1.0) * 255.0).round() as i32).collect() +} + +/// Row `y` of the step, as x 400 + `x - EDGE` in the issue's document. +fn at(row: &[i32], x_doc: usize) -> i32 { + row[x_doc + EDGE - 400] +} + +#[test] +fn one_click_on_the_step_gives_a_low_halo_that_follows_strength() { + let row = |strength: f32| levels(&pass(&step(), W, H, strength, true))[H / 2 * W..(H / 2 + 1) * W].to_vec(); + let full = row(1.0); + for (x, want) in [(396, 94), (397, 92), (398, 91), (399, 90), (400, 164), (401, 163), (402, 161)] { + assert!((at(&full, x) - want).abs() <= 3, "100 %: x {x} is {}, want {want} ± 3 ({full:?})", at(&full, x)); + } + let half = row(0.5); + assert!((at(&half, 399) - 93).abs() <= 2 && (at(&half, 400) - 162).abs() <= 2, "50 %: x 399/400 = {}/{}", at(&half, 399), at(&half, 400)); + let quarter = row(0.25); + assert!(at(&quarter, 399) < 96 && at(&quarter, 400) > 160, "25 % still sharpens: {}/{}", at(&quarter, 399), at(&quarter, 400)); + assert_eq!(row(0.01), levels(&step())[..W].to_vec(), "1 % changes nothing"); +} + +#[test] +fn one_click_on_a_lone_pixel_lifts_it_gently() { + let (w, h, c) = (41, 41, 20); + let data = grey(|x, y| if (x, y) == (c, c) { 160.0 } else { 96.0 }, w, h); + let on = levels(&pass(&data, w, h, 1.0, true)); + let off = levels(&pass(&data, w, h, 1.0, false)); + let centre = on[c * w + c]; + assert!((centre - 168).abs() <= 4, "centre {centre}, want 168 ± 4"); + for (dx, dy) in [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] { + let n = on[(c as i32 + dy) as usize * w + (c as i32 + dx) as usize]; + assert!((93..=95).contains(&n), "neighbour ({dx}, {dy}) is {n}, want 93–95"); + } + let (lift_on, lift_off) = (centre - 160, off[c * w + c] - 160); + assert!(lift_on > 0 && 2 * lift_on < lift_off, "Protect Detail lifts {lift_on}, off lifts {lift_off}"); +} + +#[test] +fn uniform_areas_and_alpha_stay_exactly_as_they_were() { + for g in [0.0, 96.0 / 255.0, 0.5, 1.0, 2.5] { + let data: Vec = (0..12 * 9).flat_map(|i| [g, g * 0.5, 0.25, [0.0, 0.3, 1.0][i % 3]]).collect(); + let out = local_sharpen(&data, 12, 9, 4, Some(3), (0, 0, 12, 9), 1.0, true); + for (o, d) in out.as_chunks::<4>().0.iter().zip(data.as_chunks::<4>().0) { + assert_eq!(o[3].to_bits(), d[3].to_bits(), "alpha unchanged"); + } + let opaque: Vec = (0..12 * 9).flat_map(|_| [g, g * 0.5, 0.25, 1.0]).collect(); + let out = local_sharpen(&opaque, 12, 9, 4, Some(3), (2, 2, 10, 7), 1.0, true); + // Exact up to the Gaussian weights' rounding, far below one 16-bit level. + let same = |a: f32, b: f32| (a - b).abs() < 1e-6; + assert!(out.as_chunks::<4>().0.iter().all(|p| same(p[0], g) && same(p[1], g * 0.5) && same(p[2], 0.25)), "grey {g} unchanged: {out:?}"); + } +} + +#[test] +fn three_drags_widen_the_halo_without_ringing_between_black_and_white() { + // A drag of a 40 px tip at 25 % spacing passes about four dabs over each point; each drag is a + // stroke of its own, rounded to 8 bits when it ends. + let (w, h, edge) = (80, 5, 40); + let mut data = grey(|x, _| if x < edge { 96.0 } else { 160.0 }, w, h); + let mut halos = Vec::new(); + for _ in 0..3 { + for _ in 0..4 { + data = pass(&data, w, h, 1.0, true); + } + data = data.iter().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0).collect(); + let row = levels(&data)[h / 2 * w..(h / 2 + 1) * w].to_vec(); + halos.push(row.iter().enumerate().filter(|&(x, &v)| (v - if x < edge { 96 } else { 160 }).abs() >= 2).count()); + // Darker towards the edge on the dark side, lighter towards it on the light side. + for x in edge - 5..edge - 1 { + assert!(row[x] >= row[x + 1], "dark side rises at x {x}: {row:?}"); + } + for x in edge..edge + 4 { + assert!(row[x] >= row[x + 1], "light side rises at x {x}: {row:?}"); + } + assert!(row[..edge].iter().all(|&v| v < 255) && row[edge..].iter().all(|&v| v > 0), "no black–white ringing: {row:?}"); + } + assert!(halos[0] < halos[2], "the halo widens with every drag: {halos:?}"); +} + +#[test] +fn protect_detail_off_keeps_the_sigma_1_unsharp_mask() { + let data = step(); + let blur = local_blur(&data, W, H, 4, Some(3), (0, 0, W, H), 1.0); + let out = local_sharpen(&data, W, H, 4, Some(3), (0, 0, W, H), 1.0, false); + for (i, ((v, b), o)) in data.iter().zip(&blur).zip(&out).enumerate() { + let want = if i % 4 == 3 { *v } else { v + (v - b) }; + assert_eq!(o.to_bits(), want.to_bits(), "sample {i}"); + } +} diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index c91a2611de..b0dec11956 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -354,6 +354,51 @@ pub fn wand_region_by( anti_alias: bool, within: Option<&[f32]>, distance: ColorDistance, +) -> Option { + region_by_rule(img, area, seed, tolerance, contiguous, anti_alias, within, distance, MatchRule::Wand) +} + +/// Which pixels count as "similar" to the clicked one. +#[derive(Clone, Copy)] +enum MatchRule { + /// The Magic Wand / Magic Eraser rule: colour and alpha each within Tolerance, except that + /// two fully transparent pixels always match. + Wand, + /// The Paint Bucket rule, see [`wand_region_bucket`]. + Bucket, +} + +/// [`wand_region`] with the Paint Bucket's match rule (measured on the reference, #12529). +/// +/// It differs from the wand rule only when the clicked pixel is not opaque. The wand lets any +/// pixel whose alpha is within Tolerance of the seed's match, so a bucket click on transparent +/// pixels leaked into the anti-aliased edge of a shape and, at Tolerance 255, filled the whole +/// layer (#6183). The bucket rule is: +/// - seed alpha 0: only pixels with alpha 0 match; Tolerance plays no role; +/// - seed alpha 255: unchanged (colour and alpha each within Tolerance); +/// - seed alpha in between: a pixel of the seed's own colour matches when its alpha is +/// above 0 — there is no alpha band for that case (alpha 40, 197 and 253 of one colour +/// were measured to fill together). A pixel of any other colour must also sit within +/// Tolerance of the seed's alpha, as before: that case was not measured, and unmeasured +/// cases keep today's behaviour. Alpha-0 pixels are never taken. +/// +/// Only that one semi-transparent case was measured; unmeasured cases keep the previous +/// behaviour. [`wand_region`] and [`wand_region_within`] are unchanged. +pub(crate) fn wand_region_bucket(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32, contiguous: bool, anti_alias: bool) -> Option { + region_by_rule(img, area, seed, tolerance, contiguous, anti_alias, None, ColorDistance::LargestChannel, MatchRule::Bucket) +} + +#[allow(clippy::too_many_arguments)] +fn region_by_rule( + img: &[[u8; 4]], + area: Rect, + seed: (i32, i32), + tolerance: f32, + contiguous: bool, + anti_alias: bool, + within: Option<&[f32]>, + distance: ColorDistance, + rule: MatchRule, ) -> Option { if !area.contains(seed.0, seed.1) { return None; @@ -371,7 +416,14 @@ pub fn wand_region_by( let tol = (tolerance + 1e-3).floor().max(0.0) as i32; // Copying a selection can leave RGB under zero alpha. Those invisible colours must not // split a transparent region into pieces, as if the copied source were still visible. - let similar = |p: [u8; 4]| (target[3] == 0 && p[3] == 0) || (distance.rgb(p, target) <= tol && (p[3] as i32 - target[3] as i32).abs() <= tol); + let similar = |p: [u8; 4]| match rule { + MatchRule::Wand => (target[3] == 0 && p[3] == 0) || (distance.rgb(p, target) <= tol && (p[3] as i32 - target[3] as i32).abs() <= tol), + MatchRule::Bucket => match target[3] { + 0 => p[3] == 0, + 255 => distance.rgb(p, target) <= tol && (p[3] as i32 - 255).abs() <= tol, + _ => p[3] != 0 && distance.rgb(p, target) <= tol && (p[..3] == target[..3] || (p[3] as i32 - target[3] as i32).abs() <= tol), + }, + }; let mut marks = vec![0u8; w * h]; let (mut bx0, mut by0, mut bx1, mut by1) = (usize::MAX, usize::MAX, 0usize, 0usize); if contiguous { diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rs index 5a46b472e9..5dabbd2a0c 100644 --- a/crates/algo/src/transform.rs +++ b/crates/algo/src/transform.rs @@ -210,6 +210,15 @@ pub fn convex_quad(q: &[[f64; 2]; 4]) -> bool { area2.is_finite() && area2 >= 2.0 } +/// Is `q` (TL, TR, BR, BL) a usable Perspective Crop quad in either winding: a [`convex_quad`], +/// or one wound counter-clockwise on screen (a box flipped on one axis, which crops mirrored, +/// #12489) with the same corner angle and area limits? Self-crossing, degenerate and non-finite +/// quads are not. The Perspective Warp steps keep the clockwise-only [`convex_quad`]. +pub fn convex_quad_any_winding(q: &[[f64; 2]; 4]) -> bool { + let [tl, tr, br, bl] = *q; + convex_quad(q) || convex_quad(&[tl, bl, br, tr]) +} + /// The output size a Perspective Crop of `q` (TL, TR, BR, BL) takes when none is given: the mean /// length of the top and bottom edges by the mean length of the left and right edges. pub fn quad_size(q: &[[f64; 2]; 4]) -> (f64, f64) { @@ -287,9 +296,10 @@ fn perspective_estimate(q: &[[f64; 2]; 4], [cx, cy]: [f64; 2]) -> Option<(f64, f /// The homography taking the quad `q` (TL, TR, BR, BL) onto the rectangle (0, 0)–(`w`, `h`), corner /// to corner: the inverse of the unit-square-to-quad map (Heckbert, "Fundamentals of Texture /// Mapping and Image Warping", 1989, §2.2.3) scaled to the rectangle. `None` when `q` isn't a -/// [`convex_quad`] or the size isn't positive. +/// [`convex_quad_any_winding`] or the size isn't positive. A quad wound counter-clockwise maps +/// mirrored, each corner onto its own rectangle corner. pub fn quad_to_rect(q: &[[f64; 2]; 4], w: f64, h: f64) -> Option { - if !(convex_quad(q) && w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { + if !(convex_quad_any_winding(q) && w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { return None; } Homography::rect_to_quad([0.0, 0.0, w, h], *q)?.inverse() diff --git a/crates/algo/src/transform/tests.rs b/crates/algo/src/transform/tests.rs index b70bc74c3d..af6e81b615 100644 --- a/crates/algo/src/transform/tests.rs +++ b/crates/algo/src/transform/tests.rs @@ -61,7 +61,7 @@ fn the_interruptible_warp_reports_progress_and_stops_when_cancelled() { } /// Perspective Crop's map lands each quad corner exactly on its rectangle corner; degenerate, -/// self-crossing, counter-clockwise and non-finite quads have none. +/// self-crossing and non-finite quads have none. #[test] fn quad_to_rect_maps_corners_and_refuses_bad_quads() { let q = [[30.0, 12.0], [140.0, 25.0], [128.0, 110.0], [14.0, 95.0]]; @@ -75,7 +75,7 @@ fn quad_to_rect_maps_corners_and_refuses_bad_quads() { for bad in [ [[0.0, 0.0], [50.0, 0.0], [100.0, 0.0], [0.0, 50.0]], [[0.0, 0.0], [50.0, 50.0], [50.0, 0.0], [0.0, 50.0]], - [[0.0, 0.0], [0.0, 50.0], [50.0, 50.0], [50.0, 0.0]], + [[0.0, 0.0], [50.0, 50.0], [0.0, 50.0], [50.0, 0.0]], [[0.0, 0.0], [f64::NAN, 0.0], [50.0, 50.0], [0.0, 50.0]], [[0.0, 0.0]; 4], ] { @@ -84,6 +84,30 @@ fn quad_to_rect_maps_corners_and_refuses_bad_quads() { assert!(quad_to_rect(&q, 0.0, 10.0).is_none()); } +/// #12489: a quad wound counter-clockwise (a box flipped on one axis) maps mirrored, each corner +/// onto its own rectangle corner. Perspective Warp's clockwise-only check still refuses it. +#[test] +fn quad_to_rect_maps_a_counter_clockwise_quad_mirrored() { + let q = [[140.0, 25.0], [30.0, 12.0], [14.0, 95.0], [128.0, 110.0]]; + assert!(!convex_quad(&q) && convex_quad_any_winding(&q)); + let h = quad_to_rect(&q, 100.0, 80.0).unwrap(); + for (c, want) in q.iter().zip([[0.0, 0.0], [100.0, 0.0], [100.0, 80.0], [0.0, 80.0]]) { + let (x, y) = h.apply(c[0], c[1]); + assert!((x - want[0]).abs() < 1e-9 && (y - want[1]).abs() < 1e-9, "{c:?} -> ({x}, {y})"); + } + // Self-crossing in either winding, three corners on a line, and a sliver stay refused. + for bad in [ + [[0.0, 0.0], [50.0, 0.0], [0.0, 50.0], [50.0, 50.0]], + [[50.0, 0.0], [0.0, 0.0], [50.0, 50.0], [0.0, 50.0]], + [[50.0, 0.0], [25.0, 0.0], [0.0, 0.0], [50.0, 50.0]], + [[50.0, 0.0], [0.0, 0.0], [0.0, 0.01], [50.0, 0.01]], + [[50.0, 0.0], [0.0, f64::INFINITY], [0.0, 50.0], [50.0, 50.0]], + ] { + assert!(!convex_quad_any_winding(&bad), "{bad:?}"); + assert!(quad_to_rect(&bad, 10.0, 10.0).is_none(), "{bad:?}"); + } +} + fn rgba() -> Surface { Surface::new(PixelFormat::RGBA8) } diff --git a/crates/algo/src/warp.rs b/crates/algo/src/warp.rs index 0dafc18867..b4e1680eb4 100644 --- a/crates/algo/src/warp.rs +++ b/crates/algo/src/warp.rs @@ -46,6 +46,8 @@ impl Fold<'_> { /// Most subsamples per axis when a warp shrinks the source; also the longest source step per /// destination pixel the filter follows (bounds the footprint each tile reads). const MAX_SS: f64 = 8.0; +/// Bounding-box pixels scanned per destination pixel of a tile, across all its triangles. +const MAX_SCAN_PER_PIXEL: usize = 256; /// Places a smart object's source image (`src`, its pixels in `src_rect`) in the document: /// through `warp` (source space) and then the affine `t` (source → document) in one resampling @@ -462,6 +464,11 @@ fn triangles( let by0 = ps.iter().map(|p| p[1]).fold(f64::MAX, f64::min).floor() as i32; let bx1 = ps.iter().map(|p| p[0]).fold(f64::MIN, f64::max).ceil() as i32; let by1 = ps.iter().map(|p| p[1]).fold(f64::MIN, f64::max).ceil() as i32; + // Degenerate triangles draw nothing (`work` skips them the same way): do not bin them. + let det = (ps[1][0] - ps[0][0]) * (ps[2][1] - ps[0][1]) - (ps[2][0] - ps[0][0]) * (ps[1][1] - ps[0][1]); + if det.is_nan() || det.abs() < 1e-12 { + continue; + } let (cx0, cy0) = ((bx0.max(dst.x0) - tx0).div_euclid(ts), (by0.max(dst.y0) - ty0).div_euclid(ts)); let (cx1, cy1) = ((bx1.min(dst.x1 - 1) - tx0).div_euclid(ts), (by1.min(dst.y1 - 1) - ty0).div_euclid(ts)); for cy in cy0.max(0)..=cy1 { @@ -515,6 +522,9 @@ fn triangles( let mut under_at: Vec = Vec::new(); let mut jac: Vec<([f64; 4], usize, usize)> = Vec::with_capacity(order.len()); 'pass: loop { + // Folded warps pile thousands of triangles over the same pixels: the bounding boxes + // scanned per tile are capped (a sound warp scans a small multiple of the tile's area). + let mut scan_left = w * h * MAX_SCAN_PER_PIXEL + (1 << 16); for (k, tri) in order.iter().enumerate() { let [(p0, s0), (p1, s1), (p2, s2)] = tri.map(|v| verts[v]); let det = (p1[0] - p0[0]) * (p2[1] - p0[1]) - (p2[0] - p0[0]) * (p1[1] - p0[1]); @@ -538,6 +548,12 @@ fn triangles( let bx1 = (p0[0].max(p1[0]).max(p2[0]) + 0.5).ceil().min(f64::from(t.x1)) as i32; let by1 = (p0[1].max(p1[1]).max(p2[1]) + 0.5).ceil().min(f64::from(t.y1)) as i32; let eps = -1e-9; + let scan = (bx1 - bx0).max(0) as usize * (by1 - by0).max(0) as usize; + // A triangle that no longer fits is skipped, not the end of the tile: later (smaller) ones still draw. + if scan > scan_left { + continue; + } + scan_left -= scan; for y in by0..by1 { let py = f64::from(y) + 0.5; for x in bx0..bx1 { diff --git a/crates/algo/tests/it/retouch_sharpen_exact.rs b/crates/algo/tests/it/retouch_sharpen_exact.rs index 9e75a261ab..499b60d6ac 100644 --- a/crates/algo/tests/it/retouch_sharpen_exact.rs +++ b/crates/algo/tests/it/retouch_sharpen_exact.rs @@ -1,5 +1,6 @@ -//! Frozen scalar sharpen from main, used as an exact-output oracle. -use photocraft_algo::retouch::{local_blur, local_sharpen}; +//! Frozen scalar sharpen from main, used as an exact-output oracle. Its Protect Detail branch +//! follows #12938: a wider unsharp mask whose differences are soft-limited to 6 levels. +use photocraft_algo::retouch::{PROTECT_DETAIL_SIGMA, local_blur, local_sharpen}; #[test] fn matches_scalar_sharpen_bit_for_bit_across_layouts_edges_and_hdr() { @@ -51,8 +52,9 @@ fn scalar_local_sharpen( if ow == 0 || oh == 0 || ch == 0 { return Vec::new(); } - let blur = local_blur(data, w, h, ch, alpha, win, 1.0); + let blur = local_blur(data, w, h, ch, alpha, win, if protect_detail { PROTECT_DETAIL_SIGMA } else { 1.0 }); let mut out = vec![0.0f32; blur.len()]; + let limit = 6.0f32 / 255.0; for y in y0..y1 { for x in x0..x1 { let o = ((y - y0) * ow + (x - x0)) * ch; @@ -63,18 +65,9 @@ fn scalar_local_sharpen( out[o + c] = v; continue; } - let mut s = v + amount * (v - blur[o + c]); - if protect_detail { - let (mut lo, mut hi) = (v, v); - for (dx, dy) in [(-1i32, -1i32), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] { - let (nx, ny) = ((x as i32 + dx).clamp(0, w as i32 - 1) as usize, (y as i32 + dy).clamp(0, h as i32 - 1) as usize); - let nv = data[(ny * w + nx) * ch + c]; - lo = lo.min(nv); - hi = hi.max(nv); - } - s = s.clamp(lo, hi); - } - out[o + c] = s; + let d = v - blur[o + c]; + let d = if protect_detail { d * limit / (limit + d.abs()) } else { d }; + out[o + c] = v + amount * d; } } } diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index bbc0aa6bb6..034bf01e70 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -39,6 +39,9 @@ hmac = "0.12" sha2 = "0.10" cap-std = "4" clap = { workspace = true } +# The suite's AI-MCP flag and the ArtCraft Launcher's agents switch (the one consent for agents). +craft-flags = { workspace = true } +craft-ai-agents = { workspace = true } # Optional native GPU rendering backend photocraft-gpu = { workspace = true, optional = true } @@ -53,7 +56,7 @@ photocraft-raw = { workspace = true, features = ["testgen"] } # Tiny generated PSDs and the scoped estimate charge for the high-memory approval tests # (no multi-gigabyte fixture or global override). photocraft-io = { workspace = true, features = ["testgen"] } -photocraft-psd = { workspace = true, features = ["testgen"] } +craft-psd = { workspace = true, features = ["testgen"] } rmcp = { version = "3.5", default-features = false, features = ["client", "server", "macros", "transport-io"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] } diff --git a/crates/automation/src/agent_link.rs b/crates/automation/src/agent_link.rs new file mode 100644 index 0000000000..c89a14246a --- /dev/null +++ b/crates/automation/src/agent_link.rs @@ -0,0 +1,387 @@ +//! Connecting AI agents to the open desktop app: whether the person lets them (one switch, in +//! the ArtCraft Launcher, [`agents_allowed`]), and how a local client finds the app's control +//! server without being told. Adding PhotoCraft to MCP clients is the launcher's job (one entry +//! for every Craft app), so nothing here writes a client's configuration. +//! +//! While agents may connect (and no `--control` was given), the app serves its control protocol +//! on loopback and publishes where in its settings folder ([`CONNECTION_FILE`]): the port, its +//! process id and the bearer-token file ([`TOKEN_FILE`] unless a token file was given at launch; +//! created `0600` on Unix, see [`crate::security::server_token`]). A local client reads that +//! file, then the token from the file it names, so nothing has to pass a port or a token to an +//! app started from the Dock, the Start menu or a file manager. +//! +//! The file holds no secret. A crashed (or, on macOS, quit) app can leave it behind; nothing then +//! listens on its port ([`probe`]), and the app's next launch replaces it or removes it +//! ([`remove_stale_connection`]). Until then another program could take that port, so a client +//! checks that [`Connection::pid`] is still running before it sends the token. That narrows the +//! gap without closing it (a pid can be reused); `docs/control-protocol.md` says when a client +//! should not send the token on the strength of this file. +//! +//! The app starts and stops that server at once when the switch changes. `photocraft-cli mcp` +//! ([`crate::live`]) reads the connection file on every tool call, so MCP client configurations +//! never hold a port or a token, and keep working when the app restarts on another port. + +use std::net::{SocketAddr, TcpStream}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use photocraft_engine::prefs::Integrations; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::AutomationError; + +/// The connection file in the settings folder, present while the app accepts agents. +pub const CONNECTION_FILE: &str = "agent-connection.json"; +/// The bearer-token file the app keeps in its settings folder for agent connections. +pub const TOKEN_FILE: &str = "agent-control.token"; +/// The server name MCP clients list PhotoCraft under. +pub const SERVER_NAME: &str = "photocraft"; +/// How long [`probe`] waits for the app to accept a connection. +pub const PROBE_TIMEOUT: Duration = Duration::from_millis(500); +/// Version of the [`Connection`] file format. +const CONNECTION_VERSION: u32 = 1; +/// Largest connection file read; anything bigger is not ours. +const MAX_CONNECTION_BYTES: u64 = 1 << 20; + +/// What the app publishes in [`CONNECTION_FILE`]. Holds no secret: the token stays in its own +/// user-only file. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Connection { + pub version: u32, + /// The app's process id: only that process removes the file. + pub pid: u32, + /// Loopback port of the control server. + pub port: u16, + pub token_file: PathBuf, + /// The app's version, for diagnostics. + pub app: String, +} + +impl Connection { + pub fn new(port: u16, token_file: PathBuf) -> Self { + Connection { version: CONNECTION_VERSION, pid: std::process::id(), port, token_file, app: photocraft_engine::build_info::long_version() } + } + + /// `127.0.0.1:`. + pub fn addr(&self) -> String { + format!("127.0.0.1:{}", self.port) + } +} + +fn io_error(path: &Path, e: impl std::fmt::Display) -> AutomationError { + AutomationError::Io(format!("{}: {e}", path.display())) +} + +/// Publish `c` in `dir` (written atomically, so a reader never sees half a file). +pub fn write_connection(dir: &Path, c: &Connection) -> Result<(), AutomationError> { + std::fs::create_dir_all(dir).map_err(|e| io_error(dir, e))?; + let path = dir.join(CONNECTION_FILE); + let text = serde_json::to_string_pretty(c).map_err(|e| AutomationError::Other(e.to_string()))?; + photocraft_format::atomic_write(&path, text.as_bytes()).map_err(|e| io_error(&path, e)) +} + +/// The connection published in `dir`, if any. A file from another version or one that doesn't +/// parse (invalid UTF-8 included) counts as none: the app rewrites it when it next starts +/// listening. Anything but a regular file (a FIFO would block the read) is an error, and left +/// alone. +pub fn read_connection(dir: &Path) -> Result, AutomationError> { + let path = dir.join(CONNECTION_FILE); + let meta = match std::fs::metadata(&path) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(io_error(&path, e)), + }; + if !meta.is_file() { + return Err(io_error(&path, "not a regular file")); + } + if meta.len() > MAX_CONNECTION_BYTES { + return Err(io_error(&path, format!("larger than {MAX_CONNECTION_BYTES} bytes"))); + } + let bytes = match std::fs::read(&path) { + Ok(b) => b, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(io_error(&path, e)), + }; + Ok(serde_json::from_slice::(&bytes).ok().filter(|c| c.version == CONNECTION_VERSION && c.port != 0)) +} + +/// Remove the connection file in `dir` if process `pid` wrote it (another instance may have +/// published its own since). Errors are ignored: a stale file only fails [`probe`]. +pub fn remove_connection(dir: &Path, pid: u32) { + if let Ok(Some(c)) = read_connection(dir) + && c.pid == pid + { + let _ = std::fs::remove_file(dir.join(CONNECTION_FILE)); + } +} + +/// Remove the connection file in `dir` when nothing listens on its port any more (an app that +/// crashed or quit without removing it), or when it doesn't read as a connection. A live +/// instance's file is kept. Errors are ignored. +pub fn remove_stale_connection(dir: &Path) { + let path = dir.join(CONNECTION_FILE); + let stale = match read_connection(dir) { + Ok(Some(c)) => !probe(c.port, PROBE_TIMEOUT), + Ok(None) => path.is_file(), + Err(_) => false, + }; + if stale { + let _ = std::fs::remove_file(path); + } +} + +/// Does something accept connections on loopback `port`? (A crashed app leaves its connection +/// file behind; nothing listens on its port any more.) +pub fn probe(port: u16, timeout: Duration) -> bool { + port != 0 && TcpStream::connect_timeout(&SocketAddr::from(([127, 0, 0, 1], port)), timeout).is_ok() +} + +/// A folder preference as a path (`None` when empty or blank). +pub fn folder(pref: &str) -> Option { + let pref = pref.trim(); + (!pref.is_empty()).then(|| PathBuf::from(pref)) +} + +/// Largest client configuration file read; anything bigger is not ours. +const MAX_CONFIG_BYTES: u64 = 16 << 20; + +/// Read a small text file, refusing anything larger than [`MAX_CONFIG_BYTES`] or anything but a +/// regular file (a FIFO would block the read). +fn read_small(path: &Path) -> Result, AutomationError> { + let meta = match std::fs::metadata(path) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(io_error(path, e)), + }; + if !meta.is_file() { + return Err(io_error(path, "not a regular file")); + } + if meta.len() > MAX_CONFIG_BYTES { + return Err(io_error(path, format!("larger than {MAX_CONFIG_BYTES} bytes"))); + } + match std::fs::read_to_string(path) { + Ok(s) => Ok(Some(s)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(io_error(path, e)), + } +} + +/// The MCP preferences saved in `dir/preferences.json` (defaults when the file or +/// the section is missing or unreadable: the CLI must not fail over the app's settings). +pub fn read_integrations(dir: &Path) -> Integrations { + read_small(&dir.join("preferences.json")) + .ok() + .flatten() + .and_then(|text| serde_json::from_str::(&text).ok()) + .and_then(|v| v.get("integrations").cloned()) + .map(photocraft_engine::prefs::read_integrations_section) + .unwrap_or_default() +} + +// ---- The agents switch ------------------------------------------------------------------------- + +/// The id the ArtCraft Launcher's app list names PhotoCraft by. +pub const LAUNCHER_APP_ID: &str = "photocraft"; + +/// The suite's `AI-MCP` feature flag (`ArtCraft/flags.toml` or `CRAFT_FLAGS`). +pub fn mcp_flag() -> bool { + craft_flags::load().enabled(&craft_flags::AI_MCP) +} + +/// The ArtCraft Launcher's switch (Settings › AI agents › *Let AI agents use Craft apps*) lets +/// agents use PhotoCraft: the `AI-MCP` flag is on and the launcher's app list names PhotoCraft, +/// read through `craft-ai-agents` like the launcher, the MCP gateway and every Craft app do. Reads +/// two small files; ask from a timer, not every frame. +pub fn launcher_allows_agents() -> bool { + mcp_flag() && craft_ai_agents::allowed(LAUNCHER_APP_ID) +} + +/// Whether agents may use the open window. With the `AI-MCP` flag only the launcher's switch +/// decides: there is one switch for every Craft app, and none in PhotoCraft. Without the flag it +/// is as on `main`: a Control Port saved in the preferences (`connect_agents`, set from it when +/// the preferences load). Allow Agent Control off still refuses agents either way. +pub fn agents_allowed(integrations: &Integrations, mcp_flag: bool, launcher: bool) -> bool { + if mcp_flag { launcher } else { integrations.connect_agents } +} + +/// [`agents_allowed`] for this run: the flag and the launcher's switch as they are now. +pub fn agents_allowed_now(integrations: &Integrations) -> bool { + let flag = mcp_flag(); + agents_allowed(integrations, flag, flag && craft_ai_agents::allowed(LAUNCHER_APP_ID)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn temp(tag: &str) -> PathBuf { + static N: AtomicUsize = AtomicUsize::new(0); + let d = std::env::temp_dir().join(format!("photocraft-agent-link-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn with_the_flag_only_the_launchers_switch_lets_agents_in() { + let legacy = Integrations { connect_agents: true, ..Default::default() }; + let none = Integrations::default(); + // Without the AI-MCP flag: as on main, a Control Port saved before. + assert!(agents_allowed(&legacy, false, false)); + assert!(!agents_allowed(&none, false, true), "the launcher's list means nothing without the flag"); + // With the flag: the launcher's switch, and nothing else. + assert!(agents_allowed(&none, true, true)); + assert!(!agents_allowed(&legacy, true, false), "no second switch in PhotoCraft"); + } + + #[test] + fn connection_round_trips_and_only_its_writer_removes_it() { + let dir = temp("conn"); + assert_eq!(read_connection(&dir).unwrap(), None); + let c = Connection::new(4242, dir.join(TOKEN_FILE)); + write_connection(&dir, &c).unwrap(); + assert_eq!(read_connection(&dir).unwrap(), Some(c.clone())); + assert_eq!(c.addr(), "127.0.0.1:4242"); + remove_connection(&dir, c.pid.wrapping_add(1)); + assert!(dir.join(CONNECTION_FILE).exists(), "another instance's file stays"); + remove_connection(&dir, c.pid); + assert!(!dir.join(CONNECTION_FILE).exists()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_damaged_or_foreign_connection_file_counts_as_none() { + let dir = temp("bad-conn"); + for text in + ["", "{", "[]", r#"{"version":99,"pid":1,"port":1,"tokenFile":"t","app":"x"}"#, r#"{"version":1,"pid":1,"port":0,"tokenFile":"t","app":"x"}"#] + { + std::fs::write(dir.join(CONNECTION_FILE), text).unwrap(); + assert_eq!(read_connection(&dir).unwrap(), None, "{text}"); + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn probe_sees_a_listener_and_not_a_closed_port() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + assert!(probe(port, PROBE_TIMEOUT)); + drop(listener); + assert!(!probe(port, PROBE_TIMEOUT)); + assert!(!probe(0, PROBE_TIMEOUT)); + } + + #[test] + fn integrations_come_from_the_saved_preferences_or_default() { + let dir = temp("prefs"); + assert_eq!(read_integrations(&dir), Integrations::default()); + std::fs::write(dir.join("preferences.json"), "not json").unwrap(); + assert_eq!(read_integrations(&dir), Integrations::default()); + // A section of the wrong type doesn't fail the CLI either. + std::fs::write(dir.join("preferences.json"), r#"{"integrations": {"connectAgents": "yes"}}"#).unwrap(); + assert_eq!(read_integrations(&dir), Integrations::default()); + std::fs::write( + dir.join("preferences.json"), + r#"{"general": {}, "integrations": {"connectAgents": true, "whenAppClosed": "headless", "readRoot": "/in"}}"#, + ) + .unwrap(); + let i = read_integrations(&dir); + assert!(i.connect_agents); + assert_eq!(i.when_app_closed, photocraft_engine::prefs::WhenAppClosed::Headless); + assert_eq!(folder(&i.read_root), Some(PathBuf::from("/in"))); + assert_eq!(folder(&i.write_root), None); + assert_eq!(folder(" "), None); + // A Control Port saved before the agents switch reads as on, as the app reads it. + std::fs::write(dir.join("preferences.json"), r#"{"integrations": {"controlPort": 7878}}"#).unwrap(); + assert!(read_integrations(&dir).connect_agents); + std::fs::write(dir.join("preferences.json"), r#"{"integrations": {"controlPort": 7878, "connectAgents": false}}"#).unwrap(); + assert!(!read_integrations(&dir).connect_agents); + // One bad value resets only itself, as in the app: the saved closed-app choice stays. + std::fs::write(dir.join("preferences.json"), r#"{"integrations": {"whenAppClosed": "error", "readRoot": 5}}"#).unwrap(); + assert_eq!(read_integrations(&dir).when_app_closed, photocraft_engine::prefs::WhenAppClosed::Error); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_published_connection_reads_back_in_the_documented_shape() { + let dir = temp("conn"); + let c = Connection::new(7878, dir.join(TOKEN_FILE)); + write_connection(&dir, &c).unwrap(); + assert_eq!(read_connection(&dir).unwrap(), Some(c.clone())); + let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(dir.join(CONNECTION_FILE)).unwrap()).unwrap(); + let mut keys: Vec<_> = v.as_object().unwrap().keys().cloned().collect(); + keys.sort(); + assert_eq!(keys, ["app", "pid", "port", "tokenFile", "version"]); + assert_eq!((v["version"].as_u64(), v["port"].as_u64()), (Some(1), Some(7878))); + assert_eq!(c.addr(), "127.0.0.1:7878"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn other_versions_garbage_and_port_zero_read_as_none() { + let dir = temp("conn"); + assert_eq!(read_connection(&dir).unwrap(), None, "no file"); + for text in [ + &b"{not json"[..], + br#"{"version":2,"pid":1,"port":7878,"tokenFile":"t","app":"x"}"#, + br#"{"version":1,"pid":1,"port":0,"tokenFile":"t","app":"x"}"#, + b"\xff\xfe not utf-8", + ] { + std::fs::write(dir.join(CONNECTION_FILE), text).unwrap(); + assert_eq!(read_connection(&dir).unwrap(), None, "{}", String::from_utf8_lossy(text)); + } + std::fs::remove_file(dir.join(CONNECTION_FILE)).unwrap(); + // Not a regular file: an error (and `remove_stale_connection` leaves it), never a read + // that could block on a FIFO. + std::fs::create_dir(dir.join(CONNECTION_FILE)).unwrap(); + assert!(read_connection(&dir).is_err()); + remove_stale_connection(&dir); + assert!(dir.join(CONNECTION_FILE).is_dir()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn only_the_publishing_process_removes_its_file() { + let dir = temp("conn"); + let c = Connection { pid: 1, ..Connection::new(7878, dir.join(TOKEN_FILE)) }; + write_connection(&dir, &c).unwrap(); + remove_connection(&dir, 2); + assert!(dir.join(CONNECTION_FILE).is_file(), "another process's file stays"); + remove_connection(&dir, 1); + assert!(!dir.join(CONNECTION_FILE).exists()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_stale_file_is_removed_and_a_live_one_kept() { + let dir = temp("conn"); + let live = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let live_port = live.local_addr().unwrap().port(); + write_connection(&dir, &Connection { pid: 1, ..Connection::new(live_port, dir.join(TOKEN_FILE)) }).unwrap(); + remove_stale_connection(&dir); + assert!(dir.join(CONNECTION_FILE).is_file(), "something listens on {live_port}"); + drop(live); + // A port nothing listens on: bind one, then close it. + let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + write_connection(&dir, &Connection { pid: 1, ..Connection::new(closed, dir.join(TOKEN_FILE)) }).unwrap(); + remove_stale_connection(&dir); + assert!(!dir.join(CONNECTION_FILE).exists(), "nothing listens on {closed}"); + for text in [&b"{not json"[..], b"\xff\xfe not utf-8"] { + std::fs::write(dir.join(CONNECTION_FILE), text).unwrap(); + remove_stale_connection(&dir); + assert!(!dir.join(CONNECTION_FILE).exists(), "an unreadable file is not a connection"); + } + remove_stale_connection(&dir); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn folder_preferences_are_trimmed_and_empty_means_none() { + assert_eq!(folder(""), None); + assert_eq!(folder(" "), None); + assert_eq!(folder(" /work/project "), Some(PathBuf::from("/work/project"))); + } +} diff --git a/crates/automation/src/app_dirs.rs b/crates/automation/src/app_dirs.rs new file mode 100644 index 0000000000..d493536eff --- /dev/null +++ b/crates/automation/src/app_dirs.rs @@ -0,0 +1,114 @@ +//! Where PhotoCraft keeps its per-user data, resolved the same way by the desktop app and +//! `photocraft-cli` (which finds the app's agent connection file there, see [`crate::agent_link`]). +//! +//! In order: +//! 1. `PHOTOCRAFT_CONFIG_DIR`, when set (tests, agents, custom setups). +//! 2. **Portable mode** (#228): a marker file ([`PORTABLE_MARKERS`]) beside the executable puts +//! everything in `/PhotoCraftData`, so a portable copy on a USB stick leaves nothing in +//! `%APPDATA%`. The Windows portable zip ships with `portable.txt`; the MSI doesn't. If that +//! folder can't be written (read-only medium, Program Files), the platform folder is used and +//! [`DataDir::warning`] says why. +//! 3. The platform convention: macOS `~/Library/Application Support/Photocraft`, Windows +//! `%APPDATA%\Photocraft`, Linux `$XDG_CONFIG_HOME/photocraft` or `~/.config/photocraft`. +//! +//! The desktop app's `app_dirs` resolves it once per process and adds the crash-recovery folder. + +use std::ffi::OsString; +use std::path::{Path, PathBuf}; + +/// Files beside the executable that switch on portable mode (either one; contents are ignored). +pub const PORTABLE_MARKERS: [&str; 2] = ["portable.txt", "PhotoCraft.portable"]; +/// The data folder created beside the executable in portable mode. +pub const PORTABLE_DATA_DIR: &str = "PhotoCraftData"; + +/// How [`DataDir::dir`] was chosen. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// `PHOTOCRAFT_CONFIG_DIR`. + Override, + /// `/PhotoCraftData`. + Portable, + /// The platform's per-user config directory. + Platform, +} + +/// The resolved data directory. +#[derive(Clone, Debug)] +pub struct DataDir { + /// `None` only when no platform directory is known either (no `HOME`/`APPDATA`). + pub dir: Option, + pub mode: Mode, + /// Set when a portable marker was found but its data folder isn't writable. + pub warning: Option, +} + +/// Resolve the data directory from the environment (`env`) and the executable's folder. +pub fn resolve(env: impl Fn(&str) -> Option, exe_dir: Option<&Path>) -> DataDir { + if let Some(d) = env("PHOTOCRAFT_CONFIG_DIR").filter(|d| !d.is_empty()) { + return DataDir { dir: Some(PathBuf::from(d)), mode: Mode::Override, warning: None }; + } + let platform = platform_dir(&env); + let Some((exe_dir, marker)) = exe_dir.and_then(|d| portable_marker(d).map(|m| (d, m))) else { + return DataDir { dir: platform, mode: Mode::Platform, warning: None }; + }; + let data = exe_dir.join(PORTABLE_DATA_DIR); + match ensure_writable(&data) { + Ok(()) => DataDir { dir: Some(data), mode: Mode::Portable, warning: None }, + Err(e) => { + let fallback = platform.as_ref().map_or_else(|| "nowhere (no user folder found)".to_string(), |p| p.display().to_string()); + let warning = + format!("portable mode ({} found) but {} isn't writable ({e}); settings are kept in {fallback} instead", marker.display(), data.display()); + DataDir { dir: platform, mode: Mode::Platform, warning: Some(warning) } + } + } +} + +/// The platform convention, from `env` (so tests can fake `HOME`/`APPDATA`/`XDG_CONFIG_HOME`). +pub fn platform_dir(env: &impl Fn(&str) -> Option) -> Option { + let home = env("HOME").filter(|h| !h.is_empty()).map(PathBuf::from); + if cfg!(target_os = "macos") { + return home.map(|h| h.join("Library/Application Support/Photocraft")); + } + if cfg!(windows) { + return env("APPDATA").filter(|a| !a.is_empty()).map(|a| PathBuf::from(a).join("Photocraft")); + } + env("XDG_CONFIG_HOME").filter(|x| !x.is_empty()).map(PathBuf::from).or_else(|| home.map(|h| h.join(".config"))).map(|c| c.join("photocraft")) +} + +/// The first portable marker file in `exe_dir`, if any. +pub fn portable_marker(exe_dir: &Path) -> Option { + PORTABLE_MARKERS.iter().map(|m| exe_dir.join(m)).find(|p| p.is_file()) +} + +/// Probe names tried before giving up on a portable data folder. +pub const WRITE_PROBE_ATTEMPTS: u32 = 64; + +/// Create `dir` and prove a file can be written in it (a folder can exist yet be read-only). +/// +/// The probe is created exclusively (`create_new`), so an entry already at its name (a link +/// someone else placed there, say) is never opened, written through or removed: the next name +/// is tried instead. Only a probe this call created is removed. +pub fn ensure_writable(dir: &Path) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + let pid = std::process::id(); + for attempt in 0..WRITE_PROBE_ATTEMPTS { + let probe = dir.join(format!(".write-test-{pid}-{attempt}")); + match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) { + Ok(file) => { + drop(file); + // A leftover probe is harmless; don't fail portable mode over it. + let _ = std::fs::remove_file(&probe); + return Ok(()); + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + } + } + Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "every write-test name is already taken")) +} + +/// The data directory for this process's environment and executable (not cached). +pub fn from_env() -> DataDir { + let exe = std::env::current_exe().ok(); + resolve(|k| std::env::var_os(k), exe.as_deref().and_then(Path::parent)) +} diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs index a9ef67274d..1913566f4a 100644 --- a/crates/automation/src/files.rs +++ b/crates/automation/src/files.rs @@ -203,7 +203,9 @@ pub fn save_bytes_with_renderer( } return Ok((bytes, warnings)); } - let result = photocraft_io::export_with_renderer(doc, &ext, opts, &photocraft_raster::Interrupt::NONE, renderer)?; + // No ambient authority: a linked path inside the document must not be read and embedded. + let opts = ExportOptions { read_linked_files: false, ..opts.clone() }; + let result = photocraft_io::export_with_renderer(doc, &ext, &opts, &photocraft_raster::Interrupt::NONE, renderer)?; Ok((result.bytes, result.warnings)) } diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index e6d99e07c8..4b86a28e18 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -11,16 +11,21 @@ //! * [`rpc`]: a headless JSON-lines server (stdio or loopback TCP) with the //! control protocol's envelope, used by `photocraft-cli serve`. //! * [`files`]: open/save any supported format, `.pcraft` natively. +//! * [`agent_link`] and [`live`]: connecting agents to the desktop app without a terminal +//! (the ArtCraft Launcher's agents switch and plain `photocraft-cli mcp`). //! //! L6, no UI-toolkit dependencies. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod agent_link; +pub mod app_dirs; pub mod args; pub mod bridge; pub mod budgets; pub mod files; pub mod headless; +pub mod live; pub mod rpc; pub mod security; pub mod server; diff --git a/crates/automation/src/live.rs b/crates/automation/src/live.rs new file mode 100644 index 0000000000..ba39eb729d --- /dev/null +++ b/crates/automation/src/live.rs @@ -0,0 +1,295 @@ +//! `photocraft-cli mcp`: tools go to the open desktop app when the person lets agents use it, +//! found through its connection file ([`crate::agent_link`]), and otherwise to a session without +//! a window, as `mcp` always did (`--headless` forces that). The file is looked up again on every +//! tool call, so the app may start, quit or move to another port while the MCP client stays +//! connected, and the MCP client's own start never opens a window. +//! +//! While agents may use the app but it is closed, When PhotoCraft Is Closed (or `--when-closed`) +//! decides: start the app and wait for it, serve a headless session with the folders chosen in +//! the app, or report an error that says what to do. A session that went headless stays headless +//! for the rest of the MCP session, so documents don't move under the agent. + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +use photocraft_engine::prefs::WhenAppClosed; + +use crate::agent_link::{self, Connection, PROBE_TIMEOUT}; +use crate::bridge::BridgeClient; +use crate::headless::Headless; +use crate::{AuthorizedWorkspace, security}; + +/// Starts the desktop app (see [`launcher`]). +pub type LaunchFn = Box Result<(), String> + Send + Sync>; +/// Prepares a headless session before its first call (see [`LiveConfig::prepare_headless`]). +pub type PrepareFn = Box; + +/// How long a started app gets to accept agents. A first start can take a while (GPU driver +/// shader caches, font scan), but MCP clients give a tool call about a minute. +pub const LAUNCH_TIMEOUT: Duration = Duration::from_secs(45); +const POLL: Duration = Duration::from_millis(250); + +pub struct LiveConfig { + /// The app's settings folder: connection file, token and preferences. + pub config_dir: PathBuf, + /// Overrides the app's preference (`--when-closed`). + pub when_closed: Option, + /// The folders a headless session may use (`--automation-read-root`, repeatable, and + /// `--automation-write-root`); while agents may use the app, they override its folders. + pub read_roots: Vec, + pub write_root: Option, + /// Starts the app; `None` when this install can't (Flatpak sandbox, no app beside the CLI). + pub launch: Option, + pub launch_timeout: Duration, + /// Whether the person lets agents use the open app, given its saved preferences + /// ([`agent_link::agents_allowed_now`]: the ArtCraft Launcher's switch); tests replace it. + pub allowed: fn(&photocraft_engine::prefs::Integrations) -> bool, + /// Prepares a headless session before its first call (the CLI's `--gpu` / `--no-gpu`). + pub prepare_headless: Option, +} + +impl LiveConfig { + pub fn new(config_dir: PathBuf) -> Self { + LiveConfig { + config_dir, + when_closed: None, + read_roots: Vec::new(), + write_root: None, + launch: None, + launch_timeout: LAUNCH_TIMEOUT, + allowed: agent_link::agents_allowed_now, + prepare_headless: None, + } + } +} + +/// Where a tool call goes once [`Live::resolve`] has run. +#[derive(Clone)] +pub(crate) enum Target { + Bridge(Arc), + Headless(Arc>), +} + +/// The port and token a bridge client was made for: when the app restarts, either changes. +type BridgeKey = (u16, String, u32); + +pub struct Live { + cfg: LiveConfig, + /// Serialises lookups, so concurrent calls start the app once. + lookup: tokio::sync::Mutex<()>, + /// The current target, and for the bridge the port and token it was made for. + current: Mutex)>>, +} + +impl Live { + pub fn new(cfg: LiveConfig) -> Self { + Live { cfg, lookup: tokio::sync::Mutex::new(()), current: Mutex::new(None) } + } + + pub(crate) fn current(&self) -> Option { + self.current.lock().unwrap_or_else(PoisonError::into_inner).as_ref().map(|(t, _)| t.clone()) + } + + fn set(&self, target: Target, key: Option) { + *self.current.lock().unwrap_or_else(PoisonError::into_inner) = Some((target, key)); + } + + /// Find the app (or apply the closed-app choice) before a tool call. The error is the tool's + /// result: it tells the agent, and through it the user, what to do. + pub(crate) async fn resolve(&self) -> Result<(), String> { + let _one_at_a_time = self.lookup.lock().await; + if matches!(self.current(), Some(Target::Headless(_))) { + return Ok(()); + } + let dir = self.cfg.config_dir.clone(); + let consent = self.cfg.allowed; + let (found, integrations, allowed) = blocking(move || { + let integrations = agent_link::read_integrations(&dir); + let allowed = consent(&integrations); + (find_app(&dir), integrations, allowed) + }) + .await?; + if let Some((c, token)) = found? { + self.use_app(&c, token)?; + return Ok(()); + } + if !allowed { + // As `mcp` always worked: a session without a window, with only the folders given to + // this command. The app's own folders are for agents the person let in. + return self.headless(&self.cfg.read_roots, self.cfg.write_root.clone(), "the automation roots can't be used"); + } + match self.cfg.when_closed.unwrap_or(integrations.when_app_closed) { + WhenAppClosed::Error => Err("PhotoCraft isn't running: open it, then try again.".into()), + WhenAppClosed::Headless => { + let reads = if self.cfg.read_roots.is_empty() { + agent_link::folder(&integrations.read_root).into_iter().collect() + } else { + self.cfg.read_roots.clone() + }; + let write = self.cfg.write_root.clone().or_else(|| agent_link::folder(&integrations.write_root)); + self.headless(&reads, write, "PhotoCraft isn't running and its agent folders can't be used") + } + WhenAppClosed::Launch => self.launch_and_wait().await, + } + } + + /// Serve a headless session with these folders from now on. + fn headless(&self, reads: &[PathBuf], write: Option, why: &str) -> Result<(), String> { + let workspace = AuthorizedWorkspace::with_read_roots(reads.iter().map(PathBuf::as_path), write.as_deref()).map_err(|e| format!("{why}: {e}"))?; + let mut session = Headless::with_workspace(workspace); + if let Some(prepare) = &self.cfg.prepare_headless { + prepare(&mut session); + } + self.set(Target::Headless(Arc::new(Mutex::new(session))), None); + Ok(()) + } + + /// Start the app (agents may use it) and wait until it accepts them. + async fn launch_and_wait(&self) -> Result<(), String> { + let Some(launch) = &self.cfg.launch else { + return Err("PhotoCraft isn't running, and this install can't start it from here: open PhotoCraft, then try again.".into()); + }; + launch().map_err(|e| format!("couldn't start PhotoCraft: {e}"))?; + let deadline = Instant::now() + self.cfg.launch_timeout; + loop { + tokio::time::sleep(POLL).await; + let dir = self.cfg.config_dir.clone(); + if let Some((c, token)) = blocking(move || find_app(&dir)).await?? { + return self.use_app(&c, token); + } + if Instant::now() >= deadline { + return Err(format!( + "PhotoCraft didn't accept agents within {} s of starting. If it's still opening, try again in a moment; otherwise check that AI agents are on in ArtCraft Launcher › Settings › AI agents.", + self.cfg.launch_timeout.as_secs() + )); + } + } + } + + fn use_app(&self, c: &Connection, token: String) -> Result<(), String> { + // The pid too: a restarted app keeps its port and token, but the old socket is dead. + let key: BridgeKey = (c.port, token, c.pid); + let same = self.current.lock().unwrap_or_else(PoisonError::into_inner).as_ref().is_some_and(|(_, k)| k.as_ref() == Some(&key)); + if !same { + let client = BridgeClient::new(c.addr(), key.1.clone()).map_err(|e| e.to_string())?; + self.set(Target::Bridge(Arc::new(client)), Some(key)); + } + Ok(()) + } +} + +/// Run blocking file and socket work off the async runtime. +async fn blocking(f: impl FnOnce() -> T + Send + 'static) -> Result { + tokio::task::spawn_blocking(f).await.map_err(|e| format!("task failed: {e}")) +} + +/// The running app's connection and token: `None` when no app accepts agents (no connection +/// file, or one left by an app that crashed). +fn find_app(dir: &Path) -> Result, String> { + let Some(c) = agent_link::read_connection(dir).map_err(|e| e.to_string())? else { return Ok(None) }; + if !agent_link::probe(c.port, PROBE_TIMEOUT) { + return Ok(None); + } + let token = security::client_token(None, Some(&c.token_file)).map_err(|e| format!("PhotoCraft's agent token: {e}"))?; + Ok(Some((c, token))) +} + +/// How to start the desktop app that ships with the CLI at `cli` (detached, with no standard +/// streams: the CLI's carry the MCP protocol, and the app must outlive the MCP client). +pub fn launcher(cli: &Path) -> Option { + use std::process::{Command, Stdio}; + if std::env::var_os("FLATPAK_ID").is_some() { + return None; + } + let command: Command = if let Some(image) = std::env::var_os("APPIMAGE").filter(|v| !v.is_empty()) { + // The AppImage's mount point goes away with the CLI; the image itself stays. + Command::new(image) + } else { + let dir = cli.parent()?; + let bundle = dir.parent().filter(|_| dir.ends_with("Contents/MacOS")).and_then(Path::parent); + match bundle { + // A macOS app bundle: LaunchServices starts (or brings forward) the app. + Some(app) if cfg!(target_os = "macos") => { + let mut c = Command::new("/usr/bin/open"); + c.arg("-a").arg(app); + c + } + _ => { + let app = dir.join(if cfg!(windows) { "photocraft.exe" } else { "photocraft" }); + if !app.is_file() { + return None; + } + if cfg!(windows) { + let (program, args) = windows_launch(&app, std::env::var_os("SystemRoot").as_deref()); + let mut c = Command::new(program); + c.args(args); + c + } else { + Command::new(app) + } + } + } + }; + let command = Mutex::new(command); + Some(Box::new(move || { + let mut c = command.lock().unwrap_or_else(PoisonError::into_inner); + c.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()); + detach(&mut c); + c.spawn().map(|_| ()).map_err(|e| e.to_string()) + })) +} + +/// How Windows starts the app at `app`: through Explorer, as a double-click would. The app is then +/// no child of the CLI, so it outlives the MCP client ending the CLI's process tree (Claude Code +/// does on Windows), and it runs outside the container of a Microsoft Store client (Claude +/// Desktop): there, new files under `%APPDATA%` land in the client's package, where the app +/// started from the Start menu would never see the settings saved meanwhile. Explorer reads a +/// comma as a separator, so such a path is started directly. (`%WINDIR%` can be empty under a +/// Store client, hence `%SystemRoot%`.) +fn windows_launch(app: &Path, system_root: Option<&std::ffi::OsStr>) -> (PathBuf, Vec) { + if app.to_string_lossy().contains(',') { + return (app.to_path_buf(), Vec::new()); + } + let root = system_root.filter(|r| !r.is_empty()).map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from); + (root.join("explorer.exe"), vec![app.as_os_str().to_os_string()]) +} + +/// Keep the app running when the MCP client stops the CLI (and its process group). +fn detach(c: &mut std::process::Command) { + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + c.process_group(0); + } + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const DETACHED_PROCESS: u32 = 0x0000_0008; + const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200; + c.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP); + } + #[cfg(not(any(unix, windows)))] + let _ = c; +} + +#[cfg(test)] +mod tests { + use super::*; + use std::ffi::OsStr; + + #[test] + fn windows_starts_the_app_through_explorer() { + let app = Path::new(r"C:\Program Files\PhotoCraft\photocraft.exe"); + let (program, args) = windows_launch(app, Some(OsStr::new(r"D:\Win"))); + assert_eq!(program, Path::new(r"D:\Win").join("explorer.exe")); + assert_eq!(args, [app.as_os_str()]); + // No usable %SystemRoot%: the default Windows folder. + let default = Path::new(r"C:\Windows").join("explorer.exe"); + assert_eq!(windows_launch(app, Some(OsStr::new(""))).0, default); + assert_eq!(windows_launch(app, None).0, default); + // Explorer would split this path at the comma. + let comma = Path::new(r"C:\Apps, tools\photocraft.exe"); + assert_eq!(windows_launch(comma, None), (comma.to_path_buf(), Vec::new())); + } +} diff --git a/crates/automation/src/rpc/tests.rs b/crates/automation/src/rpc/tests.rs index 3db0960e15..6598d5d9c0 100644 --- a/crates/automation/src/rpc/tests.rs +++ b/crates/automation/src/rpc/tests.rs @@ -312,7 +312,7 @@ fn doc_save_takes_maximize_compatibility() { let mut h = Headless::trusted_local(); h.handle("doc.new", json!({"width": 64, "height": 32})).unwrap(); h.handle("engine.execute", json!({"command": "layer.new.layer"})).unwrap(); - let real_merged = |p: &std::path::Path| photocraft_psd::PsdFile::from_bytes(&std::fs::read(p).unwrap()).unwrap().has_real_merged_data(); + let real_merged = |p: &std::path::Path| craft_psd::PsdFile::from_bytes(&std::fs::read(p).unwrap()).unwrap().has_real_merged_data(); for (name, maximize, real) in [("default.psd", json!(null), true), ("off.psd", json!(false), false), ("on.psd", json!(true), true)] { let path = dir.join(name); h.handle("doc.save", json!({"path": path.to_string_lossy(), "maximizeCompatibility": maximize})).unwrap(); @@ -1155,7 +1155,7 @@ fn doc_place_forwards_high_memory_approval() { let gb = 1u64 << 30; let root = std::env::temp_dir().join(format!("pc-doc-place-approval-{}", std::process::id())); std::fs::create_dir_all(&root).unwrap(); - let psd = photocraft_psd::testgen::small(photocraft_psd::Version::Psd, photocraft_psd::Compression::Zip).to_bytes().unwrap(); + let psd = craft_psd::testgen::small(craft_psd::Version::Psd, craft_psd::Compression::Zip).to_bytes().unwrap(); std::fs::write(root.join("high.psd"), &psd).unwrap(); // Known 5 GiB RAM: S = 2.5 GiB, H = 3.75 GiB. A 3 GiB estimate charge lands in (S, H]. let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some(5 * gb), swap_free: None, commit_headroom: None }; diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 481ff3d1c0..8f2136af45 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -282,6 +282,20 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display()))) } +/// Write a fresh token to `path`, replacing any earlier one (user-only on Unix), and return it. +/// The desktop app rotates the agent-connection token this way each time it starts listening, so +/// a token sent to a port another program took over after a crash stops working. +pub fn replace_token_file(path: &Path) -> Result { + let token = generate_token()?; + match std::fs::remove_file(path) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(AutomationError::Io(format!("{}: {e}", path.display()))), + } + create_token_file(path, &token)?; + Ok(token) +} + /// Resolve a server token. With no supplied token or file, a fresh token is returned. /// A missing token file is created atomically; an existing one is read and validated. pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result { @@ -486,6 +500,24 @@ mod tests { } } + #[test] + fn replaced_token_files_hold_a_new_valid_token() { + let dir = std::env::temp_dir().join(format!("photocraft-replace-token-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join("agent.token"); + let first = replace_token_file(&path).unwrap(); + assert_eq!(client_token(None, Some(&path)).unwrap(), first); + let second = replace_token_file(&path).unwrap(); + assert_ne!(first, second); + assert_eq!(client_token(None, Some(&path)).unwrap(), second); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + } + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn generated_tokens_are_valid_and_distinct() { let a = generate_token().unwrap(); diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 0795e1f66d..1d2729c644 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -18,6 +18,7 @@ use serde_json::{Value, json}; use crate::bridge::BridgeClient; use crate::budgets::{BatchReplyBudget, MAX_PREVIEW_SIDE, check_png, json_bytes}; use crate::headless::Headless; +use crate::live::{Live, LiveConfig, Target}; use crate::security::MAX_BATCH_STEPS; use crate::{AuthorizedWorkspace, AutomationError, files}; @@ -27,6 +28,9 @@ pub enum Backend { Headless(Arc>), /// A running desktop app reached over the control protocol. Bridge(Arc), + /// The desktop app found through its connection file before each call, or the closed-app + /// choice (plain `photocraft-cli mcp`, see [`crate::live`]). + Live(Arc), } #[derive(Clone)] @@ -619,6 +623,12 @@ impl PhotocraftMcp { Ok(Self::with_backend(Backend::Bridge(Arc::new(BridgeClient::new(addr, token)?)))) } + /// Serve the desktop app found through its connection file, or headless without consent + /// (plain `photocraft-cli mcp`). + pub fn live(config: LiveConfig) -> Self { + Self::with_backend(Backend::Live(Arc::new(Live::new(config)))) + } + pub fn with_backend(backend: Backend) -> Self { let mut tool_router = Self::tool_router(); for route in tool_router.map.values_mut() { @@ -639,10 +649,7 @@ impl PhotocraftMcp { &self, f: impl FnOnce(&mut Headless) -> Result + Send + 'static, ) -> Option> { - let Backend::Headless(h) = &*self.backend else { - return None; - }; - let h = h.clone(); + let h = self.headless_session()?; Some( tokio::task::spawn_blocking(move || { // A panicking command poisons the lock, but edits run on a copy @@ -657,13 +664,47 @@ impl PhotocraftMcp { ) } - fn bridge_client(&self) -> Option<&BridgeClient> { + /// The headless session tools run on, if this backend (or the live choice) is one. + fn headless_session(&self) -> Option>> { match &*self.backend { - Backend::Bridge(b) => Some(b), + Backend::Headless(h) => Some(h.clone()), + Backend::Live(live) => match live.current()? { + Target::Headless(h) => Some(h), + Target::Bridge(_) => None, + }, + Backend::Bridge(_) => None, + } + } + + fn bridge_client(&self) -> Option> { + match &*self.backend { + Backend::Bridge(b) => Some(b.clone()), + Backend::Live(live) => match live.current()? { + Target::Bridge(b) => Some(b), + Target::Headless(_) => None, + }, Backend::Headless(_) => None, } } + /// Where calls go now: the backend's session or app, or the live mode's last resolve. + fn target(&self) -> Option { + match &*self.backend { + Backend::Headless(h) => Some(Target::Headless(h.clone())), + Backend::Bridge(b) => Some(Target::Bridge(b.clone())), + Backend::Live(live) => live.current(), + } + } + + /// Live mode: find the app (or apply the closed-app choice) before a call; the error is the + /// call's result. Other backends are always ready. + async fn ready(&self) -> Result<(), String> { + match &*self.backend { + Backend::Live(live) => live.resolve().await, + Backend::Headless(_) | Backend::Bridge(_) => Ok(()), + } + } + async fn screenshot(&self, b: &BridgeClient, max_side: Option) -> Result { if max_side.is_some_and(|side| side > MAX_PREVIEW_SIDE) { return Ok(fail(format!("automation preview side exceeds {MAX_PREVIEW_SIDE} pixels"))); @@ -960,7 +1001,7 @@ impl PhotocraftMcp { if p.index.is_some() { return Ok(fail("`index` is only supported in headless mode; bridge previews capture the app window")); } - self.screenshot(b, Some(max)).await + self.screenshot(&b, Some(max)).await } #[tool(description = "Render a bounded flattened PNG preview (bridge mode: app window screenshot).")] @@ -1056,7 +1097,7 @@ impl PhotocraftMcp { #[tool(description = "Bridge mode: screenshot of the live app window as PNG.")] async fn ui_screenshot(&self, Parameters(p): Parameters) -> Result { match self.bridge_client() { - Some(b) => self.screenshot(b, p.max_side).await, + Some(b) => self.screenshot(&b, p.max_side).await, None => bridge_only("ui_screenshot"), } } @@ -1107,6 +1148,16 @@ impl PhotocraftMcp { } } +/// Whether two targets are the same session or the same app connection. +fn same_target(a: Option<&Target>, b: Option<&Target>) -> bool { + match (a, b) { + (Some(Target::Headless(a)), Some(Target::Headless(b))) => Arc::ptr_eq(a, b), + (Some(Target::Bridge(a)), Some(Target::Bridge(b))) => Arc::ptr_eq(a, b), + (None, None) => true, + _ => false, + } +} + fn bridge_only_headless(name: &str) -> Result { Ok(fail(format!("`{name}` is only available in headless mode (in the GUI use the window/tab UI or control_call)"))) } @@ -1119,11 +1170,13 @@ impl PhotocraftMcp { /// Run one command in either backend; `at` is its place in a batch, for progress. async fn step(&self, id: String, params: Value, wait: bool, waiter: &mut Waiter, at: (usize, usize)) -> Result { let none = || Err(AutomationError::Other("internal error: no headless session or app bridge".into())); - match &*self.backend { - Backend::Headless(_) if wait => self.headless_wait(id, params, waiter, at).await.unwrap_or_else(none), - Backend::Headless(_) => self.headless_op(move |h| h.command_start(&id, params, false)).await.unwrap_or_else(none), - Backend::Bridge(b) if wait => self.bridge_wait(b, id, params, waiter, at).await, - Backend::Bridge(b) => b.call("engine.execute", json!({"command": id, "params": params, "wait": false})).await, + // Live mode goes wherever its last resolve pointed: the app, or a headless session. + match (self.headless_session(), self.bridge_client()) { + (Some(_), _) if wait => self.headless_wait(id, params, waiter, at).await.unwrap_or_else(none), + (Some(_), _) => self.headless_op(move |h| h.command_start(&id, params, false)).await.unwrap_or_else(none), + (None, Some(b)) if wait => self.bridge_wait(&b, id, params, waiter, at).await, + (None, Some(b)) => b.call("engine.execute", json!({"command": id, "params": params, "wait": false})).await, + (None, None) => none(), } } @@ -1137,11 +1190,19 @@ impl PhotocraftMcp { let mut failed = 0; // The reply travels as escaped JSON text, so steps are charged their escaped size. let mut reply_budget = BatchReplyBudget::escaped(); + // Live mode may find a restarted app (or go headless) while a batch runs: its steps must + // not end up split across two documents in two places. + let pinned = self.target(); for (i, s) in p.steps.into_iter().enumerate() { // A cancelled request runs no further steps; the client no longer reads the reply. if waiter.is_cancelled() { break; } + if !same_target(pinned.as_ref(), self.target().as_ref()) { + failed += 1; + results.push(json!({"ok": false, "error": "PhotoCraft restarted (or the session changed) during the batch; this step and the ones after it did not run"})); + break; + } let response = self.step(s.id, s.params.unwrap_or_else(|| json!({})), s.wait.unwrap_or(true), &mut waiter, (i, total)).await; let was_error = response.is_err(); let result = match response { diff --git a/crates/automation/src/server/conventions.rs b/crates/automation/src/server/conventions.rs index c6792a1e6b..30d3344c0d 100644 --- a/crates/automation/src/server/conventions.rs +++ b/crates/automation/src/server/conventions.rs @@ -1,5 +1,5 @@ //! Catalog metadata, strict tool envelopes and live resources. -use super::{Arc, Backend, BatchParams, DocIndex, ListParams, McpError, Parameters, PhotocraftMcp, RunParams, ServerHandler, Value, json}; +use super::{Arc, BatchParams, DocIndex, ListParams, McpError, Parameters, PhotocraftMcp, RunParams, ServerHandler, Value, fail, json}; use rmcp::RoleServer; use rmcp::model::{ CallToolRequestParams, CallToolResponse, Implementation, ListResourcesResult, ListToolsResult, PaginatedRequestParams, ReadResourceRequestParams, @@ -55,7 +55,10 @@ impl ServerHandler for PhotocraftMcp { let args = Value::Object(request.arguments.clone().unwrap_or_default()); let _: BatchParams = serde_json::from_value(args).map_err(|e| McpError::invalid_params(e.to_string(), None))?; } - if request.name == "command_run" && matches!(&*self.backend, Backend::Headless(_)) { + if let Err(error) = self.ready().await { + return Ok(fail(error).into()); + } + if request.name == "command_run" && self.headless_session().is_some() { let args = Value::Object(request.arguments.clone().unwrap_or_default()); let params: RunParams = serde_json::from_value(args).map_err(|e| McpError::invalid_params(e.to_string(), None))?; if params.id == "file.export.renderVideo" { @@ -74,6 +77,9 @@ impl ServerHandler for PhotocraftMcp { } async fn read_resource(&self, request: ReadResourceRequestParams, _: RequestContext) -> Result { + if let Err(error) = self.ready().await { + return Err(McpError::internal_error(error, None)); + } let result = match request.uri.as_str() { DOCUMENT => self.doc_inspect(Parameters(DocIndex::default())).await?, COMMANDS => self.command_list(Parameters(ListParams::default())).await?, diff --git a/crates/automation/src/server/progress.rs b/crates/automation/src/server/progress.rs index 8b3697f65d..9152157dfd 100644 --- a/crates/automation/src/server/progress.rs +++ b/crates/automation/src/server/progress.rs @@ -1,8 +1,9 @@ //! Progress and cancellation for calls that wait. Render Video runs on the existing blocking //! worker; other long commands run as engine jobs that the server polls ([`Waiter`]): the headless //! session's own, or the app's over the bridge. -use super::{Arc, AutomationError, Backend, BridgeClient, CallToolResult, PhotocraftMcp, PoisonError, Value, fail, json, no_backend, ok_json}; +use super::{Arc, AutomationError, BridgeClient, CallToolResult, PhotocraftMcp, PoisonError, Value, fail, json, no_backend, ok_json}; use crate::headless::JobPoll; +use crate::live::Target; use photocraft_engine::jobs::{JobId, Started}; use rmcp::RoleServer; use rmcp::model::ProgressNotificationParam; @@ -92,7 +93,9 @@ impl Waiter { /// Cancels a waited job when its waiter goes away without collecting it: rmcp may drop the /// request future on cancellation, and nothing else would stop the job. struct Abandon { - backend: Arc, + /// The session or app that started the job: in live mode the current target can change + /// before the guard drops, and the job id means nothing elsewhere. + target: Target, job: Option, } @@ -100,8 +103,8 @@ impl Drop for Abandon { fn drop(&mut self) { let Some(job) = self.job.take() else { return }; let runtime = tokio::runtime::Handle::try_current(); - match &*self.backend { - Backend::Headless(session) => { + match &self.target { + Target::Headless(session) => { let session = session.clone(); let abandon = move || drop(session.lock().unwrap_or_else(PoisonError::into_inner).job_abandon(job)); match runtime { @@ -111,7 +114,7 @@ impl Drop for Abandon { } } // Without a runtime there is no way to reach the app; the job then runs to the end. - Backend::Bridge(client) => { + Target::Bridge(client) => { if let Ok(runtime) = runtime { let client = client.clone(); drop(runtime.spawn(async move { client.call("jobs.cancel", json!({"job": job.0})).await })); @@ -127,10 +130,7 @@ impl PhotocraftMcp { /// `waiter` as `step.0 + fraction` of `step.1`, and cancelling the request cancels the job, /// leaving the document unchanged. `None` in bridge mode. pub(super) async fn headless_wait(&self, id: String, params: Value, waiter: &mut Waiter, step: (usize, usize)) -> Option> { - if !matches!(&*self.backend, Backend::Headless(_)) { - return None; - } - let backend = self.backend.clone(); + let target = Target::Headless(self.headless_session()?); let cancel = waiter.context.as_ref().map(|context| context.ct.clone()); // The guard is armed under the lock that starts the job: when the request is dropped while // the start still waits for the lock, the closure's output is dropped unread and cancels it. @@ -143,7 +143,7 @@ impl PhotocraftMcp { Started::Job(job) if cancel.as_ref().is_some_and(|token| token.is_cancelled()) => { return h.job_abandon(job).map(Err); } - Started::Job(job) => Ok(Abandon { backend, job: Some(job) }), + Started::Job(job) => Ok(Abandon { target, job: Some(job) }), Started::Done(value) => Err(value), }) }) @@ -187,7 +187,7 @@ impl PhotocraftMcp { /// (#1007); a failed poll reports the job instead of guessing its outcome. pub(super) async fn bridge_wait( &self, - client: &BridgeClient, + client: &Arc, id: String, params: Value, waiter: &mut Waiter, @@ -202,7 +202,7 @@ impl PhotocraftMcp { let Some(job) = started.get("job").and_then(Value::as_u64).filter(|_| pending) else { return Ok(started); }; - let mut guard = Abandon { backend: self.backend.clone(), job: Some(JobId(job)) }; + let mut guard = Abandon { target: Target::Bridge(client.clone()), job: Some(JobId(job)) }; let mut delay = Duration::from_millis(10); loop { // Race the poll against a cancel: an app slow to answer must not hold it until the call times out. diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index a08715e436..93bd38ad7b 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -56,6 +56,20 @@ impl AuthorizedWorkspace { Ok(Self { read, write }) } + /// This workspace with `path` as its only read root (the write authority stays). A path + /// spelled like the write root shares its capability, as [`Self::with_read_roots`] does, so + /// an implicit save can still write where a file was read. + pub fn with_read_root(&self, path: &Path) -> Result { + let opened: Vec = self.write.iter().cloned().collect(); + Ok(Self { read: vec![open_root(path, "read", &opened)?], write: self.write.clone() }) + } + + /// This workspace with `path` as its write root (the read authority stays), sharing the + /// capability of a read root spelled the same. + pub fn with_write_root(&self, path: &Path) -> Result { + Ok(Self { read: self.read.clone(), write: Some(open_root(path, "write", &self.read)?) }) + } + /// Read the first matching regular file, trying roots in their configured order. /// Only an open that reports NotFound tries the next root. Once opened, errors /// (including a non-regular file or a failed bounded read) never select another file. @@ -738,8 +752,12 @@ fn preference_uses_ambient_filesystem(path: &str) -> bool { let mut segments = path.split('.').filter(|segment| !segment.is_empty()); let Some(section) = segments.next() else { return true }; // File Handling's LUT folder (#6558) is listed from disk; the rest of that section is not. + // Integrations' automation roots are what this policy grants (applied at once): an agent must + // not widen its own file access. + let key = segments.next(); matches!(section, "colorSettings" | "scriptEvents" | "historyLog" | "plugIns" | "scratchDisks") - || (section == "fileHandling" && segments.next().is_none_or(|key| key == "lutFolder")) + || (section == "fileHandling" && key.is_none_or(|key| key == "lutFolder")) + || (section == "integrations" && key.is_none_or(|key| matches!(key, "readRoot" | "writeRoot"))) } fn command_uses_ambient_path(id: &str, params: &Value) -> bool { diff --git a/crates/automation/src/workspace/tests.rs b/crates/automation/src/workspace/tests.rs index 59bd768bc5..82810423aa 100644 --- a/crates/automation/src/workspace/tests.rs +++ b/crates/automation/src/workspace/tests.rs @@ -802,6 +802,10 @@ fn automation_rejects_ambient_path_commands_and_preferences() { "fileHandling.lutFolder", "fileHandling", "scratchDisks.disks", + "integrations", + "integrations.readRoot", + "integrations.writeRoot", + ".integrations.writeRoot", ".", "..historyLog.filePath", ] { @@ -812,6 +816,12 @@ fn automation_rejects_ambient_path_commands_and_preferences() { ); assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "interface.language", "value": "fr"})).is_ok()); assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "fileHandling.autosave", "value": false})).is_ok()); + assert!( + authorize_engine_command("prefs.set", &serde_json::json!({"values": {"integrations.controlPort": 7878, "integrations.writeRoot": "/outside"}})) + .is_err(), + "a batch may not grant automation roots either" + ); + assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "integrations.controlPort", "value": 7878})).is_ok()); } #[test] @@ -1508,7 +1518,7 @@ fn csh_import_requires_inline_data_in_automation() { /// A one-shape CSH set (version 2) named `name`, with a single open one-knot subpath. fn one_shape_csh(name: &str) -> Vec { - use photocraft_psd::path::{PathData, PsdKnot, PsdSubpath}; + use craft_psd::path::{PathData, PsdKnot, PsdSubpath}; let mut bytes = b"cush".to_vec(); bytes.extend_from_slice(&2u32.to_be_bytes()); bytes.extend_from_slice(&1u32.to_be_bytes()); diff --git a/crates/automation/tests/it/linked_save_bytes.rs b/crates/automation/tests/it/linked_save_bytes.rs new file mode 100644 index 0000000000..42ecd8b89a --- /dev/null +++ b/crates/automation/tests/it/linked_save_bytes.rs @@ -0,0 +1,29 @@ +//! `files::save_bytes` is the capability-scoped encoder: a linked path inside the document must +//! not be read through ambient filesystem authority and embedded in the returned bytes. + +use photocraft_automation::files; +use photocraft_doc::{Document, Layer, LayerContent, SmartContentsId, SmartObject, SmartSource}; + +#[test] +fn a_linked_smart_object_is_not_read_into_the_bytes() { + let mut doc = Document::new("linked", photocraft_doc::Size::new(8, 6), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); + let linked = std::env::current_exe().unwrap(); + let smart = SmartObject { + contents_id: SmartContentsId::fresh(), + source: SmartSource::Linked { path: linked.to_string_lossy().into_owned() }, + transform: photocraft_geom::Affine::IDENTITY, + smart_filters: vec![], + cache: Some(photocraft_raster::Surface::new(doc.pixel_format())), + psd_raw: None, + filters_enabled: true, + filter_mask: None, + warp: None, + stack_mode: None, + perspective: None, + vector_preview: None, + }; + doc.layers.push(Layer::new("Linked", LayerContent::Smart(smart))); + let (bytes, warnings) = files::save_bytes(&doc, "out.psd", None, &Default::default()).unwrap(); + assert!(warnings.iter().any(|w| w.contains("not read for this export")), "{warnings:?}"); + assert!(bytes.len() < 1 << 20, "the test executable was not embedded"); +} diff --git a/crates/automation/tests/it/main.rs b/crates/automation/tests/it/main.rs index ed98e61b6b..9a551dd087 100644 --- a/crates/automation/tests/it/main.rs +++ b/crates/automation/tests/it/main.rs @@ -9,6 +9,7 @@ mod gpu_backend; mod inactive_save; mod krita; mod layered_save_dirty; +mod linked_save_bytes; mod mcp; mod mcp_wire; mod missing_font_warnings; diff --git a/crates/automation/tests/it/mcp.rs b/crates/automation/tests/it/mcp.rs index 12cc75f19f..e901ee6a37 100644 --- a/crates/automation/tests/it/mcp.rs +++ b/crates/automation/tests/it/mcp.rs @@ -532,7 +532,7 @@ async fn headless_doc_save_takes_maximize_compatibility() { let r = call(&client, tool, params.clone()).await; assert_ne!(r.is_error, Some(true), "{params}: {}", text(&r)); let bytes = std::fs::read(dir.join(params["path"].as_str().unwrap())).unwrap(); - assert_eq!(photocraft_psd::PsdFile::from_bytes(&bytes).unwrap().has_real_merged_data(), Some(real), "{params}"); + assert_eq!(craft_psd::PsdFile::from_bytes(&bytes).unwrap().has_real_merged_data(), Some(real), "{params}"); } let r = call(&client, "doc_export", json!({"path": "bad.psd", "maximizeCompatibility": "no"})).await; assert_eq!(r.is_error, Some(true), "{}", text(&r)); @@ -555,7 +555,7 @@ async fn headless_doc_export_layers_takes_maximize_compatibility() { let file = result["files"][0].as_str().unwrap(); assert!(file.starts_with(sub), "{file}"); let bytes = std::fs::read(dir.join(file)).unwrap(); - assert_eq!(photocraft_psd::PsdFile::from_bytes(&bytes).unwrap().has_real_merged_data(), Some(real), "{params}"); + assert_eq!(craft_psd::PsdFile::from_bytes(&bytes).unwrap().has_real_merged_data(), Some(real), "{params}"); } let r = call(&client, "doc_export_layers", json!({"dir": "bad", "format": "psd", "maximizeCompatibility": "no"})).await; assert_eq!(r.is_error, Some(true), "{}", text(&r)); diff --git a/crates/automation/tests/mcp_live.rs b/crates/automation/tests/mcp_live.rs new file mode 100644 index 0000000000..dc106a639b --- /dev/null +++ b/crates/automation/tests/mcp_live.rs @@ -0,0 +1,378 @@ +//! Plain `photocraft-cli mcp` with agents allowed (the ArtCraft Launcher's switch): the MCP server finds the desktop +//! app through its connection file before every call, follows it to a new port and token, and +//! applies the closed-app choice (start it, headless, or an error) when no app answers. + +use std::io::{BufRead, BufReader, Write}; +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; + +use photocraft_automation::PhotocraftMcp; +use photocraft_automation::agent_link::{self, Connection}; +use photocraft_automation::live::LiveConfig; +use photocraft_engine::prefs::WhenAppClosed; +use rmcp::model::{CallToolRequestParams, CallToolResult, ClientConfig}; +use rmcp::service::RunningService; +use rmcp::{ClientHandler, RoleClient, ServiceExt}; +use serde_json::{Value, json}; + +#[derive(Clone, Default)] +struct Client; +impl ClientHandler for Client { + fn get_info(&self) -> ClientConfig { + ClientConfig::default() + } +} + +async fn connect(server: PhotocraftMcp) -> RunningService { + let (s, c) = tokio::io::duplex(1 << 20); + tokio::spawn(async move { + if let Ok(running) = server.serve(s).await { + let _ = running.waiting().await; + } + }); + Client.serve(c).await.expect("client init") +} + +async fn call(client: &RunningService, name: &str, args: Value) -> CallToolResult { + let mut p = CallToolRequestParams::new(name.to_owned()); + if let Value::Object(m) = args { + p = p.with_arguments(m); + } + client.call_tool(p).await.expect("call_tool transport") +} + +fn text(r: &CallToolResult) -> String { + r.content.iter().filter_map(|c| c.as_text()).map(|t| t.text.clone()).collect::>().join("\n") +} + +fn settings_dir(tag: &str) -> PathBuf { + static N: AtomicUsize = AtomicUsize::new(0); + let d = std::env::temp_dir().join(format!("pc-mcp-live-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn prefs(dir: &Path, integrations: Value) { + std::fs::write(dir.join("preferences.json"), json!({"integrations": integrations}).to_string()).unwrap(); +} + +/// A desktop app as `mcp` sees it: a control server on a free port with a fresh token, its +/// connection file published in `dir`. `ui.inspect` answers with `name`. [`quit`] stops it. +struct FakeApp { + port: u16, + stop: Arc, +} + +fn fake_app(dir: &Path, name: &'static str) -> FakeApp { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let token_file = dir.join(agent_link::TOKEN_FILE); + let token = photocraft_automation::security::replace_token_file(&token_file).unwrap(); + agent_link::write_connection(dir, &Connection::new(port, token_file)).unwrap(); + let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let stopped = stop.clone(); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + if stopped.load(Ordering::SeqCst) { + break; + } + let token = token.clone(); + std::thread::spawn(move || { + let mut out = stream.try_clone().unwrap(); + // The app's own handshake (challenge or token), as `control_server` runs it. + let mut handshake = photocraft_automation::security::ServerHandshake::new(); + let mut authenticated = false; + for line in BufReader::new(stream).lines() { + let Ok(line) = line else { break }; + if !authenticated { + let (reply, step) = handshake.reply(&line, &token); + authenticated = step == photocraft_automation::security::AuthStep::Authenticated; + if writeln!(out, "{reply}").is_err() || step == photocraft_automation::security::AuthStep::Rejected { + break; + } + continue; + } + let req: Value = serde_json::from_str(&line).unwrap(); + let id = req["id"].clone(); + let reply = match req["method"].as_str().unwrap_or("") { + "ui.inspect" => json!({"id": id, "ok": true, "result": {"app": name}}), + m => json!({"id": id, "ok": false, "error": format!("unexpected {m}")}), + }; + if writeln!(out, "{reply}").is_err() { + break; + } + } + }); + } + }); + FakeApp { port, stop } +} + +/// The fake app quits: its port stops accepting (connections already open end with the test). +fn quit(app: FakeApp) { + app.stop.store(true, Ordering::SeqCst); + let _ = std::net::TcpStream::connect(("127.0.0.1", app.port)); + while agent_link::probe(app.port, Duration::from_millis(200)) { + std::thread::sleep(Duration::from_millis(10)); + } +} + +fn live(dir: &Path, when_closed: Option) -> LiveConfig { + let mut c = LiveConfig::new(dir.to_path_buf()); + c.when_closed = when_closed; + c.launch_timeout = Duration::from_secs(10); + // The machine's own ArtCraft Launcher and feature flags stay out of the tests: agents are + // allowed exactly when the test's preferences say so (as without the AI-MCP flag). + c.allowed = |i| i.connect_agents; + c +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_closed_app_is_a_tool_error_that_says_what_to_do() { + let dir = settings_dir("closed"); + prefs(&dir, json!({"connectAgents": true})); + let client = connect(PhotocraftMcp::live(live(&dir, Some(WhenAppClosed::Error)))).await; + // The tool list doesn't need the app. + assert!(client.list_all_tools().await.unwrap().iter().any(|t| t.name == "ui_inspect")); + let r = call(&client, "command_list", json!({})).await; + assert_eq!(r.is_error, Some(true)); + assert!(text(&r).contains("isn't running"), "{}", text(&r)); + // A connection file left by a crashed app (nothing listens) counts as closed. + let gone = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = gone.local_addr().unwrap().port(); + drop(gone); + agent_link::write_connection(&dir, &Connection::new(port, dir.join(agent_link::TOKEN_FILE))).unwrap(); + let r = call(&client, "ui_inspect", json!({})).await; + assert!(text(&r).contains("isn't running"), "{}", text(&r)); + client.cancel().await.unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test(flavor = "multi_thread")] +async fn follows_the_app_across_restarts_on_new_ports_and_tokens() { + let dir = settings_dir("follow"); + prefs(&dir, json!({"connectAgents": true, "whenAppClosed": "error"})); + let client = connect(PhotocraftMcp::live(live(&dir, None))).await; + let first = fake_app(&dir, "first"); + let r = call(&client, "ui_inspect", json!({})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + assert!(text(&r).contains("first")); + // Restart: another port, a new token. + quit(first); + let second = fake_app(&dir, "second"); + let r = call(&client, "ui_inspect", json!({})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + assert!(text(&r).contains("second"), "{}", text(&r)); + quit(second); + std::fs::remove_file(dir.join(agent_link::CONNECTION_FILE)).unwrap(); + let r = call(&client, "ui_inspect", json!({})).await; + assert_eq!(r.is_error, Some(true)); + client.cancel().await.unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test(flavor = "multi_thread")] +async fn launch_starts_the_app_once_and_only_when_agents_may_connect() { + let dir = settings_dir("launch"); + let launches = Arc::new(AtomicUsize::new(0)); + let apps = Arc::new(std::sync::Mutex::new(Vec::new())); + let config = |dir: &Path| { + let mut c = live(dir, Some(WhenAppClosed::Launch)); + let (launches, apps, dir) = (launches.clone(), apps.clone(), dir.to_path_buf()); + c.launch = Some(Box::new(move || { + launches.fetch_add(1, Ordering::SeqCst); + let (apps, dir) = (apps.clone(), dir.clone()); + // The app takes a moment to start listening. + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(300)); + apps.lock().unwrap().push(fake_app(&dir, "launched")); + }); + Ok(()) + })); + c + }; + // Agents not allowed: the app would never listen, so it isn't started; the session works + // without a window, as `mcp` always did. + let client = connect(PhotocraftMcp::live(config(&dir))).await; + let r = call(&client, "ui_inspect", json!({})).await; + assert!(text(&r).contains("bridge"), "UI tools need the open app: {}", text(&r)); + let r = call(&client, "command_list", json!({})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + assert_eq!(launches.load(Ordering::SeqCst), 0); + client.cancel().await.unwrap(); + + // The ArtCraft Launcher's switch is the consent: the app is started on it alone. + let mut c = config(&dir); + c.allowed = |_| true; + let client = connect(PhotocraftMcp::live(c)).await; + let r = call(&client, "ui_inspect", json!({})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + assert_eq!(launches.load(Ordering::SeqCst), 1); + client.cancel().await.unwrap(); + for app in apps.lock().unwrap().drain(..) { + quit(app); + } + launches.store(0, Ordering::SeqCst); + + prefs(&dir, json!({"connectAgents": true})); + let client = connect(PhotocraftMcp::live(config(&dir))).await; + // Two calls at once start one app. + let (a, b) = tokio::join!(call(&client, "ui_inspect", json!({})), call(&client, "ui_inspect", json!({}))); + for r in [a, b] { + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + assert!(text(&r).contains("launched")); + } + assert_eq!(launches.load(Ordering::SeqCst), 1); + client.cancel().await.unwrap(); + for app in apps.lock().unwrap().drain(..) { + quit(app); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_launch_that_never_listens_times_out_with_advice() { + let dir = settings_dir("timeout"); + prefs(&dir, json!({"connectAgents": true})); + let mut c = live(&dir, Some(WhenAppClosed::Launch)); + c.launch_timeout = Duration::from_millis(600); + c.launch = Some(Box::new(|| Ok(()))); + let client = connect(PhotocraftMcp::live(c)).await; + let r = call(&client, "ui_inspect", json!({})).await; + assert_eq!(r.is_error, Some(true)); + assert!(text(&r).contains("didn't accept agents"), "{}", text(&r)); + // A launcher that fails says so. + let mut c = live(&dir, Some(WhenAppClosed::Launch)); + c.launch = Some(Box::new(|| Err("no such file".into()))); + let client2 = connect(PhotocraftMcp::live(c)).await; + let r = call(&client2, "ui_inspect", json!({})).await; + assert!(text(&r).contains("couldn't start PhotoCraft: no such file"), "{}", text(&r)); + // No launcher (Flatpak, the app not installed beside the CLI): ask the user. + let client3 = connect(PhotocraftMcp::live(live(&dir, Some(WhenAppClosed::Launch)))).await; + let r = call(&client3, "ui_inspect", json!({})).await; + assert!(text(&r).contains("open PhotoCraft"), "{}", text(&r)); + for c in [client, client2, client3] { + c.cancel().await.unwrap(); + } + let _ = std::fs::remove_dir_all(&dir); +} + +#[tokio::test(flavor = "multi_thread")] +async fn headless_uses_the_app_folders_and_stays_headless() { + let dir = settings_dir("headless"); + let work = dir.join("work"); + std::fs::create_dir_all(&work).unwrap(); + prefs(&dir, json!({"connectAgents": true, "whenAppClosed": "headless", "writeRoot": work.to_string_lossy()})); + let client = connect(PhotocraftMcp::live(live(&dir, None))).await; + let r = call(&client, "doc_new", json!({"width": 8, "height": 8})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + let r = call(&client, "doc_save", json!({"path": "out.pcraft"})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + assert!(work.join("out.pcraft").exists(), "saved into the app's write folder"); + // No read folder was chosen: reads are refused. + let r = call(&client, "doc_open", json!({"path": "out.pcraft"})).await; + assert_eq!(r.is_error, Some(true)); + // The app starting later doesn't move the documents away from the agent. + let app = fake_app(&dir, "late"); + let r = call(&client, "ui_inspect", json!({})).await; + assert!(text(&r).contains("bridge"), "UI tools stay unavailable in the headless session: {}", text(&r)); + let r = call(&client, "session_list", json!({})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + client.cancel().await.unwrap(); + quit(app); + // A folder that doesn't exist is a clear error, not a crash. + prefs(&dir, json!({"connectAgents": true, "whenAppClosed": "headless", "readRoot": dir.join("missing").to_string_lossy()})); + std::fs::remove_file(dir.join(agent_link::CONNECTION_FILE)).unwrap(); + let client = connect(PhotocraftMcp::live(live(&dir, None))).await; + let r = call(&client, "command_list", json!({})).await; + assert_eq!(r.is_error, Some(true)); + assert!(text(&r).contains("agent folders"), "{}", text(&r)); + client.cancel().await.unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Agents allowed, app closed, headless: a root flag given to `mcp` replaces the app's folder for +/// its own direction only; the other direction still falls back to the app's folder. +#[tokio::test(flavor = "multi_thread")] +async fn headless_root_flags_override_each_direction_on_their_own() { + let dir = settings_dir("headless-override"); + let (app_read, app_write, given) = (dir.join("app-read"), dir.join("app-write"), dir.join("given")); + for d in [&app_read, &app_write, &given] { + std::fs::create_dir_all(d).unwrap(); + } + prefs(&dir, json!({"connectAgents": true, "whenAppClosed": "headless", "readRoot": app_read.to_string_lossy(), "writeRoot": app_write.to_string_lossy()})); + // Only the write root is given: saves go there, reads still come from the app's read folder. + let mut c = live(&dir, None); + c.write_root = Some(given.clone()); + let client = connect(PhotocraftMcp::live(c)).await; + let r = call(&client, "doc_new", json!({"width": 8, "height": 8})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + let r = call(&client, "doc_save", json!({"path": "out.pcraft"})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + assert!(given.join("out.pcraft").exists(), "saved into the given write root"); + assert!(!app_write.join("out.pcraft").exists(), "not into the app's write folder"); + std::fs::copy(given.join("out.pcraft"), app_read.join("in.pcraft")).unwrap(); + let r = call(&client, "doc_open", json!({"path": app_read.join("in.pcraft").to_string_lossy()})).await; + assert_eq!(r.is_error, Some(false), "the app's read folder still applies: {}", text(&r)); + client.cancel().await.unwrap(); + // Only a read root is given: it replaces the app's read folder; saves still go to the app's write folder. + let mut c = live(&dir, None); + c.read_roots = vec![given.clone()]; + let client = connect(PhotocraftMcp::live(c)).await; + let r = call(&client, "doc_open", json!({"path": app_read.join("in.pcraft").to_string_lossy()})).await; + assert_eq!(r.is_error, Some(true), "the app's read folder is replaced by the given one"); + let r = call(&client, "doc_open", json!({"path": given.join("out.pcraft").to_string_lossy()})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + let r = call(&client, "doc_save", json!({"path": "again.pcraft"})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + assert!(app_write.join("again.pcraft").exists(), "saved into the app's write folder"); + client.cancel().await.unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Agents not allowed: `mcp` serves a session without a window as it always did, with only the +/// folders given to the command (the app's own folders are for agents the person let in), never +/// starts the app, and prepares the session as the command asked (`--gpu`). +#[tokio::test(flavor = "multi_thread")] +async fn without_consent_mcp_is_headless_with_its_own_folders() { + static PREPARED: AtomicUsize = AtomicUsize::new(0); + let dir = settings_dir("no-consent"); + let (app_folder, given) = (dir.join("app-folder"), dir.join("given")); + std::fs::create_dir_all(&app_folder).unwrap(); + std::fs::create_dir_all(&given).unwrap(); + prefs(&dir, json!({"whenAppClosed": "launch", "writeRoot": app_folder.to_string_lossy()})); + let launches = Arc::new(AtomicUsize::new(0)); + let config = |write_root: Option| { + let mut c = live(&dir, None); + c.write_root = write_root; + let launches = launches.clone(); + c.launch = Some(Box::new(move || { + launches.fetch_add(1, Ordering::SeqCst); + Ok(()) + })); + c.prepare_headless = Some(Box::new(|_| { + PREPARED.fetch_add(1, Ordering::SeqCst); + })); + c + }; + let client = connect(PhotocraftMcp::live(config(None))).await; + let r = call(&client, "doc_new", json!({"width": 8, "height": 8})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + let r = call(&client, "doc_save", json!({"path": "out.pcraft"})).await; + assert_eq!(r.is_error, Some(true), "the app's folder isn't granted without consent"); + assert!(!app_folder.join("out.pcraft").exists()); + client.cancel().await.unwrap(); + let client = connect(PhotocraftMcp::live(config(Some(given.clone())))).await; + call(&client, "doc_new", json!({"width": 8, "height": 8})).await; + let r = call(&client, "doc_save", json!({"path": "out.pcraft"})).await; + assert_eq!(r.is_error, Some(false), "{}", text(&r)); + assert!(given.join("out.pcraft").exists(), "the command's own root is used"); + client.cancel().await.unwrap(); + assert_eq!(launches.load(Ordering::SeqCst), 0, "never started without consent"); + assert_eq!(PREPARED.load(Ordering::SeqCst), 2, "each headless session is prepared once"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/cms/src/gamut.rs b/crates/cms/src/gamut.rs index 8b1abe1dd3..94818dddb8 100644 --- a/crates/cms/src/gamut.rs +++ b/crates/cms/src/gamut.rs @@ -2,13 +2,18 @@ use crate::clut::Clut; use crate::pipeline::{Pipeline, Stage}; -use crate::profile::Profile; +use crate::profile::{ColorSpace, Profile}; use crate::transform::link_stages; use crate::{CmsError, Intent}; /// Default ΔE76 threshold above which a colour counts as out of gamut. pub const DEFAULT_THRESHOLD: f32 = 4.0; +#[cfg(not(target_arch = "wasm32"))] +const PAR_MIN_PIXELS: usize = 16 * 1024; +#[cfg(not(target_arch = "wasm32"))] +const PAR_CHUNK_PIXELS: usize = 16 * 1024; + /// Precomputed out-of-gamut test for colours of `src` against `proof`. /// /// A colour is out of gamut when sending it to the proof device (relative colorimetric, @@ -17,6 +22,7 @@ pub const DEFAULT_THRESHOLD: f32 = 4.0; #[derive(Debug)] pub struct GamutCheck { inputs: usize, + source_space: ColorSpace, grid: Option, exact: (Pipeline, Pipeline), pub threshold: f32, @@ -44,7 +50,7 @@ impl GamutCheck { 4 => Some(Clut::sample(vec![17; 4], 1, de)), _ => None, }; - Ok(GamutCheck { inputs: n, grid, exact: (direct, via), threshold }) + Ok(GamutCheck { inputs: n, source_space: src.color_space, grid, exact: (direct, via), threshold }) } pub fn inputs(&self) -> usize { @@ -75,4 +81,83 @@ impl GamutCheck { pub fn out_of_gamut(&self, px: &[f32]) -> bool { self.delta_e(px) > self.threshold } + + /// Out-of-gamut mask for RGBA pixels: `255` where the pixel has alpha > 0 and its RGB + /// channels are out of gamut, `0` elsewhere. Returns the number of flagged pixels. Only + /// `min(px.len(), mask.len())` pixels are processed. Runs on the rayon pool (not on wasm); + /// the result is identical to calling [`Self::out_of_gamut`] per pixel. + /// + /// # Errors + /// [`CmsError::Invalid`] when the check was not built from an RGB source profile: an RGBA + /// pixel carries only RGB colour channels, so it cannot be tested against a CMYK, gray or + /// Lab source. Nothing is written to `mask` in that case. + pub fn mask_rgba(&self, px: &[[f32; 4]], mask: &mut [u8]) -> Result { + if self.source_space != ColorSpace::Rgb || self.inputs != 3 { + return Err(CmsError::Invalid(format!("gamut mask needs an RGB source profile, got {:?} with {} channels", self.source_space, self.inputs))); + } + let n = px.len().min(mask.len()); + let (px, mask) = (&px[..n], &mut mask[..n]); + let run = |p: &[[f32; 4]], m: &mut [u8]| { + let mut count = 0; + for (p, m) in p.iter().zip(m.iter_mut()) { + let hit = p[3] > 0.0 && self.out_of_gamut(&p[..3]); + *m = if hit { 255 } else { 0 }; + count += usize::from(hit); + } + count + }; + #[cfg(not(target_arch = "wasm32"))] + if n >= PAR_MIN_PIXELS { + use rayon::prelude::*; + return Ok(px.par_chunks(PAR_CHUNK_PIXELS).zip(mask.par_chunks_mut(PAR_CHUNK_PIXELS)).map(|(p, m)| run(p, m)).sum()); + } + Ok(run(px, mask)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Builtin; + + fn image(n: usize) -> Vec<[f32; 4]> { + let mut s = 0x9E37_79B9u32; + let mut rnd = move || { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + (s >> 8) as f32 / (1u32 << 24) as f32 + }; + // Includes out-of-range values and zero alpha. + (0..n).map(|i| [rnd() * 1.2 - 0.1, rnd(), rnd(), if i % 7 == 0 { 0.0 } else { rnd() }]).collect() + } + + #[test] + fn mask_rgba_matches_per_pixel_check() { + let src = Builtin::Srgb.profile(); + // Sizes straddle the parallel threshold and the chunk size, odd ones included. + for (proof, threshold) in [(Builtin::CoatedCmyk, 4.0), (Builtin::CoatedCmyk, 1.5), (Builtin::GrayGamma22, 4.0), (Builtin::DisplayP3, 0.5)] { + let check = GamutCheck::new(src, proof.profile(), threshold).unwrap(); + for n in [0, 1, 1023, 16 * 1024 - 1, 16 * 1024, 16 * 1024 + 1, 50_001] { + let px = image(n); + let want: Vec = px.iter().map(|p| if p[3] > 0.0 && check.out_of_gamut(&p[..3]) { 255 } else { 0 }).collect(); + let mut got = vec![7u8; n]; + let count = check.mask_rgba(&px, &mut got).unwrap(); + assert_eq!(got, want, "{proof:?} threshold {threshold} n {n}"); + assert_eq!(count, want.iter().filter(|&&m| m == 255).count()); + } + } + } + + #[test] + fn mask_rgba_rejects_non_rgb_source() { + // A CMYK (4-channel), gray (1-channel) and Lab (3-channel, not RGB) source cannot be tested from RGBA pixels. + for src in [Builtin::CoatedCmyk, Builtin::GrayGamma22, Builtin::LabD50] { + let check = GamutCheck::new(src.profile(), Builtin::Srgb.profile(), 4.0).unwrap(); + let px = image(64); + let mut mask = vec![9u8; 64]; + assert!(matches!(check.mask_rgba(&px, &mut mask), Err(CmsError::Invalid(_))), "{src:?}"); + assert!(mask.iter().all(|&m| m == 9), "mask must stay untouched"); + } + } } diff --git a/crates/cms/src/profile.rs b/crates/cms/src/profile.rs index 01b2327df8..89512a0bee 100644 --- a/crates/cms/src/profile.rs +++ b/crates/cms/src/profile.rs @@ -185,6 +185,7 @@ impl Profile { /// Parses ICC profile bytes. pub fn parse(bytes: &[u8]) -> Result { CURVE_SAMPLES_LEFT.with(|left| left.set(MAX_CURVE_SAMPLES)); + CLUT_VALUES_LEFT.with(|left| left.set(MAX_PROFILE_CLUT_VALUES)); let mut p = parse_profile(bytes)?; p.bytes = Some(Arc::new(bytes.to_vec())); Ok(p) @@ -595,6 +596,24 @@ thread_local! { static CURVE_SAMPLES_LEFT: std::cell::Cell = const { std::cell::Cell::new(MAX_CURVE_SAMPLES) }; } +/// CLUT values one profile may decode in all (128 MB of `f32`): the twelve LUT tags can alias +/// one table, and each reference decodes its own copy. +const MAX_PROFILE_CLUT_VALUES: usize = 32 << 20; + +thread_local! { + /// What is left of [`MAX_PROFILE_CLUT_VALUES`] for the profile being parsed on this thread. + static CLUT_VALUES_LEFT: std::cell::Cell = const { std::cell::Cell::new(MAX_PROFILE_CLUT_VALUES) }; +} + +/// Charges `n` decoded CLUT values to the profile being parsed. +fn charge_clut_values(n: usize) -> Result<(), CmsError> { + CLUT_VALUES_LEFT.with(|left| { + let rest = left.get().checked_sub(n).ok_or_else(|| CmsError::Invalid("the profile's lookup tables hold too many values".into()))?; + left.set(rest); + Ok(()) + }) +} + /// Charges `n` decoded curve samples to the profile being parsed. fn charge_curve_samples(n: usize) -> Result<(), CmsError> { CURVE_SAMPLES_LEFT.with(|left| { @@ -698,6 +717,7 @@ fn parse_lut(d: &[u8], a2b: bool) -> Result { return Err(CmsError::Invalid("CLUT too large".into())); } let total = nodes as usize * o; + charge_clut_values(total)?; let s = r.slice(off, total * bps)?; let data: Vec = if wide { s.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]]) as f32 / 65535.0).collect() @@ -803,6 +823,7 @@ fn lut_ab_clut(r: &Reader, off: usize, cin: usize, cout: usize) -> Result = match prec { 1 => r.slice(samples, total)?.iter().map(|b| *b as f32 / 255.0).collect(), @@ -984,6 +1005,22 @@ mod tests { mod curve_budget_tests { use super::*; + #[test] + fn aliased_cluts_are_charged_for_each_decoded_table() { + // A 255³ × 1 CLUT (within one table's limit) referenced by LUT tags three times. + let mut element = vec![255u8, 255, 255]; + element.resize(16, 0); + element.extend([1, 0, 0, 0]); + element.extend(std::iter::repeat_n(0u8, 255 * 255 * 255)); + let r = Reader { b: &element }; + CLUT_VALUES_LEFT.with(|left| left.set(MAX_PROFILE_CLUT_VALUES)); + assert!(lut_ab_clut(&r, 0, 3, 1).is_ok()); + assert!(lut_ab_clut(&r, 0, 3, 1).is_ok()); + assert!(lut_ab_clut(&r, 0, 3, 1).is_err(), "the third decoded copy passes the profile's allowance"); + CLUT_VALUES_LEFT.with(|left| left.set(MAX_PROFILE_CLUT_VALUES)); + assert!(lut_ab_clut(&r, 0, 3, 1).is_ok()); + } + #[test] fn aliased_curves_are_charged_for_each_decoded_table() { // One 1M-sample `curv` element referenced seventeen times decodes 17M samples. diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs index 390e509dce..c86bedc9bd 100644 --- a/crates/cms/src/synth.rs +++ b/crates/cms/src/synth.rs @@ -119,7 +119,7 @@ impl CmykModel { (v + 4.0 * self.tvi[i] * v * (1.0 - v)).clamp(0.0, 1.0) }); let mut s = [0.0; 3]; - for m in 0..16 { + for (m, prim) in self.prim_n.iter().enumerate() { let mut w = 1.0; for (i, ai) in a.iter().enumerate() { w *= if m & (1 << i) != 0 { *ai } else { 1.0 - ai }; @@ -127,7 +127,7 @@ impl CmykModel { if w == 0.0 { continue; } - for (acc, p) in s.iter_mut().zip(&self.prim_n[m]) { + for (acc, p) in s.iter_mut().zip(prim) { *acc += w * p; } } diff --git a/crates/codecs/Cargo.toml b/crates/codecs/Cargo.toml index 9b79605b43..100bbcff57 100644 --- a/crates/codecs/Cargo.toml +++ b/crates/codecs/Cargo.toml @@ -33,6 +33,11 @@ zune-core = "0.5" jpeg-encoder = "0.6" # 12-bit and arithmetic-coded JPEG, which zune-jpeg does not decode. craft-jpeg.workspace = true +craft-raster-codecs.workspace = true +craft-dpx.workspace = true +craft-tga.workspace = true +craft-gif.workspace = true +craft-exr.workspace = true # Pure-Rust modular JPEG XL lossless encoder. zune-jpegxl = { version = "=0.5.2", default-features = false, features = ["std"] } craft-heif = { workspace = true, optional = true } diff --git a/crates/codecs/src/codecs.rs b/crates/codecs/src/codecs.rs index 4c4c22388c..17bafd30a8 100644 --- a/crates/codecs/src/codecs.rs +++ b/crates/codecs/src/codecs.rs @@ -1,20 +1,13 @@ -pub(crate) mod dds; -pub(crate) mod dds_bc; pub(crate) mod deep_exr; -pub(crate) mod dicom; pub(crate) mod dpx; pub(crate) mod exr; pub(crate) mod exr_cryptomatte; -pub(crate) mod fits; pub(crate) mod gif_frames; -pub(crate) mod gif_palette; pub(crate) mod heif; -pub(crate) mod iff; pub(crate) mod jpeg; pub(crate) mod jxl; -pub(crate) mod pcx; pub(crate) mod png; -pub(crate) mod pnm; +mod raster; pub(crate) mod tga; pub(crate) mod tiff; pub(crate) mod tiff_exif; @@ -22,4 +15,4 @@ pub(crate) mod tiff_ifd; pub(crate) mod via_image; pub(crate) mod vp8; pub(crate) mod webp; -pub(crate) mod xpm; +pub(crate) use raster::{dds, dicom, fits, iff, pcx, pnm, xpm}; diff --git a/crates/codecs/src/codecs/dds.rs b/crates/codecs/src/codecs/dds.rs deleted file mode 100644 index 1d220e6ac7..0000000000 --- a/crates/codecs/src/codecs/dds.rs +++ /dev/null @@ -1,556 +0,0 @@ -//! DirectDraw Surface (DDS) textures, after Microsoft's public DDS documentation ("DDS", -//! "DDS_HEADER", "DDS_PIXELFORMAT", "DDS_HEADER_DXT10"). -//! -//! Reading: the top mip level of a 2D texture, either uncompressed (8 to 32 bits per pixel -//! described by channel masks, RGB or luminance) or block-compressed BC1/BC2/BC3 -//! (DXT1/DXT3/DXT5), with or without the DX10 header. Cubemaps, texture arrays and volume -//! textures are refused rather than flattened to one face or slice. -//! -//! Writing: a 2D texture, uncompressed (BGRA or BGRX, luminance with or without alpha) or -//! BC1/BC2/BC3, optionally with its full mip chain. The legacy header describes all of these, -//! so no DX10 header is written; formats only DXGI can name (BC4–BC7, sRGB) aren't written. - -use std::borrow::Cow; - -use super::dds_bc::{self, Block, Mask}; -use crate::SampleType; -use crate::error::CodecError; -use crate::fidelity::Plan; -use crate::format::Format; -use crate::image::{ChannelLayout, Image}; -use crate::options::{DdsCompression, EncodeOptions, Limits}; - -/// `DDS ` plus the 124-byte DDS_HEADER. -const HEADER: usize = 128; -/// DDS_HEADER_DXT10, present when the FourCC is `DX10`. -const DX10_HEADER: usize = 20; - -const DDSD_DEPTH: u32 = 0x80_0000; -const DDPF_ALPHAPIXELS: u32 = 0x1; -const DDPF_FOURCC: u32 = 0x4; -const DDPF_RGB: u32 = 0x40; -const DDPF_LUMINANCE: u32 = 0x2_0000; -const DDSCAPS2_CUBEMAP: u32 = 0x200; -const DDSCAPS2_CUBEMAP_FACES: u32 = 0xfc00; -const DDSCAPS2_VOLUME: u32 = 0x20_0000; -const DIMENSION_TEXTURE2D: u32 = 3; -const MISC_TEXTURECUBE: u32 = 0x4; - -fn bad(reason: impl std::fmt::Display) -> CodecError { - CodecError::malformed(Format::Dds, reason) -} -fn unsupported(reason: impl Into) -> CodecError { - CodecError::unsupported(Format::Dds, reason) -} -fn le32(b: &[u8], at: usize) -> Result { - let bytes = b.get(at..at + 4).and_then(|s| <[u8; 4]>::try_from(s).ok()).ok_or_else(|| bad("truncated header"))?; - Ok(u32::from_le_bytes(bytes)) -} - -/// Header-declared extra subresources cannot survive a single-image rewrite, even without presence flags. -pub(crate) fn has_additional_images(bytes: &[u8]) -> Result { - let depth = le32(bytes, 24)?; - let mips = le32(bytes, 28)?; - let faces = (le32(bytes, 112)? & DDSCAPS2_CUBEMAP_FACES).count_ones(); - let dx10 = le32(bytes, 80)? & DDPF_FOURCC != 0 && bytes.get(84..88) == Some(b"DX10"); - let (cube, array) = if dx10 { (le32(bytes, 136)? & MISC_TEXTURECUBE != 0, le32(bytes, 140)?) } else { (false, 0) }; - Ok(depth > 1 || mips > 1 || faces > 1 || cube || array > 1) -} - -/// A FourCC as text when it is printable, else as the number legacy writers store there. -fn fourcc_name(fourcc: u32) -> String { - let bytes = fourcc.to_le_bytes(); - if bytes.iter().all(|c| c.is_ascii_graphic() || *c == b' ') { bytes.iter().map(|&c| char::from(c)).collect() } else { fourcc.to_string() } -} - -/// One channel of an uncompressed pixel: where it sits and its largest value. -#[derive(Clone, Copy)] -struct Field { - shift: u32, - max: u32, -} - -impl Field { - /// `None` for an empty mask; an error for one with gaps or wider than the pixel. - fn new(mask: u32, bits: u32) -> Result, CodecError> { - if mask == 0 { - return Ok(None); - } - let shift = mask.trailing_zeros(); - let max = mask >> shift; - if max & max.wrapping_add(1) != 0 || (bits < 32 && mask >> bits != 0) { - return Err(bad(format!("channel mask {mask:#x} is not a contiguous field of a {bits}-bit pixel"))); - } - Ok(Some(Field { shift, max })) - } - - fn get(self, pixel: u32) -> u8 { - let v = u64::from((pixel >> self.shift) & self.max); - let max = u64::from(self.max); - ((v * 255 + max / 2) / max) as u8 - } -} - -enum Encoding { - /// Uncompressed: bytes per pixel, then red (or luminance), green, blue and alpha. - Masks { - bytes: usize, - gray: bool, - fields: [Option; 4], - }, - Bc1, - Bc2, - Bc3, -} - -impl Encoding { - fn masks(bits: u32, masks: [u32; 4], gray: bool) -> Result { - if !matches!(bits, 8 | 16 | 24 | 32) { - return Err(bad(format!("{bits} bits per pixel is not 8, 16, 24 or 32"))); - } - let mut fields = [None; 4]; - for (field, mask) in fields.iter_mut().zip(masks) { - *field = Field::new(mask, bits)?; - } - let colour = if gray { fields[0].is_some() } else { fields[..3].iter().any(Option::is_some) }; - if !colour { - return Err(bad("the pixel format has no colour channel masks")); - } - Ok(Encoding::Masks { bytes: bits as usize / 8, gray, fields }) - } - - fn layout(&self) -> ChannelLayout { - match self { - Encoding::Masks { gray: true, fields, .. } if fields[3].is_some() => ChannelLayout::GrayA, - Encoding::Masks { gray: true, .. } => ChannelLayout::Gray, - Encoding::Masks { fields, .. } if fields[3].is_none() => ChannelLayout::Rgb, - _ => ChannelLayout::Rgba, - } - } - - /// Stored row stride and byte size of the top mip level (block rows for BC). - fn level_layout(&self, width: u32, height: u32, pitch: Option) -> Result<(usize, usize), CodecError> { - let overflow = || bad("pixel data size overflow"); - let (w, h) = (usize::try_from(width).map_err(|_| overflow())?, usize::try_from(height).map_err(|_| overflow())?); - let (row_bytes, rows) = match self { - Encoding::Masks { bytes, .. } => { - let packed = w.checked_mul(*bytes).ok_or_else(overflow)?; - let row_bytes = match pitch { - Some(pitch) => usize::try_from(pitch).map_err(|_| overflow())?, - None => packed, - }; - if row_bytes < packed { - return Err(bad(format!("row pitch {row_bytes} is smaller than the {packed}-byte pixel row"))); - } - (row_bytes, h) - } - Encoding::Bc1 | Encoding::Bc2 | Encoding::Bc3 => { - let block = if matches!(self, Encoding::Bc1) { 8 } else { 16 }; - (w.div_ceil(4).checked_mul(block).ok_or_else(overflow)?, h.div_ceil(4)) - } - }; - let size = row_bytes.checked_mul(rows).ok_or_else(overflow)?; - Ok((row_bytes, size)) - } -} - -/// The legacy pixel format: a FourCC, or channel masks. -fn legacy_encoding(b: &[u8]) -> Result { - let (flags, fourcc, bits) = (le32(b, 80)?, le32(b, 84)?, le32(b, 88)?); - let alpha = if flags & DDPF_ALPHAPIXELS != 0 { le32(b, 104)? } else { 0 }; - if flags & DDPF_FOURCC != 0 { - return match &fourcc.to_le_bytes() { - b"DXT1" => Ok(Encoding::Bc1), - b"DXT3" => Ok(Encoding::Bc2), - b"DXT5" => Ok(Encoding::Bc3), - b"DXT2" | b"DXT4" => Err(unsupported("premultiplied-alpha DXT2/DXT4 textures are not supported")), - _ => Err(unsupported(format!("compression `{}` is not supported (DXT1, DXT3 and DXT5 are)", fourcc_name(fourcc)))), - }; - } - if flags & DDPF_RGB != 0 { - return Encoding::masks(bits, [le32(b, 92)?, le32(b, 96)?, le32(b, 100)?, alpha], false); - } - if flags & DDPF_LUMINANCE != 0 { - return Encoding::masks(bits, [le32(b, 92)?, 0, 0, alpha], true); - } - Err(unsupported(format!("pixel format flags {flags:#x} are not RGB, luminance or a supported compression"))) -} - -/// The DX10 header's DXGI format, refusing anything but a single 2D texture. -fn dx10_encoding(b: &[u8]) -> Result { - let (dxgi, dimension, misc, array) = (le32(b, HEADER)?, le32(b, HEADER + 4)?, le32(b, HEADER + 8)?, le32(b, HEADER + 12)?); - if misc & MISC_TEXTURECUBE != 0 { - return Err(unsupported("cubemaps are not supported")); - } - if dimension != DIMENSION_TEXTURE2D { - return Err(unsupported(format!("only 2D textures are supported (resource dimension {dimension})"))); - } - if array > 1 { - return Err(unsupported(format!("texture arrays are not supported ({array} textures)"))); - } - const RGBA: [u32; 4] = [0xff, 0xff00, 0xff_0000, 0xff00_0000]; - const BGRA: [u32; 4] = [0xff_0000, 0xff00, 0xff, 0xff00_0000]; - const BGRX: [u32; 4] = [0xff_0000, 0xff00, 0xff, 0]; - match dxgi { - 27..=29 => Encoding::masks(32, RGBA, false), - 87 | 90 | 91 => Encoding::masks(32, BGRA, false), - 88 | 92 | 93 => Encoding::masks(32, BGRX, false), - 70..=72 => Ok(Encoding::Bc1), - 73..=75 => Ok(Encoding::Bc2), - 76..=78 => Ok(Encoding::Bc3), - _ => Err(unsupported(format!("DXGI format {dxgi} is not supported (BC1, BC2, BC3 and 8-bit RGBA or BGRA are)"))), - } -} - -pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { - if !b.starts_with(b"DDS ") { - return Err(bad("missing the `DDS ` signature")); - } - if le32(b, 4)? != 124 { - return Err(bad("header size is not 124")); - } - let (flags, height, width, depth, caps2) = (le32(b, 8)?, le32(b, 12)?, le32(b, 16)?, le32(b, 24)?, le32(b, 112)?); - if caps2 & DDSCAPS2_CUBEMAP != 0 { - return Err(unsupported("cubemaps are not supported")); - } - if caps2 & DDSCAPS2_VOLUME != 0 || (flags & DDSD_DEPTH != 0 && depth > 1) { - return Err(unsupported("volume textures are not supported")); - } - let dx10 = le32(b, 80)? & DDPF_FOURCC != 0 && &le32(b, 84)?.to_le_bytes() == b"DX10"; - let (encoding, start) = if dx10 { (dx10_encoding(b)?, HEADER + DX10_HEADER) } else { (legacy_encoding(b)?, HEADER) }; - let layout = encoding.layout(); - limits.check(width, height, layout, SampleType::U8)?; - // The same header field is a total level size for BC, but a row stride when DDSD_PITCH is set. - let pitch = if flags & DDSD_PITCH != 0 { Some(le32(b, 20)?) } else { None }; - let (row_pitch, size) = encoding.level_layout(width, height, pitch)?; - let data = b.get(start..).and_then(|d| d.get(..size)).ok_or_else(|| bad(format!("truncated pixel data: {size} bytes needed")))?; - let (w, h) = (width as usize, height as usize); - let channels = layout.channels(); - let row_size = w.checked_mul(channels).ok_or_else(|| bad("pixel size overflow"))?; - let total = row_size.checked_mul(h).ok_or_else(|| bad("pixel size overflow"))?; - let mut pixels = vec![0u8; total]; - match encoding { - Encoding::Masks { bytes, gray, fields } => { - for (src_row, dst_row) in data.chunks_exact(row_pitch).zip(pixels.chunks_exact_mut(row_size)) { - // Stop at the output width, leaving any stored row padding unread. - for (src, dst) in src_row.chunks_exact(bytes).zip(dst_row.chunks_exact_mut(channels)) { - let pixel = src.iter().rev().fold(0u32, |v, &byte| v << 8 | u32::from(byte)); - let channel = |i: usize| fields[i].map_or(0, |f| f.get(pixel)); - let values = if gray { [channel(0), channel(3), 0, 0] } else { [channel(0), channel(1), channel(2), channel(3)] }; - dst.copy_from_slice(&values[..channels]); - } - } - } - Encoding::Bc1 | Encoding::Bc2 | Encoding::Bc3 => { - let block_size = if matches!(encoding, Encoding::Bc1) { 8 } else { 16 }; - let blocks_x = w.div_ceil(4); - for (i, block) in data.chunks_exact(block_size).enumerate() { - let texels = match encoding { - Encoding::Bc1 => bc1(block, true), - Encoding::Bc2 => with_alpha(bc1(block.get(8..).unwrap_or_default(), false), bc2_alpha(block)), - _ => with_alpha(bc1(block.get(8..).unwrap_or_default(), false), bc3_alpha(block)), - }; - let (bx, by) = ((i % blocks_x) * 4, (i / blocks_x) * 4); - for (t, texel) in texels.iter().enumerate() { - let (x, y) = (bx + t % 4, by + t / 4); - if x < w && y < h { - let at = (y * w + x) * 4; - if let Some(dst) = pixels.get_mut(at..at + 4) { - dst.copy_from_slice(texel); - } - } - } - } - } - } - Image::from_u8(width, height, layout, pixels) -} - -/// A BC1 colour block. BC2 and BC3 colour blocks always have four colours; only BC1's -/// `c0 <= c1` order selects three colours and transparent black. -fn bc1(block: &[u8], one_bit_alpha: bool) -> [[u8; 4]; 16] { - let byte = |i: usize| block.get(i).copied().unwrap_or(0); - let (c0, c1) = (u16::from_le_bytes([byte(0), byte(1)]), u16::from_le_bytes([byte(2), byte(3)])); - let palette = dds_bc::colour_palette(c0, c1, c0 > c1 || !one_bit_alpha); - let indices = u32::from_le_bytes([byte(4), byte(5), byte(6), byte(7)]); - std::array::from_fn(|t| palette[(indices >> (2 * t)) as usize & 3]) -} - -/// BC2: four explicit bits of alpha per texel. -fn bc2_alpha(block: &[u8]) -> [u8; 16] { - let bits = u64::from_le_bytes(std::array::from_fn(|i| block.get(i).copied().unwrap_or(0))); - std::array::from_fn(|t| ((bits >> (4 * t)) & 0xf) as u8 * 17) -} - -/// BC3: two alpha endpoints and a 3-bit index per texel into eight values, or into six plus -/// 0 and 255 when `a0 <= a1`. -fn bc3_alpha(block: &[u8]) -> [u8; 16] { - let byte = |i: usize| block.get(i).copied().unwrap_or(0); - let palette = dds_bc::alpha_palette(byte(0), byte(1)); - let bits = u64::from_le_bytes([byte(2), byte(3), byte(4), byte(5), byte(6), byte(7), 0, 0]); - std::array::from_fn(|t| palette[((bits >> (3 * t)) & 7) as usize]) -} - -fn with_alpha(mut texels: [[u8; 4]; 16], alpha: [u8; 16]) -> [[u8; 4]; 16] { - for (texel, a) in texels.iter_mut().zip(alpha) { - texel[3] = a; - } - texels -} - -const DDSD_CAPS: u32 = 0x1; -const DDSD_HEIGHT: u32 = 0x2; -const DDSD_WIDTH: u32 = 0x4; -const DDSD_PITCH: u32 = 0x8; -const DDSD_PIXELFORMAT: u32 = 0x1000; -const DDSD_MIPMAPCOUNT: u32 = 0x2_0000; -const DDSD_LINEARSIZE: u32 = 0x8_0000; -const DDSCAPS_COMPLEX: u32 = 0x8; -const DDSCAPS_TEXTURE: u32 = 0x1000; -const DDSCAPS_MIPMAP: u32 = 0x40_0000; - -fn encode_err(reason: impl std::fmt::Display) -> CodecError { - CodecError::encode(Format::Dds, reason) -} - -/// How a written texture stores its pixels. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Store { - /// 8-bit luminance. - Luminance, - /// 8-bit luminance, then 8-bit alpha. - LuminanceAlpha, - /// Blue, green, red and an unused byte (written as 255, so a reader that takes it for - /// alpha still sees an opaque texture). - Bgrx, - Bgra, - Bc1, - Bc2, - Bc3, -} - -impl Store { - /// The storage for an image of `layout`, as [`crate::fidelity::plan`] chose it. - fn new(compression: DdsCompression, layout: ChannelLayout) -> Result { - Ok(match (compression, layout) { - (DdsCompression::None, ChannelLayout::Gray) => Store::Luminance, - (DdsCompression::None, ChannelLayout::GrayA) => Store::LuminanceAlpha, - (DdsCompression::None, ChannelLayout::Rgb) => Store::Bgrx, - (DdsCompression::None, ChannelLayout::Rgba) => Store::Bgra, - (DdsCompression::Bc1, ChannelLayout::Rgba) => Store::Bc1, - (DdsCompression::Bc2, ChannelLayout::Rgba) => Store::Bc2, - (DdsCompression::Bc3, ChannelLayout::Rgba) => Store::Bc3, - (_, layout) => return Err(encode_err(format!("{layout:?} pixels can't be written as `{}`", compression.name()))), - }) - } - - /// Bytes per pixel, or per 4×4 block for a block compression. - fn unit(self) -> usize { - match self { - Store::Luminance => 1, - Store::LuminanceAlpha => 2, - Store::Bgrx | Store::Bgra => 4, - Store::Bc1 => 8, - Store::Bc2 | Store::Bc3 => 16, - } - } - - fn is_block(self) -> bool { - matches!(self, Store::Bc1 | Store::Bc2 | Store::Bc3) - } - - /// Bytes of one row of pixels (or of 4×4 blocks) of a level `width` wide. - fn row_bytes(self, width: usize) -> Option { - if self.is_block() { width.div_ceil(4).checked_mul(self.unit()) } else { width.checked_mul(self.unit()) } - } - - fn level_bytes(self, width: usize, height: usize) -> Option { - let rows = if self.is_block() { height.div_ceil(4) } else { height }; - self.row_bytes(width)?.checked_mul(rows) - } - - /// DDS_PIXELFORMAT: flags, FourCC, bits per pixel and the red, green, blue and alpha masks. - fn pixel_format(self) -> (u32, [u8; 4], u32, [u32; 4]) { - match self { - Store::Luminance => (DDPF_LUMINANCE, [0; 4], 8, [0xff, 0, 0, 0]), - Store::LuminanceAlpha => (DDPF_LUMINANCE | DDPF_ALPHAPIXELS, [0; 4], 16, [0xff, 0, 0, 0xff00]), - Store::Bgrx => (DDPF_RGB, [0; 4], 32, [0xff_0000, 0xff00, 0xff, 0]), - Store::Bgra => (DDPF_RGB | DDPF_ALPHAPIXELS, [0; 4], 32, [0xff_0000, 0xff00, 0xff, 0xff00_0000]), - Store::Bc1 => (DDPF_FOURCC, *b"DXT1", 0, [0; 4]), - Store::Bc2 => (DDPF_FOURCC, *b"DXT3", 0, [0; 4]), - Store::Bc3 => (DDPF_FOURCC, *b"DXT5", 0, [0; 4]), - } - } -} - -/// Levels in a full mip chain: the larger side halves down to 1. -fn mip_levels(width: u32, height: u32) -> u32 { - 32 - width.max(height).max(1).leading_zeros() -} - -fn half((w, h): (usize, usize)) -> (usize, usize) { - ((w / 2).max(1), (h / 2).max(1)) -} - -pub(crate) fn encode(image: &Image, plan: Plan, opts: &EncodeOptions) -> Result, CodecError> { - let img = image.converted(plan.layout, SampleType::U8); - let pixels = img.as_u8().ok_or_else(|| encode_err("the image was not converted to 8 bits per channel"))?; - let store = Store::new(opts.dds.compression, img.layout())?; - let (width, height) = img.dimensions(); - let levels = if opts.dds.mipmaps { mip_levels(width, height) } else { 1 }; - let top = (width as usize, height as usize); - // Every level's size, checked before anything is allocated. - let mut sizes = Vec::new(); - let mut size = top; - for _ in 0..levels { - sizes.push(store.level_bytes(size.0, size.1).ok_or_else(|| encode_err("texture size overflow"))?); - size = half(size); - } - let total = sizes.iter().try_fold(HEADER, |total, &s| total.checked_add(s)).ok_or_else(|| encode_err("texture size overflow"))?; - let header = header(width, height, store, levels, sizes.first().copied().unwrap_or(0))?; - let mut out = crate::options::alloc_zeroed::(total)?; - out.get_mut(..HEADER).ok_or_else(|| encode_err("output buffer too small"))?.copy_from_slice(&header); - - let channels = img.layout().channels(); - let mut level = Cow::Borrowed(pixels); - let (mut size, mut at) = (top, HEADER); - for (i, &bytes) in sizes.iter().enumerate() { - let dst = out.get_mut(at..at + bytes).ok_or_else(|| encode_err("output buffer too small"))?; - write_level(store, &level, size, dst)?; - at += bytes; - if i + 1 < sizes.len() { - let next = half(size); - level = Cow::Owned(downsample(&level, size, next, channels)?); - size = next; - } - } - Ok(out) -} - -/// The `DDS ` signature and DDS_HEADER. `top` is the top level's size in bytes. -fn header(width: u32, height: u32, store: Store, levels: u32, top: usize) -> Result<[u8; HEADER], CodecError> { - let mut b = [0u8; HEADER]; - let mut put = |at: usize, v: u32| { - if let Some(d) = b.get_mut(at..at + 4) { - d.copy_from_slice(&v.to_le_bytes()); - } - }; - // Uncompressed: the pitch of one row. Compressed: the whole top level (its "linear size"). - let (size_flag, pitch_or_size) = if store.is_block() { (DDSD_LINEARSIZE, Some(top)) } else { (DDSD_PITCH, store.row_bytes(width as usize)) }; - let pitch_or_size = - pitch_or_size.and_then(|v| u32::try_from(v).ok()).ok_or_else(|| encode_err(format!("a {width}x{height} level is too large for a DDS header")))?; - let mipmapped = levels > 1; - put(4, 124); - put(8, DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | size_flag | if mipmapped { DDSD_MIPMAPCOUNT } else { 0 }); - put(12, height); - put(16, width); - put(20, pitch_or_size); - put(28, levels); - let (flags, fourcc, bits, masks) = store.pixel_format(); - put(76, 32); - put(80, flags); - put(84, u32::from_le_bytes(fourcc)); - put(88, bits); - for (i, mask) in masks.into_iter().enumerate() { - put(92 + 4 * i, mask); - } - put(108, DDSCAPS_TEXTURE | if mipmapped { DDSCAPS_COMPLEX | DDSCAPS_MIPMAP } else { 0 }); - b[..4].copy_from_slice(b"DDS "); - Ok(b) -} - -/// Runs `f` on each `len`-byte row of `out` with its index, in parallel on native targets. -fn rows(out: &mut [u8], len: usize, f: impl Fn(usize, &mut [u8]) + Send + Sync) { - #[cfg(not(target_arch = "wasm32"))] - { - use rayon::prelude::*; - out.par_chunks_mut(len.max(1)).enumerate().for_each(|(i, row)| f(i, row)); - } - #[cfg(target_arch = "wasm32")] - for (i, row) in out.chunks_mut(len.max(1)).enumerate() { - f(i, row); - } -} - -/// Writes one level of `width` × `height` pixels (in the image's layout) into `dst`. -fn write_level(store: Store, pixels: &[u8], (width, height): (usize, usize), dst: &mut [u8]) -> Result<(), CodecError> { - let row_bytes = store.row_bytes(width).ok_or_else(|| encode_err("texture size overflow"))?; - match store { - Store::Luminance | Store::LuminanceAlpha => { - // The image's gray (and alpha) samples, in the same order. - let src = pixels.get(..dst.len()).ok_or_else(|| encode_err("the level is smaller than its size"))?; - dst.copy_from_slice(src); - } - Store::Bgrx | Store::Bgra => { - let channels = if store == Store::Bgra { 4 } else { 3 }; - rows(dst, row_bytes, |y, row| { - let src = pixels.get(y * width * channels..).unwrap_or_default(); - for (d, s) in row.as_chunks_mut::<4>().0.iter_mut().zip(src.chunks_exact(channels)) { - let byte = |i: usize| s.get(i).copied().unwrap_or(255); - *d = [byte(2), byte(1), byte(0), byte(3)]; - } - }); - } - Store::Bc1 | Store::Bc2 | Store::Bc3 => { - let (texels, _) = pixels.as_chunks::<4>(); - rows(dst, row_bytes, |by, row| { - for (bx, d) in row.chunks_exact_mut(store.unit()).enumerate() { - let (block, inside) = gather(texels, (width, height), bx, by); - let encoded: &[u8] = match store { - Store::Bc1 => &dds_bc::encode_bc1(&block, inside), - Store::Bc2 => &dds_bc::encode_bc2(&block, inside), - _ => &dds_bc::encode_bc3(&block, inside), - }; - for (d, s) in d.iter_mut().zip(encoded) { - *d = *s; - } - } - }); - } - } - Ok(()) -} - -/// Block (`bx`, `by`)'s texels, and which of them lie inside the image. -fn gather(texels: &[[u8; 4]], (width, height): (usize, usize), bx: usize, by: usize) -> (Block, Mask) { - let mut block = [[0u8; 4]; 16]; - let mut inside: Mask = 0; - for (t, texel) in block.iter_mut().enumerate() { - let (x, y) = (bx * 4 + t % 4, by * 4 + t / 4); - if x < width - && y < height - && let Some(p) = texels.get(y * width + x) - { - *texel = *p; - inside |= 1 << t; - } - } - (block, inside) -} - -/// The next mip level: each pixel the average of the 2×2 pixels it covers, or of 2×3, 3×2 or -/// 3×3 along the last column and row of an odd-sized level, so no pixel is dropped. -fn downsample(src: &[u8], (w, h): (usize, usize), (nw, nh): (usize, usize), channels: usize) -> Result, CodecError> { - let len = nw.checked_mul(nh).and_then(|n| n.checked_mul(channels)).ok_or_else(|| encode_err("mip level size overflow"))?; - let mut dst = crate::options::alloc_zeroed::(len)?; - let span = |i: usize, n: usize, size: usize| 2 * i..=if i + 1 == n { size.saturating_sub(1) } else { 2 * i + 1 }; - rows(&mut dst, nw * channels, |y, row| { - let ys = span(y, nh, h); - for (x, px) in row.chunks_exact_mut(channels.max(1)).enumerate() { - let xs = span(x, nw, w); - for (c, v) in px.iter_mut().enumerate() { - let (mut sum, mut n) = (0u32, 0u32); - for sy in ys.clone() { - for sx in xs.clone() { - if let Some(&s) = src.get((sy * w + sx) * channels + c) { - sum += u32::from(s); - n += 1; - } - } - } - *v = ((sum + n / 2) / n.max(1)) as u8; - } - } - }); - Ok(dst) -} diff --git a/crates/codecs/src/codecs/dds_bc.rs b/crates/codecs/src/codecs/dds_bc.rs deleted file mode 100644 index bbd55b4bf3..0000000000 --- a/crates/codecs/src/codecs/dds_bc.rs +++ /dev/null @@ -1,368 +0,0 @@ -//! BC1, BC2 and BC3 (DXT1, DXT3, DXT5) blocks, after Microsoft's public block compression -//! documentation ("Block Compression (Direct3D 10)" and "Texture Block Compression in Direct3D -//! 11"): the palettes the DDS reader decodes with, and the block encoder the DDS writer uses. -//! -//! The encoder fits a block's colours with two RGB565 endpoints along their principal axis, -//! refines them by least squares, and scores every candidate against the exact palette the -//! reader rebuilds, so the indices it picks are the best ones for what a decoder shows. - -/// The 16 texels of a 4×4 block, row by row, as RGBA. -pub(crate) type Block = [[u8; 4]; 16]; - -/// Bit `t` set for each texel `t` of a block that counts: edge blocks of a texture whose size is -/// not a multiple of four have texels outside the image. -pub(crate) type Mask = u16; - -pub(crate) fn rgb565(c: u16) -> [u8; 3] { - let scale = |v: u16, max: u16| ((u32::from(v) * 255 + u32::from(max) / 2) / u32::from(max)) as u8; - [scale(c >> 11, 31), scale((c >> 5) & 63, 63), scale(c & 31, 31)] -} - -/// The colours a colour block's indices select. Four-colour mode (BC1 with `c0 > c1`, and every -/// BC2 and BC3 block) adds two colours at thirds; three-colour mode adds the midpoint and -/// transparent black. -pub(crate) fn colour_palette(c0: u16, c1: u16, four: bool) -> [[u8; 4]; 4] { - let (a, b) = (rgb565(c0), rgb565(c1)); - let mix = |wa: u32, wb: u32| { - let d = wa + wb; - let at = |i: usize| ((wa * u32::from(a[i]) + wb * u32::from(b[i]) + d / 2) / d) as u8; - [at(0), at(1), at(2), 255] - }; - if four { - [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(2, 1), mix(1, 2)] - } else { - [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(1, 1), [0; 4]] - } -} - -/// A BC3 alpha block's eight values: six interpolated at sevenths when `a0 > a1`, else four -/// interpolated at fifths followed by 0 and 255. -pub(crate) fn alpha_palette(a0: u8, a1: u8) -> [u8; 8] { - let (a0, a1) = (u32::from(a0), u32::from(a1)); - let mut palette = [a0, a1, 0, 0, 0, 0, 0, 255]; - if a0 > a1 { - for (k, v) in palette.iter_mut().enumerate().skip(2) { - let k = k as u32; - *v = ((8 - k) * a0 + (k - 1) * a1 + 3) / 7; - } - } else { - for (k, v) in palette.iter_mut().enumerate().take(6).skip(2) { - let k = k as u32; - *v = ((6 - k) * a0 + (k - 1) * a1 + 2) / 5; - } - } - palette.map(|v| v as u8) -} - -/// A BC1 block. Texels under half opacity become BC1's transparent black, which needs the -/// three-colour mode; an opaque block takes whichever mode fits its colours better. -pub(crate) fn encode_bc1(block: &Block, inside: Mask) -> [u8; 8] { - let transparent = select(block, inside, |t| t[3] < 128); - colour_block(block, inside & !transparent, transparent, true) -} - -/// A BC2 block: four bits of alpha per texel, then a four-colour block. -pub(crate) fn encode_bc2(block: &Block, inside: Mask) -> [u8; 16] { - let bits = block.iter().enumerate().fold(0u64, |bits, (t, texel)| bits | ((u64::from(texel[3]) * 15 + 127) / 255) << (4 * t)); - join(bits.to_le_bytes(), colour_block(block, inside, 0, false)) -} - -/// A BC3 block: an interpolated alpha block, then a four-colour block. -pub(crate) fn encode_bc3(block: &Block, inside: Mask) -> [u8; 16] { - join(alpha_block(block, inside), colour_block(block, inside, 0, false)) -} - -fn join(a: [u8; 8], b: [u8; 8]) -> [u8; 16] { - std::array::from_fn(|i| if i < 8 { a.get(i) } else { b.get(i - 8) }.copied().unwrap_or(0)) -} - -/// The texels of `inside` for which `f` holds. -fn select(block: &Block, inside: Mask, f: impl Fn(&[u8; 4]) -> bool) -> Mask { - block.iter().enumerate().filter(|(t, texel)| inside >> t & 1 != 0 && f(texel)).fold(0, |m, (t, _)| m | 1 << t) -} - -fn rgb_of(texel: &[u8; 4]) -> [f32; 3] { - [f32::from(texel[0]), f32::from(texel[1]), f32::from(texel[2])] -} - -/// RGB565 of a colour, rounding each channel to the nearest level. -fn to565(c: [f32; 3]) -> u16 { - let q = |v: f32, max: f32| (v.clamp(0.0, 255.0) * max / 255.0).round() as u16; - q(c[0], 31.0) << 11 | q(c[1], 63.0) << 5 | q(c[2], 31.0) -} - -fn distance(a: &[u8; 4], b: &[u8; 4]) -> u32 { - (0..3).map(|i| u32::from(a[i].abs_diff(b[i])).pow(2)).sum() -} - -/// A colour block (endpoints, then 2-bit indices) for the `opaque` texels' colours, with the -/// `transparent` ones on BC1's transparent index. `bc1` allows the three-colour mode; BC2 and -/// BC3 always decode four colours. -fn colour_block(block: &Block, opaque: Mask, transparent: Mask, bc1: bool) -> [u8; 8] { - let colours: Vec<[f32; 3]> = block.iter().enumerate().filter(|(t, _)| opaque >> t & 1 != 0).map(|(_, texel)| rgb_of(texel)).collect(); - if colours.is_empty() { - // Nothing visible: every texel on the transparent index (or index 0 of black). - let indices = if transparent != 0 { u32::MAX } else { 0 }; - return pack(0, 0, indices); - } - let (lo, hi) = principal_endpoints(&colours); - let mut candidates = vec![(to565(lo), to565(hi))]; - let modes: &[bool] = if transparent != 0 { - &[false] - } else if bc1 { - &[true, false] - } else { - &[true] - }; - let mut best: Option<(u32, [u8; 8])> = None; - // Each refinement starts from the best block so far: its indices give the least-squares - // endpoints, which become one more candidate. - for round in 0..3 { - for &(e0, e1) in &candidates { - for &four in modes { - let (bytes, error) = fit(block, opaque, transparent, e0, e1, four); - if best.is_none_or(|(e, _)| error < e) { - best = Some((error, bytes)); - } - } - } - let Some((error, bytes)) = best else { break }; - if error == 0 || round == 2 { - break; - } - candidates = least_squares(block, opaque, &bytes).into_iter().collect(); - if candidates.is_empty() { - break; - } - } - best.map_or([0; 8], |(_, bytes)| bytes) -} - -/// Orders endpoints `e0`, `e1` for the mode (`c0 > c1` for four colours, `c0 <= c1` for three) -/// and picks each texel's nearest palette colour. Returns the block and its squared error. -fn fit(block: &Block, opaque: Mask, transparent: Mask, e0: u16, e1: u16, four: bool) -> ([u8; 8], u32) { - let (c0, c1) = if four == (e0 >= e1) { (e0, e1) } else { (e1, e0) }; - // Equal endpoints can't be in four-colour order; the palette is then one colour either way. - let palette = colour_palette(c0, c1, four && c0 > c1); - let choices = if four && c0 > c1 { 4 } else { 3 }; - let mut indices = 0u32; - let mut error = 0u32; - for (t, texel) in block.iter().enumerate() { - let index = if transparent >> t & 1 != 0 { - 3 - } else if opaque >> t & 1 != 0 { - let (i, d) = palette.iter().take(choices).enumerate().map(|(i, p)| (i, distance(texel, p))).min_by_key(|&(_, d)| d).unwrap_or((0, 0)); - error += d; - i as u32 - } else { - 0 - }; - indices |= index << (2 * t); - } - (pack(c0, c1, indices), error) -} - -fn pack(c0: u16, c1: u16, indices: u32) -> [u8; 8] { - let (c0, c1, i) = (c0.to_le_bytes(), c1.to_le_bytes(), indices.to_le_bytes()); - [c0[0], c0[1], c1[0], c1[1], i[0], i[1], i[2], i[3]] -} - -/// The ends of the colours' spread along their principal axis (the covariance's dominant -/// eigenvector, by power iteration), clamped to the RGB cube. -fn principal_endpoints(colours: &[[f32; 3]]) -> ([f32; 3], [f32; 3]) { - let n = colours.len().max(1) as f32; - let mean = [0, 1, 2].map(|i| colours.iter().map(|c| c[i]).sum::() / n); - let mut cov = [[0f32; 3]; 3]; - for c in colours { - let d = [c[0] - mean[0], c[1] - mean[1], c[2] - mean[2]]; - for (i, row) in cov.iter_mut().enumerate() { - for (j, v) in row.iter_mut().enumerate() { - *v += d[i] * d[j]; - } - } - } - let times = |a: [f32; 3]| [0, 1, 2].map(|i| cov[i][0] * a[0] + cov[i][1] * a[1] + cov[i][2] * a[2]); - let iterate = |start: usize| { - let mut axis = [0f32; 3]; - axis[start] = 1.0; - for _ in 0..8 { - let next = times(axis); - let len = next.iter().map(|v| v * v).sum::().sqrt(); - if !len.is_normal() { - break; - } - axis = next.map(|v| v / len); - } - axis - }; - // From each channel's axis, keeping the one the colours spread along most: a channel that - // varies on its own is already an eigenvector, so a single start there would never leave it - // even when the others vary more together. - let spread = |a: [f32; 3]| times(a).iter().zip(a).map(|(x, y)| x * y).sum::(); - let axis = [0, 1, 2].map(iterate).into_iter().max_by(|&a, &b| spread(a).total_cmp(&spread(b))).unwrap_or([1.0, 0.0, 0.0]); - let along = |c: &[f32; 3]| (c[0] - mean[0]) * axis[0] + (c[1] - mean[1]) * axis[1] + (c[2] - mean[2]) * axis[2]; - let (lo, hi) = colours.iter().map(along).fold((f32::MAX, f32::MIN), |(lo, hi), t| (lo.min(t), hi.max(t))); - let at = |t: f32| [0, 1, 2].map(|i| (mean[i] + t * axis[i]).clamp(0.0, 255.0)); - if lo > hi { (mean, mean) } else { (at(lo), at(hi)) } -} - -/// The endpoints that minimise the squared error for the indices `bytes` already chose: each -/// texel's index fixes its weights between the endpoints, giving 2×2 normal equations per -/// channel. `None` when the indices don't constrain both endpoints. -fn least_squares(block: &Block, opaque: Mask, bytes: &[u8; 8]) -> Option<(u16, u16)> { - let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]])); - let indices = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]); - let four = c0 > c1; - // How much of c0 each index holds. - let weight = |i: u32| match (four, i) { - (_, 0) => Some(1.0f32), - (_, 1) => Some(0.0), - (true, 2) => Some(2.0 / 3.0), - (true, _) => Some(1.0 / 3.0), - (false, 2) => Some(0.5), - (false, _) => None, - }; - let (mut aa, mut ab, mut bb) = (0f32, 0f32, 0f32); - let (mut ax, mut bx) = ([0f32; 3], [0f32; 3]); - for (t, texel) in block.iter().enumerate() { - if opaque >> t & 1 == 0 { - continue; - } - let Some(a) = weight(indices >> (2 * t) & 3) else { continue }; - let b = 1.0 - a; - let c = rgb_of(texel); - aa += a * a; - ab += a * b; - bb += b * b; - for ((x0, x1), v) in ax.iter_mut().zip(bx.iter_mut()).zip(c) { - *x0 += a * v; - *x1 += b * v; - } - } - let det = aa * bb - ab * ab; - if det.abs() < 1e-3 { - return None; - } - let e0 = [0, 1, 2].map(|i| (ax[i] * bb - bx[i] * ab) / det); - let e1 = [0, 1, 2].map(|i| (bx[i] * aa - ax[i] * ab) / det); - Some((to565(e0), to565(e1))) -} - -/// A BC3 alpha block: whichever of the two modes (eight values between the extremes, or six -/// between the extremes other than 0 and 255, plus exact 0 and 255) fits better. -fn alpha_block(block: &Block, inside: Mask) -> [u8; 8] { - let alphas = || block.iter().enumerate().filter(move |(t, _)| inside >> t & 1 != 0).map(|(_, texel)| texel[3]); - let range = |values: &mut dyn Iterator| values.fold(None, |r: Option<(u8, u8)>, a| Some(r.map_or((a, a), |(lo, hi)| (lo.min(a), hi.max(a))))); - let (lo, hi) = range(&mut alphas()).unwrap_or((0, 0)); - // Eight values need a0 > a1; equal ends fall to the six-value mode, which starts with a0 too. - let eight = alpha_fit(block, inside, hi, lo); - let (mid_lo, mid_hi) = range(&mut alphas().filter(|a| !matches!(a, 0 | 255))).unwrap_or((0, 0)); - let six = alpha_fit(block, inside, mid_lo, mid_hi); - if six.1 < eight.1 { six.0 } else { eight.0 } -} - -fn alpha_fit(block: &Block, inside: Mask, a0: u8, a1: u8) -> ([u8; 8], u32) { - let palette = alpha_palette(a0, a1); - let mut bits = 0u64; - let mut error = 0u32; - for (t, texel) in block.iter().enumerate() { - if inside >> t & 1 == 0 { - continue; - } - let (i, d) = palette.iter().enumerate().map(|(i, &p)| (i, u32::from(p.abs_diff(texel[3])).pow(2))).min_by_key(|&(_, d)| d).unwrap_or((0, 0)); - error += d; - bits |= (i as u64) << (3 * t); - } - let b = bits.to_le_bytes(); - ([a0, a1, b[0], b[1], b[2], b[3], b[4], b[5]], error) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn decode_colour(bytes: &[u8; 8], bc1: bool) -> Block { - let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]])); - let palette = colour_palette(c0, c1, c0 > c1 || !bc1); - let indices = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]); - std::array::from_fn(|t| palette[(indices >> (2 * t)) as usize & 3]) - } - - #[test] - fn solid_blocks_land_on_the_nearest_565_colour() { - for colour in [[0, 0, 0, 255], [255, 255, 255, 255], [12, 200, 77, 255]] { - let block = [colour; 16]; - let out = decode_colour(&encode_bc1(&block, u16::MAX), true); - for texel in out { - assert!(texel.iter().zip(colour).all(|(a, b)| a.abs_diff(b) <= 4), "{texel:?} for {colour:?}"); - } - } - } - - #[test] - fn two_colour_blocks_are_exact_when_the_colours_are_565() { - let (a, b) = ([255, 0, 0, 255], [0, 0, 255, 255]); - let block: Block = std::array::from_fn(|t| if t % 3 == 0 { a } else { b }); - for bc1 in [true, false] { - let bytes = if bc1 { encode_bc1(&block, u16::MAX) } else { colour_block(&block, u16::MAX, 0, false) }; - assert_eq!(decode_colour(&bytes, bc1), block); - } - } - - #[test] - fn bc1_punches_through_texels_under_half_alpha() { - let block: Block = std::array::from_fn(|t| if t < 8 { [200, 100, 50, 255] } else { [9, 9, 9, 127] }); - let bytes = encode_bc1(&block, u16::MAX); - let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]])); - assert!(c0 <= c1, "three-colour mode"); - let out = decode_colour(&bytes, true); - assert!(out[..8].iter().all(|t| t[3] == 255) && out[8..].iter().all(|t| *t == [0; 4]), "{out:?}"); - } - - #[test] - fn four_colour_blocks_keep_c0_above_c1() { - // A ramp needs all four colours; BC2 and BC3 blocks must not rely on the order, but - // older decoders read c0 <= c1 as three colours, so the encoder never writes that. - let block: Block = std::array::from_fn(|t| [(t * 16) as u8, 0, 0, 255]); - let bytes = colour_block(&block, u16::MAX, 0, false); - assert!(u16::from_le_bytes([bytes[0], bytes[1]]) > u16::from_le_bytes([bytes[2], bytes[3]])); - } - - #[test] - fn alpha_blocks_pick_the_mode_that_keeps_0_and_255() { - // 0, 255 and a cluster in between: the six-value mode stores 0 and 255 exactly. - let block: Block = std::array::from_fn(|t| [0, 0, 0, [0, 255, 100, 110][t % 4]]); - let bytes = alpha_block(&block, u16::MAX); - assert!(bytes[0] <= bytes[1], "six-value mode"); - let palette = alpha_palette(bytes[0], bytes[1]); - let bits = u64::from_le_bytes([bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], 0, 0]); - for (t, texel) in block.iter().enumerate() { - let got = palette[(bits >> (3 * t)) as usize & 7]; - assert!(got.abs_diff(texel[3]) <= 2, "texel {t}: {got} for {}", texel[3]); - } - } - - #[test] - fn the_principal_axis_is_found_when_one_channel_varies_on_its_own() { - // Red alternates on its own (variance 64); green and blue alternate together (variance 49 - // each, 98 along their shared axis), uncorrelated with red. Starting on red alone would - // keep red's axis and flatten green and blue; the block must do better than its bounding box. - let block: Block = std::array::from_fn(|t| { - let gb = if (t / 2) % 2 == 0 { 121 } else { 135 }; - [if t % 2 == 0 { 120 } else { 136 }, gb, gb, 255] - }); - let error = |bytes: &[u8; 8]| decode_colour(bytes, false).iter().zip(&block).map(|(a, b)| distance(a, b)).sum::(); - let (_, bounding_box) = fit(&block, u16::MAX, 0, to565([120.0, 121.0, 121.0]), to565([136.0, 135.0, 135.0]), true); - let ours = error(&colour_block(&block, u16::MAX, 0, false)); - assert!(ours < bounding_box, "{ours} vs the bounding box's {bounding_box}"); - } - - #[test] - fn texels_outside_the_image_are_ignored() { - // Only the top-left texel is inside: its colour alone decides the endpoints. - let mut block: Block = [[0, 255, 0, 255]; 16]; - block[0] = [255, 0, 255, 255]; - let out = decode_colour(&encode_bc1(&block, 1), true); - assert_eq!(out[0], [255, 0, 255, 255]); - } -} diff --git a/crates/codecs/src/codecs/dicom.rs b/crates/codecs/src/codecs/dicom.rs deleted file mode 100644 index ea2674dae7..0000000000 --- a/crates/codecs/src/codecs/dicom.rs +++ /dev/null @@ -1,517 +0,0 @@ -//! DICOM (medical imaging) reader, uncompressed transfer syntaxes only. -//! -//! Supports what a viewer needs from a single-frame image: MONOCHROME1/2 (gray) and RGB or -//! YBR_FULL, 8- and 16-bit samples, interleaved or planar, both byte orders and explicit or -//! implicit VR. Undefined-length sequences outside the pixel data are skipped (clinical files -//! contain them); compressed transfer syntaxes, encapsulated pixel data and other photometric -//! interpretations are refused with a clear error. Read-only in this crate. - -use std::collections::HashMap; - -use crate::error::CodecError; -use crate::format::Format; -use crate::image::{ChannelLayout, Image, SampleType}; -use crate::options::Limits; - -const F: Format = Format::Dicom; -const PREAMBLE: usize = 132; // 128 zero bytes + "DICM" -const UNDEFINED: u32 = 0xFFFF_FFFF; - -fn bad(msg: impl std::fmt::Display) -> CodecError { - CodecError::malformed(F, msg) -} - -/// A DICOM file begins with a 128-byte preamble and the `DICM` magic. -pub(crate) fn is_dicom(b: &[u8]) -> bool { - b.get(128..132) == Some(b"DICM") -} - -#[derive(Clone, Copy)] -struct Endian { - big: bool, -} - -/// The transfer syntax: byte order and whether value representations are explicit. -#[derive(Clone, Copy)] -struct Syntax { - endian: Endian, - explicit: bool, -} - -/// The value representations whose length field is 2 reserved bytes + `u32` in explicit VR. -fn long_vr(vr: &[u8]) -> bool { - matches!(vr, b"OB" | b"OW" | b"OF" | b"SQ" | b"UT" | b"UN" | b"OD" | b"OL" | b"OV" | b"UC" | b"UR") -} - -/// A cursor over the byte stream. -struct Cur<'a> { - b: &'a [u8], - pos: usize, - big: bool, -} - -impl<'a> Cur<'a> { - fn take(&mut self, n: usize) -> Option<&'a [u8]> { - let s = self.b.get(self.pos..self.pos.checked_add(n)?)?; - self.pos += n; - Some(s) - } - fn u16(&mut self) -> Option { - let c = self.take(2)?; - Some(if self.big { u16::from_be_bytes([c[0], c[1]]) } else { u16::from_le_bytes([c[0], c[1]]) }) - } - fn u32(&mut self) -> Option { - let c = self.take(4)?; - Some(if self.big { u32::from_be_bytes([c[0], c[1], c[2], c[3]]) } else { u32::from_le_bytes([c[0], c[1], c[2], c[3]]) }) - } - /// Skip `len` bytes, refusing to run past the buffer. - fn skip(&mut self, len: usize) -> Result<(), CodecError> { - self.pos = self.pos.checked_add(len).filter(|p| *p <= self.b.len()).ok_or_else(|| bad("a value runs past the end of the file"))?; - Ok(()) - } -} - -/// Read one element's tag and value length, leaving the cursor at the value. Item and delimiter -/// tags (group `FFFE`) carry a `u32` length with no VR even under explicit VR. -fn read_header(c: &mut Cur, syn: &Syntax) -> Result<(u16, u16, [u8; 2], u32), CodecError> { - let group = c.u16().ok_or_else(|| bad("truncated element tag"))?; - let elem = c.u16().ok_or_else(|| bad("truncated element tag"))?; - let (vr, len) = if group == 0xFFFE { - ([0, 0], c.u32().ok_or_else(|| bad("truncated item length"))?) - } else if syn.explicit { - let vr = c.take(2).ok_or_else(|| bad("truncated VR"))?; - let v = [vr[0], vr[1]]; - let len = if long_vr(&v) { - c.take(2).ok_or_else(|| bad("truncated VR"))?; // reserved - c.u32().ok_or_else(|| bad("truncated length"))? - } else { - u32::from(c.u16().ok_or_else(|| bad("truncated length"))?) - }; - (v, len) - } else { - ([0, 0], c.u32().ok_or_else(|| bad("truncated length"))?) - }; - Ok((group, elem, vr, len)) -} - -/// Skip an undefined-length sequence, ending just after its `FFFE,E0DD` delimiter. Nesting is -/// tracked through undefined-length items and nested sequences; everything else is skipped by -/// its length. Returns the position after the delimiter. -fn skip_undefined(c: &mut Cur, syn: &Syntax) -> Result<(), CodecError> { - let mut depth = 1u32; - while depth > 0 { - let (group, elem, _, len) = read_header(c, syn)?; - // Item (E00D) and sequence (E0DD) delimiters close one undefined length; they carry no - // content of their own. - if group == 0xFFFE && matches!(elem, 0xE00D | 0xE0DD) { - depth -= 1; - continue; - } - if len == UNDEFINED { - depth += 1; - } else { - c.skip(len as usize)?; - } - } - Ok(()) -} - -/// Walk the elements from `start`, calling `f` with each `(group, element, value)`. An -/// undefined-length sequence outside the pixel data is skipped; encapsulated (undefined-length) -/// pixel data is refused. Returns the number of bytes walked. -fn elements(b: &[u8], start: usize, syn: &Syntax, mut f: impl FnMut(u16, u16, &Elem) -> Result<(), CodecError>) -> Result { - let mut c = Cur { b, pos: start, big: syn.endian.big }; - loop { - if c.pos >= b.len() { - return Ok(c.pos - start); - } - let (group, elem, vr, len) = read_header(&mut c, syn)?; - if len == UNDEFINED { - if (group, elem) == (0x7FE0, 0x0010) { - return Err(CodecError::unsupported(F, "encapsulated (compressed) pixel data")); - } - skip_undefined(&mut c, syn)?; - continue; - } - let len = len as usize; - let start = c.pos; - if b.len() < start.saturating_add(len) { - return Err(bad("an element value runs past the end of the file")); - } - f(group, elem, &Elem { vr, start, len })?; - c.pos = start + len; - } -} - -/// A parsed element: its VR and the byte range of its value. -struct Elem { - vr: [u8; 2], - start: usize, - len: usize, -} - -fn u16_val(b: &[u8], e: &Elem, big: bool) -> Option { - let c = b.get(e.start..e.start.checked_add(2)?)?; - Some(if big { u16::from_be_bytes([c[0], c[1]]) } else { u16::from_le_bytes([c[0], c[1]]) }) -} - -/// The transfer syntax (byte order and explicit/implicit VR) and the data-set start. The file -/// meta group is always explicit VR little-endian; the data set follows its `(0002,0010)` -/// TransferSyntaxUID. -fn transfer_syntax(b: &[u8]) -> Result<(Syntax, usize), CodecError> { - let meta = Syntax { endian: Endian { big: false }, explicit: true }; - let mut ts: Option = None; - let mut data_start = b.len(); - let mut c = Cur { b, pos: PREAMBLE, big: false }; - while c.pos + 8 <= b.len() { - let save = c.pos; - let (group, elem, _, len) = read_header(&mut c, &meta)?; - if group != 0x0002 { - // A non-meta group begins the data set. - data_start = save; - break; - } - if len == UNDEFINED { - return Err(CodecError::unsupported(F, "undefined-length meta element")); - } - let start = c.pos; - if b.len() < start.saturating_add(len as usize) { - return Err(bad("a meta element runs past the end of the file")); - } - if elem == 0x0010 { - ts = Some(String::from_utf8_lossy(&b[start..start + len as usize]).trim_end_matches(['\0', ' ']).to_string()); - } - c.pos = start + len as usize; - } - let syn = match ts.as_deref() { - Some("1.2.840.10008.1.2") => Syntax { endian: Endian { big: false }, explicit: false }, - Some("1.2.840.10008.1.2.1") => Syntax { endian: Endian { big: false }, explicit: true }, - Some("1.2.840.10008.1.2.2") => Syntax { endian: Endian { big: true }, explicit: true }, - Some(other) => return Err(CodecError::unsupported(F, format!("transfer syntax {other} (only uncompressed is read)"))), - // No meta: the historical default is implicit VR little-endian. - None => Syntax { endian: Endian { big: false }, explicit: false }, - }; - Ok((syn, data_start)) -} - -pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { - if !is_dicom(b) { - return Err(bad("not a DICOM file (no DICM magic)")); - } - let (syn, start) = transfer_syntax(b)?; - let mut tags: HashMap<(u16, u16), Elem> = HashMap::new(); - elements(b, start, &syn, |g, e, el| { - // Later duplicates must not silently override the first (DICOM forbids duplicates). - tags.entry((g, e)).or_insert_with(|| Elem { vr: el.vr, start: el.start, len: el.len }); - Ok(()) - })?; - let big = syn.endian.big; - let get_u16 = |tag: (u16, u16)| tags.get(&tag).and_then(|e| u16_val(b, e, big)); - let rows = u32::from(get_u16((0x0028, 0x0010)).ok_or_else(|| bad("missing Rows (0028,0010)"))?); - let cols = u32::from(get_u16((0x0028, 0x0011)).ok_or_else(|| bad("missing Columns (0028,0011)"))?); - let samples = u32::from(get_u16((0x0028, 0x0002)).unwrap_or(1)); - let bits = get_u16((0x0028, 0x0100)).ok_or_else(|| bad("missing BitsAllocated (0028,0100)"))?; - let bits_stored = get_u16((0x0028, 0x0101)).unwrap_or(bits); - let high_bit = get_u16((0x0028, 0x0102)).unwrap_or(bits_stored.saturating_sub(1)); - if u32::from(high_bit) >= u32::from(bits) { - return Err(bad("HighBit is outside the allocated bits")); - } - let signed = get_u16((0x0028, 0x0103)).unwrap_or(0) == 1; - let planar = get_u16((0x0028, 0x0006)).unwrap_or(0); - let photometric = tags - .get(&(0x0028, 0x0004)) - .and_then(|e| b.get(e.start..e.start.checked_add(e.len)?)) - .map(|v| String::from_utf8_lossy(v).trim_end_matches(['\0', ' ']).to_string()) - .ok_or_else(|| bad("missing PhotometricInterpretation (0028,0004)"))?; - let pixel = tags.get(&(0x7FE0, 0x0010)).ok_or_else(|| CodecError::unsupported(F, "no pixel data (7FE0,0010)"))?; - if !matches!(bits, 8 | 16) || !matches!(bits_stored, 1..=16) { - return Err(CodecError::unsupported(F, format!("{bits}-bit allocated / {bits_stored}-bit stored samples"))); - } - let mono = matches!(photometric.as_str(), "MONOCHROME1" | "MONOCHROME2"); - let rgb = photometric == "RGB"; - let ybr = photometric == "YBR_FULL"; - if !(mono || rgb || ybr) { - return Err(CodecError::unsupported(F, format!("photometric interpretation {photometric}"))); - } - // Mono stores one sample; RGB and YBR_FULL store three. Any other count would index past the - // pixel data, so it is refused rather than misread. - let want_samples = if mono { 1 } else { 3 }; - if samples != want_samples { - return Err(CodecError::unsupported(F, format!("{samples} samples per pixel with {photometric}"))); - } - if ybr && bits != 8 { - return Err(CodecError::unsupported(F, format!("{bits}-bit {photometric} (8-bit only)"))); - } - let layout = if mono { ChannelLayout::Gray } else { ChannelLayout::Rgb }; - let out_sample = if bits == 8 { SampleType::U8 } else { SampleType::U16 }; - limits.check(cols, rows, layout, out_sample)?; - - let pixels = (cols as usize).checked_mul(rows as usize).ok_or_else(|| CodecError::LimitExceeded("image too large".into()))?; - let n = pixels.checked_mul(samples as usize).ok_or_else(|| CodecError::LimitExceeded("image too large".into()))?; - let bytes_per = if bits == 16 { 2usize } else { 1 }; - let need = n.checked_mul(bytes_per).ok_or_else(|| CodecError::LimitExceeded("pixel data too large".into()))?; - let data = b - .get(pixel.start..pixel.start.checked_add(need).ok_or_else(|| CodecError::LimitExceeded("pixel data too large".into()))?) - .ok_or_else(|| bad("pixel data is truncated"))?; - let out_channels = layout.channels(); - let out_len = pixels.checked_mul(out_channels).and_then(|k| k.checked_mul(bytes_per)).ok_or_else(|| CodecError::LimitExceeded("image too large".into()))?; - let mut out = Vec::new(); - out.try_reserve_exact(out_len).map_err(|_| CodecError::LimitExceeded("cannot allocate the image".into()))?; - // Raw sample of channel `ch` at pixel `p`, honouring the planar configuration. - let sample_at = |p: usize, ch: usize| -> Option { - let idx = if planar == 1 { ch.checked_mul(pixels)?.checked_add(p)? } else { p.checked_mul(samples as usize)?.checked_add(ch)? }; - let off = idx.checked_mul(bytes_per)?; - if bits == 16 { - let c = data.get(off..off.checked_add(2)?)?; - Some(if big { u16::from_be_bytes([c[0], c[1]]) } else { u16::from_le_bytes([c[0], c[1]]) }.into()) - } else { - Some(u32::from(*data.get(off)?)) - } - }; - let stored_max = f64::from((1u32 << bits_stored) - 1); - // Extract the `bits_stored` samples (the least significant one at `high_bit`) and scale to - // [0, 1]; signed values are shifted up by half a range first. `high_bit` is 1-based here. - let shift = (u32::from(high_bit) + 1).saturating_sub(u32::from(bits_stored)); - let mask = (1u32 << bits_stored) - 1; - let half = 1u32 << (bits_stored - 1); - let norm = move |raw: u32| -> f64 { - let v = (raw >> shift) & mask; - // Signed: flip the sign bit to map [-2^(b-1), 2^(b-1)-1] onto [0, 2^b-1]. - let v = if signed { v ^ half } else { v }; - (f64::from(v) / stored_max).clamp(0.0, 1.0) - }; - let q = |x: f64| -> u16 { (x * 65535.0).round() as u16 }; - let push = |out: &mut Vec, x: f64| { - if bits == 8 { - out.push((x * 255.0).round() as u8); - } else { - out.extend_from_slice(&q(x).to_ne_bytes()); - } - }; - for p in 0..pixels { - let s = |ch: usize| sample_at(p, ch).ok_or_else(|| bad("pixel data is shorter than the image")); - if mono { - let x = norm(s(0)?); - push(&mut out, if photometric == "MONOCHROME1" { 1.0 - x } else { x }); - } else if rgb { - for ch in 0..3 { - push(&mut out, norm(s(ch)?)); - } - } else { - // YBR_FULL (8-bit): BT.601 full-range to RGB. - let y = f64::from(s(0)?); - let cb = f64::from(s(1)?) - 128.0; - let cr = f64::from(s(2)?) - 128.0; - let r = (y + 1.402 * cr).clamp(0.0, 255.0); - let g = (y - 0.344_136 * cb - 0.714_136 * cr).clamp(0.0, 255.0); - let bl = (y + 1.772 * cb).clamp(0.0, 255.0); - for v in [r, g, bl] { - push(&mut out, v / 255.0); - } - } - } - Image::from_raw(cols, rows, layout, out_sample, out) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Build the file meta group (explicit VR little-endian), including the given extra - /// `(element, ascii)` pairs before the TransferSyntaxUID. - fn meta(b: &mut Vec, ts: &str, extra: &[(u16, &str)]) { - let ui = |e: u16, v: &str, b: &mut Vec| { - let mut s = v.as_bytes().to_vec(); - if s.len() % 2 == 1 { - s.push(0); - } - b.extend_from_slice(&0x0002u16.to_le_bytes()); - b.extend_from_slice(&e.to_le_bytes()); - b.extend_from_slice(b"UI"); - b.extend_from_slice(&(s.len() as u16).to_le_bytes()); - b.extend_from_slice(&s); - }; - for (e, v) in extra { - ui(*e, v, b); - } - ui(0x0010, ts, b); - } - - fn us(b: &mut Vec, g: u16, e: u16, v: u16, explicit: bool) { - b.extend_from_slice(&g.to_le_bytes()); - b.extend_from_slice(&e.to_le_bytes()); - if explicit { - b.extend_from_slice(b"US"); - b.extend_from_slice(&2u16.to_le_bytes()); - } else { - b.extend_from_slice(&2u32.to_le_bytes()); - } - b.extend_from_slice(&v.to_le_bytes()); - } - - fn cs(b: &mut Vec, g: u16, e: u16, v: &str, explicit: bool) { - let mut s = v.as_bytes().to_vec(); - if s.len() % 2 == 1 { - s.push(0); - } - b.extend_from_slice(&g.to_le_bytes()); - b.extend_from_slice(&e.to_le_bytes()); - if explicit { - b.extend_from_slice(b"CS"); - b.extend_from_slice(&(s.len() as u16).to_le_bytes()); - } else { - b.extend_from_slice(&(s.len() as u32).to_le_bytes()); - } - b.extend_from_slice(&s); - } - - /// A DICOM with the given transfer syntax UID and data-set encoding. - #[allow(clippy::too_many_arguments)] - fn synth(ts: &str, explicit: bool, big: bool, planar: u16, rows: u16, cols: u16, samples: u16, bits: u16, photometric: &str, pixels: &[u8]) -> Vec { - let mut b = vec![0u8; 128]; - b.extend_from_slice(b"DICM"); - // One extra meta element before the syntax, so a reader that only looks at the last - // group-0002 element takes the wrong one. - meta(&mut b, ts, &[(0x0002, "1.2.840.10008.5.1.4.1.1.7")]); - let _ = big; - us(&mut b, 0x0028, 0x0010, rows, explicit); - us(&mut b, 0x0028, 0x0011, cols, explicit); - us(&mut b, 0x0028, 0x0002, samples, explicit); - us(&mut b, 0x0028, 0x0006, planar, explicit); - cs(&mut b, 0x0028, 0x0004, photometric, explicit); - us(&mut b, 0x0028, 0x0100, bits, explicit); - us(&mut b, 0x0028, 0x0101, bits, explicit); - us(&mut b, 0x0028, 0x0102, bits - 1, explicit); - us(&mut b, 0x0028, 0x0103, 0, explicit); - b.extend_from_slice(&0x7FE0u16.to_le_bytes()); - b.extend_from_slice(&0x0010u16.to_le_bytes()); - if explicit { - b.extend_from_slice(b"OB"); - b.extend_from_slice(&0u16.to_le_bytes()); - } - b.extend_from_slice(&(pixels.len() as u32).to_le_bytes()); - b.extend_from_slice(pixels); - b - } - - #[test] - fn decodes_8bit_monochrome() { - let b = synth("1.2.840.10008.1.2.1", true, false, 0, 2, 2, 1, 8, "MONOCHROME2", &[0, 51, 102, 255]); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!((img.width(), img.height(), img.layout(), img.sample_type()), (2, 2, ChannelLayout::Gray, SampleType::U8)); - assert_eq!(img.data(), &[0, 51, 102, 255]); - } - - #[test] - fn decodes_16bit_monochrome_and_scales() { - let px: Vec = [0u16, 32768, 65535].iter().flat_map(|v| v.to_le_bytes()).collect(); - let b = synth("1.2.840.10008.1.2.1", true, false, 0, 3, 1, 1, 16, "MONOCHROME2", &px); - let img = decode(&b, &Limits::default()).unwrap(); - let v = img.to_u16_samples().unwrap(); - assert_eq!(v[0], 0); - assert!((i32::from(v[1]) - 32768).abs() <= 1); - assert_eq!(v[2], 65535); - } - - #[test] - fn monochrome1_is_inverted() { - let b = synth("1.2.840.10008.1.2.1", true, false, 0, 2, 1, 1, 8, "MONOCHROME1", &[0, 255]); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.data(), &[255, 0]); - } - - #[test] - fn decodes_rgb_interleaved_and_planar() { - // 2 pixels: (10,20,30) and (40,50,60). - let interleaved = synth("1.2.840.10008.1.2.1", true, false, 0, 1, 2, 3, 8, "RGB", &[10, 20, 30, 40, 50, 60]); - let img = decode(&interleaved, &Limits::default()).unwrap(); - assert_eq!((img.layout(), img.data()), (ChannelLayout::Rgb, &[10u8, 20, 30, 40, 50, 60][..])); - // Planar 0: R plane, then G, then B. - let planar = synth("1.2.840.10008.1.2.1", true, false, 1, 1, 2, 3, 8, "RGB", &[10, 40, 20, 50, 30, 60]); - let img = decode(&planar, &Limits::default()).unwrap(); - assert_eq!(img.data(), &[10, 20, 30, 40, 50, 60]); - } - - #[test] - fn decodes_ybr_full_to_rgb() { - // White (Y=128, Cb=Cr=128) stays neutral grey. - let b = synth("1.2.840.10008.1.2.1", true, false, 0, 1, 1, 3, 8, "YBR_FULL", &[128, 128, 128]); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.layout(), ChannelLayout::Rgb); - let d = img.data(); - assert!(d[0].abs_diff(d[1]) <= 1 && d[1].abs_diff(d[2]) <= 1, "{d:?}"); - } - - #[test] - fn decodes_implicit_vr() { - let b = synth("1.2.840.10008.1.2", false, false, 0, 2, 2, 1, 8, "MONOCHROME2", &[0, 51, 102, 255]); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.layout(), ChannelLayout::Gray); - assert_eq!(img.data(), &[0, 51, 102, 255]); - } - - #[test] - fn skips_an_undefined_length_sequence_outside_the_pixel_data() { - // Insert an undefined-length SQ (0008,2218) with one item, then a defined-length one, - // before the pixel data: the reader must skip both and still decode the image. - let mut b = vec![0u8; 128]; - b.extend_from_slice(b"DICM"); - meta(&mut b, "1.2.840.10008.1.2.1", &[]); - for (g, e, v) in [ - (0x0028, 0x0010, 1u16), - (0x0028, 0x0011, 1), - (0x0028, 0x0002, 1), - (0x0028, 0x0100, 8), - (0x0028, 0x0101, 8), - (0x0028, 0x0102, 7), - (0x0028, 0x0103, 0), - ] { - us(&mut b, g, e, v, true); - } - cs(&mut b, 0x0028, 0x0004, "MONOCHROME2", true); - // Undefined-length sequence (0008,2211), one undefined-length item containing a nested - // defined-length sequence, then the delimiters. - b.extend_from_slice(&[0x08, 0x00, 0x11, 0x22, b'S', b'Q', 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF]); - b.extend_from_slice(&[0xFE, 0xFF, 0x00, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF]); // item, undefined - b.extend_from_slice(&[0x08, 0x00, 0x55, 0x22, b'S', b'Q', 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 1, 2, 3, 4]); // nested, defined - b.extend_from_slice(&[0xFE, 0xFF, 0x0D, 0xE0, 0x00, 0x00, 0x00, 0x00]); // item delimitation - b.extend_from_slice(&[0xFE, 0xFF, 0xDD, 0xE0, 0x00, 0x00, 0x00, 0x00]); // sequence delimitation - // Pixel data (defined length). - b.extend_from_slice(&0x7FE0u16.to_le_bytes()); - b.extend_from_slice(&0x0010u16.to_le_bytes()); - b.extend_from_slice(b"OB"); - b.extend_from_slice(&0u16.to_le_bytes()); - b.extend_from_slice(&1u32.to_le_bytes()); - b.push(200); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.data(), &[200]); - } - - #[test] - fn truncated_and_bad_is_error_not_panic() { - let b = synth("1.2.840.10008.1.2.1", true, false, 0, 2, 2, 1, 8, "MONOCHROME2", &[0, 1, 2, 3]); - for cut in [0, 4, 128, 132, 140, b.len() - 1] { - assert!(decode(&b[..cut.min(b.len())], &Limits::default()).is_err(), "cut {cut}"); - } - assert!(decode(b"not dicom", &Limits::default()).is_err()); - } - - #[test] - fn high_bit_outside_the_allocated_bits_is_an_error_not_a_panic() { - let mut b = synth("1.2.840.10008.1.2.1", true, false, 0, 1, 1, 1, 8, "MONOCHROME2", &[7]); - let tag = [0x28, 0x00, 0x02, 0x01, b'U', b'S', 0x02, 0x00]; - let at = b.windows(tag.len()).position(|w| w == tag).unwrap() + tag.len(); - b[at..at + 2].copy_from_slice(&200u16.to_le_bytes()); - assert!(decode(&b, &Limits::default()).is_err()); - } - - #[test] - fn rejects_compressed_transfer_syntax() { - let mut b = synth("1.2.840.10008.1.2.1", true, false, 0, 1, 1, 1, 8, "MONOCHROME2", &[0]); - let uncompressed = b"1.2.840.10008.1.2.1\0"; - let compressed = b"1.2.840.10008.1.2.4\0"; // same length, a compressed family - let at = b.windows(uncompressed.len()).position(|w| w == uncompressed).expect("transfer syntax in the fixture"); - b[at..at + compressed.len()].copy_from_slice(compressed); - assert!(matches!(decode(&b, &Limits::default()), Err(CodecError::Unsupported { .. }))); - } -} diff --git a/crates/codecs/src/codecs/dpx.rs b/crates/codecs/src/codecs/dpx.rs index 86e4938b0d..734ef41cbd 100644 --- a/crates/codecs/src/codecs/dpx.rs +++ b/crates/codecs/src/codecs/dpx.rs @@ -1,15 +1,8 @@ -//! DPX (SMPTE 268M Digital Picture Exchange), implemented here from the published layout: the -//! 1664-byte generic header (file and image information, image source), the 384-byte industry -//! header (film and television), then the image data of each element. +//! DPX (SMPTE 268M Digital Picture Exchange) and Kodak Cineon (`.cin`): the format code is +//! craft-libs' `craft-dpx`. This maps its frames and header fields onto this crate's image: //! -//! Reading: -//! -//! * Both byte orders: `SDPX` (big-endian) and `XPDS` (little-endian). -//! * The first image element, descriptor 6 (luma), 50 (RGB) or 51 (RGBA), unsigned, without -//! run-length encoding, at 8, 10, 12 or 16 bits. 10-bit samples are packed into 32-bit words -//! (packing 0), or three to a word with the padding bits at the bottom (1, method A) or the -//! top (2, method B); 12-bit samples are packed (0) or one to a 16-bit word in its top bits -//! (1, method A). Lines start on a 32-bit word boundary. +//! * The first image element, luma, RGB or RGBA (ABGR comes back as RGBA). Y'CbCr elements are +//! not converted here and stay unsupported. //! * 8- and 16-bit code values become U8 and U16 samples unchanged; 10- and 12-bit ones become U16 //! as `round(c × 65535 / (2^b − 1))`, so they come back exactly when written at their depth. //! * No colour transform: the transfer characteristic and colorimetric specification are reported @@ -18,11 +11,11 @@ //! * Header fields a pipeline relies on travel as text metadata under the [`KEYS`] names, and a //! DPX export writes them back. //! -//! Writing: one element, big-endian, unencoded, descriptor 6, 50 or 51; 8 and 16 bits with -//! packing 0, 10 and 12 bits with packing 1 (method A). The bit depth follows the image -//! (8 → 8, 16 → 16) unless [`EncodeOptions::dpx_bits`] picks one. -//! -//! Kodak Cineon (`.cin`), the format DPX grew from, is read and written here too (see its section). +//! Writing: one element, big-endian, unencoded, luma, RGB or RGBA; 8 and 16 bits with packing 0, +//! 10 and 12 bits with packing 1 (method A). The bit depth follows the image (8 → 8, 16 → 16) +//! unless [`EncodeOptions::dpx_bits`] picks one. Cineon is written at 10 bits. + +use craft_dpx::{Frame, Info, Kind, Layout}; use crate::Format; use crate::error::CodecError; @@ -31,29 +24,8 @@ use crate::image::{ChannelLayout, DecodeWarning, Image, SampleType}; use crate::options::{DpxBits, EncodeOptions, Limits}; const F: Format = Format::Dpx; -/// Generic plus industry header: where our image data starts. -const HEADER_LEN: usize = 2048; -const GENERIC_LEN: u32 = 1664; -const INDUSTRY_LEN: u32 = 384; -/// "Undefined" for 32-bit fields (also the bit pattern of an undefined float). -const UNDEF32: u32 = u32::MAX; -const UNDEF8: u8 = u8::MAX; -/// Offset of the first image element and the size of one. -const ELEMENT0: usize = 780; -const ELEMENT_LEN: usize = 72; -const MAX_ELEMENTS: u16 = 8; -// Header field offsets (generic file header, image information, film and TV headers). -const CREATION_TIME: (usize, usize) = (136, 24); -const CREATOR: (usize, usize) = (160, 100); -const PROJECT: (usize, usize) = (260, 200); -const COPYRIGHT: (usize, usize) = (460, 200); -const ORIENTATION: usize = 768; -const FRAME_POSITION: usize = 1712; -const FRAME_RATE: usize = 1724; -const TIME_CODE: usize = 1920; - -/// Text metadata keys of the header fields kept through a DPX → document → DPX round trip. +/// Header fields carried as text metadata. pub(crate) const KEY_CREATOR: &str = "DPX:Creator"; pub(crate) const KEY_PROJECT: &str = "DPX:Project"; pub(crate) const KEY_COPYRIGHT: &str = "DPX:Copyright"; @@ -66,473 +38,126 @@ pub(crate) const KEY_TIME_CODE: &str = "DPX:TimeCode"; pub(crate) const KEYS: [&str; 9] = [KEY_CREATOR, KEY_PROJECT, KEY_COPYRIGHT, KEY_CREATION_TIME, KEY_TRANSFER, KEY_COLORIMETRIC, KEY_FRAME_POSITION, KEY_FRAME_RATE, KEY_TIME_CODE]; -fn err(msg: impl std::fmt::Display) -> CodecError { - CodecError::malformed(F, msg) -} - -fn unsupported(msg: impl Into) -> CodecError { - CodecError::unsupported(F, msg) -} - -/// The file's byte order. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Order { - Big, - Little, -} - -impl Order { - fn bytes(b: &[u8], at: usize) -> Option<[u8; N]> { - b.get(at..at.checked_add(N)?)?.try_into().ok() - } - - fn u16(self, b: &[u8], at: usize) -> Option { - let s = Self::bytes::<2>(b, at)?; - Some(if self == Order::Big { u16::from_be_bytes(s) } else { u16::from_le_bytes(s) }) - } - - fn u32(self, b: &[u8], at: usize) -> Option { - let s = Self::bytes::<4>(b, at)?; - Some(if self == Order::Big { u32::from_be_bytes(s) } else { u32::from_le_bytes(s) }) - } - - /// A 32-bit field that may be undefined (all ones). - fn defined_u32(self, b: &[u8], at: usize) -> Option { - self.u32(b, at).filter(|&v| v != UNDEF32) - } - - fn f32(self, b: &[u8], at: usize) -> Option { - self.defined_u32(b, at).map(f32::from_bits).filter(|v| v.is_finite()) +fn err(format: Format, e: craft_dpx::Error) -> CodecError { + match e { + craft_dpx::Error::NotDpx => CodecError::malformed(format, "missing the DPX or Cineon magic number"), + craft_dpx::Error::Malformed(m) => CodecError::malformed(format, m), + craft_dpx::Error::Unsupported(m) => CodecError::unsupported(format, m), + craft_dpx::Error::LimitExceeded(m) => CodecError::LimitExceeded(m.into()), + craft_dpx::Error::Encode(m) => CodecError::encode(format, m), } } -/// The byte order from the magic number, `None` when it is not DPX. -fn order(b: &[u8]) -> Option { - match b.get(..4)? { - b"SDPX" => Some(Order::Big), - b"XPDS" => Some(Order::Little), - _ => None, +fn dpx_limits(l: &Limits) -> craft_dpx::Limits { + let mut out = craft_dpx::Limits::default(); + out.max_pixels = l.max_pixels; + out +} + +/// The header, for a file of `kind`; anything else is malformed. +fn info(bytes: &[u8], kind: Kind) -> Result { + let format = if kind == Kind::Dpx { F } else { Format::Cineon }; + if craft_dpx::sniff(bytes) != Some(kind) { + return Err(CodecError::malformed( + format, + if kind == Kind::Dpx { "missing SDPX/XPDS magic number" } else { "missing the Cineon magic number (802A5FD7)" }, + )); } -} - -/// An ASCII header string: up to the first NUL, printable characters only, trimmed. `None` when -/// empty or undefined (all ones). -fn string(b: &[u8], (at, len): (usize, usize)) -> Option { - let raw = b.get(at..at.checked_add(len)?)?; - let end = raw.iter().position(|&c| c == 0).unwrap_or(raw.len()); - let s: String = raw.get(..end)?.iter().filter(|c| (32..=126).contains(*c)).map(|&c| c as char).collect(); - Some(s.trim().to_string()).filter(|s| !s.is_empty()) -} - -/// The descriptive fields of image element 0 that decoding needs. -#[derive(Debug, Clone, Copy)] -struct Element { - signed: bool, - descriptor: u8, - transfer: u8, - colorimetric: u8, - bits: u8, - packing: u16, - encoding: u16, - data_offset: usize, - eol_padding: usize, -} - -struct Header { - order: Order, - width: u32, - height: u32, - elements: u16, - element: Element, + // The size is checked by the caller, against its own limits. + let mut unlimited = craft_dpx::Limits::default(); + unlimited.max_pixels = u64::MAX; + craft_dpx::probe(bytes, &unlimited).map_err(|e| err(format, e)) } /// The decoder opens only element zero; protect the other declared elements from flat saves. pub(crate) fn has_additional_images(bytes: &[u8]) -> Result { - Ok(parse(bytes)?.elements > 1) + Ok(info(bytes, Kind::Dpx)?.elements > 1) } -fn parse(b: &[u8]) -> Result { - let o = order(b).ok_or_else(|| err("missing SDPX/XPDS magic number"))?; - let missing = |what: &str| err(format!("the header ends before {what}")); - let image_offset = o.u32(b, 4).ok_or_else(|| missing("the image data offset"))?; - o.u16(b, ORIENTATION).ok_or_else(|| missing("the orientation"))?; - let elements = o.u16(b, ORIENTATION + 2).ok_or_else(|| missing("the element count"))?; - if !(1..=MAX_ELEMENTS).contains(&elements) { - return Err(err(format!("invalid number of image elements {elements}"))); - } - let width = o.u32(b, 772).ok_or_else(|| missing("the line length"))?; - let height = o.u32(b, 776).ok_or_else(|| missing("the line count"))?; - let e = ELEMENT0; - let field = |at: usize| o.u32(b, e + at).ok_or_else(|| missing("image element 1")); - let byte = |at: usize| b.get(e + at).copied().ok_or_else(|| missing("image element 1")); - let half = |at: usize| o.u16(b, e + at).ok_or_else(|| missing("image element 1")); - let data_offset = match field(28)? { - 0 | UNDEF32 => image_offset, - v => v, - }; - let eol_padding = match field(32)? { - UNDEF32 => 0, - v => v, - }; - let element = Element { - signed: field(0)? == 1, - descriptor: byte(20)?, - transfer: byte(21)?, - colorimetric: byte(22)?, - bits: byte(23)?, - packing: half(24)?, - encoding: half(26)?, - data_offset: usize::try_from(data_offset).map_err(|_| err("image data offset out of range"))?, - eol_padding: usize::try_from(eol_padding).map_err(|_| err("line padding out of range"))?, - }; - Ok(Header { order: o, width, height, elements, element }) -} - -/// The EXIF orientation (1–8) that turns the stored lines upright: the DPX orientation codes 0–7 -/// in SMPTE 268M order (left-to-right top-to-bottom, mirrored, flipped, rotated, transposed…). -/// Anything else, undefined included, is taken as the default (1). +/// The EXIF orientation (1–8) that turns the stored lines upright; 1 for an unreadable header. pub(crate) fn orientation(b: &[u8]) -> u16 { - let Some(o) = order(b).and_then(|o| o.u16(b, ORIENTATION)) else { return 1 }; - match o { - 1 => 2, - 2 => 4, - 3 => 3, - 4 => 5, - 5 => 6, - 6 => 8, - 7 => 7, - _ => 1, - } + info(b, Kind::Dpx).map_or(1, |i| i.exif_orientation()) } -/// Bytes in one stored line of `samples` samples, padded to a 32-bit word. -fn line_bytes(samples: usize, bits: u8, packing: u16) -> Option { - let words = match (bits, packing) { - // Three samples to a word, or one to a 16-bit half word. - (10, 1 | 2) => samples.div_ceil(3), - (12, 1 | 2) => samples.div_ceil(2), - _ => samples.checked_mul(usize::from(bits))?.div_ceil(32), +/// The Cineon magic number (`802A5FD7` hex). +pub(crate) fn is_cineon(b: &[u8]) -> bool { + craft_dpx::sniff(b) == Some(Kind::Cineon) +} + +/// The EXIF orientation (1–8) for a Cineon header's orientation code. +pub(crate) fn cineon_orientation(b: &[u8]) -> u16 { + info(b, Kind::Cineon).map_or(1, |i| i.exif_orientation()) +} + +/// A decoded frame as an image: luma, RGB or RGBA, 8 bits as U8, deeper codes widened to U16. +fn image(format: Format, frame: Frame) -> Result<(Info, Image), CodecError> { + let i = &frame.info; + let layout = match i.layout { + Layout::Luma => ChannelLayout::Gray, + Layout::Rgb => ChannelLayout::Rgb, + Layout::Rgba => ChannelLayout::Rgba, + l => return Err(CodecError::unsupported(format, format!("{l:?} (Y'CbCr) elements are not supported (only luma, RGB and RGBA)"))), }; - words.checked_mul(4) + let img = match i.bits { + 8 => Image::from_u8(i.width, i.height, layout, frame.codes.iter().map(|&c| c as u8).collect())?, + _ => Image::from_u16(i.width, i.height, layout, &frame.samples_u16())?, + }; + Ok((frame.info, img)) } -/// Code values of one stored line. -fn unpack_line(line: &[u8], o: Order, bits: u8, packing: u16, out: &mut [u16]) -> Result<(), CodecError> { - let short = || err("truncated image data"); - match (bits, packing) { - (8, _) => { - let src = line.get(..out.len()).ok_or_else(short)?; - for (v, &c) in out.iter_mut().zip(src) { - *v = u16::from(c); - } - } - (16, _) => { - for (i, v) in out.iter_mut().enumerate() { - *v = o.u16(line, i * 2).ok_or_else(short)?; - } - } - (10, 1 | 2) => { - let base = if packing == 1 { 22 } else { 20 }; - for (i, v) in out.iter_mut().enumerate() { - let word = o.u32(line, i / 3 * 4).ok_or_else(short)?; - *v = ((word >> (base - 10 * (i % 3) as u32)) & 0x3FF) as u16; - } - } - (12, 1 | 2) => { - let shift = if packing == 1 { 4 } else { 0 }; - for (i, v) in out.iter_mut().enumerate() { - *v = (o.u16(line, i * 2).ok_or_else(short)? >> shift) & 0xFFF; - } - } - // Packing 0: one bit stream through the line's 32-bit words, high bits first. - _ => { - let mask = (1u64 << bits) - 1; - let (mut acc, mut have, mut word) = (0u64, 0u32, 0usize); - for v in out.iter_mut() { - while have < u32::from(bits) { - acc = (acc << 32) | u64::from(o.u32(line, word * 4).ok_or_else(short)?); - word += 1; - have += 32; - } - have -= u32::from(bits); - *v = ((acc >> have) & mask) as u16; - } - } - } - Ok(()) -} - -/// A 10- or 12-bit code value as a 16-bit sample: `round(c × 65535 / max)`. -fn widen(c: u16, max: u64) -> u16 { - ((u64::from(c) * 2 * 65535 + max) / (2 * max)).min(65535) as u16 -} - -/// The inverse of [`widen`]: `round(v × max / 65535)`. -fn narrow(v: u16, max: u64) -> u16 { - ((u64::from(v) * 2 * max + 65535) / (2 * 65535)) as u16 +/// Decodes a frame of `kind` within `limits`, checked as this crate checks every decoder. +fn decode_kind(bytes: &[u8], limits: &Limits, kind: Kind) -> Result<(Info, Image), CodecError> { + let format = if kind == Kind::Dpx { F } else { Format::Cineon }; + let i = info(bytes, kind)?; + let layout = match i.layout { + Layout::Luma => ChannelLayout::Gray, + Layout::Rgb => ChannelLayout::Rgb, + _ => ChannelLayout::Rgba, + }; + limits.check(i.width, i.height, layout, if i.bits == 8 { SampleType::U8 } else { SampleType::U16 })?; + image(format, craft_dpx::decode(bytes, &dpx_limits(limits)).map_err(|e| err(format, e))?) } pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { - let h = parse(bytes)?; - let e = h.element; - let layout = match e.descriptor { - 6 => ChannelLayout::Gray, - 50 => ChannelLayout::Rgb, - 51 => ChannelLayout::Rgba, - d => return Err(unsupported(format!("descriptor {d} is not supported (only 6 luma, 50 RGB and 51 RGBA)"))), - }; - if e.signed { - return Err(unsupported("data sign 1 (signed samples) is not supported")); + let (info, mut img) = decode_kind(bytes, limits, Kind::Dpx)?; + let i = &info; + if i.elements > 1 { + img.warnings.push(DecodeWarning::MoreElements { total: u32::from(i.elements) }); } - if e.encoding != 0 { - return Err(unsupported(format!("encoding {} (run-length encoded data) is not supported", e.encoding))); + if i.transfer.is_some() || i.colorimetric.is_some() { + img.warnings.push(DecodeWarning::DpxEncoding { transfer: i.transfer.unwrap_or(u8::MAX), colorimetric: i.colorimetric.unwrap_or(u8::MAX) }); } - let packing_ok = match e.bits { - 8 | 16 => e.packing == 0, - 10 => e.packing <= 2, - 12 => e.packing <= 1, - b => return Err(unsupported(format!("bit size {b} is not supported (only 8, 10, 12 and 16)"))), - }; - if !packing_ok { - return Err(unsupported(format!("packing {} is not supported at {} bits", e.packing, e.bits))); - } - let sample = if e.bits == 8 { SampleType::U8 } else { SampleType::U16 }; - limits.check(h.width, h.height, layout, sample)?; - - let nc = layout.channels(); - let per_line = (h.width as usize).checked_mul(nc).ok_or_else(|| CodecError::LimitExceeded("line too long".into()))?; - let height = h.height as usize; - let data = bytes.get(e.data_offset..).ok_or_else(|| err("the image data offset is past the end of the file"))?; - let too_large = || CodecError::LimitExceeded("image too large".into()); - let mut line_len = line_bytes(per_line, e.bits, e.packing).ok_or_else(too_large)?; - let mut stride = line_len.checked_add(e.eol_padding).ok_or_else(too_large)?; - // Lines run `stride` apart; the last one needs no padding after it. - let span = |stride: usize, line_len: usize| stride.checked_mul(height - 1)?.checked_add(line_len); - // Some writers pack 8- and 16-bit lines without padding them to a word; take that layout - // when the file is too short for padded lines but holds the unpadded ones. - let tight = per_line * usize::from(e.bits / 8); - if matches!(e.bits, 8 | 16) && e.eol_padding == 0 && line_len != tight && span(stride, line_len).is_none_or(|need| data.len() < need) { - (line_len, stride) = (tight, tight); - } - if span(stride, line_len).ok_or_else(too_large)? > data.len() { - return Err(err("truncated image data")); - } - - let mut codes = vec![0u16; per_line.checked_mul(height).ok_or_else(too_large)?]; - for (y, row) in codes.chunks_exact_mut(per_line.max(1)).enumerate() { - let start = y * stride; - let line = data.get(start..).ok_or_else(|| err("truncated image data"))?; - unpack_line(line, h.order, e.bits, e.packing, row)?; - } - - let mut img = match e.bits { - 8 => Image::from_u8(h.width, h.height, layout, codes.iter().map(|&c| c as u8).collect())?, - 16 => Image::from_u16(h.width, h.height, layout, &codes)?, - b => { - let max = (1u64 << b) - 1; - let wide: Vec = codes.iter().map(|&c| widen(c, max)).collect(); - Image::from_u16(h.width, h.height, layout, &wide)? - } - }; - if h.elements > 1 { - img.warnings.push(DecodeWarning::MoreElements { total: u32::from(h.elements) }); - } - if e.transfer != UNDEF8 || e.colorimetric != UNDEF8 { - img.warnings.push(DecodeWarning::DpxEncoding { transfer: e.transfer, colorimetric: e.colorimetric }); - } - img.meta.text = header_text(bytes, h.order, e); + img.meta.text = header_text(i); Ok(img) } -// ---------------------------------------------------------------- Cineon (Kodak .cin) -// -// Cineon is the 10-bit film-scan format DPX grew from (same Kodak header family, big-endian). -// The generic header is 1024 bytes: the file information fields, then at offset 192 the image -// orientation (1 byte), the channel count (1 byte) and up to eight 28-byte channel descriptors -// (the first carries the bits per pixel and the line/image dimensions). Image data is three -// 10-bit samples packed into each 32-bit word, lines on a word boundary — the same layout as -// DPX's 10-bit packing method A, so the unpacking and packing are shared. - -/// The Cineon magic number (`802A5FD7` hex), big-endian. -pub(crate) fn is_cineon(b: &[u8]) -> bool { - b.get(..4) == Some(&[0x80, 0x2A, 0x5F, 0xD7]) -} - -/// The EXIF orientation (1–8) for a Cineon header's orientation code (the same 0–7 order as DPX). -pub(crate) fn cineon_orientation(b: &[u8]) -> u16 { - let Some(code) = b.get(192).copied() else { return 1 }; - match code { - 1 => 2, - 2 => 4, - 3 => 3, - 4 => 5, - 5 => 6, - 6 => 8, - 7 => 7, - _ => 1, - } -} - -/// Decode a Cineon (`.cin`) frame: 10-bit logarithmic film scans, big-endian, one (gray) or -/// three (RGB) channels. The 10-bit code values become U16 as `round(c × 65535 / 1023)`; the -/// file's black/white reference points are not applied (a log conversion is a display choice). +/// Decode a Cineon (`.cin`) frame: 10-bit logarithmic film scans, one (gray) or three (RGB) +/// channels. The file's black/white reference points are not applied (a log conversion is a +/// display choice). pub(crate) fn decode_cineon(bytes: &[u8], limits: &Limits) -> Result { - if !is_cineon(bytes) { - return Err(err("missing the Cineon magic number (802A5FD7)")); - } - let o = Order::Big; - let missing = |what: &str| err(format!("the header ends before {what}")); - let image_offset = usize::try_from(o.u32(bytes, 4).ok_or_else(|| missing("the image data offset"))?).map_err(|_| err("image data offset out of range"))?; - let channels = *bytes.get(193).ok_or_else(|| missing("the channel count"))?; - let bits = *bytes.get(198).ok_or_else(|| missing("the bits per pixel"))?; - if bits != 10 { - return Err(unsupported(format!("{bits}-bit samples (Cineon frames are 10-bit)"))); - } - let layout = match channels { - 1 => ChannelLayout::Gray, - 3 => ChannelLayout::Rgb, - n => return Err(unsupported(format!("{n} channels (Cineon frames have 1 or 3)"))), - }; - let width = o.u32(bytes, 200).ok_or_else(|| missing("the pixels per line"))?; - let height = o.u32(bytes, 204).ok_or_else(|| missing("the lines per image"))?; - limits.check(width, height, layout, SampleType::U16)?; - - let (w, h) = (width as usize, height as usize); - let per_line = w.checked_mul(layout.channels()).ok_or_else(|| CodecError::LimitExceeded("line too long".into()))?; - // Three 10-bit samples per 32-bit word, lines on a word boundary (DPX packing 1). - let line_len = line_bytes(per_line, 10, 1).ok_or_else(|| CodecError::LimitExceeded("line too long".into()))?; - let data = bytes.get(image_offset..).ok_or_else(|| err("the image data offset is past the end of the file"))?; - let need = line_len.checked_mul(h).ok_or_else(|| CodecError::LimitExceeded("image too large".into()))?; - if data.len() < need { - return Err(err("truncated image data")); - } - let mut codes = vec![0u16; per_line.checked_mul(h).ok_or_else(|| CodecError::LimitExceeded("image too large".into()))?]; - for (y, row) in codes.chunks_exact_mut(per_line).enumerate() { - let start = y * line_len; - let line = data.get(start..start + line_len).ok_or_else(|| err("truncated image data"))?; - unpack_line(line, o, 10, 1, row)?; - } - let wide: Vec = codes.iter().map(|&c| widen(c, 1023)).collect(); - Image::from_u16(width, height, layout, &wide) -} - -/// Cineon's generic plus film header: where our image data starts. -const CINEON_HEADER_LEN: usize = 2048; -const CINEON_GENERIC_LEN: u32 = 1024; -/// Offset of the first of the eight 28-byte channel descriptors. -const CINEON_CHANNEL0: usize = 196; - -/// Encode a Cineon 4.5 frame: the generic header, an undefined film header, then the samples as -/// 10-bit code values `round(v × 1023 / 65535)`, three to a big-endian word, left justified -/// (packing 5), lines on a word boundary. The plan has already made the image U16 gray or RGB. -pub(crate) fn encode_cineon(src: &Image, plan: Plan) -> Result, CodecError> { - let enc = |msg: String| CodecError::encode(Format::Cineon, msg); - let img = src.converted(plan.layout, plan.sample); - let (w, h) = img.dimensions(); - // Channel designators: 0 for black and white, 1–3 for red, green and blue. - let designators: &[u8] = match img.layout() { - ChannelLayout::Gray => &[0], - ChannelLayout::Rgb => &[1, 2, 3], - l => return Err(enc(format!("Cineon cannot store {l:?}"))), - }; - let samples = img.to_u16_samples().ok_or_else(|| enc(format!("cannot write {:?} samples at 10 bits", img.sample_type())))?; - let codes: Vec = samples.into_iter().map(|v| narrow(v, 1023)).collect(); - let per_line = (w as usize).checked_mul(designators.len()).ok_or_else(|| enc("image too large".into()))?; - if codes.len() != per_line.checked_mul(h as usize).ok_or_else(|| enc("image too large".into()))? { - return Err(enc("the image has the wrong number of samples".into())); - } - let data_len = line_bytes(per_line, 10, 1).and_then(|l| l.checked_mul(h as usize)).ok_or_else(|| enc("image too large".into()))?; - let total = - CINEON_HEADER_LEN.checked_add(data_len).and_then(|t| u32::try_from(t).ok()).ok_or_else(|| enc("image too large for a Cineon file (4 GiB)".into()))?; - - let mut wr = Writer { h: vec![0; CINEON_HEADER_LEN] }; - // File information. - wr.u32(0, 0x802A_5FD7); - wr.u32(4, CINEON_HEADER_LEN as u32); - wr.u32(8, CINEON_GENERIC_LEN); - wr.u32(12, CINEON_HEADER_LEN as u32 - CINEON_GENERIC_LEN); - wr.u32(16, 0); - wr.u32(20, total); - wr.string((24, 8), "V4.5"); - // Image information: default orientation, then each channel's descriptor; the unused ones, - // the white point and the primaries are undefined. - wr.u8(192, 0); - wr.u8(193, designators.len() as u8); - wr.undefined(CINEON_CHANNEL0, 420); - for (i, &designator) in designators.iter().enumerate() { - let c = CINEON_CHANNEL0 + 28 * i; - wr.u8(c, 0); - wr.u8(c + 1, designator); - wr.u8(c + 2, 10); - wr.u8(c + 3, 0); - wr.u32(c + 4, w); - wr.u32(c + 8, h); - // Code values 0–1023 stand for printing densities 0–2.048, the Cineon convention. All - // four are 32-bit floats here (DPX stores the data values as integers). - wr.u32(c + 12, 0f32.to_bits()); - wr.u32(c + 16, 0f32.to_bits()); - wr.u32(c + 20, 1023f32.to_bits()); - wr.u32(c + 24, 2.048f32.to_bits()); - } - // Pixel-interleaved, unsigned, positive, no line or channel padding. - wr.u8(681, 5); - // Image origination: pixel pitches and gamma unknown. - wr.undefined(972, 984); - // Film header: manufacturer, type, perforation offset, prefix, count, frame position and rate - // unknown; its strings stay empty. - wr.undefined(1024, 1036); - wr.undefined(1068, 1076); - - let mut out = wr.h; - out.try_reserve_exact(data_len).map_err(|_| enc("out of memory".into()))?; - for row in codes.chunks_exact(per_line.max(1)) { - pack_line(&mut out, row, 10); - } - Ok(out) + decode_kind(bytes, limits, Kind::Cineon).map(|(_, img)| img) } /// The kept header fields as text metadata, in [`KEYS`] order; undefined ones are left out. -fn header_text(b: &[u8], o: Order, e: Element) -> Vec<(String, String)> { +fn header_text(i: &Info) -> Vec<(String, String)> { let mut text = Vec::new(); let mut put = |k: &str, v: Option| { if let Some(v) = v { text.push((k.to_string(), v)); } }; - put(KEY_CREATOR, string(b, CREATOR)); - put(KEY_PROJECT, string(b, PROJECT)); - put(KEY_COPYRIGHT, string(b, COPYRIGHT)); - put(KEY_CREATION_TIME, string(b, CREATION_TIME)); - put(KEY_TRANSFER, (e.transfer != UNDEF8).then(|| e.transfer.to_string())); - put(KEY_COLORIMETRIC, (e.colorimetric != UNDEF8).then(|| e.colorimetric.to_string())); - // The industry header is there when the generic header says so and the file holds it. - let industry = o.u32(b, 28).is_some_and(|l| l != 0 && l != UNDEF32) && b.len() >= HEADER_LEN; - if industry { - put(KEY_FRAME_POSITION, o.defined_u32(b, FRAME_POSITION).map(|v| v.to_string())); - put(KEY_FRAME_RATE, o.f32(b, FRAME_RATE).map(|v| v.to_string())); - put(KEY_TIME_CODE, o.defined_u32(b, TIME_CODE).map(format_time_code)); - } + put(KEY_CREATOR, i.creator.clone()); + put(KEY_PROJECT, i.project.clone()); + put(KEY_COPYRIGHT, i.copyright.clone()); + put(KEY_CREATION_TIME, i.creation_time.clone()); + put(KEY_TRANSFER, i.transfer.map(|v| v.to_string())); + put(KEY_COLORIMETRIC, i.colorimetric.map(|v| v.to_string())); + put(KEY_FRAME_POSITION, i.frame_position.map(|v| v.to_string())); + put(KEY_FRAME_RATE, i.frame_rate.map(|v| v.to_string())); + put(KEY_TIME_CODE, i.time_code.map(craft_dpx::format_time_code)); text } -/// A SMPTE time code (BCD `HHMMSSFF`) as `HH:MM:SS:FF`, or `0x…` when it is not valid BCD. -fn format_time_code(v: u32) -> String { - let d: [u32; 8] = std::array::from_fn(|i| (v >> ((7 - i) * 4)) & 0xF); - if d.iter().all(|&d| d <= 9) { format!("{}{}:{}{}:{}{}:{}{}", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7]) } else { format!("{v:#010x}") } -} - -/// The inverse of [`format_time_code`]; `None` for anything else. -fn parse_time_code(s: &str) -> Option { - if let Some(hex) = s.strip_prefix("0x") { - return u32::from_str_radix(hex, 16).ok(); - } - let parts: Vec<&str> = s.split(':').collect(); - if parts.len() != 4 || parts.iter().any(|p| p.len() != 2 || !p.bytes().all(|c| c.is_ascii_digit())) { - return None; - } - parts.iter().flat_map(|p| p.bytes()).try_fold(0u32, |acc, c| Some((acc << 4) | u32::from(c - b'0'))) -} - /// Bits written for `sample` when the options pick none: 8 for U8, 16 otherwise. pub(crate) fn bits_for(opt: Option, sample: SampleType) -> u8 { match opt { @@ -558,8 +183,7 @@ pub(crate) fn keeps_u16_samples(img: &Image, bits: u8) -> bool { if img.sample_type() != SampleType::U16 || !(1..16).contains(&bits) { return false; } - let max = (1u64 << bits) - 1; - img.data().as_chunks::<2>().0.iter().map(|c| u16::from_ne_bytes(*c)).all(|v| widen(narrow(v, max), max) == v) + img.data().as_chunks::<2>().0.iter().map(|c| u16::from_ne_bytes(*c)).all(|v| craft_dpx::widen(craft_dpx::narrow(v, bits), bits) == v) } /// The plan's sample type for the chosen bits: U8 for 8 bits, U16 for 10, 12 and 16. @@ -572,315 +196,53 @@ pub(crate) fn plan_sample(opt: Option, src: SampleType) -> SampleType { } } -struct Writer { - h: Vec, -} - -impl Writer { - fn u8(&mut self, at: usize, v: u8) { - if let Some(b) = self.h.get_mut(at) { - *b = v; - } - } - - fn u16(&mut self, at: usize, v: u16) { - if let Some(s) = self.h.get_mut(at..at + 2) { - s.copy_from_slice(&v.to_be_bytes()); - } - } - - fn u32(&mut self, at: usize, v: u32) { - if let Some(s) = self.h.get_mut(at..at + 4) { - s.copy_from_slice(&v.to_be_bytes()); - } - } - - /// Marks a run of numeric fields undefined (all ones). - fn undefined(&mut self, from: usize, to: usize) { - if let Some(s) = self.h.get_mut(from..to) { - s.fill(0xFF); - } - } - - /// An ASCII string field, cut to leave room for a terminating NUL. - fn string(&mut self, (at, len): (usize, usize), v: &str) { - let ascii: Vec = v.chars().map(|c| if (' '..='~').contains(&c) { c as u8 } else { b'?' }).take(len.saturating_sub(1)).collect(); - if let Some(s) = self.h.get_mut(at..at + ascii.len()) { - s.copy_from_slice(&ascii); - } - } -} - fn text<'a>(img: &'a Image, key: &str) -> Option<&'a str> { img.meta.text.iter().find(|(k, _)| k == key).map(|(_, v)| v.trim()).filter(|v| !v.is_empty()) } -/// Appends one line's code values, padded to a 32-bit word. -fn pack_line(out: &mut Vec, codes: &[u16], bits: u8) { - let start = out.len(); - match bits { - 8 => out.extend(codes.iter().map(|&c| c as u8)), - 10 => { - for chunk in codes.chunks(3) { - let word = chunk.iter().enumerate().fold(0u32, |w, (i, &c)| w | (u32::from(c & 0x3FF) << (22 - 10 * i as u32))); - out.extend_from_slice(&word.to_be_bytes()); - } - } - 12 => out.extend(codes.iter().flat_map(|&c| ((c & 0xFFF) << 4).to_be_bytes())), - _ => out.extend(codes.iter().flat_map(|&c| c.to_be_bytes())), - } - let written = out.len() - start; - out.resize(start + written.div_ceil(4) * 4, 0); +/// `img`'s samples as `bits`-bit code values, with the layout they are written in. +fn codes(format: Format, img: &Image, bits: u8) -> Result<(Layout, Vec), CodecError> { + let layout = match img.layout() { + ChannelLayout::Gray => Layout::Luma, + ChannelLayout::Rgb => Layout::Rgb, + ChannelLayout::Rgba if format == F => Layout::Rgba, + l => return Err(CodecError::encode(format, format!("{format:?} cannot store {l:?}"))), + }; + let codes: Vec = match (img.sample_type(), bits) { + (SampleType::U8, 8) => img.data().iter().map(|&v| u16::from(v)).collect(), + (SampleType::U16, 16) => img.to_u16_samples().unwrap_or_default(), + (SampleType::U16, 10 | 12) => img.to_u16_samples().unwrap_or_default().into_iter().map(|v| craft_dpx::narrow(v, bits)).collect(), + (s, b) => return Err(CodecError::encode(format, format!("cannot write {s:?} samples at {b} bits"))), + }; + Ok((layout, codes)) +} + +/// Encode a Cineon 4.5 frame at 10 bits. The plan has already made the image U16 gray or RGB. +pub(crate) fn encode_cineon(src: &Image, plan: Plan) -> Result, CodecError> { + let img = src.converted(plan.layout, plan.sample); + let (layout, codes) = codes(Format::Cineon, &img, 10)?; + let (width, height) = img.dimensions(); + craft_dpx::encode_cineon(&craft_dpx::Picture { width, height, layout, bits: 10, codes: &codes }).map_err(|e| err(Format::Cineon, e)) } pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result, CodecError> { let img = src.converted(plan.layout, plan.sample); - let (w, h) = img.dimensions(); - let (descriptor, layout) = match img.layout() { - ChannelLayout::Gray => (6u8, ChannelLayout::Gray), - ChannelLayout::Rgb => (50, ChannelLayout::Rgb), - ChannelLayout::Rgba => (51, ChannelLayout::Rgba), - l => return Err(CodecError::encode(F, format!("DPX cannot store {l:?}"))), - }; let bits = bits_for(opts.dpx_bits, img.sample_type()); - let codes: Vec = match (img.sample_type(), bits) { - (SampleType::U8, 8) => img.data().iter().map(|&v| u16::from(v)).collect(), - (SampleType::U16, 16) => img.to_u16_samples().unwrap_or_default(), - (SampleType::U16, 10 | 12) => { - let max = (1u64 << bits) - 1; - img.to_u16_samples().unwrap_or_default().into_iter().map(|v| narrow(v, max)).collect() - } - (s, b) => return Err(CodecError::encode(F, format!("cannot write {s:?} samples at {b} bits"))), - }; - let per_line = w as usize * layout.channels(); - if codes.len() != per_line * h as usize { - return Err(CodecError::encode(F, "the image has the wrong number of samples")); - } - let data_len = line_bytes(per_line, bits, if matches!(bits, 10 | 12) { 1 } else { 0 }) - .and_then(|l| l.checked_mul(h as usize)) - .ok_or_else(|| CodecError::encode(F, "image too large"))?; - let total = u32::try_from(HEADER_LEN + data_len).map_err(|_| CodecError::encode(F, "image too large for a DPX file (4 GiB)"))?; - - let mut wr = Writer { h: vec![0; HEADER_LEN] }; - // Generic file header. - wr.h[..4].copy_from_slice(b"SDPX"); - wr.u32(4, HEADER_LEN as u32); - wr.string((8, 8), "V2.0"); - wr.u32(16, total); - wr.u32(20, 1); - wr.u32(24, GENERIC_LEN); - wr.u32(28, INDUSTRY_LEN); - wr.u32(32, 0); + let (layout, codes) = codes(F, &img, bits)?; let keep = |key| if opts.embed_metadata { text(&img, key) } else { None }; - wr.string(CREATION_TIME, keep(KEY_CREATION_TIME).unwrap_or("")); - wr.string(CREATOR, keep(KEY_CREATOR).unwrap_or("PhotoCraft")); - wr.string(PROJECT, keep(KEY_PROJECT).unwrap_or("")); - wr.string(COPYRIGHT, keep(KEY_COPYRIGHT).unwrap_or("")); - wr.u32(660, UNDEF32); - // Image information: default orientation, one element. - wr.u16(ORIENTATION, 0); - wr.u16(ORIENTATION + 2, 1); - wr.u32(772, w); - wr.u32(776, h); - let e = ELEMENT0; - wr.u32(e, 0); - wr.u32(e + 4, 0); - wr.u32(e + 8, UNDEF32); - wr.u32(e + 12, ((1u32 << bits) - 1).min(65535)); - wr.u32(e + 16, UNDEF32); - wr.u8(e + 20, descriptor); // No claim about the encoding unless the document came with one. - let code = |key| keep(key).and_then(|v| v.parse::().ok()).unwrap_or(UNDEF8); - wr.u8(e + 21, code(KEY_TRANSFER)); - wr.u8(e + 22, code(KEY_COLORIMETRIC)); - wr.u8(e + 23, bits); - wr.u16(e + 24, if matches!(bits, 10 | 12) { 1 } else { 0 }); - wr.u16(e + 26, 0); - wr.u32(e + 28, HEADER_LEN as u32); - wr.u32(e + 32, 0); - wr.u32(e + 36, 0); - // The seven unused elements, the image source header's numbers and the industry header's - // numbers are undefined; their strings stay empty. - wr.undefined(e + ELEMENT_LEN, e + ELEMENT_LEN * usize::from(MAX_ELEMENTS)); - wr.undefined(1408, 1432); - wr.undefined(1620, 1644); - wr.undefined(FRAME_POSITION, 1732); - wr.undefined(TIME_CODE, 1972); - if let Some(v) = keep(KEY_FRAME_POSITION).and_then(|v| v.parse::().ok()) { - wr.u32(FRAME_POSITION, v); - } - if let Some(v) = keep(KEY_FRAME_RATE).and_then(|v| v.parse::().ok()).filter(|v| v.is_finite()) { - wr.u32(FRAME_RATE, v.to_bits()); - } - if let Some(v) = keep(KEY_TIME_CODE).and_then(parse_time_code) { - wr.u32(TIME_CODE, v); - } - - let mut out = wr.h; - out.try_reserve_exact(data_len).map_err(|_| CodecError::encode(F, "out of memory"))?; - for row in codes.chunks_exact(per_line.max(1)) { - pack_line(&mut out, row, bits); - } - Ok(out) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// A minimal header for `w`×`h` with element 0 set; image data at 2048. - fn header(o: Order, w: u32, h: u32, descriptor: u8, bits: u8, packing: u16) -> Vec { - let mut b = vec![0u8; HEADER_LEN]; - let put32 = |b: &mut Vec, at: usize, v: u32| b[at..at + 4].copy_from_slice(&if o == Order::Big { v.to_be_bytes() } else { v.to_le_bytes() }); - let put16 = |b: &mut Vec, at: usize, v: u16| b[at..at + 2].copy_from_slice(&if o == Order::Big { v.to_be_bytes() } else { v.to_le_bytes() }); - b[..4].copy_from_slice(if o == Order::Big { b"SDPX" } else { b"XPDS" }); - put32(&mut b, 4, HEADER_LEN as u32); - put32(&mut b, 28, INDUSTRY_LEN); - put16(&mut b, ORIENTATION, 0); - put16(&mut b, ORIENTATION + 2, 1); - put32(&mut b, 772, w); - put32(&mut b, 776, h); - b[ELEMENT0 + 20] = descriptor; - b[ELEMENT0 + 21] = UNDEF8; - b[ELEMENT0 + 22] = UNDEF8; - b[ELEMENT0 + 23] = bits; - put16(&mut b, ELEMENT0 + 24, packing); - put32(&mut b, ELEMENT0 + 28, HEADER_LEN as u32); - b[FRAME_POSITION..1732].fill(0xFF); - b[TIME_CODE..1972].fill(0xFF); - b - } - - fn words(o: Order, ws: &[u32]) -> Vec { - ws.iter().flat_map(|w| if o == Order::Big { w.to_be_bytes() } else { w.to_le_bytes() }).collect() - } - - #[test] - fn ten_bit_method_a_and_b_unpack_three_to_a_word() { - for o in [Order::Big, Order::Little] { - for (packing, base) in [(1u16, 22u32), (2, 20)] { - let mut b = header(o, 1, 1, 50, 10, packing); - b.extend(words(o, &[(1023 << base) | (512 << (base - 10)) | (1 << (base - 20))])); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.to_u16_samples().unwrap(), vec![65535, widen(512, 1023), widen(1, 1023)], "{o:?} packing {packing}"); - } - } - } - - #[test] - fn ten_bit_packing_0_is_one_bit_stream_per_line() { - // Four luma samples: 40 bits over two words, the line padded to the second word. - let samples = [1u64, 2, 1022, 1023]; - let stream = samples.iter().fold(0u64, |acc, &s| (acc << 10) | s) << 24; - for o in [Order::Big, Order::Little] { - let mut b = header(o, 4, 2, 6, 10, 0); - let line = words(o, &[(stream >> 32) as u32, stream as u32]); - b.extend(&line); - b.extend(&line); - let img = decode(&b, &Limits::default()).unwrap(); - let want: Vec = samples.iter().map(|&s| widen(s as u16, 1023)).collect(); - assert_eq!(img.to_u16_samples().unwrap(), [want.clone(), want].concat(), "{o:?}"); - } - } - - #[test] - fn twelve_bit_method_a_keeps_the_top_bits() { - let mut b = header(Order::Big, 2, 1, 6, 12, 1); - b.extend_from_slice(&[0xFF, 0xF0, 0x00, 0x10]); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.to_u16_samples().unwrap(), vec![65535, widen(1, 4095)]); - } - - #[test] - fn widen_and_narrow_round_trip_every_code() { - for bits in [10u8, 12] { - let max = (1u64 << bits) - 1; - for c in 0..=max as u16 { - assert_eq!(narrow(widen(c, max), max), c, "{bits}-bit {c}"); - } - } - assert_eq!(widen(512, 1023), ((512.0f64 * 65535.0 / 1023.0).round()) as u16); - } - - #[test] - fn orientation_codes_map_to_exif() { - let mut b = header(Order::Big, 1, 1, 6, 8, 0); - for (dpx, exif) in [(0u16, 1u16), (1, 2), (2, 4), (3, 3), (4, 5), (5, 6), (6, 8), (7, 7), (0xFFFF, 1)] { - b[ORIENTATION..ORIENTATION + 2].copy_from_slice(&dpx.to_be_bytes()); - assert_eq!(orientation(&b), exif, "DPX {dpx}"); - } - } - - #[test] - fn time_codes_round_trip() { - assert_eq!(format_time_code(0x0102_0304), "01:02:03:04"); - assert_eq!(parse_time_code("01:02:03:04"), Some(0x0102_0304)); - assert_eq!(parse_time_code(&format_time_code(0xABCD_0000)), Some(0xABCD_0000)); - assert_eq!(parse_time_code("1:2:3:4"), None); - } - - #[test] - fn eight_bit_lines_without_word_padding_still_open() { - // 1 × 2 RGB: 3 bytes a line, 6 in all; padded lines would need 8. - let mut b = header(Order::Big, 1, 2, 50, 8, 0); - b.extend_from_slice(&[1, 2, 3, 4, 5, 6]); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.data(), &[1, 2, 3, 4, 5, 6]); - } - - /// A minimal Cineon: a 1024-byte generic header, then `w × h` 10-bit samples packed three - /// to a 32-bit word (RGB in word order, or gray three pixels per word). - fn cineon(w: u32, h: u32, channels: u8, px: &[[u16; 3]]) -> Vec { - let mut b = vec![0u8; 1024]; - b[0..4].copy_from_slice(&[0x80, 0x2A, 0x5F, 0xD7]); // magic (802A5FD7) - b[4..8].copy_from_slice(&1024u32.to_be_bytes()); // image data offset - b[192] = 0; // orientation: left-to-right, top-to-bottom - b[193] = channels; - b[198] = 10; // bits per pixel (channel 1) - b[200..204].copy_from_slice(&w.to_be_bytes()); // pixels per line - b[204..208].copy_from_slice(&h.to_be_bytes()); // lines per image - let word = |a: u16, c: u16, e: u16| ((u32::from(a) << 22) | (u32::from(c) << 12) | (u32::from(e) << 2)).to_be_bytes(); - if channels == 3 { - for p in px { - b.extend_from_slice(&word(p[0], p[1], p[2])); - } - } else { - let g = |i: usize| px.get(i).map_or(0, |p| p[0]); - for i in (0..px.len()).step_by(3) { - b.extend_from_slice(&word(g(i), g(i + 1), g(i + 2))); - } - } - b - } - - #[test] - fn cineon_reads_ten_bit_rgb() { - let px = [[0, 512, 1023], [1023, 0, 256]]; - let b = cineon(2, 1, 3, &px); - assert!(is_cineon(&b)); - assert_eq!(order(&b), None, "Cineon is not DPX"); - let img = decode_cineon(&b, &Limits::default()).unwrap(); - assert_eq!((img.width(), img.height(), img.layout()), (2, 1, ChannelLayout::Rgb)); - assert_eq!( - img.to_u16_samples().unwrap(), - vec![widen(0, 1023), widen(512, 1023), widen(1023, 1023), widen(1023, 1023), widen(0, 1023), widen(256, 1023)] - ); - } - - #[test] - fn cineon_reads_grayscale_and_rejects_other_depths() { - let px = [[10, 0, 0], [20, 0, 0], [30, 0, 0], [40, 0, 0]]; - let b = cineon(4, 1, 1, &px); - let img = decode_cineon(&b, &Limits::default()).unwrap(); - assert_eq!(img.layout(), ChannelLayout::Gray); - assert_eq!(img.to_u16_samples().unwrap(), vec![widen(10, 1023), widen(20, 1023), widen(30, 1023), widen(40, 1023)]); - // A depth other than 10 is unsupported, and truncation errors rather than panicking. - let mut bad = cineon(1, 1, 3, &[[0, 0, 0]]); - bad[198] = 8; - assert!(matches!(decode_cineon(&bad, &Limits::default()), Err(CodecError::Unsupported { .. }))); - let full = cineon(4, 4, 3, &[[0; 3]; 16]); - for cut in [0, 4, 200, 1024, full.len() - 1] { - assert!(decode_cineon(&full[..cut.min(full.len())], &Limits::default()).is_err(), "cut {cut}"); - } - } + let code = |key| keep(key).and_then(|v| v.parse::().ok()); + let meta = craft_dpx::Metadata { + creator: Some(keep(KEY_CREATOR).unwrap_or("PhotoCraft")), + project: keep(KEY_PROJECT), + copyright: keep(KEY_COPYRIGHT), + creation_time: keep(KEY_CREATION_TIME), + transfer: code(KEY_TRANSFER), + colorimetric: code(KEY_COLORIMETRIC), + frame_position: keep(KEY_FRAME_POSITION).and_then(|v| v.parse::().ok()), + frame_rate: keep(KEY_FRAME_RATE).and_then(|v| v.parse::().ok()), + time_code: keep(KEY_TIME_CODE).and_then(craft_dpx::parse_time_code), + }; + let (width, height) = img.dimensions(); + craft_dpx::encode(&craft_dpx::Picture { width, height, layout, bits, codes: &codes }, &meta).map_err(|e| err(F, e)) } diff --git a/crates/codecs/src/codecs/exr.rs b/crates/codecs/src/codecs/exr.rs index 0d68d20ca9..15d352fad0 100644 --- a/crates/codecs/src/codecs/exr.rs +++ b/crates/codecs/src/codecs/exr.rs @@ -296,9 +296,14 @@ pub(crate) fn decode_channels(bytes: &[u8], index: usize, names: &[&str], limits let (w, h) = (layer.size.0, layer.size.1); let channels = &layer.channel_data.list; let npx = w * h; + // More names than channels can only repeat one: refuse before the per-name lookups multiply. + if names.len() > channels.len() { + return Err(err("more channel names than the part has channels")); + } + let have: Vec = channels.iter().map(|c| c.name.to_string()).collect(); let mut picked: Vec<&AnyChannel> = Vec::with_capacity(names.len()); for name in names { - let c = channels.iter().find(|c| c.name.to_string() == *name).ok_or_else(|| err(format!("the part has no channel {name}")))?; + let c = have.iter().position(|n| n == name).map(|i| &channels[i]).ok_or_else(|| err(format!("the part has no channel {name}")))?; if c.sample_data.len() != npx { return Err(err("channel sample count mismatch (subsampled channels are unsupported)")); } diff --git a/crates/codecs/src/codecs/exr_cryptomatte.rs b/crates/codecs/src/codecs/exr_cryptomatte.rs index 62fd2e1e0d..63a14cf9b7 100644 --- a/crates/codecs/src/codecs/exr_cryptomatte.rs +++ b/crates/codecs/src/codecs/exr_cryptomatte.rs @@ -20,84 +20,23 @@ use crate::options::Limits; const F: Format = Format::OpenExr; -/// A Cryptomatte stream channel (`crypto_asset00.red`) splits into its stream name -/// (`crypto_asset00`), the stream index, whether it is a coverage channel (green/alpha) -/// instead of an ID (red/blue), and its rank within the set (0 for red/green, 1 for -/// blue/alpha). -pub(crate) struct StreamChannel { - pub stream: String, - pub index: u32, - pub coverage: bool, - pub rank: usize, -} - -/// `NN` where NN is one or more digits (the reference readers match `\d+`), with a -/// `.red`/`.r` or `.blue`/`.b` (ID) or `.green`/`.g` or `.alpha`/`.a` (coverage) suffix, -/// in any case (Blender writes `.R`/`.G`/`.B`/`.A`). -pub(crate) fn split_stream(channel: &str) -> Option { - let (stream, suffix) = channel.rsplit_once('.')?; - let (coverage, rank) = match suffix.to_ascii_lowercase().as_str() { - "red" | "r" => (false, 0), - "green" | "g" => (true, 0), - "blue" | "b" => (false, 1), - "alpha" | "a" => (true, 1), - _ => return None, - }; - let digits = stream.chars().rev().take_while(|c| c.is_ascii_digit()).count(); - if digits == 0 || digits == stream.len() { - return None; - } - let split = stream.len() - digits; - let index = stream[split..].parse().ok()?; - Some(StreamChannel { stream: stream.to_string(), index, coverage, rank }) -} - -/// MurmurHash3, x86-32 bit variant, seed 0 (public-domain algorithm, Austin Appleby). -fn murmur3_32(data: &[u8]) -> u32 { - const C1: u32 = 0xcc9e_2d51; - const C2: u32 = 0x1b87_3593; - let mut h = 0u32; - let (chunks, rest) = data.as_chunks::<4>(); - for c in chunks { - let mut k = u32::from_le_bytes(*c); - k = k.wrapping_mul(C1).rotate_left(15).wrapping_mul(C2); - h ^= k; - h = h.rotate_left(13).wrapping_mul(5).wrapping_add(0xe654_6b64); - } - if !rest.is_empty() { - let mut k = [0u8; 4]; - k[..rest.len()].copy_from_slice(rest); - let mut k = u32::from_le_bytes(k); - k = k.wrapping_mul(C1).rotate_left(15).wrapping_mul(C2); - h ^= k; - } - h ^= data.len() as u32; - h ^= h >> 16; - h = h.wrapping_mul(0x85eb_ca6b); - h ^= h >> 13; - h = h.wrapping_mul(0xc2b2_ae35); - h ^ (h >> 16) -} +pub(crate) use craft_exr::cryptomatte::split_stream; /// The Cryptomatte ID of a name: the MurmurHash3 bits with the exponent fixed away from /// 0 and 255, as an f32 value. pub fn cryptomatte_id(name: &str) -> f32 { - let bits = murmur3_32(name.as_bytes()); - let exp = (bits >> 23) & 0xff; - let bits = if exp == 0 || exp == 255 { bits ^ (1 << 23) } else { bits }; - f32::from_bits(bits) + craft_exr::cryptomatte::id(name) } /// The 7-hex-digit metadata key of a layer name (the ID bits without their last digit). pub fn cryptomatte_key(name: &str) -> String { - format!("{:08x}", cryptomatte_id(name).to_bits())[..7].to_string() + craft_exr::cryptomatte::key(name) } /// The preview colour of an ID (the reference formula): green and blue channels shifted /// out of the ID's bit pattern, red unused. pub fn cryptomatte_preview_color(id: f32) -> [f32; 3] { - let bits = id.to_bits(); - [0.0, f32::from_bits(bits << 8), f32::from_bits(bits << 16)] + craft_exr::cryptomatte::preview_color(id) } /// The `cryptomatte//` text attribute of a header, if present. @@ -109,40 +48,39 @@ fn attribute(other: &std::collections::HashMap"}`) into (ID value, name) -/// pairs. Entries that are not strings of up to eight hex digits are skipped, like the -/// reference readers tolerate a partially broken manifest; a broken document yields none. +/// A manifest JSON (`{"object name": "<8-hex ID bits>"}`) as (ID value, name) pairs, by name. +/// Entries that are not hex strings are skipped; a broken document yields none. fn parse_manifest(json: &str) -> Vec<(f32, String)> { - let Ok(value) = serde_json::from_str::(json) else { return Vec::new() }; - let Some(map) = value.as_object() else { return Vec::new() }; - let mut out = Vec::with_capacity(map.len().min(1 << 20)); - for (name, hex) in map { - let Some(hex) = hex.as_str() else { continue }; - let Some(bits) = u32::from_str_radix(hex.trim_start_matches("0x"), 16).ok() else { continue }; - out.push((f32::from_bits(bits), name.clone())); - } - out + craft_exr::cryptomatte::parse_manifest(json).into_iter().map(|(name, bits)| (f32::from_bits(bits), name)).collect() } -/// The stream channel names of a layer (`crypto_asset00`, `crypto_asset01`, …, exactly as -/// the file spells them), matched leniently: the channel prefix and the `name` attribute -/// differ in case or `_`/`-` between renderers (`CryptoAsset` vs `crypto_asset`). -fn layer_streams(header: &exr::meta::header::Header, name: &str) -> Vec { - let normalize = |s: &str| s.to_ascii_lowercase().replace(['_', '-'], ""); - let want = normalize(name); - let mut found: Vec<(u32, String)> = header - .channels - .list - .iter() - .filter_map(|c| { - let s = split_stream(&c.name.to_string())?; - (!s.coverage).then_some((s.index, s.stream)) +/// How a layer name compares with a stream's channel prefix: the channel prefix and the `name` +/// attribute differ in case or `_`/`-` between renderers (`CryptoAsset` vs `crypto_asset`). +fn normalize_layer(s: &str) -> String { + s.to_ascii_lowercase().replace(['_', '-'], "") +} + +/// The stream channel names of every layer of a header (`crypto_asset00`, `crypto_asset01`, …, +/// exactly as the file spells them), keyed by [`normalize_layer`] of their prefix. Built in one +/// pass over the channels, so looking up each `cryptomatte//name` costs no channel scan. +fn layer_streams(header: &exr::meta::header::Header) -> std::collections::HashMap> { + let mut found: std::collections::HashMap> = std::collections::HashMap::new(); + for c in &header.channels.list { + let Some(s) = split_stream(&c.name.to_string()) else { continue }; + if s.coverage { + continue; + } + let layer = normalize_layer(s.stream.trim_end_matches(|c: char| c.is_ascii_digit())); + found.entry(layer).or_default().push((s.index, s.stream)); + } + found + .into_iter() + .map(|(layer, mut streams)| { + streams.sort(); + streams.dedup(); + (layer, streams.into_iter().map(|(_, stream)| stream).collect()) }) - .filter(|(_, stream)| normalize(stream.trim_end_matches(|c: char| c.is_ascii_digit())) == want) - .collect(); - found.sort(); - found.dedup(); - found.into_iter().map(|(_, stream)| stream).collect() + .collect() } /// Lists every Cryptomatte layer of the file from the headers alone: what a Cryptomatte @@ -157,50 +95,55 @@ pub(crate) fn layers(bytes: &[u8], limits: &Limits) -> Result> = std::collections::HashMap::new(); - for key in cryptomatte_keys(&header.own_attributes.other) { - let Some(name) = attribute(&header.own_attributes.other, &key, "name") else { continue }; - let channels = streams_for.entry(name.clone()).or_insert_with(|| layer_streams(header, name.as_str())).clone(); - if channels.is_empty() { - continue; - } - let manifest = attribute(&header.own_attributes.other, &key, "manifest") - .filter(|m| m.len() <= MANIFEST_CAP) - .map(|m| parse_manifest(m.as_str())) - .unwrap_or_default(); + // Every channel's stream, indexed once by layer. Each layer's list is moved into the + // first key that names it: file-controlled keys can all name the same layer (in any + // case or `_`/`-` spelling), and copying its list for each of them would make the + // result grow with keys * channels. A second key naming a listed layer is skipped; + // `decode` resolves a name to its first layer anyway. + let mut streams_for = layer_streams(header); + // A key whose manifest is missing or unparseable only stands in for its layer when no later + // key naming it has a usable one. + let mut fallback: std::collections::HashMap = std::collections::HashMap::new(); + let other = &header.own_attributes.other; + let mut push = |name: String, key: String, manifest: Vec<_>, channels: Vec| { out.push(CryptomatteLayer { part, name, - key: key.clone(), - conversion: attribute(&header.own_attributes.other, &key, "conversion"), + conversion: attribute(other, &key, "conversion"), manifest, - sidecar_manifest: attribute(&header.own_attributes.other, &key, "manif_file"), + sidecar_manifest: attribute(other, &key, "manif_file"), + key, channels, }); + }; + for key in cryptomatte_keys(other) { + let Some(name) = attribute(other, &key, "name") else { continue }; + let norm = normalize_layer(&name); + if streams_for.get(&norm).is_none_or(|c| c.is_empty()) { + continue; + } + let manifest = attribute(other, &key, "manifest").filter(|m| m.len() <= MANIFEST_CAP).map(|m| parse_manifest(m.as_str())).unwrap_or_default(); + if manifest.is_empty() { + fallback.entry(norm).or_insert((name, key)); + } else if let Some(channels) = streams_for.remove(&norm) { + push(name, key, manifest, channels); + } + } + for (norm, (name, key)) in fallback { + if let Some(channels) = streams_for.remove(&norm) { + push(name, key, Vec::new(), channels); + } } } out.sort_by(|a, b| (&a.part, &a.name).cmp(&(&b.part, &b.name))); Ok(out) } -/// Every `cryptomatte//` key of a header, in file order, without duplicates. +/// Every `cryptomatte//` key of a header, sorted, without duplicates. fn cryptomatte_keys(other: &std::collections::HashMap) -> Vec { - let mut keys = Vec::new(); - // Track seen keys in a set: the attribute names are file-controlled, so membership with - // keys.iter().any() is O(n^2) in the number of distinct `cryptomatte//` - // groups. The Vec still records file order; the set only answers "seen before". - let mut seen = std::collections::HashSet::new(); - for name in other.keys() { - let full = name.to_string(); - let Some(rest) = full.strip_prefix("cryptomatte/") else { continue }; - let Some((key, _field)) = rest.split_once('/') else { continue }; - if !key.is_empty() && seen.insert(key.to_string()) { - keys.push(key.to_string()); - } - } + let names: Vec = other.keys().map(|name| name.to_string()).collect(); + let mut keys = craft_exr::cryptomatte::keys(names.iter().map(String::as_str)); + keys.sort(); // HashMap order varies per call; layer names must stay stable keys } @@ -210,9 +153,11 @@ fn cryptomatte_keys(other: &std::collections::HashMap Result { let found = layers(bytes, limits)?; + // An exact name wins, so layers whose names only differ after normalising can each be asked for. let layer = found .iter() - .find(|l| l.name.eq_ignore_ascii_case(layer_name)) + .find(|l| l.name == layer_name) + .or_else(|| found.iter().find(|l| normalize_layer(&l.name) == normalize_layer(layer_name))) .ok_or_else(|| CodecError::unsupported(F, format!("no Cryptomatte layer named {layer_name}")))?; // Also caps all parts' declared sizes together, like every other flat decode. let meta = super::exr::read_meta(bytes, limits)?; @@ -240,9 +185,12 @@ pub(crate) fn decode(bytes: &[u8], layer_name: &str, limits: &Limits) -> Result< // Two (ID, coverage) ranks per set: rank `slot * 2 + stream.rank`. let mut ids: Vec> = vec![Vec::new(); ranks]; let mut coverages: Vec> = vec![Vec::new(); ranks]; + // Stream name -> its slot, built once: a linear search per decoded channel is quadratic in + // the file's stream count. + let slots: std::collections::HashMap<&str, usize> = layer.channels.iter().enumerate().rev().map(|(i, s)| (s.as_str(), i)).collect(); for c in &ex_layer.channel_data.list { let Some(stream) = split_stream(&c.name.to_string()) else { continue }; - let Some(slot) = layer.channels.iter().position(|s| *s == stream.stream) else { continue }; + let Some(&slot) = slots.get(stream.stream.as_str()) else { continue }; let values: Vec = c.sample_data.values_as_f32().collect(); if values.len() != npx { return Err(CodecError::malformed(F, "a Cryptomatte channel is smaller than its layer")); diff --git a/crates/codecs/src/codecs/fits.rs b/crates/codecs/src/codecs/fits.rs deleted file mode 100644 index ae6e945054..0000000000 --- a/crates/codecs/src/codecs/fits.rs +++ /dev/null @@ -1,855 +0,0 @@ -//! FITS (Flexible Image Transport System, FITS Standard 4.0), implemented here: the image in the -//! primary HDU, or the first `IMAGE` extension when the primary HDU holds no data. -//! -//! Reading: -//! -//! * `BITPIX` 8, 16, 32, 64, -32 and -64, with `BSCALE`/`BZERO` and integer `BLANK`. -//! * `NAXIS3 = 3` opens as RGB (the planes are R, G, B); any other plane count opens the first -//! plane as gray with [`DecodeWarning::MorePages`]. -//! * Rows are stored bottom-to-top, as the standard's convention has it (Siril, DS9, Astropy), -//! unless `ROWORDER = 'TOP-DOWN'`. -//! * Physical values that fit (unsigned 8-bit, or integers in 0..=65535 such as a camera's -//! `BITPIX = 16`, `BZERO = 32768`) are kept exactly as U8/U16. Everything else becomes F32: -//! values up to 2 are taken as already normalised (Siril, PixInsight), larger ones are scaled by -//! 65535 when they fit in it (DeepSkyStacker, most stackers) and by the maximum otherwise. NaN -//! and blank pixels read as 0. -//! * The other header cards are kept as text: `KEY` → value (strings unquoted), `COMMENT` and -//! `HISTORY` by their text, `HIERARCH` keywords by their long name. Long strings continued -//! on `CONTINUE` cards are joined. -//! -//! Writing: gray or RGB, U8 (`BITPIX = 8`), U16 (`BITPIX = 16`, `BZERO = 32768`) or F32 -//! (`BITPIX = -32`, 0..1), bottom-to-top with `ROWORDER = 'BOTTOM-UP'`, plus the text cards -//! (strings longer than one card on `CONTINUE` cards). -//! Tile-compressed files (fpack `ZIMAGE` tables) are recognised and refused. - -use std::collections::HashMap; - -use crate::Format; -use crate::error::CodecError; -use crate::fidelity::Plan; -use crate::image::{ChannelLayout, DecodeWarning, Image, SampleType}; -use crate::options::{EncodeOptions, Limits}; - -const F: Format = Format::Fits; -const BLOCK: usize = 2880; -const CARD: usize = 80; -/// Most HDUs walked looking for an image; FITS files from cameras and stackers hold a handful. -const MAX_HDUS: usize = 1000; - -/// Keywords that describe the data layout. They are written from the image, never copied from -/// (or kept as) text metadata: after decoding they no longer describe the pixels. -const STRUCTURAL: &[&str] = &[ - "SIMPLE", "BITPIX", "NAXIS", "EXTEND", "BZERO", "BSCALE", "BLANK", "END", "XTENSION", "PCOUNT", "GCOUNT", "ROWORDER", "CHECKSUM", "DATASUM", "DATAMIN", - "DATAMAX", "ZIMAGE", -]; - -fn err(msg: impl std::fmt::Display) -> CodecError { - CodecError::malformed(F, msg) -} - -#[derive(Debug, Clone, PartialEq)] -enum Value { - /// A quoted string, unescaped, trailing blanks removed. - Str(String), - /// Anything else (number, logical, complex) as written. - Raw(String), -} - -#[derive(Debug, Clone)] -struct Card { - key: String, - /// `None` for commentary cards (`COMMENT`, `HISTORY`, blank keyword). - value: Option, - /// The text of a commentary card. - text: String, - /// A `HIERARCH` keyword (`key` holds its long name). - hierarch: bool, -} - -fn parse_value(field: &str) -> Value { - let t = field.trim_start(); - if let Some(rest) = t.strip_prefix('\'') { - let mut s = String::new(); - let mut chars = rest.chars().peekable(); - while let Some(c) = chars.next() { - if c == '\'' { - if chars.peek() == Some(&'\'') { - chars.next(); - s.push('\''); - } else { - break; - } - } else { - s.push(c); - } - } - Value::Str(s.trim_end().to_string()) - } else { - Value::Raw(t.split('/').next().unwrap_or("").trim().to_string()) - } -} - -fn parse_card(raw: &[u8]) -> Card { - // Header bytes are ASCII 32–126 by the standard; anything else is replaced, never trusted. - let s: String = raw.iter().map(|&b| if (32..=126).contains(&b) { b as char } else { '?' }).collect(); - let key_field = s.get(..8).unwrap_or(&s).trim_end().to_string(); - if key_field == "HIERARCH" { - let rest = s.get(9..).unwrap_or(""); - if let Some((k, v)) = rest.split_once('=') { - return Card { key: k.trim().to_string(), value: Some(parse_value(v)), text: String::new(), hierarch: true }; - } - } - if s.get(8..10) == Some("= ") { - let v = parse_value(s.get(10..).unwrap_or("")); - return Card { key: key_field, value: Some(v), text: String::new(), hierarch: false }; - } - Card { key: key_field, value: None, text: s.get(8..).unwrap_or("").trim_end().to_string(), hierarch: false } -} - -struct Header { - cards: Vec, - /// First-occurrence index of each non-HIERARCH keyword, so `get` is O(1). The card - /// count and the number of looked-up keywords (NAXIS1..NAXISn) are both file-controlled, - /// so a linear scan per lookup lets a crafted header multiply commentary cards by axis - /// count into quadratic work. - index: HashMap, - /// Offset of the data unit. - data_start: usize, -} - -impl Header { - fn get(&self, key: &str) -> Option<&Value> { - let c = &self.cards[*self.index.get(key)?]; - c.value.as_ref() - } - - fn int(&self, key: &str) -> Option { - match self.get(key)? { - Value::Raw(r) => r.parse::().ok().or_else(|| self.float(key).filter(|f| f.fract() == 0.0 && f.abs() < 9.0e15).map(|f| f as i64)), - Value::Str(_) => None, - } - } - - fn float(&self, key: &str) -> Option { - match self.get(key)? { - // Fortran-style `D` exponents are allowed in FITS. - Value::Raw(r) => r.replace(['D', 'd'], "E").parse::().ok().filter(|f| f.is_finite()), - Value::Str(_) => None, - } - } - - fn logical(&self, key: &str) -> bool { - matches!(self.get(key), Some(Value::Raw(r)) if r == "T") - } - - fn string(&self, key: &str) -> Option<&str> { - match self.get(key)? { - Value::Str(s) => Some(s.trim()), - Value::Raw(_) => None, - } - } -} - -fn parse_header(b: &[u8], start: usize) -> Result { - let mut cards = Vec::new(); - let mut pos = start; - loop { - let raw = b.get(pos..pos.checked_add(CARD).ok_or_else(|| err("header too long"))?).ok_or_else(|| err("header ends before END"))?; - pos += CARD; - if raw.starts_with(b"END") && raw.get(3..).is_some_and(|r| r.iter().all(|&c| c == b' ')) { - break; - } - let card = parse_card(raw); - // Long strings (FITS 4.0 section 4.2.1.2): a string ending in '&' goes on in the next - // `CONTINUE` record. An orphaned `CONTINUE` stays a card of its own (commentary). - if let Some(Card { value: Some(Value::Str(s)), .. }) = cards.last_mut() - && s.ends_with('&') - && card.key == "CONTINUE" - && card.text.starts_with(" ") - && let Value::Str(more) = parse_value(&card.text) - { - s.pop(); - s.push_str(&more); - continue; - } - cards.push(card); - } - let data_start = pos.div_ceil(BLOCK).checked_mul(BLOCK).ok_or_else(|| err("header too long"))?; - // Index each non-HIERARCH keyword to its first occurrence, matching the previous - // `find(|c| !c.hierarch && c.key == key)` lookup while making `get` O(1). - let mut index = HashMap::with_capacity(cards.len()); - for (i, c) in cards.iter().enumerate() { - if !c.hierarch { - index.entry(c.key.clone()).or_insert(i); - } - } - Ok(Header { cards, index, data_start }) -} - -/// The axis lengths (`NAXIS1`, `NAXIS2`, …). -fn axes(h: &Header) -> Result, CodecError> { - let n = h.int("NAXIS").ok_or_else(|| err("missing NAXIS"))?; - if !(0..=999).contains(&n) { - return Err(err(format!("invalid NAXIS {n}"))); - } - (1..=n).map(|i| h.int(&format!("NAXIS{i}")).and_then(|v| u64::try_from(v).ok()).ok_or_else(|| err(format!("missing or negative NAXIS{i}")))).collect() -} - -/// Bytes in the data unit (before padding to a block). -fn data_len(h: &Header, bitpix: i64) -> Result { - let ax = axes(h)?; - if ax.is_empty() { - return Ok(0); - } - let pcount = u64::try_from(h.int("PCOUNT").unwrap_or(0)).map_err(|_| err("negative PCOUNT"))?; - let gcount = u64::try_from(h.int("GCOUNT").unwrap_or(1)).map_err(|_| err("negative GCOUNT"))?; - let elems = ax.iter().try_fold(1u64, |a, &n| a.checked_mul(n)).ok_or_else(|| err("data size overflows"))?; - elems - .checked_add(pcount) - .and_then(|v| v.checked_mul(gcount)) - .and_then(|v| v.checked_mul(bitpix.unsigned_abs() / 8)) - .ok_or_else(|| err("data size overflows")) -} - -/// Inspect every HDU without decoding pixels: one gray plane or three RGB planes are retained, -/// while other cubes, image extensions, tables and other data-bearing HDUs cannot survive a flat save. -/// Incomplete or over-limit walks fail closed rather than treating an unchecked suffix as safe. -pub(crate) fn has_additional_images(bytes: &[u8]) -> Result { - let mut start = 0; - let mut image_seen = false; - for index in 0..MAX_HDUS { - let h = parse_header(bytes, start)?; - if index == 0 && h.get("SIMPLE").is_none() { - return Err(err("missing SIMPLE")); - } - let ax = axes(&h)?; - let size = data_len(&h, h.int("BITPIX").unwrap_or(8))?; - let image_hdu = index == 0 || h.string("XTENSION") == Some("IMAGE"); - if h.logical("ZIMAGE") { - return Ok(true); - } - if !image_hdu && size > 0 { - return Ok(true); - } - // An image HDU with a zero axis has no data (FITS 4.0, NAXISn) and holds no image, like - // the empty primary: `find_image` skips it too. - if image_hdu && size > 0 && ax.len() >= 2 && ax[..2].iter().all(|n| *n > 0) { - let planes = ax.iter().skip(2).try_fold(1u64, |n, axis| n.checked_mul(*axis)).ok_or_else(|| err("plane count overflows"))?; - let retained = planes == 1 || (ax.get(2) == Some(&3) && planes == 3); - if image_seen || !retained || h.int("GCOUNT").unwrap_or(1) > 1 || h.int("PCOUNT").unwrap_or(0) > 0 { - return Ok(true); - } - image_seen = true; - } else if size > 0 { - return Ok(true); - } - let padded = size.div_ceil(BLOCK as u64).checked_mul(BLOCK as u64).ok_or_else(|| err("data size overflows"))?; - let next = usize::try_from(padded).ok().and_then(|size| h.data_start.checked_add(size)).ok_or_else(|| err("data size overflows"))?; - if next > bytes.len() { - return Err(err("truncated HDU data")); - } - if next == bytes.len() { - return Ok(false); - } - start = next; - } - Err(err("too many HDUs to inspect every source image")) -} - -/// Whether an HDU with these axes stores pixels: at least two axes and none of them zero (FITS 4.0, -/// NAXISn: a zero axis means no data follow the header). -fn holds_pixels(ax: &[u64]) -> bool { - ax.len() >= 2 && ax.iter().all(|n| *n > 0) -} - -/// Finds the image HDU: the primary one when it holds pixels, else the first `IMAGE` extension -/// that does. Returns its header and the primary header (for its descriptive cards). -fn find_image(b: &[u8]) -> Result<(Header, Option
), CodecError> { - let primary = parse_header(b, 0)?; - if primary.get("SIMPLE").is_none() { - return Err(err("missing SIMPLE")); - } - if holds_pixels(&axes(&primary)?) { - return Ok((primary, None)); - } - let mut compressed = false; - let mut cur_start = primary.data_start; - let mut cur_len = data_len(&primary, primary.int("BITPIX").unwrap_or(8))?; - for _ in 0..MAX_HDUS { - let next = usize::try_from(cur_len.div_ceil(BLOCK as u64).saturating_mul(BLOCK as u64)) - .ok() - .and_then(|l| cur_start.checked_add(l)) - .ok_or_else(|| err("data size overflows"))?; - if next >= b.len() { - break; - } - let h = parse_header(b, next)?; - let kind = h.string("XTENSION").unwrap_or("").to_string(); - if kind == "IMAGE" && holds_pixels(&axes(&h)?) { - return Ok((h, Some(primary))); - } - if kind == "BINTABLE" && h.logical("ZIMAGE") { - compressed = true; - } - cur_len = data_len(&h, h.int("BITPIX").unwrap_or(8))?; - cur_start = h.data_start; - } - if compressed { - return Err(CodecError::unsupported(F, "tile-compressed FITS (fpack) is not supported; decompress it with funpack first")); - } - Err(err("the file holds no image")) -} - -pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { - let (h, primary) = find_image(bytes)?; - let bitpix = h.int("BITPIX").ok_or_else(|| err("missing BITPIX"))?; - if !matches!(bitpix, 8 | 16 | 32 | 64 | -32 | -64) { - return Err(err(format!("invalid BITPIX {bitpix}"))); - } - let ax = axes(&h)?; - let (Some(&w), Some(&hgt)) = (ax.first(), ax.get(1)) else { return Err(err("the image has fewer than two axes")) }; - let w = u32::try_from(w).map_err(|_| CodecError::LimitExceeded(format!("width {w}")))?; - let hgt = u32::try_from(hgt).map_err(|_| CodecError::LimitExceeded(format!("height {hgt}")))?; - let planes = ax.iter().skip(2).try_fold(1u64, |a, &n| a.checked_mul(n)).ok_or_else(|| err("too many planes"))?; - let (layout, nplanes) = if ax.get(2) == Some(&3) && planes == 3 { (ChannelLayout::Rgb, 3usize) } else { (ChannelLayout::Gray, 1) }; - - let bscale = h.float("BSCALE").unwrap_or(1.0); - let bzero = h.float("BZERO").unwrap_or(0.0); - let blank = if bitpix > 0 { h.int("BLANK") } else { None }; - let integral = bscale == 1.0 && bzero.fract() == 0.0; - let candidate = match bitpix { - 8 if integral && bzero == 0.0 => SampleType::U8, - 8 | 16 if integral => SampleType::U16, - _ => SampleType::F32, - }; - limits.check(w, hgt, layout, candidate)?; - - let bps = (bitpix.unsigned_abs() / 8) as usize; - let plane_len = (w as usize).checked_mul(hgt as usize).ok_or_else(|| CodecError::LimitExceeded(format!("{w}x{hgt} does not fit in memory")))?; - let n = plane_len.checked_mul(nplanes).ok_or_else(|| CodecError::LimitExceeded("image does not fit in memory".into()))?; - let need = n.checked_mul(bps).and_then(|l| l.checked_add(h.data_start)).ok_or_else(|| err("data size overflows"))?; - let data = bytes.get(h.data_start..need).ok_or_else(|| err("truncated data"))?; - - // Physical value of sample `i` (planar order); `None` for a blank or NaN pixel. - let physical = |i: usize| -> Option { - let s = data.get(i * bps..(i + 1) * bps)?; - let raw = match bitpix { - 8 => s.first().map(|&v| v as i64)?, - 16 => i16::from_be_bytes([s[0], s[1]]) as i64, - 32 => i32::from_be_bytes([s[0], s[1], s[2], s[3]]) as i64, - 64 => i64::from_be_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]), - -32 => return Some(f32::from_be_bytes([s[0], s[1], s[2], s[3]]) as f64 * bscale + bzero).filter(|v| v.is_finite()), - _ => return Some(f64::from_be_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]) * bscale + bzero).filter(|v| v.is_finite()), - }; - if blank == Some(raw) { - return None; - } - Some(raw as f64 * bscale + bzero) - }; - - let top_down = h.string("ROWORDER").is_some_and(|r| r.eq_ignore_ascii_case("TOP-DOWN")); - let (wu, hu) = (w as usize, hgt as usize); - // Planar, bottom-up (by default) → interleaved, top-down. - let dest = |i: usize| -> usize { - let (p, rem) = (i / plane_len, i % plane_len); - let (y, x) = (rem / wu, rem % wu); - let y = if top_down { y } else { hu - 1 - y }; - (y * wu + x) * nplanes + p - }; - - let mut img = match candidate { - SampleType::U8 => { - let mut out = vec![0u8; n]; - for i in 0..n { - out[dest(i)] = physical(i).unwrap_or(0.0) as u8; - } - Image::from_u8(w, hgt, layout, out)? - } - _ => { - let mut out16 = if candidate == SampleType::U16 { Some(vec![0u16; n]) } else { None }; - if let Some(out) = out16.as_mut() { - for i in 0..n { - let v = physical(i).unwrap_or(0.0); - if !(0.0..=65535.0).contains(&v) { - // Signed data with negative values: fall back to float. - out16 = None; - break; - } - out[dest(i)] = v as u16; - } - } - match out16 { - Some(out) => Image::from_u16(w, hgt, layout, &out)?, - None => { - let max = (0..n).filter_map(physical).fold(0.0f64, f64::max); - let white = if max <= 2.0 { - 1.0 - } else if max <= 65535.0 { - 65535.0 - } else { - max - }; - let mut out = vec![0f32; n]; - for i in 0..n { - out[dest(i)] = (physical(i).unwrap_or(0.0) / white) as f32; - } - Image::from_f32(w, hgt, layout, &out)? - } - } - } - }; - - if planes > nplanes as u64 { - img.warnings.push(DecodeWarning::MorePages { total: u32::try_from(planes).ok() }); - } - let mut text = Vec::new(); - for c in primary.iter().flat_map(|p| p.cards.iter()).chain(h.cards.iter()) { - if !c.hierarch && (STRUCTURAL.contains(&c.key.as_str()) || is_naxis(&c.key)) { - continue; - } - let entry = match &c.value { - Some(Value::Str(s) | Value::Raw(s)) => (c.key.clone(), s.clone()), - None if c.key.is_empty() && c.text.trim().is_empty() => continue, - None => (if c.key.is_empty() { "COMMENT".to_string() } else { c.key.clone() }, c.text.trim().to_string()), - }; - text.push(entry); - } - img.meta.text = text; - Ok(img) -} - -fn is_naxis(key: &str) -> bool { - key.strip_prefix("NAXIS").is_some_and(|d| d.chars().all(|c| c.is_ascii_digit())) -} - -/// A standard keyword: 1–8 characters from `A-Z 0-9 _ -`. -fn standard_key(key: &str) -> bool { - (1..=8).contains(&key.len()) && key.bytes().all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_' || b == b'-') -} - -fn ascii(s: &str) -> String { - s.chars().map(|c| if (' '..='~').contains(&c) { c } else { '?' }).collect() -} - -/// A FITS literal (number or logical) that can be written unquoted. -fn literal(v: &str) -> bool { - v == "T" || v == "F" || (v.replace(['D', 'd'], "E").parse::().is_ok_and(|f| f.is_finite()) && v.bytes().all(|b| b"0123456789+-.EeDd".contains(&b))) -} - -fn quoted(v: &str, room: usize) -> String { - let mut s = String::from("'"); - for c in ascii(v).chars() { - let add = if c == '\'' { 2 } else { 1 }; - // Keep room for the closing quote. - if s.len() + add + 1 > room { - break; - } - s.push(c); - if c == '\'' { - s.push('\''); - } - } - // Strings are at least eight characters inside the quotes. - while s.len() < 9 { - s.push(' '); - } - s.push('\''); - s -} - -struct Writer { - out: Vec, -} - -impl Writer { - fn card(&mut self, text: &str) { - let mut c: Vec = ascii(text).into_bytes(); - c.truncate(CARD); - c.resize(CARD, b' '); - self.out.extend_from_slice(&c); - } - - fn value(&mut self, key: &str, v: &str) { - if literal(v) { - self.card(&format!("{key:<8}= {v:>20}")); - return; - } - // A string too long for one card goes on in `CONTINUE` cards, every piece but the last - // ending in '&' (FITS 4.0 section 4.2.1.2). A doubled quote is never split, and trailing - // blanks (not significant) are dropped so none are kept before an '&'. - let escaped = ascii(v).trim_end().replace('\'', "''"); - let mut rest = escaped.as_str(); - let mut head = format!("{key:<8}= "); - while rest.len() > CARD - 12 { - let cut = CARD - 13 - rest.get(..CARD - 13).unwrap_or("").bytes().rev().take_while(|&b| b == b'\'').count() % 2; - let (piece, tail) = rest.split_at_checked(cut).unwrap_or((rest, "")); - self.card(&format!("{head}'{piece}&'")); - head = "CONTINUE ".to_string(); - rest = tail; - } - self.card(&format!("{head}'{rest:<8}'")); - } - - fn commentary(&mut self, key: &str, text: &str) { - let chars: Vec = ascii(text).chars().collect(); - if chars.is_empty() { - self.card(key); - } - for chunk in chars.chunks(CARD - 8) { - self.card(&format!("{key:<8}{}", chunk.iter().collect::())); - } - } - - fn text(&mut self, key: &str, v: &str) { - let upper = key.to_ascii_uppercase(); - if matches!(upper.as_str(), "COMMENT" | "HISTORY") { - self.commentary(&upper, v); - } else if standard_key(key) { - // `CONTINUE` only ever carries a string's continuation, written by `value`. - if !STRUCTURAL.contains(&key) && !is_naxis(key) && key != "CONTINUE" { - self.value(key, v); - } - } else { - // Long or mixed-case names (`Description`, `Software`): the HIERARCH convention, - // when the card fits, else a comment. - let name = ascii(key); - let head = format!("HIERARCH {name} = "); - let fits_key = !name.contains('=') && !name.trim().is_empty(); - let body = if literal(v) { v.to_string() } else { quoted(v, CARD.saturating_sub(head.len())) }; - if fits_key && head.len() + body.len() <= CARD && (literal(v) || body.ends_with('\'')) && quoted_whole(v, &body) { - self.card(&format!("{head}{body}")); - } else { - self.commentary("COMMENT", &format!("{key} = {v}")); - } - } - } -} - -/// `body` holds all of `v` (it was not cut short to fit the card). -fn quoted_whole(v: &str, body: &str) -> bool { - literal(v) || body.trim_matches('\'').trim_end().replace("''", "'") == ascii(v).trim_end() -} - -pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result, CodecError> { - let img = src.converted(plan.layout, plan.sample); - let (w, h) = img.dimensions(); - let layout = img.layout(); - let nc = match layout { - ChannelLayout::Gray => 1, - ChannelLayout::Rgb => 3, - l => return Err(CodecError::encode(F, format!("FITS cannot store {l:?}"))), - }; - let bitpix = match img.sample_type() { - SampleType::U8 => 8, - SampleType::U16 => 16, - SampleType::F32 => -32, - s => return Err(CodecError::encode(F, format!("unsupported sample {s:?}"))), - }; - let mut wr = Writer { out: Vec::new() }; - wr.value("SIMPLE", "T"); - wr.value("BITPIX", &bitpix.to_string()); - wr.value("NAXIS", if nc == 3 { "3" } else { "2" }); - wr.value("NAXIS1", &w.to_string()); - wr.value("NAXIS2", &h.to_string()); - if nc == 3 { - wr.value("NAXIS3", "3"); - } - if bitpix == 16 { - wr.value("BZERO", "32768"); - wr.value("BSCALE", "1"); - } - wr.value("ROWORDER", "BOTTOM-UP"); - if opts.embed_metadata { - for (k, v) in &img.meta.text { - wr.text(k, v); - } - } - wr.card("END"); - let mut out = wr.out; - out.resize(out.len().div_ceil(BLOCK) * BLOCK, b' '); - - // Planar, bottom row first. - let (wu, hu) = (w as usize, h as usize); - let idx = |p: usize, y: usize, x: usize| ((hu - 1 - y) * wu + x) * nc + p; - match bitpix { - 8 => { - let d = img.data(); - for p in 0..nc { - for y in 0..hu { - for x in 0..wu { - out.push(d[idx(p, y, x)]); - } - } - } - } - 16 => { - let d = img.to_u16_samples().unwrap_or_default(); - for p in 0..nc { - for y in 0..hu { - for x in 0..wu { - out.extend_from_slice(&((d[idx(p, y, x)] as i32 - 32768) as i16).to_be_bytes()); - } - } - } - } - _ => { - let d = img.to_f32_samples().unwrap_or_default(); - for p in 0..nc { - for y in 0..hu { - for x in 0..wu { - // 0..1 as documented: a value above 2 would make readers (ours too) - // take the data as ADU and scale it by 65535. NaN is written as 0. - let v = d[idx(p, y, x)]; - let v = if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) }; - out.extend_from_slice(&v.to_be_bytes()); - } - } - } - } - } - out.resize(out.len().div_ceil(BLOCK) * BLOCK, 0); - Ok(out) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn header(cards: &[&str]) -> Vec { - let mut w = Writer { out: Vec::new() }; - for c in cards { - w.card(c); - } - w.card("END"); - let mut out = w.out; - out.resize(out.len().div_ceil(BLOCK) * BLOCK, b' '); - out - } - - #[test] - fn continue_strings_decode() { - let mut b = header(&[ - "SIMPLE = T", - "BITPIX = 8", - "NAXIS = 2", - "NAXIS1 = 1", - "NAXIS2 = 1", - "OBJECT = 'aaa&'", - "CONTINUE 'bbb&' / a comment", - "CONTINUE '&'", - "CONTINUE ''", - "OBSERVER= 'R&'", - "COMMENT hi", - "CONTINUE 'orphan'", - ]); - b.push(0); - let img = decode(&b, &Limits::default()).unwrap(); - let text = [("OBJECT", "aaabbb"), ("OBSERVER", "R&"), ("COMMENT", "hi"), ("CONTINUE", "'orphan'")]; - assert_eq!(img.meta.text, text.map(|(k, v)| (k.to_string(), v.to_string()))); - } - - #[test] - fn continue_strings_round_trip() { - for value in ["a".repeat(100), format!("{}' {}", "a".repeat(65), "b".repeat(100)), "'".repeat(100), "a".repeat(68)] { - let mut img = Image::from_u8(1, 1, ChannelLayout::Gray, vec![0]).unwrap(); - img.meta.text = vec![("OBJECT".into(), value.clone()), ("CONTINUE".into(), "orphan".into())]; - let b = crate::encode(&img, F, &EncodeOptions::default()).unwrap(); - assert!(!b.chunks(CARD).any(|c| c.starts_with(b"CONTINUE="))); - let decoded = decode(&b, &Limits::default()).unwrap(); - assert_eq!(decoded.meta.text, vec![("OBJECT".into(), value)]); - } - } - - #[test] - fn camera_u16_with_bzero_reads_exactly_and_bottom_up() { - let mut b = header(&[ - "SIMPLE = T", - "BITPIX = 16", - "NAXIS = 2", - "NAXIS1 = 2", - "NAXIS2 = 2", - "BZERO = 32768", - "OBJECT = 'M 31 '", - "EXPTIME = 300.0 / seconds", - ]); - for v in [0u16, 1000, 40000, 65535] { - b.extend_from_slice(&((v as i32 - 32768) as i16).to_be_bytes()); - } - b.resize(b.len().div_ceil(BLOCK) * BLOCK, 0); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.sample_type(), SampleType::U16); - // The first stored row is the bottom one. - assert_eq!(img.to_u16_samples().unwrap(), vec![40000, 65535, 0, 1000]); - assert!(img.meta.text.contains(&("OBJECT".into(), "M 31".into()))); - assert!(img.meta.text.contains(&("EXPTIME".into(), "300.0".into()))); - assert!(!img.meta.text.iter().any(|(k, _)| k == "BZERO" || k == "NAXIS1")); - } - - #[test] - fn roworder_top_down_is_honoured() { - let mut b = header(&["SIMPLE = T", "BITPIX = 8", "NAXIS = 2", "NAXIS1 = 1", "NAXIS2 = 2", "ROWORDER= 'TOP-DOWN'"]); - b.extend_from_slice(&[10, 20]); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.data(), &[10, 20]); - } - - #[test] - fn stacked_float_in_adu_is_scaled_by_65535() { - let mut b = header(&["SIMPLE = T", "BITPIX = -32", "NAXIS = 2", "NAXIS1 = 2", "NAXIS2 = 1"]); - for v in [65535.0f32, f32::NAN] { - b.extend_from_slice(&v.to_be_bytes()); - } - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.to_f32_samples().unwrap(), vec![1.0, 0.0]); - } - - #[test] - fn hdr_float_saves_clamped_and_reopens_as_saved() { - // One value above 2 used to make the reader scale everything by 65535 (all black). - let img = Image::from_f32(2, 1, ChannelLayout::Gray, &[0.5, 3.0]).unwrap(); - let opts = EncodeOptions::default(); - let bytes = encode(&img, crate::fidelity::plan(&img, F, &opts), &opts).unwrap(); - let back = decode(&bytes, &Limits::default()).unwrap().to_f32_samples().unwrap(); - assert!((back[0] - 0.5).abs() < 1e-6, "{back:?}"); - assert!((back[1] - 1.0).abs() < 1e-6, "{back:?}"); - } - - #[test] - fn signed_negative_data_falls_back_to_float() { - let mut b = header(&["SIMPLE = T", "BITPIX = 16", "NAXIS = 2", "NAXIS1 = 2", "NAXIS2 = 1"]); - for v in [-100i16, 1000] { - b.extend_from_slice(&v.to_be_bytes()); - } - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.sample_type(), SampleType::F32); - } - - #[test] - fn image_extension_after_empty_primary() { - let mut b = header(&["SIMPLE = T", "BITPIX = 8", "NAXIS = 0", "EXTEND = T", "TELESCOP= 'Seestar S50'"]); - b.extend(header(&["XTENSION= 'IMAGE '", "BITPIX = 8", "NAXIS = 2", "NAXIS1 = 1", "NAXIS2 = 1", "PCOUNT = 0", "GCOUNT = 1"])); - b.push(42); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.data(), &[42]); - assert!(img.meta.text.contains(&("TELESCOP".into(), "Seestar S50".into()))); - } - - /// A zero axis (`NAXIS3 = 0`) means the HDU has no data: it is neither the opened image nor - /// an additional one that Batch Save and Close would discard. - #[test] - fn zero_axis_image_hdus_are_empty() { - let empty = |primary: bool| { - let first = if primary { "SIMPLE = T" } else { "XTENSION= 'IMAGE '" }; - header(&[first, "BITPIX = 8", "NAXIS = 3", "NAXIS1 = 1", "NAXIS2 = 1", "NAXIS3 = 0", "PCOUNT = 0", "GCOUNT = 1"]) - }; - let image = || { - let mut b = header(&["XTENSION= 'IMAGE '", "BITPIX = 8", "NAXIS = 2", "NAXIS1 = 1", "NAXIS2 = 1", "PCOUNT = 0", "GCOUNT = 1"]); - b.push(42); - b.resize(b.len().div_ceil(BLOCK) * BLOCK, 0); - b - }; - let mut after_empty_primary = empty(true); - after_empty_primary.extend(image()); - let mut after_empty_extension = header(&["SIMPLE = T", "BITPIX = 8", "NAXIS = 0", "EXTEND = T"]); - after_empty_extension.extend(empty(false)); - after_empty_extension.extend(image()); - let mut before_empty_extension = header(&["SIMPLE = T", "BITPIX = 8", "NAXIS = 0", "EXTEND = T"]); - before_empty_extension.extend(image()); - before_empty_extension.extend(empty(false)); - for b in [&after_empty_primary, &after_empty_extension, &before_empty_extension] { - assert!(!crate::has_unretained_source_data(b).unwrap()); - assert_eq!(decode(b, &Limits::default()).unwrap().data(), &[42]); - } - // Only empty HDUs: nothing to open, nothing to lose. - assert!(!crate::has_unretained_source_data(&empty(true)).unwrap()); - assert!(decode(&empty(true), &Limits::default()).is_err()); - // A second non-empty image is still additional data. - let mut two = after_empty_primary.clone(); - two.extend(image()); - assert!(crate::has_unretained_source_data(&two).unwrap()); - } - - #[test] - fn fpack_is_refused_as_unsupported() { - let mut b = header(&["SIMPLE = T", "BITPIX = 8", "NAXIS = 0"]); - b.extend(header(&["XTENSION= 'BINTABLE'", "BITPIX = 8", "NAXIS = 2", "NAXIS1 = 0", "NAXIS2 = 0", "ZIMAGE = T"])); - b.extend(header(&["XTENSION= 'BINTABLE'", "BITPIX = 8", "NAXIS = 1", "NAXIS1 = 0"])); - assert!(matches!(decode(&b, &Limits::default()), Err(CodecError::Unsupported { .. }))); - } - - /// Hostile headers: absurd or negative axes, bad BITPIX, overflowing sizes, missing END, - /// a long chain of empty HDUs and declared data past the end all error, never panic or - /// allocate the declared size. - #[test] - fn hostile_headers_error_without_panicking() { - let base = ["SIMPLE = T", "BITPIX = 16"]; - let cases: &[&[&str]] = &[ - &["NAXIS = 2", "NAXIS1 = 4294967296", "NAXIS2 = 1"], - &["NAXIS = 2", "NAXIS1 = -5", "NAXIS2 = 1"], - &["NAXIS = 2", "NAXIS1 = 2000000", "NAXIS2 = 2000000"], - &["NAXIS = 3", "NAXIS1 = 65536", "NAXIS2 = 65536", "NAXIS3 = 9223372036854775807"], - &["NAXIS = 1000"], - &["NAXIS = -1"], - &["NAXIS = 2", "NAXIS1 = 0", "NAXIS2 = 0"], - &["NAXIS = 2", "NAXIS1 = 1.5D300", "NAXIS2 = 1"], - &["NAXIS = 2"], - &["NAXIS = 2", "NAXIS1 = 100", "NAXIS2 = 100"], - ]; - for extra in cases { - let cards: Vec<&str> = base.iter().chain(extra.iter()).copied().collect(); - let b = header(&cards); - assert!(decode(&b, &Limits::default()).is_err(), "{extra:?}"); - } - for bitpix in ["0", "7", "-16", "128", "'X'"] { - let card = format!("BITPIX = {bitpix}"); - let b = header(&["SIMPLE = T", &card, "NAXIS = 2", "NAXIS1 = 1", "NAXIS2 = 1"]); - assert!(decode(&b, &Limits::default()).is_err(), "BITPIX {bitpix}"); - } - // No END card: the header runs off the end of the file. - let mut w = Writer { out: Vec::new() }; - for c in ["SIMPLE = T", "BITPIX = 8", "NAXIS = 2"] { - w.card(c); - } - assert!(decode(&w.out, &Limits::default()).is_err()); - // An empty primary followed by many empty extensions: bounded walk, then "no image". - let mut b = header(&["SIMPLE = T", "BITPIX = 8", "NAXIS = 0"]); - for _ in 0..(MAX_HDUS + 5) { - b.extend(header(&["XTENSION= 'IMAGE '", "BITPIX = 8", "NAXIS = 0"])); - } - assert!(decode(&b, &Limits::default()).is_err()); - // An extension whose declared data size overflows. - let mut b = header(&["SIMPLE = T", "BITPIX = 8", "NAXIS = 0"]); - b.extend(header(&[ - "XTENSION= 'BINTABLE'", - "BITPIX = 64", - "NAXIS = 2", - "NAXIS1 = 9223372036854775807", - "NAXIS2 = 4", - "PCOUNT = 0", - "GCOUNT = 1", - ])); - assert!(decode(&b, &Limits::default()).is_err()); - } - - #[test] - fn extra_planes_warn() { - let mut b = header(&["SIMPLE = T", "BITPIX = 8", "NAXIS = 3", "NAXIS1 = 1", "NAXIS2 = 1", "NAXIS3 = 4"]); - b.extend_from_slice(&[1, 2, 3, 4]); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.layout(), ChannelLayout::Gray); - assert_eq!(img.warnings, vec![DecodeWarning::MorePages { total: Some(4) }]); - } - - #[test] - fn strings_with_quotes_and_hierarch_round_trip() { - let mut w = Writer { out: Vec::new() }; - w.text("OBSERVER", "O'Brien"); - w.text("Software", "photocraft 1.0"); - w.text("HISTORY", "stacked"); - let cards: Vec = w.out.chunks(CARD).map(parse_card).collect(); - assert_eq!(cards[0].value, Some(Value::Str("O'Brien".into()))); - assert!(cards[1].hierarch && cards[1].key == "Software"); - assert_eq!(cards[1].value, Some(Value::Str("photocraft 1.0".into()))); - assert_eq!((cards[2].key.as_str(), cards[2].text.as_str()), ("HISTORY", "stacked")); - } -} diff --git a/crates/codecs/src/codecs/gif_palette.rs b/crates/codecs/src/codecs/gif_palette.rs deleted file mode 100644 index eb0a0e2180..0000000000 --- a/crates/codecs/src/codecs/gif_palette.rs +++ /dev/null @@ -1,126 +0,0 @@ -//! The colour table of a GIF, read from its blocks without decoding pixels (GIF89a -//! specification: Logical Screen Descriptor, Global and Local Color Tables, Graphic Control -//! Extension). -//! -//! A GIF is always palette-based, so it opens in Indexed Color with the table of the frame that -//! [`crate::decode`] keeps, the first: its Local Color Table when it has one, else the Global -//! one, and the transparent entry that frame's Graphic Control Extension names. - -/// Colours of the table the first frame uses, and its transparent entry. `None` for anything -/// that isn't a well-formed GIF up to its first image, or a first frame without a table. -pub(crate) fn palette(b: &[u8]) -> Option<(Vec<[u8; 3]>, Option)> { - if !(b.starts_with(b"GIF87a") || b.starts_with(b"GIF89a")) { - return None; - } - // Logical Screen Descriptor: width, height, packed fields, background, aspect. - let packed = *b.get(10)?; - let mut at = 13; - let table = |at: usize, packed: u8| -> Option> { - let n = 2usize << (packed & 0x07); - let bytes = b.get(at..at.checked_add(n.checked_mul(3)?)?)?; - Some(bytes.as_chunks::<3>().0.to_vec()) - }; - let global = if packed & 0x80 != 0 { - let t = table(at, packed)?; - at += t.len() * 3; - Some(t) - } else { - None - }; - let mut transparent = None; - loop { - match *b.get(at)? { - // Extension: label, then data sub-blocks up to a zero-length one. - 0x21 => { - let label = *b.get(at + 1)?; - at += 2; - // Graphic Control Extension: block size 4, packed (bit 0: transparent colour - // given), delay (2 bytes), transparent colour index. - if label == 0xF9 && *b.get(at)? == 4 { - let flags = *b.get(at + 1)?; - transparent = (flags & 0x01 != 0).then_some(*b.get(at + 4)?); - } - loop { - let size = usize::from(*b.get(at)?); - at = at.checked_add(1 + size)?; - if size == 0 { - break; - } - } - } - // Image Descriptor: position and size (8 bytes), packed fields, then the Local Color - // Table if bit 7 is set. This is the first frame: its table is the one used. - 0x2C => { - let packed = *b.get(at + 9)?; - let colors = if packed & 0x80 != 0 { table(at + 10, packed)? } else { global? }; - let transparent = transparent.filter(|i| usize::from(*i) < colors.len()); - return Some((colors, transparent)); - } - // Trailer, or anything else: no image. - _ => return None, - } - } -} - -#[cfg(test)] -mod tests { - use super::palette; - - /// A GIF up to its first image: `global` table entries, optional GCE transparency, optional - /// local table. - fn gif(global: &[[u8; 3]], transparent: Option, local: Option<&[[u8; 3]]>) -> Vec { - let size_bits = |n: usize| (n.max(2).next_power_of_two().trailing_zeros() - 1) as u8; - let mut b = b"GIF89a".to_vec(); - b.extend([4, 0, 4, 0]); - b.push(if global.is_empty() { 0 } else { 0x80 | size_bits(global.len()) }); - b.extend([0, 0]); - let pad = |b: &mut Vec, t: &[[u8; 3]]| { - let n = 2usize << size_bits(t.len()); - for k in 0..n { - b.extend(t.get(k).copied().unwrap_or([0, 0, 0])); - } - }; - if !global.is_empty() { - pad(&mut b, global); - } - // A comment extension first, to skip. - b.extend([0x21, 0xFE, 3, b'h', b'i', b'!', 0]); - if let Some(i) = transparent { - b.extend([0x21, 0xF9, 4, 0x01, 0, 0, i, 0]); - } - b.extend([0x2C, 0, 0, 0, 0, 4, 0, 4, 0]); - match local { - Some(t) => { - b.push(0x80 | size_bits(t.len())); - pad(&mut b, t); - } - None => b.push(0), - } - b.extend([2, 2, 0x4C, 0x01, 0, 0x3B]); - b - } - - #[test] - fn the_first_frames_table_and_transparent_entry() { - let g = [[255, 0, 0], [0, 255, 0], [0, 0, 255], [255, 255, 255]]; - assert_eq!(palette(&gif(&g, None, None)), Some((g.to_vec(), None))); - assert_eq!(palette(&gif(&g, Some(2), None)), Some((g.to_vec(), Some(2)))); - // A local table wins over the global one. - let l = [[1, 2, 3], [4, 5, 6]]; - assert_eq!(palette(&gif(&g, Some(1), Some(&l))), Some((l.to_vec(), Some(1)))); - // A transparent index past the table is no transparent entry. - assert_eq!(palette(&gif(&l, Some(9), None)), Some((l.to_vec(), None))); - } - - #[test] - fn no_table_or_not_a_gif_is_none() { - assert_eq!(palette(&gif(&[], None, None)), None, "no table at all"); - assert_eq!(palette(b"\x89PNG\r\n\x1a\n"), None); - assert_eq!(palette(b""), None); - let whole = gif(&[[9, 9, 9], [8, 8, 8]], Some(0), None); - for cut in 0..whole.len() - 6 { - // Cut short anywhere before the image descriptor's fields: never a panic. - let _ = palette(&whole[..cut]); - } - } -} diff --git a/crates/codecs/src/codecs/iff.rs b/crates/codecs/src/codecs/iff.rs deleted file mode 100644 index 4997817ca9..0000000000 --- a/crates/codecs/src/codecs/iff.rs +++ /dev/null @@ -1,544 +0,0 @@ -//! Amiga IFF/ILBM reader and writer (EA "Interchange File Format", "InterLeaved BitMap" and the -//! chunky "PBM " variant). Written from the published IFF/ILBM layout: a `FORM` chunk of four-byte -//! chunks (`BMHD` bitmap header, `CMAP` palette, `CAMG` Amiga viewport mode, `BODY` pixel data). -//! -//! Read: 1–8 bitplanes with a palette (or a gray ramp when there is none) with masking 0/1/2, and -//! 24-bitplane "deep" ILBMs (8 planes each of red, green and blue, least significant bit first, -//! no palette) with masking 0/1, both stored (0) and ByteRun1/PackBits (1) compressed. Anything -//! else is a clear `Unsupported`/`Malformed` error, never a panic. -//! -//! Write: a 24-bitplane ILBM, ByteRun1 compressed one plane row at a time, with a mask plane -//! (masking 1) when the image has alpha. The mask plane is one bit per pixel: alpha of 128 or -//! more is opaque. - -use crate::error::CodecError; -use crate::fidelity::Plan; -use crate::format::Format; -use crate::image::{ChannelLayout, Image, SampleType}; -use crate::options::Limits; - -const F: Format = Format::Iff; - -fn bad(msg: impl std::fmt::Display) -> CodecError { - CodecError::malformed(F, msg) -} - -fn unsupported(msg: impl Into) -> CodecError { - CodecError::unsupported(F, msg) -} - -fn be32(b: &[u8], at: usize) -> Option { - let s = b.get(at..at.checked_add(4)?)?.try_into().ok()?; - Some(u32::from_be_bytes(s)) -} - -fn be16(b: &[u8], at: usize) -> Option { - let s = b.get(at..at.checked_add(2)?)?.try_into().ok()?; - Some(u16::from_be_bytes(s)) -} - -/// `FORM` + a bitmap type (`ILBM` interleaved, `PBM ` chunky) at offset 8. -pub(crate) fn looks_like_iff(b: &[u8]) -> bool { - b.get(0..4) == Some(b"FORM") && matches!(b.get(8..12), Some(b"ILBM" | b"PBM ")) -} - -/// Bitplanes of a "deep" ILBM: red, green and blue, 8 each, least significant bit first. -const DEEP_PLANES: u8 = 24; - -/// The bitmap header fields decoding needs. -struct Header { - width: u32, - height: u32, - planes: u8, - masking: u8, - compression: u8, - transparent: u16, - /// `PBM ` stores one palette index per byte, padded to even row lengths. - chunky: bool, -} - -/// One four-byte chunk's id and byte range. -struct Chunk<'a> { - id: [u8; 4], - data: &'a [u8], -} - -/// Walk the `FORM`'s chunks from offset 12 to `end` (the form length), stopping at the first -/// malformed length so a hostile file can't run past the buffer. -fn chunks(b: &[u8]) -> impl Iterator> { - let end = be32(b, 4).map_or(b.len(), |n| (n as usize).saturating_add(8).min(b.len())); - let mut pos = 12usize; - std::iter::from_fn(move || { - if pos + 8 > end { - return None; - } - let id = b.get(pos..pos + 4)?.try_into().ok()?; - let len = be32(b, pos + 4)? as usize; - let start = pos + 8; - let data = b.get(start..start.checked_add(len)?)?; - // Chunks are padded to an even length. - pos = start.checked_add(len)?.checked_add(len & 1)?; - Some(Chunk { id, data }) - }) -} - -fn parse_header(b: &[u8], chunky: bool) -> Result { - let bmhd = chunks(b).find(|c| &c.id == b"BMHD").ok_or_else(|| bad("no BMHD chunk"))?; - let d = bmhd.data; - if d.len() < 20 { - return Err(bad("BMHD chunk is too short")); - } - let width = u32::from(be16(d, 0).ok_or_else(|| bad("BMHD width"))?); - let height = u32::from(be16(d, 2).ok_or_else(|| bad("BMHD height"))?); - let planes = *d.get(8).ok_or_else(|| bad("BMHD planes"))?; - let masking = *d.get(9).ok_or_else(|| bad("BMHD masking"))?; - let compression = *d.get(10).ok_or_else(|| bad("BMHD compression"))?; - if width == 0 || height == 0 { - return Err(bad("zero-sized bitmap")); - } - if !(1..=8).contains(&planes) && planes != DEEP_PLANES { - return Err(unsupported(format!("{planes} bitplanes (1–8 with a palette, or 24)"))); - } - if masking > 2 { - return Err(unsupported(format!("masking {masking}"))); - } - if planes == DEEP_PLANES && masking == 2 { - return Err(unsupported("a transparent color in a 24-bitplane ILBM")); - } - if compression > 1 { - return Err(unsupported(format!("compression {compression} (only stored and ByteRun1)"))); - } - if chunky && (planes != 8 || masking == 1) { - return Err(unsupported("PBM requires 8-bit indices without a mask plane")); - } - let transparent = be16(d, 12).ok_or_else(|| bad("BMHD transparent colour"))?; - Ok(Header { width, height, planes, masking, compression, transparent, chunky }) -} - -/// ByteRun1 / PackBits decode of one plane row into `out`; returns the bytes consumed. A `0x80` -/// control byte is a no-op, as the layout specifies. -fn unpack_byte_run1(src: &[u8], out: &mut [u8]) -> Result { - let (mut i, mut o) = (0usize, 0usize); - while o < out.len() { - let n = *src.get(i).ok_or_else(|| bad("truncated ByteRun1 data"))? as i8; - i += 1; - if n >= 0 { - let count = n as usize + 1; - let lit = src.get(i..i.checked_add(count).ok_or_else(|| bad("ByteRun1 overflow"))?).ok_or_else(|| bad("truncated ByteRun1 run"))?; - if count > out.len() - o { - return Err(bad("ByteRun1 run crosses the plane row")); - } - out[o..o + count].copy_from_slice(lit); - i += count; - o += count; - } else if n != -128 { - let count = (1 - n as i32) as usize; - let value = *src.get(i).ok_or_else(|| bad("truncated ByteRun1 repeat"))?; - i += 1; - if count > out.len() - o { - return Err(bad("ByteRun1 repeat crosses the plane row")); - } - out[o..o + count].fill(value); - o += count; - } - } - Ok(i) -} - -pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { - if !looks_like_iff(b) { - return Err(bad("not an IFF/ILBM file (no FORM ... ILBM)")); - } - let h = parse_header(b, b.get(8..12) == Some(b"PBM "))?; - if let Some(camg) = chunks(b).find(|c| &c.id == b"CAMG") { - let mode = be32(camg.data, 0).ok_or_else(|| bad("short CAMG chunk"))?; - if mode & (0x80 | 0x800) != 0 { - return Err(unsupported("EHB and HAM viewport modes")); - } - } - let layout = if h.masking == 0 { ChannelLayout::Rgb } else { ChannelLayout::Rgba }; - limits.check(h.width, h.height, layout, SampleType::U8)?; - - // Palette: three bytes per colour; missing entries read as black. - let cmap = chunks(b).find(|c| &c.id == b"CMAP").map(|c| c.data).filter(|p| !p.is_empty()); - let colors = 1usize << h.planes; - let palette = |idx: usize| -> [u8; 3] { - if let Some(p) = cmap { - p.get(idx * 3..idx * 3 + 3).map(|c| [c[0], c[1], c[2]]).unwrap_or([0; 3]) - } else { - let v = ((idx as u32 * 255) / (colors as u32 - 1).max(1)) as u8; - [v, v, v] - } - }; - - let body = chunks(b).find(|c| &c.id == b"BODY").map(|c| c.data).ok_or_else(|| bad("no BODY chunk"))?; - let (w, hh) = (h.width as usize, h.height as usize); - // Each plane row is stored as a whole number of 16-bit words. - let plane_row = if h.chunky { w.div_ceil(2) * 2 } else { w.div_ceil(16) * 2 }; - // A masking type 1 bitmap carries one extra (mask) plane per row. - let rows_planes: usize = if h.chunky { 1 } else { usize::from(h.planes) + usize::from(h.masking == 1) }; - - // Decode every stored plane row up front, then recombine. - let total_rows = hh.checked_mul(rows_planes).ok_or_else(|| CodecError::LimitExceeded("bitmap too large".into()))?; - let total_bytes = total_rows.checked_mul(plane_row).ok_or_else(|| CodecError::LimitExceeded("bitmap too large".into()))?; - if total_bytes as u64 > limits.max_alloc { - return Err(CodecError::LimitExceeded("bitmap storage exceeds max_alloc".into())); - } - Limits::check_plausible(total_bytes as u64, body.len(), if h.compression == 0 { 1 } else { 128 })?; - let mut stored = crate::options::alloc_zeroed::(total_bytes)?; - let mut cursor = 0usize; - for row in stored.chunks_mut(plane_row.max(1)).take(total_rows) { - match h.compression { - 0 => { - let src = body.get(cursor..cursor.checked_add(plane_row).ok_or_else(|| bad("BODY overflow"))?).ok_or_else(|| bad("truncated BODY data"))?; - let n = row.len().min(src.len()); - row[..n].copy_from_slice(&src[..n]); - cursor += plane_row; - } - _ => { - let tail = body.get(cursor..).ok_or_else(|| bad("truncated BODY data"))?; - cursor += unpack_byte_run1(tail, row)?; - } - } - } - - let mut out = Vec::new(); - out.try_reserve_exact(w.saturating_mul(hh).saturating_mul(layout.channels())).map_err(|_| CodecError::LimitExceeded("cannot allocate the image".into()))?; - let planes = usize::from(h.planes); - for y in 0..hh { - for x in 0..w { - let index = if h.chunky { - usize::from(*stored.get(y * plane_row + x).ok_or_else(|| bad("PBM pixel outside BODY"))?) - } else { - (0..planes).filter(|&p| bit_at(&stored, (y * rows_planes + p) * plane_row, x)).fold(0usize, |acc, p| acc | (1 << p)) - }; - let c = if h.planes == DEEP_PLANES { [index as u8, (index >> 8) as u8, (index >> 16) as u8] } else { palette(index) }; - out.extend_from_slice(&c); - if h.masking != 0 { - let opaque = if h.masking == 1 { bit_at(&stored, (y * rows_planes + planes) * plane_row, x) } else { index != usize::from(h.transparent) }; - out.push(if opaque { 255 } else { 0 }); - } - } - } - Image::from_u8(h.width, h.height, layout, out) -} - -/// The bit for pixel `x` of a stored plane row at `base` (bits run MSB-first). -fn bit_at(stored: &[u8], base: usize, x: usize) -> bool { - stored.get(base + x / 8).is_some_and(|byte| byte & (0x80 >> (x % 8)) != 0) -} - -/// ByteRun1 / PackBits encode of one plane row, appended to `out`: three or more equal bytes -/// become a repeat (at most 128), everything else literal runs (at most 128 bytes). -fn pack_byte_run1(row: &[u8], out: &mut Vec) { - let mut i = 0usize; - while let Some(&value) = row.get(i) { - let repeat = row[i..].iter().take(128).take_while(|&&b| b == value).count(); - if repeat >= 3 { - out.push((1 - repeat as i32) as i8 as u8); - out.push(value); - i += repeat; - continue; - } - let start = i; - while i < row.len() && i - start < 128 { - if row.get(i..i + 3).is_some_and(|r| r[0] == r[1] && r[1] == r[2]) { - break; - } - i += 1; - } - out.push((i - start - 1) as u8); - out.extend_from_slice(&row[start..i]); - } -} - -fn push_chunk(out: &mut Vec, id: &[u8; 4], data: &[u8]) -> Result<(), CodecError> { - let len = u32::try_from(data.len()).map_err(|_| CodecError::encode(F, "chunk too large for an IFF file (4 GiB)"))?; - out.extend_from_slice(id); - out.extend_from_slice(&len.to_be_bytes()); - out.extend_from_slice(data); - // Chunks are padded to an even length. - if data.len() % 2 == 1 { - out.push(0); - } - Ok(()) -} - -/// Writes a 24-bitplane `FORM ILBM`: `BMHD` then a ByteRun1-compressed `BODY`, each row stored as -/// the red, green and blue planes (least significant bit first) and, for RGBA, a mask plane. -pub(crate) fn encode(src: &Image, plan: Plan) -> Result, CodecError> { - let enc = |msg: String| CodecError::encode(F, msg); - let img = src.converted(plan.layout, plan.sample); - let masked = match img.layout() { - ChannelLayout::Rgb => false, - ChannelLayout::Rgba => true, - l => return Err(enc(format!("IFF/ILBM cannot store {l:?}"))), - }; - if img.sample_type() != SampleType::U8 { - return Err(enc(format!("IFF/ILBM cannot store {:?} samples", img.sample_type()))); - } - let (w, h) = img.dimensions(); - let (Ok(w16), Ok(h16)) = (u16::try_from(w), u16::try_from(h)) else { - return Err(enc("IFF/ILBM stores at most 65535 × 65535 pixels".into())); - }; - let (w, ch) = (w as usize, img.layout().channels()); - let data = img.data(); - let row_len = w.checked_mul(ch).ok_or_else(|| enc("image too large".into()))?; - if data.len() != row_len.checked_mul(h as usize).ok_or_else(|| enc("image too large".into()))? { - return Err(enc("the image has the wrong number of samples".into())); - } - let planes = usize::from(DEEP_PLANES) + usize::from(masked); - let mut plane_row = vec![0u8; w.div_ceil(16) * 2]; - let mut body = Vec::new(); - for px in data.chunks_exact(row_len.max(1)) { - for plane in 0..planes { - plane_row.fill(0); - for (x, p) in px.chunks_exact(ch).enumerate() { - let on = if plane == usize::from(DEEP_PLANES) { p[3] >= 128 } else { (p[plane / 8] >> (plane % 8)) & 1 == 1 }; - if on { - plane_row[x / 8] |= 0x80 >> (x % 8); - } - } - pack_byte_run1(&plane_row, &mut body); - } - } - - let mut bmhd = Vec::with_capacity(20); - bmhd.extend_from_slice(&w16.to_be_bytes()); - bmhd.extend_from_slice(&h16.to_be_bytes()); - bmhd.extend_from_slice(&[0, 0, 0, 0]); // x/y origin - bmhd.push(DEEP_PLANES); - bmhd.push(u8::from(masked)); // masking: 1 = a mask plane follows the color planes - bmhd.push(1); // ByteRun1 - bmhd.push(0); // pad - bmhd.extend_from_slice(&[0, 0]); // transparent color (unused) - bmhd.extend_from_slice(&[1, 1]); // square pixels - bmhd.extend_from_slice(&w16.to_be_bytes()); // page size - bmhd.extend_from_slice(&h16.to_be_bytes()); - - let mut out = b"FORM".to_vec(); - out.extend_from_slice(&[0; 4]); // patched below - out.extend_from_slice(b"ILBM"); - push_chunk(&mut out, b"BMHD", &bmhd)?; - push_chunk(&mut out, b"BODY", &body)?; - let form_len = u32::try_from(out.len() - 8).map_err(|_| enc("image too large for an IFF file (4 GiB)".into()))?; - out[4..8].copy_from_slice(&form_len.to_be_bytes()); - Ok(out) -} - -#[cfg(test)] -mod tests { - use super::*; - - /// A `FORM ILBM` with a `BMHD`, `CMAP` and `BODY`. `planes` plane rows per row, - /// `compression` 0 (stored) or 1 (ByteRun1), MSB-first. - fn ilbm(w: u16, h: u16, planes: u8, palette: &[[u8; 3]], compression: u8, body: &[u8]) -> Vec { - let mut b = b"FORM".to_vec(); - b.extend_from_slice(&0u32.to_be_bytes()); // patched below - b.extend_from_slice(b"ILBM"); - // BMHD (20 bytes) - b.extend_from_slice(b"BMHD"); - b.extend_from_slice(&20u32.to_be_bytes()); - b.extend_from_slice(&w.to_be_bytes()); - b.extend_from_slice(&h.to_be_bytes()); - b.extend_from_slice(&[0, 0, 0, 0]); // x/y origin - b.push(planes); - b.push(0); // masking - b.push(compression); - b.push(0); // pad - b.extend_from_slice(&[0, 0]); // transparent colour - b.extend_from_slice(&[1, 1]); // aspect - b.extend_from_slice(&[0, 0, 0, 0]); // page size - // CMAP - b.extend_from_slice(b"CMAP"); - b.extend_from_slice(&((palette.len() * 3) as u32).to_be_bytes()); - for c in palette { - b.extend_from_slice(c); - } - if palette.len() % 2 == 1 { - b.push(0); - } - // BODY - b.extend_from_slice(b"BODY"); - b.extend_from_slice(&(body.len() as u32).to_be_bytes()); - b.extend_from_slice(body); - if body.len() % 2 == 1 { - b.push(0); - } - let size = (b.len() - 8) as u32; - b[4..8].copy_from_slice(&size.to_be_bytes()); - b - } - - #[test] - fn reads_a_stored_two_plane_bitmap() { - // 2×1, 2 planes: pixel 0 index 0 (plane bits 0,0), pixel 1 index 3 (bits 1,1). - // Plane 0 = 0b0100_0000, plane 1 = 0b0100_0000, each padded to 2 bytes. - let body = [0b0100_0000, 0, 0b0100_0000, 0]; - let pal = [[10, 20, 30], [40, 50, 60], [70, 80, 90], [100, 110, 120]]; - let b = ilbm(2, 1, 2, &pal, 0, &body); - assert!(looks_like_iff(&b)); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!((img.width(), img.height(), img.layout()), (2, 1, ChannelLayout::Rgb)); - assert_eq!(img.data(), &[10, 20, 30, 100, 110, 120]); - } - - #[test] - fn reads_byte_run1_compressed_rows() { - // Same image, ByteRun1: literal run of two bytes (0x01) then the two plane bytes each row. - let body = [0x01, 0b0100_0000, 0, 0x01, 0b0100_0000, 0]; - let pal = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [250, 251, 252]]; - let b = ilbm(2, 1, 2, &pal, 1, &body); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.data(), &[1, 2, 3, 250, 251, 252]); - } - - #[test] - fn no_palette_falls_back_to_a_grey_ramp() { - // 2×1, 1 plane, no CMAP: indices 0 and 1 → black and white. - let body = [0b0100_0000, 0]; - let b = ilbm(2, 1, 1, &[], 0, &body); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.data(), &[0, 0, 0, 255, 255, 255]); - } - - #[test] - fn pbm_reads_chunky_indices_with_odd_width_padding() { - let pal = [[10, 20, 30], [40, 50, 60], [70, 80, 90]]; - for (compression, body) in [(0, vec![2, 0, 1, 255, 1, 2, 0, 255]), (1, vec![3, 2, 0, 1, 255, 3, 1, 2, 0, 255])] { - let mut b = ilbm(3, 2, 8, &pal, compression, &body); - b[8..12].copy_from_slice(b"PBM "); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.data(), &[70, 80, 90, 10, 20, 30, 40, 50, 60, 40, 50, 60, 70, 80, 90, 10, 20, 30]); - } - } - - #[test] - fn transparency_uses_the_mask_plane_or_transparent_index() { - for masking in [1, 2] { - let mut b = ilbm(2, 1, 1, &[[10, 20, 30], [40, 50, 60]], 0, if masking == 1 { &[0x40, 0, 0x40, 0] } else { &[0x40, 0] }); - b[29] = masking; - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!(img.layout(), ChannelLayout::Rgba); - assert_eq!(img.data(), &[10, 20, 30, 0, 40, 50, 60, 255]); - } - let mut b = ilbm(2, 1, 8, &[[10, 20, 30], [40, 50, 60]], 0, &[0, 1]); - b[8..12].copy_from_slice(b"PBM "); - b[29] = 2; - b[32..34].copy_from_slice(&1u16.to_be_bytes()); - assert_eq!(decode(&b, &Limits::default()).unwrap().data(), &[10, 20, 30, 255, 40, 50, 60, 0]); - } - - #[test] - fn rejects_ham_and_ehb_instead_of_returning_wrong_colours() { - for mode in [0x80u32, 0x800] { - let mut b = ilbm(1, 1, 1, &[], 0, &[0, 0]); - b.extend_from_slice(b"CAMG"); - b.extend_from_slice(&4u32.to_be_bytes()); - b.extend_from_slice(&mode.to_be_bytes()); - let len = (b.len() - 8) as u32; - b[4..8].copy_from_slice(&len.to_be_bytes()); - assert!(matches!(decode(&b, &Limits::default()), Err(CodecError::Unsupported { .. }))); - } - } - - #[test] - fn missing_palette_entries_are_black() { - let b = ilbm(1, 1, 2, &[[10, 20, 30]], 0, &[0x80, 0, 0x80, 0]); - assert_eq!(decode(&b, &Limits::default()).unwrap().data(), &[0, 0, 0]); - } - - fn plan(layout: ChannelLayout) -> Plan { - Plan { layout, sample: SampleType::U8 } - } - - #[test] - fn reads_a_stored_24_plane_bitmap() { - // 2×1: pixel 0 = (1, 0, 128), pixel 1 = (0, 255, 0). Each plane row is 2 bytes; red bit 0 - // has pixel 0 set, green bits 0–7 have pixel 1 set, blue bit 7 has pixel 0 set. - let mut body = Vec::new(); - for plane in 0..24 { - let byte = match plane { - 0 | 23 => 0x80, - 8..=15 => 0x40, - _ => 0, - }; - body.extend_from_slice(&[byte, 0]); - } - let b = ilbm(2, 1, 24, &[], 0, &body); - let img = decode(&b, &Limits::default()).unwrap(); - assert_eq!((img.width(), img.height(), img.layout()), (2, 1, ChannelLayout::Rgb)); - assert_eq!(img.data(), &[1, 0, 128, 0, 255, 0]); - } - - #[test] - fn writes_24_plane_byte_run1_that_reads_back_exactly() { - // 37 pixels wide: three plane-row words, the last one partly padding. - let (w, h) = (37u32, 3u32); - let data: Vec = (0..w * h * 3).map(|i| (i * 7 % 256) as u8).collect(); - let img = Image::from_u8(w, h, ChannelLayout::Rgb, data.clone()).unwrap(); - let bytes = encode(&img, plan(ChannelLayout::Rgb)).unwrap(); - assert!(looks_like_iff(&bytes)); - assert_eq!(be32(&bytes, 4).unwrap() as usize, bytes.len() - 8, "FORM length"); - let h = parse_header(&bytes, false).unwrap(); - assert_eq!((h.width, h.height, h.planes, h.masking, h.compression), (37, 3, 24, 0, 1)); - assert!(chunks(&bytes).all(|c| &c.id != b"CMAP"), "a deep ILBM has no palette"); - let back = decode(&bytes, &Limits::default()).unwrap(); - assert_eq!(back.layout(), ChannelLayout::Rgb); - assert_eq!(back.data(), &data[..]); - } - - #[test] - fn alpha_is_written_as_a_mask_plane() { - let data = [10, 20, 30, 0, 40, 50, 60, 127, 70, 80, 90, 128, 1, 2, 3, 255]; - let img = Image::from_u8(4, 1, ChannelLayout::Rgba, data.to_vec()).unwrap(); - let bytes = encode(&img, plan(ChannelLayout::Rgba)).unwrap(); - assert_eq!(parse_header(&bytes, false).unwrap().masking, 1); - let back = decode(&bytes, &Limits::default()).unwrap(); - assert_eq!(back.layout(), ChannelLayout::Rgba); - assert_eq!(back.data(), &[10, 20, 30, 0, 40, 50, 60, 0, 70, 80, 90, 255, 1, 2, 3, 255]); - } - - #[test] - fn byte_run1_round_trips_runs_literals_and_long_rows() { - let mut rows: Vec> = vec![vec![], vec![5], vec![5, 5], vec![5, 5, 5], vec![1, 2, 2, 2, 3], vec![9; 300]]; - rows.push((0..300).map(|i| (i % 251) as u8).collect()); - rows.push([vec![1, 2], vec![7; 129], vec![3]].concat()); - for row in rows { - let mut packed = Vec::new(); - pack_byte_run1(&row, &mut packed); - let mut back = vec![0; row.len()]; - assert_eq!(unpack_byte_run1(&packed, &mut back).unwrap(), packed.len(), "{row:?}"); - assert_eq!(back, row); - } - // A long repeat packs into two-byte runs. - let mut packed = Vec::new(); - pack_byte_run1(&[0; 256], &mut packed); - assert_eq!(packed, [0x81, 0, 0x81, 0]); - } - - #[test] - fn rejects_what_ilbm_cannot_store() { - let gray = Image::from_u8(1, 1, ChannelLayout::Gray, vec![0]).unwrap(); - assert!(encode(&gray, plan(ChannelLayout::Gray)).is_err()); - let wide = Image::from_u8(65536, 1, ChannelLayout::Rgb, vec![0; 65536 * 3]).unwrap(); - assert!(encode(&wide, plan(ChannelLayout::Rgb)).is_err()); - // A transparent color index has no meaning without a palette. - let mut b = ilbm(1, 1, 24, &[], 0, &[0; 48]); - b[29] = 2; - assert!(matches!(decode(&b, &Limits::default()), Err(CodecError::Unsupported { .. }))); - } - - #[test] - fn hostile_input_errors_not_panics() { - // Truncations of a valid file never panic. - let body = [0b0100_0000, 0, 0b0100_0000, 0]; - let full = ilbm(2, 1, 2, &[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], 0, &body); - for cut in [0, 4, 8, 12, 40, full.len() - 1] { - assert!(decode(&full[..cut.min(full.len())], &Limits::default()).is_err(), "cut {cut}"); - } - // Too many planes is unsupported. - let bad = ilbm(1, 1, 9, &[], 0, &[0, 0]); - assert!(matches!(decode(&bad, &Limits::default()), Err(CodecError::Unsupported { .. }))); - } -} diff --git a/crates/codecs/src/codecs/pcx.rs b/crates/codecs/src/codecs/pcx.rs deleted file mode 100644 index 48dbf1169e..0000000000 --- a/crates/codecs/src/codecs/pcx.rs +++ /dev/null @@ -1,139 +0,0 @@ -//! ZSoft PCX (Paintbrush) reader: strictly bounded scanline RLE, 16/256-colour -//! palettes and 8-bit three-plane RGB. Read-only: modern saves should use PNG. - -use crate::SampleType; -use crate::error::CodecError; -use crate::format::Format; -use crate::image::{ChannelLayout, Image}; -use crate::options::Limits; - -const HEADER: usize = 128; - -fn bad(reason: impl std::fmt::Display) -> CodecError { - CodecError::malformed(Format::Pcx, reason) -} -fn le16(b: &[u8], i: usize) -> u16 { - u16::from_le_bytes([b[i], b[i + 1]]) -} - -/// PCX lacks a strong magic number. Require plausible complete header fields before -/// identifying it, rather than classifying every file starting with 0x0a as PCX. -pub(crate) fn looks_like_pcx(b: &[u8]) -> bool { - if b.len() < HEADER || b[0] != 0x0a || !matches!(b[1], 0 | 2 | 3 | 5) || b[2] != 1 { - return false; - } - let bits = b[3]; - let planes = b[65]; - let stride = u32::from(le16(b, 66)); - let (x0, y0, x1, y1) = (le16(b, 4), le16(b, 6), le16(b, 8), le16(b, 10)); - if x1 < x0 || y1 < y0 || !matches!(bits, 1 | 2 | 4 | 8) || !(1..=4).contains(&planes) { - return false; - } - let width = u32::from(x1 - x0) + 1; - let min_stride = (width * u32::from(bits)).div_ceil(8); - stride >= min_stride && stride > 0 && (bits != 8 || matches!(planes, 1 | 3)) && (bits == 8 || u32::from(bits) * u32::from(planes) <= 4) -} - -/// Read one compressed scanline, including all planes. RLE packets never cross a scanline. -fn read_row(b: &[u8], pos: &mut usize, out: &mut [u8]) -> Result<(), CodecError> { - let mut n = 0; - while n < out.len() { - let code = *b.get(*pos).ok_or_else(|| bad("truncated pixel RLE"))?; - *pos += 1; - let (count, value) = if code >= 0xc0 { - let count = usize::from(code & 0x3f); - let value = *b.get(*pos).ok_or_else(|| bad("truncated RLE packet"))?; - *pos += 1; - (count, value) - } else { - (1, code) - }; - if count == 0 || count > out.len() - n { - return Err(bad("RLE packet crosses a scanline or has zero length")); - } - out[n..n + count].fill(value); - n += count; - } - Ok(()) -} - -pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { - if !looks_like_pcx(b) { - return Err(bad("invalid PCX header or unsupported pixel layout")); - } - let (w, h) = (u32::from(le16(b, 8) - le16(b, 4)) + 1, u32::from(le16(b, 10) - le16(b, 6)) + 1); - limits.check(w, h, ChannelLayout::Rgb, SampleType::U8)?; - let (bits, planes, stride) = (usize::from(b[3]), usize::from(b[65]), usize::from(le16(b, 66))); - let row_len = stride.checked_mul(planes).ok_or_else(|| bad("row size overflow"))?; - let total = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(3)).ok_or_else(|| bad("pixel size overflow"))?; - // The last 769 bytes are the optional VGA palette for 8-bit indexed images. - let vga = bits == 8 && planes == 1 && b.len() >= HEADER + 769 && b[b.len() - 769] == 0x0c; - if bits == 8 && planes == 1 && !vga && le16(b, 68) != 2 { - return Err(bad("8-bit indexed PCX has no 256-colour palette")); - } - let image_end = if vga { b.len() - 769 } else { b.len() }; - // A 63-byte RLE packet takes 2 bytes; a trailing remainder of 1 byte below 0xC0 - // can be encoded as a 1-byte literal, while any larger remainder takes at least 2 bytes. - // Because RLE packets may span planes within a scanline (`row_len`), compute the - // minimum encoded bytes across the full scanline (`row_len`) and multiply by `h`. - // Reject inputs that cannot possibly contain all scanlines before allocating - // the decoded image buffer. - let min_packets = (row_len / 63) - .checked_mul(2) - .and_then(|n| { - n.checked_add(match row_len % 63 { - 0 => 0, - 1 => 1, - _ => 2, - }) - }) - .ok_or_else(|| bad("compressed row size overflow"))?; - let min_encoded = min_packets.checked_mul(h as usize).ok_or_else(|| bad("compressed image size overflow"))?; - let encoded_len = image_end.saturating_sub(HEADER); - if encoded_len < min_encoded { - return Err(bad("PCX pixel data is too short for the declared image")); - } - let mut row = vec![0u8; row_len]; - let mut pixels = Vec::new(); - pixels.try_reserve_exact(total).map_err(|_| bad("PCX pixel buffer is too large"))?; - pixels.resize(total, 0); - let mut p = HEADER; - let width = w as usize; - for y in 0..h as usize { - read_row(&b[..image_end], &mut p, &mut row)?; - for x in 0..width { - let rgb = if bits == 8 && planes == 3 { - [row[x], row[stride + x], row[2 * stride + x]] - } else { - let index = if bits == 8 { - usize::from(row[x]) - } else { - let bit = x * bits; - let shift = 8 - bits - (bit % 8); - let mask = (1usize << bits) - 1; - (0..planes).fold(0usize, |v, plane| { - let sample = (usize::from(row[plane * stride + bit / 8]) >> shift) & mask; - v | sample << (plane * bits) - }) - }; - if vga { - let o = image_end + 1 + index * 3; - [b[o], b[o + 1], b[o + 2]] - } else if bits == 8 { - let g = index as u8; - [g, g, g] // palette-info 2: gray scale - } else { - let o = 16 + index * 3; - [b[o], b[o + 1], b[o + 2]] - } - }; - pixels[(y * width + x) * 3..(y * width + x + 1) * 3].copy_from_slice(&rgb); - } - } - let mut image = Image::from_u8(w, h, ChannelLayout::Rgb, pixels)?; - let (xdpi, ydpi) = (le16(b, 12), le16(b, 14)); - if xdpi > 0 && ydpi > 0 { - image.meta.dpi = Some((f32::from(xdpi), f32::from(ydpi))); - } - Ok(image) -} diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rs index b4675dbbda..b1d574de50 100644 --- a/crates/codecs/src/codecs/png.rs +++ b/crates/codecs/src/codecs/png.rs @@ -1598,7 +1598,7 @@ pub fn encode_indexed( dpi: Option<(f32, f32)>, stereo: Option, ) -> Result, CodecError> { - if width == 0 || height == 0 || indices.len() != width as usize * height as usize { + if width == 0 || height == 0 || (width as usize).checked_mul(height as usize) != Some(indices.len()) { return Err(CodecError::InvalidImage("index data does not match the size".into())); } if palette.is_empty() || palette.len() > 256 || indices.iter().any(|&i| usize::from(i) >= palette.len()) { diff --git a/crates/codecs/src/codecs/pnm.rs b/crates/codecs/src/codecs/pnm.rs deleted file mode 100644 index c16cccfd02..0000000000 --- a/crates/codecs/src/codecs/pnm.rs +++ /dev/null @@ -1,355 +0,0 @@ -//! Netpbm family, implemented here: P1–P6 (PBM/PGM/PPM, ASCII and binary), -//! P7 (PAM, including the common `CMYK`/`CMYK_ALPHA` tuple types) and PFM -//! (`PF` colour / `Pf` gray float). -//! -//! Writing picks the subtype from the image: float → PFM (gray/RGB), gray -//! → P5, RGB → P6, anything with alpha or CMYK → P7. - -use crate::Format; -use crate::error::CodecError; -use crate::fidelity::Plan; -use crate::image::{ChannelLayout, Image, SampleType}; -use crate::options::{EncodeOptions, Limits}; - -const F: Format = Format::Pnm; - -fn err(msg: impl std::fmt::Display) -> CodecError { - CodecError::malformed(F, msg) -} - -struct Reader<'a> { - b: &'a [u8], - pos: usize, -} - -impl<'a> Reader<'a> { - fn skip_ws_and_comments(&mut self) { - while self.pos < self.b.len() { - let c = self.b[self.pos]; - if c == b'#' { - while self.pos < self.b.len() && self.b[self.pos] != b'\n' && self.b[self.pos] != b'\r' { - self.pos += 1; - } - } else if c.is_ascii_whitespace() { - self.pos += 1; - } else { - break; - } - } - } - - fn token(&mut self) -> Result<&'a [u8], CodecError> { - self.skip_ws_and_comments(); - let start = self.pos; - while self.pos < self.b.len() && !self.b[self.pos].is_ascii_whitespace() && self.b[self.pos] != b'#' { - self.pos += 1; - } - if start == self.pos { - return Err(err("unexpected end of header")); - } - Ok(&self.b[start..self.pos]) - } - - fn uint(&mut self) -> Result { - let t = self.token()?; - std::str::from_utf8(t).ok().and_then(|s| s.parse::().ok()).ok_or_else(|| err("invalid integer in header")) - } - - /// Consume the single whitespace byte that separates header and raster. - fn single_ws(&mut self) -> Result<(), CodecError> { - match self.b.get(self.pos) { - Some(c) if c.is_ascii_whitespace() => { - self.pos += 1; - Ok(()) - } - _ => Err(err("missing whitespace after header")), - } - } - - /// PAM ends its header with an LF-terminated line, unlike P4–P6's single separator. - fn pam_endhdr(&mut self) -> Result<(), CodecError> { - while let Some(&c) = self.b.get(self.pos) { - self.pos += 1; - if c == b'\n' { - // Stop at the first LF: whitespace and '#' after it are raster bytes. - return Ok(()); - } - if !c.is_ascii_whitespace() { - return Err(err("unexpected data after PAM ENDHDR")); - } - } - Err(err("unterminated PAM ENDHDR line")) - } - - fn rest(&self) -> &'a [u8] { - &self.b[self.pos.min(self.b.len())..] - } -} - -fn sample_for_maxval(maxval: u32) -> Result { - match maxval { - 1..=255 => Ok(SampleType::U8), - 256..=65535 => Ok(SampleType::U16), - _ => Err(err(format!("invalid maxval {maxval}"))), - } -} - -/// The decoded raster, built straight in the output representation. It is the only buffer sized -/// by the header, so `Limits::check` on the output budgets all of it: no wider scratch buffer -/// (such as one `u32` per sample) sits beside it (#2938). -struct Samples { - maxval: u32, - sample: SampleType, - bytes: Vec, -} - -impl Samples { - /// Reserve room for `cap` samples (callers bound `cap` by the file length where the header - /// alone could overstate it). - fn with_capacity(maxval: u32, cap: usize) -> Result { - let sample = sample_for_maxval(maxval)?; - let len = cap.checked_mul(sample.bytes()).ok_or_else(|| CodecError::LimitExceeded(format!("{cap} samples do not fit in memory")))?; - let mut bytes = Vec::new(); - bytes.try_reserve_exact(len).map_err(|_| CodecError::LimitExceeded(format!("cannot allocate {len} bytes for the image")))?; - Ok(Samples { maxval, sample, bytes }) - } - - /// Append one raw value in `[0, maxval]`, rescaled to the full range of the output sample. - fn push(&mut self, v: u32) -> Result<(), CodecError> { - let m = self.maxval; - if v > m { - return Err(err("sample exceeds maxval")); - } - match (self.sample, m) { - (SampleType::U8, 255) => self.bytes.push(v as u8), - (SampleType::U8, m) => self.bytes.push(((v * 255 + m / 2) / m) as u8), - (_, 65535) => self.bytes.extend_from_slice(&(v as u16).to_ne_bytes()), - (_, m) => self.bytes.extend_from_slice(&(((v as u64 * 65535 + m as u64 / 2) / m as u64) as u16).to_ne_bytes()), - } - Ok(()) - } - - fn into_image(self, w: u32, h: u32, layout: ChannelLayout) -> Result { - Image::from_raw(w, h, layout, self.sample, self.bytes) - } -} - -/// `w × h × channels` samples. `Limits::none()` lets any header through, so the product is -/// checked here rather than trusted to the limits. -fn sample_count(w: u32, h: u32, channels: usize) -> Result { - (w as usize) - .checked_mul(h as usize) - .and_then(|p| p.checked_mul(channels)) - .ok_or_else(|| CodecError::LimitExceeded(format!("{w}x{h}x{channels} samples do not fit in memory"))) -} - -fn read_binary(data: &[u8], n: usize, maxval: u32) -> Result { - let mut out = Samples::with_capacity(maxval, n)?; - if maxval < 256 { - let Some(raw) = data.get(..n) else { - return Err(err("truncated raster")); - }; - for &v in raw { - out.push(v as u32)?; - } - } else { - let Some(raw) = n.checked_mul(2).and_then(|len| data.get(..len)) else { - return Err(err("truncated raster")); - }; - for c in raw.as_chunks::<2>().0 { - out.push(u16::from_be_bytes(*c) as u32)?; - } - } - Ok(out) -} - -pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { - if bytes.len() < 2 || bytes[0] != b'P' { - return Err(err("not a Netpbm file")); - } - let kind = bytes[1]; - let mut r = Reader { b: bytes, pos: 2 }; - match kind { - b'1' | b'4' => { - let (w, h) = (r.uint()?, r.uint()?); - limits.check(w, h, ChannelLayout::Gray, SampleType::U8)?; - let n = sample_count(w, h, 1)?; - let mut px; - if kind == b'4' { - r.single_ws()?; - let row = (w as usize).div_ceil(8); - let data = r.rest(); - if row.checked_mul(h as usize).is_none_or(|len| data.len() < len) { - return Err(err("truncated raster")); - } - px = Vec::with_capacity(n); - for y in 0..h as usize { - for x in 0..w as usize { - let bit = (data[y * row + x / 8] >> (7 - x % 8)) & 1; - px.push(if bit == 1 { 0 } else { 255 }); - } - } - } else { - // Each ASCII pixel takes at least a byte, so the file bounds the reservation (#1110). - px = Vec::with_capacity(n.min(r.rest().len())); - while px.len() < n { - r.skip_ws_and_comments(); - match r.b.get(r.pos) { - Some(b'0') => px.push(255), - Some(b'1') => px.push(0), - Some(_) => return Err(err("invalid PBM digit")), - None => return Err(err("truncated raster")), - } - r.pos += 1; - } - } - Image::from_u8(w, h, ChannelLayout::Gray, px) - } - b'2' | b'3' | b'5' | b'6' => { - let (w, h, maxval) = (r.uint()?, r.uint()?, r.uint()?); - let layout = if matches!(kind, b'2' | b'5') { ChannelLayout::Gray } else { ChannelLayout::Rgb }; - limits.check(w, h, layout, sample_for_maxval(maxval)?)?; - let n = sample_count(w, h, layout.channels())?; - let samples = if matches!(kind, b'5' | b'6') { - r.single_ws()?; - read_binary(r.rest(), n, maxval)? - } else { - // Each ASCII sample is a digit and a separator (the last may lack one), so the - // file, not the header, bounds the reservation (#1110). - let mut v = Samples::with_capacity(maxval, n.min(r.rest().len() / 2 + 1))?; - for _ in 0..n { - v.push(r.uint()?)?; - } - v - }; - samples.into_image(w, h, layout) - } - b'7' => decode_pam(&mut r, limits), - b'F' | b'f' => { - let layout = if kind == b'F' { ChannelLayout::Rgb } else { ChannelLayout::Gray }; - let (w, h) = (r.uint()?, r.uint()?); - let scale: f32 = std::str::from_utf8(r.token()?) - .ok() - .and_then(|s| s.parse().ok()) - .filter(|s: &f32| s.is_finite() && *s != 0.0) - .ok_or_else(|| err("invalid PFM scale"))?; - r.single_ws()?; - limits.check(w, h, layout, SampleType::F32)?; - let nc = layout.channels(); - let row = w as usize * nc; - let data = r.rest(); - if sample_count(w, h, nc)?.checked_mul(4).is_none_or(|len| data.len() < len) { - return Err(err("truncated raster")); - } - let le = scale < 0.0; - // Write native-endian bytes straight into the output buffer: a separate `Vec` - // would double the budgeted allocation (#2938). - let row_bytes = row * 4; - let mut out = vec![0u8; row_bytes * h as usize]; - for (y, src) in data.chunks_exact(row_bytes).take(h as usize).enumerate() { - // PFM rows are stored bottom-to-top. - let dst_start = (h as usize - 1 - y) * row_bytes; - let Some(dst) = out.get_mut(dst_start..dst_start + row_bytes) else { - return Err(err("truncated raster")); - }; - for (d, s) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src.as_chunks::<4>().0) { - let v = if le { f32::from_le_bytes(*s) } else { f32::from_be_bytes(*s) }; - *d = v.to_ne_bytes(); - } - } - Image::from_raw(w, h, layout, SampleType::F32, out) - } - _ => Err(err("unknown Netpbm subtype")), - } -} - -fn decode_pam(r: &mut Reader<'_>, limits: &Limits) -> Result { - let (mut w, mut h, mut depth, mut maxval) = (None, None, None, None); - let mut tupltype = String::new(); - loop { - let tok = r.token()?; - match tok { - b"WIDTH" => w = Some(r.uint()?), - b"HEIGHT" => h = Some(r.uint()?), - b"DEPTH" => depth = Some(r.uint()?), - b"MAXVAL" => maxval = Some(r.uint()?), - b"TUPLTYPE" => { - let t = r.token()?; - if !tupltype.is_empty() { - tupltype.push(' '); - } - tupltype.push_str(std::str::from_utf8(t).map_err(|_| err("bad TUPLTYPE"))?); - } - b"ENDHDR" => break, - _ => return Err(err("unknown PAM header field")), - } - } - r.pam_endhdr()?; - let (w, h, depth, maxval) = match (w, h, depth, maxval) { - (Some(a), Some(b), Some(c), Some(d)) => (a, b, c, d), - _ => return Err(err("incomplete PAM header")), - }; - let layout = match (tupltype.as_str(), depth) { - ("BLACKANDWHITE" | "GRAYSCALE", 1) | ("", 1) => ChannelLayout::Gray, - ("BLACKANDWHITE_ALPHA" | "GRAYSCALE_ALPHA", 2) | ("", 2) => ChannelLayout::GrayA, - ("RGB", 3) | ("", 3) => ChannelLayout::Rgb, - ("RGB_ALPHA", 4) | ("", 4) => ChannelLayout::Rgba, - ("CMYK", 4) => ChannelLayout::Cmyk, - ("CMYK_ALPHA", 5) => ChannelLayout::CmykA, - (t, d) => { - return Err(CodecError::unsupported(F, format!("PAM tuple type {t:?} with depth {d}"))); - } - }; - limits.check(w, h, layout, sample_for_maxval(maxval)?)?; - let n = sample_count(w, h, layout.channels())?; - read_binary(r.rest(), n, maxval)?.into_image(w, h, layout) -} - -pub(crate) fn encode(src: &Image, plan: Plan, _opts: &EncodeOptions) -> Result, CodecError> { - let img = src.converted(plan.layout, plan.sample); - let (w, h) = img.dimensions(); - let layout = img.layout(); - let mut out = Vec::new(); - match img.sample_type() { - SampleType::F32 => { - let tag = match layout { - ChannelLayout::Gray => "Pf", - ChannelLayout::Rgb => "PF", - l => return Err(CodecError::encode(F, format!("PFM cannot store {l:?}"))), - }; - out.extend_from_slice(format!("{tag}\n{w} {h}\n-1.0\n").as_bytes()); - let s = img.to_f32_samples().unwrap_or_default(); - let row = w as usize * layout.channels(); - for y in (0..h as usize).rev() { - for v in &s[y * row..(y + 1) * row] { - out.extend_from_slice(&v.to_le_bytes()); - } - } - } - sample @ (SampleType::U8 | SampleType::U16) => { - let maxval = if sample == SampleType::U8 { 255 } else { 65535 }; - match layout { - ChannelLayout::Gray => out.extend_from_slice(format!("P5\n{w} {h}\n{maxval}\n").as_bytes()), - ChannelLayout::Rgb => out.extend_from_slice(format!("P6\n{w} {h}\n{maxval}\n").as_bytes()), - l => { - let t = match l { - ChannelLayout::GrayA => "GRAYSCALE_ALPHA", - ChannelLayout::Rgba => "RGB_ALPHA", - ChannelLayout::Cmyk => "CMYK", - _ => "CMYK_ALPHA", - }; - out.extend_from_slice(format!("P7\nWIDTH {w}\nHEIGHT {h}\nDEPTH {}\nMAXVAL {maxval}\nTUPLTYPE {t}\nENDHDR\n", l.channels()).as_bytes()); - } - } - if sample == SampleType::U8 { - out.extend_from_slice(img.data()); - } else { - for v in img.to_u16_samples().unwrap_or_default() { - out.extend_from_slice(&v.to_be_bytes()); - } - } - } - s => return Err(CodecError::encode(F, format!("unsupported sample {s:?}"))), - } - Ok(out) -} diff --git a/crates/codecs/src/codecs/raster.rs b/crates/codecs/src/codecs/raster.rs new file mode 100644 index 0000000000..2e83e8881f --- /dev/null +++ b/crates/codecs/src/codecs/raster.rs @@ -0,0 +1,169 @@ +//! DDS, DICOM, FITS, IFF/ILBM, PCX, PNM and XPM: the format code is craft-libs' +//! `craft-raster-codecs`. This maps its image, limits and errors onto this crate's, and the +//! encoders take this crate's [`Plan`] (the layout and depth conversion stays here). + +use craft_raster_codecs as rc; + +use crate::error::CodecError; +use crate::fidelity::Plan; +use crate::format::Format; +use crate::image::{ChannelLayout, DecodeWarning, Image, SampleType}; +use crate::options::Limits; + +fn limits(l: &Limits) -> rc::Limits { + rc::Limits { max_width: l.max_width, max_height: l.max_height, max_pixels: l.max_pixels, max_alloc: l.max_alloc } +} + +fn err(format: Format, e: rc::CodecError) -> CodecError { + match e { + rc::CodecError::Unsupported { reason, .. } => CodecError::Unsupported { format, reason }, + rc::CodecError::Malformed { message, .. } => CodecError::Malformed { format, message }, + rc::CodecError::LimitExceeded(m) => CodecError::LimitExceeded(m), + rc::CodecError::Encode { message, .. } => CodecError::Encode { format, message }, + rc::CodecError::InvalidImage(m) => CodecError::InvalidImage(m), + } +} + +/// A decoded image as this crate's. +fn from_rc(format: Format, img: rc::Image) -> Result { + let layout = match img.layout() { + rc::ChannelLayout::Gray => ChannelLayout::Gray, + rc::ChannelLayout::GrayA => ChannelLayout::GrayA, + rc::ChannelLayout::Rgb => ChannelLayout::Rgb, + rc::ChannelLayout::Rgba => ChannelLayout::Rgba, + rc::ChannelLayout::Cmyk => ChannelLayout::Cmyk, + rc::ChannelLayout::CmykA => ChannelLayout::CmykA, + }; + let sample = match img.sample_type() { + rc::SampleType::U8 => SampleType::U8, + rc::SampleType::U16 => SampleType::U16, + rc::SampleType::F32 => SampleType::F32, + }; + let (w, h) = img.dimensions(); + let (dpi, text) = (img.dpi, img.text.clone()); + let warnings: Vec = img.warnings.iter().map(|rc::DecodeWarning::MorePages { total }| DecodeWarning::MorePages { total: *total }).collect(); + let mut out = Image::from_raw(w, h, layout, sample, img.into_data()).map_err(|e| CodecError::malformed(format, e))?; + out.meta.dpi = dpi; + out.meta.text = text; + out.warnings = warnings; + Ok(out) +} + +/// `image` converted as `plan` says, as the shared crate's image (with its resolution and text). +fn to_rc(format: Format, image: &Image, plan: Plan) -> Result { + let img = image.converted(plan.layout, plan.sample); + let layout = match img.layout() { + ChannelLayout::Gray => rc::ChannelLayout::Gray, + ChannelLayout::GrayA => rc::ChannelLayout::GrayA, + ChannelLayout::Rgb => rc::ChannelLayout::Rgb, + ChannelLayout::Rgba => rc::ChannelLayout::Rgba, + ChannelLayout::Cmyk => rc::ChannelLayout::Cmyk, + ChannelLayout::CmykA => rc::ChannelLayout::CmykA, + l => return Err(CodecError::encode(format, format!("cannot store {l:?}"))), + }; + let sample = match img.sample_type() { + SampleType::U8 => rc::SampleType::U8, + SampleType::U16 => rc::SampleType::U16, + SampleType::F32 => rc::SampleType::F32, + s => return Err(CodecError::encode(format, format!("unsupported sample {s:?}"))), + }; + let (w, h) = img.dimensions(); + let mut out = rc::Image::from_raw(w, h, layout, sample, img.data().to_vec()).map_err(|e| err(format, e))?; + out.dpi = img.meta.dpi; + out.text = img.meta.text.clone(); + Ok(out) +} + +pub(crate) mod dds { + use super::{CodecError, Format, Image, Limits, Plan, SampleType, err, from_rc, limits, rc, to_rc}; + use crate::options::EncodeOptions; + const F: Format = Format::Dds; + + pub(crate) fn has_additional_images(bytes: &[u8]) -> Result { + rc::dds::has_additional_images(bytes).map_err(|e| err(F, e)) + } + pub(crate) fn decode(b: &[u8], l: &Limits) -> Result { + from_rc(F, rc::dds::decode(b, &limits(l)).map_err(|e| err(F, e))?) + } + pub(crate) fn encode(image: &Image, plan: Plan, opts: &EncodeOptions) -> Result, CodecError> { + let img = to_rc(F, image, Plan { sample: SampleType::U8, ..plan })?; + rc::dds::encode(&img, opts.dds).map_err(|e| err(F, e)) + } +} + +pub(crate) mod dicom { + use super::{CodecError, Format, Image, Limits, err, from_rc, limits, rc}; + const F: Format = Format::Dicom; + + pub(crate) fn is_dicom(b: &[u8]) -> bool { + rc::dicom::is_dicom(b) + } + pub(crate) fn decode(b: &[u8], l: &Limits) -> Result { + from_rc(F, rc::dicom::decode(b, &limits(l)).map_err(|e| err(F, e))?) + } +} + +pub(crate) mod fits { + use super::{CodecError, Format, Image, Limits, Plan, err, from_rc, limits, rc, to_rc}; + use crate::options::EncodeOptions; + const F: Format = Format::Fits; + + pub(crate) fn has_additional_images(bytes: &[u8]) -> Result { + rc::fits::has_additional_images(bytes).map_err(|e| err(F, e)) + } + pub(crate) fn decode(b: &[u8], l: &Limits) -> Result { + from_rc(F, rc::fits::decode(b, &limits(l)).map_err(|e| err(F, e))?) + } + pub(crate) fn encode(image: &Image, plan: Plan, _opts: &EncodeOptions) -> Result, CodecError> { + rc::fits::encode(&to_rc(F, image, plan)?).map_err(|e| err(F, e)) + } +} + +pub(crate) mod iff { + use super::{CodecError, Format, Image, Limits, Plan, err, from_rc, limits, rc, to_rc}; + const F: Format = Format::Iff; + + pub(crate) fn looks_like_iff(b: &[u8]) -> bool { + rc::iff::looks_like_iff(b) + } + pub(crate) fn decode(b: &[u8], l: &Limits) -> Result { + from_rc(F, rc::iff::decode(b, &limits(l)).map_err(|e| err(F, e))?) + } + pub(crate) fn encode(image: &Image, plan: Plan) -> Result, CodecError> { + rc::iff::encode(&to_rc(F, image, plan)?).map_err(|e| err(F, e)) + } +} + +pub(crate) mod pcx { + use super::{CodecError, Format, Image, Limits, err, from_rc, limits, rc}; + const F: Format = Format::Pcx; + + pub(crate) fn looks_like_pcx(b: &[u8]) -> bool { + rc::pcx::looks_like_pcx(b) + } + pub(crate) fn decode(b: &[u8], l: &Limits) -> Result { + from_rc(F, rc::pcx::decode(b, &limits(l)).map_err(|e| err(F, e))?) + } +} + +pub(crate) mod pnm { + use super::{CodecError, Format, Image, Limits, Plan, err, from_rc, limits, rc, to_rc}; + use crate::options::EncodeOptions; + const F: Format = Format::Pnm; + + pub(crate) fn decode(b: &[u8], l: &Limits) -> Result { + from_rc(F, rc::pnm::decode(b, &limits(l)).map_err(|e| err(F, e))?) + } + pub(crate) fn encode(image: &Image, plan: Plan, _opts: &EncodeOptions) -> Result, CodecError> { + rc::pnm::encode(&to_rc(F, image, plan)?).map_err(|e| err(F, e)) + } +} + +pub(crate) mod xpm { + use super::{CodecError, Format, Image, Limits, err, from_rc, limits, rc}; + const F: Format = Format::Xpm; + + pub(crate) fn decode(b: &[u8], l: &Limits) -> Result { + from_rc(F, rc::xpm::decode(b, &limits(l)).map_err(|e| err(F, e))?) + } +} diff --git a/crates/codecs/src/codecs/tga.rs b/crates/codecs/src/codecs/tga.rs index 2f382efcf3..de21797d01 100644 --- a/crates/codecs/src/codecs/tga.rs +++ b/crates/codecs/src/codecs/tga.rs @@ -1,175 +1,26 @@ -//! Targa writer. The `image` crate still reads Targa ([`super::via_image`]); writing is ours -//! because its run-length packets ran on from the end of one row into the next. TGA 2.0 says a -//! packet must not cross a scanline, and readers that decode a row at a time (Pillow, texture -//! converters, game engines) misread such files (#6382). -//! -//! Like Photoshop's Targa: RLE (types 10 and 11), rows stored bottom-up (the bottom-left origin -//! every reader assumes, also those that ignore the origin bits), alpha bits in the descriptor, -//! and the TGA 2.0 footer. +//! Targa writer: craft-libs' `craft-tga` (run-length packets that end with their scanline, rows +//! bottom-up, alpha bits in the descriptor, the TGA 2.0 footer, #6382). The `image` crate still +//! reads Targa ([`super::via_image`]). use crate::Format; use crate::error::CodecError; use crate::image::{ChannelLayout, Image, SampleType}; -/// Most pixels one packet holds (a 7-bit count, plus one). -const MAX_PACKET: usize = 128; - -/// The TGA 2.0 footer: no extension or developer area, then the signature. -const FOOTER: &[u8; 26] = b"\0\0\0\0\0\0\0\0TRUEVISION-XFILE.\0"; - /// Encodes an 8-bit Gray, Gray+alpha, RGB or RGBA image as a run-length encoded Targa. pub(crate) fn encode(img: &Image) -> Result, CodecError> { - let (w, h) = img.dimensions(); if img.sample_type() != SampleType::U8 { return Err(CodecError::encode(Format::Tga, format!("{:?} samples (Targa stores 8 bits)", img.sample_type()))); } - let (bpp, image_type, alpha_bits) = match img.layout() { - ChannelLayout::Gray => (1, 11, 0), - ChannelLayout::GrayA => (2, 11, 8), - ChannelLayout::Rgb => (3, 10, 0), - ChannelLayout::Rgba => (4, 10, 8), + let layout = match img.layout() { + ChannelLayout::Gray => craft_tga::Layout::Gray, + ChannelLayout::GrayA => craft_tga::Layout::GrayAlpha, + ChannelLayout::Rgb => craft_tga::Layout::Rgb, + ChannelLayout::Rgba => craft_tga::Layout::Rgba, l => return Err(CodecError::encode(Format::Tga, format!("no Targa layout for {l:?}"))), }; - let (Ok(w16), Ok(h16)) = (u16::try_from(w), u16::try_from(h)) else { - return Err(CodecError::encode(Format::Tga, format!("dimensions exceed 65535x65535: {w}x{h}"))); - }; - let row = w as usize * bpp; - let data = img.data(); - if data.len() != row * h as usize { - return Err(CodecError::InvalidImage("buffer size mismatch".into())); - } - let mut out = Vec::with_capacity(18 + data.len() + data.len() / MAX_PACKET + FOOTER.len()); - out.extend_from_slice(&[0, 0, image_type, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - out.extend_from_slice(&w16.to_le_bytes()); - out.extend_from_slice(&h16.to_le_bytes()); - // Bits per pixel; the descriptor holds the alpha bits, origin bits 0 (bottom-left). - out.extend_from_slice(&[(bpp * 8) as u8, alpha_bits]); - let mut px = vec![0u8; row]; - for y in (0..h as usize).rev() { - px.copy_from_slice(&data[y * row..(y + 1) * row]); - // Targa stores colour as BGR. - if bpp >= 3 { - for p in px.chunks_exact_mut(bpp) { - p.swap(0, 2); - } - } - rle_row(&px, bpp, &mut out); - } - out.extend_from_slice(FOOTER); - Ok(out) -} - -/// One scanline as run-length packets that end with it: a run of two or more equal pixels is a -/// run packet, anything else goes out in raw packets. -fn rle_row(row: &[u8], bpp: usize, out: &mut Vec) { - let px: Vec<&[u8]> = row.chunks_exact(bpp).collect(); - let n = px.len(); - let mut i = 0; - while i < n { - let mut run = 1; - while i + run < n && run < MAX_PACKET && px[i + run] == px[i] { - run += 1; - } - if run >= 2 { - out.push(0x80 | (run - 1) as u8); - out.extend_from_slice(px[i]); - i += run; - continue; - } - // Raw until two equal pixels start a run, the packet is full or the row ends. The first - // pixel always goes in: it differs from the one after it, or it is the row's last. - let start = i; - while i < n && i - start < MAX_PACKET && !(i > start && i + 1 < n && px[i] == px[i + 1]) { - i += 1; - } - out.push((i - start - 1) as u8); - for p in &px[start..i] { - out.extend_from_slice(p); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn run_packets_at_the_128_pixel_boundary() { - for bpp in 1..=4 { - for (pixels, headers) in [(1, vec![0]), (2, vec![0x81]), (127, vec![0xfe]), (128, vec![0xff]), (129, vec![0xff, 0])] { - let pixel: Vec = (1..=bpp as u8).collect(); - let mut encoded = Vec::new(); - rle_row(&pixel.repeat(pixels), bpp, &mut encoded); - let expected: Vec = headers.into_iter().flat_map(|header| std::iter::once(header).chain(pixel.iter().copied())).collect(); - assert_eq!(encoded, expected, "{pixels} pixels, {bpp} bytes per pixel"); - } - } - } - - #[test] - fn raw_packets_at_the_128_pixel_boundary() { - for bpp in 1..=4 { - for pixels in [127usize, 128, 129] { - let row: Vec = (0..pixels).flat_map(|x| vec![x as u8; bpp]).collect(); - let mut encoded = Vec::new(); - rle_row(&row, bpp, &mut encoded); - let mut expected = vec![(pixels.min(128) - 1) as u8]; - expected.extend_from_slice(&row[..pixels.min(128) * bpp]); - if pixels > 128 { - expected.push(0); - expected.extend_from_slice(&row[128 * bpp..]); - } - assert_eq!(encoded, expected, "{pixels} pixels, {bpp} bytes per pixel"); - } - } - } - - #[test] - fn raw_packets_stop_before_a_run_of_complete_pixels() { - // Equal first channels alone do not make an RGBA run; alpha participates too. - let a = [10, 20, 30, 40]; - let b = [10, 20, 30, 41]; - let c = [50, 60, 70, 80]; - let row = [a, b, c, c, a].concat(); - let mut encoded = Vec::new(); - rle_row(&row, 4, &mut encoded); - assert_eq!(encoded, [vec![1], a.to_vec(), b.to_vec(), vec![0x81], c.to_vec(), vec![0], a.to_vec()].concat()); - } - - #[test] - fn rejects_sample_types_and_layouts_targa_cannot_store() { - for sample in [SampleType::U16, SampleType::F16, SampleType::F32] { - let img = Image::new(1, 1, ChannelLayout::Rgb, sample).unwrap(); - assert!(matches!(encode(&img), Err(CodecError::Encode { format: Format::Tga, .. })), "{sample:?}"); - } - for layout in [ChannelLayout::Cmyk, ChannelLayout::CmykA, ChannelLayout::Lab, ChannelLayout::LabA] { - let img = Image::new(1, 1, layout, SampleType::U8).unwrap(); - assert!(matches!(encode(&img), Err(CodecError::Encode { format: Format::Tga, .. })), "{layout:?}"); - } - } - - #[test] - fn dimensions_fit_the_unsigned_16_bit_header() { - for (width, height) in [(65535, 1), (1, 65535)] { - let img = Image::new(width, height, ChannelLayout::Gray, SampleType::U8).unwrap(); - let file = encode(&img).unwrap(); - assert_eq!(&file[12..14], &(width as u16).to_le_bytes()); - assert_eq!(&file[14..16], &(height as u16).to_le_bytes()); - } - for (width, height) in [(65536, 1), (1, 65536)] { - let img = Image::new(width, height, ChannelLayout::Gray, SampleType::U8).unwrap(); - assert!(matches!(encode(&img), Err(CodecError::Encode { format: Format::Tga, .. })), "{width}x{height}"); - } - } - - #[test] - fn invalid_buffers_are_rejected_before_targa_encoding() { - // Image keeps its buffer private, so malformed buffers must fail at construction. - for layout in [ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb, ChannelLayout::Rgba] { - let len = 2 * 2 * layout.channels(); - for bytes in [len - 1, len + 1] { - assert!(matches!(Image::from_u8(2, 2, layout, vec![0; bytes]), Err(CodecError::InvalidImage(_))), "{layout:?}: {bytes} bytes"); - } - } - } + let (w, h) = img.dimensions(); + craft_tga::encode(w, h, layout, img.data()).map_err(|e| match e { + craft_tga::Error::Encode(m) if m == "buffer size mismatch" => CodecError::InvalidImage(m), + e => CodecError::encode(Format::Tga, e), + }) } diff --git a/crates/codecs/src/codecs/via_image.rs b/crates/codecs/src/codecs/via_image.rs index 7c02c614e9..e1d3dc38a4 100644 --- a/crates/codecs/src/codecs/via_image.rs +++ b/crates/codecs/src/codecs/via_image.rs @@ -231,75 +231,29 @@ fn bmp_is_rle(b: &[u8]) -> bool { u32_at(14).is_some_and(|n| n >= 40) && matches!(u32_at(30), Some(1 | 2)) } +/// The blocks of a GIF (craft-gif), every frame recorded. The frame list is bounded by the file: +/// each image descriptor takes at least 11 of its bytes. +fn gif_scan(b: &[u8]) -> Option { + craft_gif::scan(b, usize::MAX) +} + /// The width and height of a GIF's first image descriptor, if the blocks reach one. fn gif_first_frame(b: &[u8]) -> Option<(u32, u32)> { - let mut at = None; - gif_walk(b, |i| { - at = Some(i); - false - }); - let u16_at = |at: usize| b.get(at..at + 2).and_then(|b| b.try_into().ok()).map(u16::from_le_bytes); - // Descriptor: separator, left, top, width, height (little-endian u16s), packed fields. - let i = at?; - Some((u32::from(u16_at(i + 5)?), u32::from(u16_at(i + 7)?))) + craft_gif::scan(b, 1)?.frames.first().map(|f| (u32::from(f.width), u32::from(f.height))) } /// Counts a GIF's frames (image descriptors) by walking its blocks, without decompressing any. /// The total is unknown when the blocks end before the trailer or break off. pub(crate) fn gif_more_frames(b: &[u8]) -> Option { - let (frames, total) = gif_walk(b, |_| true); - (frames > 1).then_some(DecodeWarning::MoreFrames { total }) + let info = gif_scan(b)?; + let total = info.complete.then(|| u32::try_from(info.frames.len()).unwrap_or(u32::MAX)); + (info.frames.len() > 1).then_some(DecodeWarning::MoreFrames { total }) } /// Whether a GIF holds more than one frame, or None when the walk stops before the trailer /// after at most one frame (so frames past the break could not be counted). pub(crate) fn gif_has_more_frames(b: &[u8]) -> Option { - let (frames, total) = gif_walk(b, |_| true); - if frames > 1 { Some(true) } else { total.map(|_| false) } -} - -/// Walks a GIF's blocks without decompressing any, handing `frame` the offset of each image -/// descriptor until it returns false. Gives the descriptors seen, and the frame count if the -/// blocks reached the trailer. -fn gif_walk(b: &[u8], mut frame: impl FnMut(usize) -> bool) -> (u32, Option) { - // Size of the colour table a packed-fields byte announces. - let table = |flags: u8| if flags & 0x80 != 0 { 3usize << ((flags & 7) + 1) } else { 0 }; - // Skips the data sub-blocks starting at `i` (each length-prefixed, ended by a zero length). - let skip = |mut i: usize| -> Option { - loop { - let n = usize::from(*b.get(i)?); - i = i.checked_add(1 + n)?; - if n == 0 { - return Some(i); - } - } - }; - // Header (6 bytes), logical screen descriptor (7) and the global colour table. - let Some(&flags) = b.get(10) else { - return (0, None); - }; - let mut i = 13 + table(flags); - let mut frames = 0u32; - let total = loop { - let next = match b.get(i) { - Some(0x3B) => break Some(frames), - Some(0x21) => skip(i + 2), - Some(0x2C) => { - frames = frames.saturating_add(1); - if !frame(i) { - break None; - } - // Descriptor (10 bytes, packed fields last), local colour table, LZW code size. - b.get(i + 9).and_then(|&flags| skip(i + 11 + table(flags))) - } - _ => None, - }; - match next { - Some(n) => i = n, - None => break None, - } - }; - (frames, total) + gif_scan(b)?.has_more_frames() } pub(crate) fn from_dynamic(f: Format, d: DynamicImage) -> Result { diff --git a/crates/codecs/src/codecs/vp8.rs b/crates/codecs/src/codecs/vp8.rs index a24fb727cc..7e5ef59bdd 100644 --- a/crates/codecs/src/codecs/vp8.rs +++ b/crates/codecs/src/codecs/vp8.rs @@ -448,7 +448,9 @@ impl<'a> Encoder<'a> { let whole_cost = best_sse + 3 * lambda; // B_PRED: sub-blocks in raster order, each predicted from the reconstruction so far. - let saved_y = self.rec_y.data.clone(); + // B_PRED writes only this macroblock's 16 rows: save those, not the whole plane. + let rows = |p: &Plane| -> [[u8; 16]; 16] { std::array::from_fn(|r| p.data[(y0 + r) * p.width + x0..][..16].try_into().unwrap_or([0; 16])) }; + let saved_y = rows(&self.rec_y); let mut b_modes = [B_DC_PRED; 16]; let mut b_blocks: Vec = Vec::with_capacity(16); let mut b_sse = 0u64; @@ -490,7 +492,10 @@ impl<'a> Encoder<'a> { (B_PRED, None, b_blocks) } else { // Whole-block mode: undo the B_PRED reconstruction, code 16 blocks + Y2. - self.rec_y.data = saved_y; + let w = self.rec_y.width; + for (r, row) in saved_y.iter().enumerate() { + self.rec_y.data[(y0 + r) * w + x0..][..16].copy_from_slice(row); + } let mut dcs = [0i32; 16]; let mut ac_blocks: Vec<[i32; 16]> = Vec::with_capacity(16); let mut deq_blocks: Vec<[i32; 16]> = Vec::with_capacity(16); diff --git a/crates/codecs/src/codecs/xpm.rs b/crates/codecs/src/codecs/xpm.rs deleted file mode 100644 index c20f3c58e9..0000000000 --- a/crates/codecs/src/codecs/xpm.rs +++ /dev/null @@ -1,226 +0,0 @@ -//! X PixMap reader for XPM2 plain-text icons and XPM3 C-source icon arrays. -//! Supports transparency (None), RGB hex at 4/8/16 bits per channel and -//! common X11 colour names. Does not execute C code. - -use std::collections::HashMap; - -mod x11_colors; - -use crate::SampleType; -use crate::error::CodecError; -use crate::format::Format; -use crate::image::{ChannelLayout, Image}; -use crate::options::Limits; - -const MAX_SOURCE: usize = 256 << 20; -const MAX_COLOURS: usize = 65_536; -const MAX_CPP: usize = 8; - -fn bad(msg: impl std::fmt::Display) -> CodecError { - CodecError::malformed(Format::Xpm, msg) -} - -/// Extract C string literals without treating quoted text or // in a string as a comment. -/// XPM uses one literal for the header, each palette entry and each row. -fn c_strings(bytes: &[u8]) -> Result>, CodecError> { - let mut lines = Vec::new(); - let mut i = 0usize; - while i < bytes.len() { - if bytes[i..].starts_with(b"/*") { - let tail = &bytes[i + 2..]; - let Some(end) = tail.windows(2).position(|p| p == b"*/") else { return Err(bad("unterminated C comment")) }; - i += end + 4; - } else if bytes[i..].starts_with(b"//") { - i += bytes[i..].iter().position(|&c| c == b'\n').unwrap_or(bytes.len() - i); - } else if bytes[i] == b'"' { - i += 1; - let mut s = Vec::new(); - let mut closed = false; - while i < bytes.len() { - let c = bytes[i]; - i += 1; - match c { - b'"' => { - closed = true; - break; - } - b'\\' => { - let next = *bytes.get(i).ok_or_else(|| bad("truncated C escape"))?; - i += 1; - s.push(match next { - b'n' => b'\n', - b'r' => b'\r', - b't' => b'\t', - b'0' => 0, - _ => next, // quoted backslash or quote - }); - } - _ => s.push(c), - } - } - if !closed { - return Err(bad("unterminated XPM string")); - } - lines.push(s); - } else { - i += 1; - } - } - Ok(lines) -} - -/// Extract XPM2's plain-text lines without trimming pixel rows: leading and -/// trailing spaces can be palette keys, and physical CRLF is not image data. -fn xpm2_lines(bytes: &[u8]) -> Result>, CodecError> { - let mut input = bytes.split(|&b| b == b'\n'); - let header = input.next().ok_or_else(|| bad("missing XPM2 marker"))?; - if header.strip_suffix(b"\r").unwrap_or(header) != b"! XPM2" { - return Err(bad("not an XPM2 image")); - } - let mut lines = Vec::new(); - for raw in input { - let line = raw.strip_suffix(b"\r").unwrap_or(raw); - // The header may be preceded by comments and blank lines. After the - // header, a leading '!' is allowed as a palette key or pixel value. - if lines.is_empty() && (line.is_empty() || line.starts_with(b"!")) { - continue; - } - lines.push(line.to_vec()); - } - Ok(lines) -} - -fn channel(hex: &str) -> Option { - let v = u32::from_str_radix(hex, 16).ok()?; - let max = (1u32 << (hex.len() * 4)) - 1; - Some(((v * 255 + max / 2) / max) as u8) -} - -fn named(name: &str) -> Option<[u8; 3]> { - let s = name.to_ascii_lowercase().replace([' ', '-', '_'], ""); - // XPM imports X11 names, whose RGB values differ from CSS for names - // such as gray, maroon and purple. Keep these exact rather than guessing. - if let Ok(index) = x11_colors::X11_COLORS.binary_search_by_key(&s.as_str(), |(name, _)| *name) { - return Some(x11_colors::X11_COLORS[index].1); - } - // Retain useful web color aliases not present in the X11 database. - Some(match s.as_str() { - "silver" => [192, 192, 192], - "olive" => [128, 128, 0], - "teal" => [0, 128, 128], - "fuchsia" => [255, 0, 255], - "navyblue" => [0, 0, 128], - _ => return None, - }) -} - -fn color(name: &str) -> Option<[u8; 4]> { - if name.eq_ignore_ascii_case("none") { - return Some([0, 0, 0, 0]); - } - let rgb = if let Some(hex) = name.strip_prefix('#') { - // UTF-8 byte lengths can match a supported hex width while slicing would panic. - // `from_str_radix` would also take a leading `+`: accept hex digits only. - if !hex.bytes().all(|b| b.is_ascii_hexdigit()) { - return None; - } - let digits = match hex.len() { - 3 => 1, - 6 => 2, - 12 => 4, - _ => return None, - }; - let rgb = (0..3).map(|i| channel(&hex[i * digits..(i + 1) * digits])).collect::>>()?; - [rgb[0], rgb[1], rgb[2]] - } else { - named(name)? - }; - Some([rgb[0], rgb[1], rgb[2], 255]) -} - -pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { - if bytes.len() > MAX_SOURCE { - return Err(CodecError::LimitExceeded("XPM source exceeds 256 MiB".into())); - } - let lines = if bytes.starts_with(b"/* XPM */") { - c_strings(bytes)? - } else if bytes.starts_with(b"! XPM2\n") || bytes.starts_with(b"! XPM2\r\n") { - xpm2_lines(bytes)? - } else { - return Err(bad("not an XPM2/XPM3 image")); - }; - decode_lines(&lines, limits) -} - -fn decode_lines(lines: &[Vec], limits: &Limits) -> Result { - let header = lines.first().ok_or_else(|| bad("missing image header"))?; - let parts = std::str::from_utf8(header).map_err(|_| bad("non-UTF-8 XPM header"))?; - let mut parts = parts.split_ascii_whitespace(); - let number = |key: &str, s: Option<&str>| -> Result { - s.ok_or_else(|| bad(format!("missing {key}")))?.parse::().map_err(|_| bad(format!("invalid {key}"))) - }; - let width = number("width", parts.next())?; - let height = number("height", parts.next())?; - let colours = number("palette size", parts.next())?; - let cpp = number("chars per pixel", parts.next())?; - if width == 0 || height == 0 || colours == 0 || colours > MAX_COLOURS || !(1..=MAX_CPP).contains(&cpp) { - return Err(bad("invalid XPM dimensions, palette size or chars per pixel")); - } - let (w, h) = (u32::try_from(width).map_err(|_| bad("width overflow"))?, u32::try_from(height).map_err(|_| bad("height overflow"))?); - limits.check(w, h, ChannelLayout::Rgba, SampleType::U8)?; - let required = 1usize.checked_add(colours).and_then(|n| n.checked_add(height)).ok_or_else(|| bad("row count overflow"))?; - if lines.len() < required { - return Err(bad("truncated palette or image rows")); - } - let mut palette = HashMap::, [u8; 4]>::with_capacity(colours); - for line in &lines[1..1 + colours] { - if line.len() < cpp { - return Err(bad("truncated colour key")); - } - let fields = std::str::from_utf8(&line[cpp..]).map_err(|_| bad("invalid colour name"))?; - // XPM priority is colour, gray, four-level gray, then monochrome, - // regardless of the order of keys in the palette entry. - let terms: Vec<&str> = fields.split_ascii_whitespace().collect(); - let mut picked: Option<(u8, String)> = None; - let mut i = 0; - while i < terms.len() { - let priority = match terms[i] { - "c" => 4, - "g" => 3, - "g4" => 2, - "m" => 1, - _ => 0, // Symbolic names ('s') are not colour values. - }; - let start = i + 1; - i = start; - while i < terms.len() && !matches!(terms[i], "c" | "g" | "g4" | "m" | "s") { - i += 1; - } - if priority > 0 && i > start && picked.as_ref().is_none_or(|(current, _)| priority > *current) { - picked = Some((priority, terms[start..i].join(" "))); - } - } - let value = picked.as_ref().and_then(|(_, name)| color(name)).ok_or_else(|| bad("unsupported or missing XPM colour"))?; - if palette.insert(line[..cpp].to_vec(), value).is_some() { - return Err(bad("duplicate XPM palette key")); - } - } - let row_len = width.checked_mul(cpp).ok_or_else(|| bad("row byte count overflow"))?; - // Validate all source rows before reserving the decoded RGBA image. A malformed - // short row must not be able to make a large header-sized allocation first. - if lines[1 + colours..required].iter().any(|line| line.len() != row_len) { - return Err(bad("XPM row has the wrong width")); - } - let total = width.checked_mul(height).and_then(|n| n.checked_mul(4)).ok_or_else(|| bad("pixel size overflow"))?; - let mut pixels = Vec::new(); - pixels.try_reserve_exact(total).map_err(|_| bad("XPM pixel buffer is too large"))?; - pixels.resize(total, 0); - for (y, line) in lines[1 + colours..required].iter().enumerate() { - for x in 0..width { - let key = &line[x * cpp..(x + 1) * cpp]; - let rgba = palette.get(key).ok_or_else(|| bad("unknown palette key"))?; - pixels[(y * width + x) * 4..(y * width + x + 1) * 4].copy_from_slice(rgba); - } - } - Image::from_u8(w, h, ChannelLayout::Rgba, pixels) -} diff --git a/crates/codecs/src/codecs/xpm/x11_colors.rs b/crates/codecs/src/codecs/xpm/x11_colors.rs deleted file mode 100644 index 1d47b37061..0000000000 --- a/crates/codecs/src/codecs/xpm/x11_colors.rs +++ /dev/null @@ -1,666 +0,0 @@ -//! X11 color-name database (X.Org rgb.txt) normalized to lowercase without -//! spaces, underscores, or hyphens. RGB values are *X11* values, not CSS values. -//! Source: https://cgit.freedesktop.org/xorg/app/rgb/tree/rgb.txt -//! License: MIT (X.Org Foundation), see the upstream app/rgb COPYING file. -//! Aliases differing only in case or spaces have been collapsed. -//! Keep sorted: decoder uses binary search without allocation per candidate. - -pub(super) const X11_COLORS: &[(&str, [u8; 3])] = &[ - ("aliceblue", [240, 248, 255]), - ("antiquewhite", [250, 235, 215]), - ("antiquewhite1", [255, 239, 219]), - ("antiquewhite2", [238, 223, 204]), - ("antiquewhite3", [205, 192, 176]), - ("antiquewhite4", [139, 131, 120]), - ("aquamarine", [127, 255, 212]), - ("aquamarine1", [127, 255, 212]), - ("aquamarine2", [118, 238, 198]), - ("aquamarine3", [102, 205, 170]), - ("aquamarine4", [69, 139, 116]), - ("azure", [240, 255, 255]), - ("azure1", [240, 255, 255]), - ("azure2", [224, 238, 238]), - ("azure3", [193, 205, 205]), - ("azure4", [131, 139, 139]), - ("beige", [245, 245, 220]), - ("bisque", [255, 228, 196]), - ("bisque1", [255, 228, 196]), - ("bisque2", [238, 213, 183]), - ("bisque3", [205, 183, 158]), - ("bisque4", [139, 125, 107]), - ("black", [0, 0, 0]), - ("blanchedalmond", [255, 235, 205]), - ("blue", [0, 0, 255]), - ("blue1", [0, 0, 255]), - ("blue2", [0, 0, 238]), - ("blue3", [0, 0, 205]), - ("blue4", [0, 0, 139]), - ("blueviolet", [138, 43, 226]), - ("brown", [165, 42, 42]), - ("brown1", [255, 64, 64]), - ("brown2", [238, 59, 59]), - ("brown3", [205, 51, 51]), - ("brown4", [139, 35, 35]), - ("burlywood", [222, 184, 135]), - ("burlywood1", [255, 211, 155]), - ("burlywood2", [238, 197, 145]), - ("burlywood3", [205, 170, 125]), - ("burlywood4", [139, 115, 85]), - ("cadetblue", [95, 158, 160]), - ("cadetblue1", [152, 245, 255]), - ("cadetblue2", [142, 229, 238]), - ("cadetblue3", [122, 197, 205]), - ("cadetblue4", [83, 134, 139]), - ("chartreuse", [127, 255, 0]), - ("chartreuse1", [127, 255, 0]), - ("chartreuse2", [118, 238, 0]), - ("chartreuse3", [102, 205, 0]), - ("chartreuse4", [69, 139, 0]), - ("chocolate", [210, 105, 30]), - ("chocolate1", [255, 127, 36]), - ("chocolate2", [238, 118, 33]), - ("chocolate3", [205, 102, 29]), - ("chocolate4", [139, 69, 19]), - ("coral", [255, 127, 80]), - ("coral1", [255, 114, 86]), - ("coral2", [238, 106, 80]), - ("coral3", [205, 91, 69]), - ("coral4", [139, 62, 47]), - ("cornflowerblue", [100, 149, 237]), - ("cornsilk", [255, 248, 220]), - ("cornsilk1", [255, 248, 220]), - ("cornsilk2", [238, 232, 205]), - ("cornsilk3", [205, 200, 177]), - ("cornsilk4", [139, 136, 120]), - ("cyan", [0, 255, 255]), - ("cyan1", [0, 255, 255]), - ("cyan2", [0, 238, 238]), - ("cyan3", [0, 205, 205]), - ("cyan4", [0, 139, 139]), - ("darkblue", [0, 0, 139]), - ("darkcyan", [0, 139, 139]), - ("darkgoldenrod", [184, 134, 11]), - ("darkgoldenrod1", [255, 185, 15]), - ("darkgoldenrod2", [238, 173, 14]), - ("darkgoldenrod3", [205, 149, 12]), - ("darkgoldenrod4", [139, 101, 8]), - ("darkgray", [169, 169, 169]), - ("darkgreen", [0, 100, 0]), - ("darkgrey", [169, 169, 169]), - ("darkkhaki", [189, 183, 107]), - ("darkmagenta", [139, 0, 139]), - ("darkolivegreen", [85, 107, 47]), - ("darkolivegreen1", [202, 255, 112]), - ("darkolivegreen2", [188, 238, 104]), - ("darkolivegreen3", [162, 205, 90]), - ("darkolivegreen4", [110, 139, 61]), - ("darkorange", [255, 140, 0]), - ("darkorange1", [255, 127, 0]), - ("darkorange2", [238, 118, 0]), - ("darkorange3", [205, 102, 0]), - ("darkorange4", [139, 69, 0]), - ("darkorchid", [153, 50, 204]), - ("darkorchid1", [191, 62, 255]), - ("darkorchid2", [178, 58, 238]), - ("darkorchid3", [154, 50, 205]), - ("darkorchid4", [104, 34, 139]), - ("darkred", [139, 0, 0]), - ("darksalmon", [233, 150, 122]), - ("darkseagreen", [143, 188, 143]), - ("darkseagreen1", [193, 255, 193]), - ("darkseagreen2", [180, 238, 180]), - ("darkseagreen3", [155, 205, 155]), - ("darkseagreen4", [105, 139, 105]), - ("darkslateblue", [72, 61, 139]), - ("darkslategray", [47, 79, 79]), - ("darkslategray1", [151, 255, 255]), - ("darkslategray2", [141, 238, 238]), - ("darkslategray3", [121, 205, 205]), - ("darkslategray4", [82, 139, 139]), - ("darkslategrey", [47, 79, 79]), - ("darkturquoise", [0, 206, 209]), - ("darkviolet", [148, 0, 211]), - ("deeppink", [255, 20, 147]), - ("deeppink1", [255, 20, 147]), - ("deeppink2", [238, 18, 137]), - ("deeppink3", [205, 16, 118]), - ("deeppink4", [139, 10, 80]), - ("deepskyblue", [0, 191, 255]), - ("deepskyblue1", [0, 191, 255]), - ("deepskyblue2", [0, 178, 238]), - ("deepskyblue3", [0, 154, 205]), - ("deepskyblue4", [0, 104, 139]), - ("dimgray", [105, 105, 105]), - ("dimgrey", [105, 105, 105]), - ("dodgerblue", [30, 144, 255]), - ("dodgerblue1", [30, 144, 255]), - ("dodgerblue2", [28, 134, 238]), - ("dodgerblue3", [24, 116, 205]), - ("dodgerblue4", [16, 78, 139]), - ("firebrick", [178, 34, 34]), - ("firebrick1", [255, 48, 48]), - ("firebrick2", [238, 44, 44]), - ("firebrick3", [205, 38, 38]), - ("firebrick4", [139, 26, 26]), - ("floralwhite", [255, 250, 240]), - ("forestgreen", [34, 139, 34]), - ("gainsboro", [220, 220, 220]), - ("ghostwhite", [248, 248, 255]), - ("gold", [255, 215, 0]), - ("gold1", [255, 215, 0]), - ("gold2", [238, 201, 0]), - ("gold3", [205, 173, 0]), - ("gold4", [139, 117, 0]), - ("goldenrod", [218, 165, 32]), - ("goldenrod1", [255, 193, 37]), - ("goldenrod2", [238, 180, 34]), - ("goldenrod3", [205, 155, 29]), - ("goldenrod4", [139, 105, 20]), - ("gray", [190, 190, 190]), - ("gray0", [0, 0, 0]), - ("gray1", [3, 3, 3]), - ("gray10", [26, 26, 26]), - ("gray100", [255, 255, 255]), - ("gray11", [28, 28, 28]), - ("gray12", [31, 31, 31]), - ("gray13", [33, 33, 33]), - ("gray14", [36, 36, 36]), - ("gray15", [38, 38, 38]), - ("gray16", [41, 41, 41]), - ("gray17", [43, 43, 43]), - ("gray18", [46, 46, 46]), - ("gray19", [48, 48, 48]), - ("gray2", [5, 5, 5]), - ("gray20", [51, 51, 51]), - ("gray21", [54, 54, 54]), - ("gray22", [56, 56, 56]), - ("gray23", [59, 59, 59]), - ("gray24", [61, 61, 61]), - ("gray25", [64, 64, 64]), - ("gray26", [66, 66, 66]), - ("gray27", [69, 69, 69]), - ("gray28", [71, 71, 71]), - ("gray29", [74, 74, 74]), - ("gray3", [8, 8, 8]), - ("gray30", [77, 77, 77]), - ("gray31", [79, 79, 79]), - ("gray32", [82, 82, 82]), - ("gray33", [84, 84, 84]), - ("gray34", [87, 87, 87]), - ("gray35", [89, 89, 89]), - ("gray36", [92, 92, 92]), - ("gray37", [94, 94, 94]), - ("gray38", [97, 97, 97]), - ("gray39", [99, 99, 99]), - ("gray4", [10, 10, 10]), - ("gray40", [102, 102, 102]), - ("gray41", [105, 105, 105]), - ("gray42", [107, 107, 107]), - ("gray43", [110, 110, 110]), - ("gray44", [112, 112, 112]), - ("gray45", [115, 115, 115]), - ("gray46", [117, 117, 117]), - ("gray47", [120, 120, 120]), - ("gray48", [122, 122, 122]), - ("gray49", [125, 125, 125]), - ("gray5", [13, 13, 13]), - ("gray50", [127, 127, 127]), - ("gray51", [130, 130, 130]), - ("gray52", [133, 133, 133]), - ("gray53", [135, 135, 135]), - ("gray54", [138, 138, 138]), - ("gray55", [140, 140, 140]), - ("gray56", [143, 143, 143]), - ("gray57", [145, 145, 145]), - ("gray58", [148, 148, 148]), - ("gray59", [150, 150, 150]), - ("gray6", [15, 15, 15]), - ("gray60", [153, 153, 153]), - ("gray61", [156, 156, 156]), - ("gray62", [158, 158, 158]), - ("gray63", [161, 161, 161]), - ("gray64", [163, 163, 163]), - ("gray65", [166, 166, 166]), - ("gray66", [168, 168, 168]), - ("gray67", [171, 171, 171]), - ("gray68", [173, 173, 173]), - ("gray69", [176, 176, 176]), - ("gray7", [18, 18, 18]), - ("gray70", [179, 179, 179]), - ("gray71", [181, 181, 181]), - ("gray72", [184, 184, 184]), - ("gray73", [186, 186, 186]), - ("gray74", [189, 189, 189]), - ("gray75", [191, 191, 191]), - ("gray76", [194, 194, 194]), - ("gray77", [196, 196, 196]), - ("gray78", [199, 199, 199]), - ("gray79", [201, 201, 201]), - ("gray8", [20, 20, 20]), - ("gray80", [204, 204, 204]), - ("gray81", [207, 207, 207]), - ("gray82", [209, 209, 209]), - ("gray83", [212, 212, 212]), - ("gray84", [214, 214, 214]), - ("gray85", [217, 217, 217]), - ("gray86", [219, 219, 219]), - ("gray87", [222, 222, 222]), - ("gray88", [224, 224, 224]), - ("gray89", [227, 227, 227]), - ("gray9", [23, 23, 23]), - ("gray90", [229, 229, 229]), - ("gray91", [232, 232, 232]), - ("gray92", [235, 235, 235]), - ("gray93", [237, 237, 237]), - ("gray94", [240, 240, 240]), - ("gray95", [242, 242, 242]), - ("gray96", [245, 245, 245]), - ("gray97", [247, 247, 247]), - ("gray98", [250, 250, 250]), - ("gray99", [252, 252, 252]), - ("green", [0, 255, 0]), - ("green1", [0, 255, 0]), - ("green2", [0, 238, 0]), - ("green3", [0, 205, 0]), - ("green4", [0, 139, 0]), - ("greenyellow", [173, 255, 47]), - ("grey", [190, 190, 190]), - ("grey0", [0, 0, 0]), - ("grey1", [3, 3, 3]), - ("grey10", [26, 26, 26]), - ("grey100", [255, 255, 255]), - ("grey11", [28, 28, 28]), - ("grey12", [31, 31, 31]), - ("grey13", [33, 33, 33]), - ("grey14", [36, 36, 36]), - ("grey15", [38, 38, 38]), - ("grey16", [41, 41, 41]), - ("grey17", [43, 43, 43]), - ("grey18", [46, 46, 46]), - ("grey19", [48, 48, 48]), - ("grey2", [5, 5, 5]), - ("grey20", [51, 51, 51]), - ("grey21", [54, 54, 54]), - ("grey22", [56, 56, 56]), - ("grey23", [59, 59, 59]), - ("grey24", [61, 61, 61]), - ("grey25", [64, 64, 64]), - ("grey26", [66, 66, 66]), - ("grey27", [69, 69, 69]), - ("grey28", [71, 71, 71]), - ("grey29", [74, 74, 74]), - ("grey3", [8, 8, 8]), - ("grey30", [77, 77, 77]), - ("grey31", [79, 79, 79]), - ("grey32", [82, 82, 82]), - ("grey33", [84, 84, 84]), - ("grey34", [87, 87, 87]), - ("grey35", [89, 89, 89]), - ("grey36", [92, 92, 92]), - ("grey37", [94, 94, 94]), - ("grey38", [97, 97, 97]), - ("grey39", [99, 99, 99]), - ("grey4", [10, 10, 10]), - ("grey40", [102, 102, 102]), - ("grey41", [105, 105, 105]), - ("grey42", [107, 107, 107]), - ("grey43", [110, 110, 110]), - ("grey44", [112, 112, 112]), - ("grey45", [115, 115, 115]), - ("grey46", [117, 117, 117]), - ("grey47", [120, 120, 120]), - ("grey48", [122, 122, 122]), - ("grey49", [125, 125, 125]), - ("grey5", [13, 13, 13]), - ("grey50", [127, 127, 127]), - ("grey51", [130, 130, 130]), - ("grey52", [133, 133, 133]), - ("grey53", [135, 135, 135]), - ("grey54", [138, 138, 138]), - ("grey55", [140, 140, 140]), - ("grey56", [143, 143, 143]), - ("grey57", [145, 145, 145]), - ("grey58", [148, 148, 148]), - ("grey59", [150, 150, 150]), - ("grey6", [15, 15, 15]), - ("grey60", [153, 153, 153]), - ("grey61", [156, 156, 156]), - ("grey62", [158, 158, 158]), - ("grey63", [161, 161, 161]), - ("grey64", [163, 163, 163]), - ("grey65", [166, 166, 166]), - ("grey66", [168, 168, 168]), - ("grey67", [171, 171, 171]), - ("grey68", [173, 173, 173]), - ("grey69", [176, 176, 176]), - ("grey7", [18, 18, 18]), - ("grey70", [179, 179, 179]), - ("grey71", [181, 181, 181]), - ("grey72", [184, 184, 184]), - ("grey73", [186, 186, 186]), - ("grey74", [189, 189, 189]), - ("grey75", [191, 191, 191]), - ("grey76", [194, 194, 194]), - ("grey77", [196, 196, 196]), - ("grey78", [199, 199, 199]), - ("grey79", [201, 201, 201]), - ("grey8", [20, 20, 20]), - ("grey80", [204, 204, 204]), - ("grey81", [207, 207, 207]), - ("grey82", [209, 209, 209]), - ("grey83", [212, 212, 212]), - ("grey84", [214, 214, 214]), - ("grey85", [217, 217, 217]), - ("grey86", [219, 219, 219]), - ("grey87", [222, 222, 222]), - ("grey88", [224, 224, 224]), - ("grey89", [227, 227, 227]), - ("grey9", [23, 23, 23]), - ("grey90", [229, 229, 229]), - ("grey91", [232, 232, 232]), - ("grey92", [235, 235, 235]), - ("grey93", [237, 237, 237]), - ("grey94", [240, 240, 240]), - ("grey95", [242, 242, 242]), - ("grey96", [245, 245, 245]), - ("grey97", [247, 247, 247]), - ("grey98", [250, 250, 250]), - ("grey99", [252, 252, 252]), - ("honeydew", [240, 255, 240]), - ("honeydew1", [240, 255, 240]), - ("honeydew2", [224, 238, 224]), - ("honeydew3", [193, 205, 193]), - ("honeydew4", [131, 139, 131]), - ("hotpink", [255, 105, 180]), - ("hotpink1", [255, 110, 180]), - ("hotpink2", [238, 106, 167]), - ("hotpink3", [205, 96, 144]), - ("hotpink4", [139, 58, 98]), - ("indianred", [205, 92, 92]), - ("indianred1", [255, 106, 106]), - ("indianred2", [238, 99, 99]), - ("indianred3", [205, 85, 85]), - ("indianred4", [139, 58, 58]), - ("ivory", [255, 255, 240]), - ("ivory1", [255, 255, 240]), - ("ivory2", [238, 238, 224]), - ("ivory3", [205, 205, 193]), - ("ivory4", [139, 139, 131]), - ("khaki", [240, 230, 140]), - ("khaki1", [255, 246, 143]), - ("khaki2", [238, 230, 133]), - ("khaki3", [205, 198, 115]), - ("khaki4", [139, 134, 78]), - ("lavender", [230, 230, 250]), - ("lavenderblush", [255, 240, 245]), - ("lavenderblush1", [255, 240, 245]), - ("lavenderblush2", [238, 224, 229]), - ("lavenderblush3", [205, 193, 197]), - ("lavenderblush4", [139, 131, 134]), - ("lawngreen", [124, 252, 0]), - ("lemonchiffon", [255, 250, 205]), - ("lemonchiffon1", [255, 250, 205]), - ("lemonchiffon2", [238, 233, 191]), - ("lemonchiffon3", [205, 201, 165]), - ("lemonchiffon4", [139, 137, 112]), - ("lightblue", [173, 216, 230]), - ("lightblue1", [191, 239, 255]), - ("lightblue2", [178, 223, 238]), - ("lightblue3", [154, 192, 205]), - ("lightblue4", [104, 131, 139]), - ("lightcoral", [240, 128, 128]), - ("lightcyan", [224, 255, 255]), - ("lightcyan1", [224, 255, 255]), - ("lightcyan2", [209, 238, 238]), - ("lightcyan3", [180, 205, 205]), - ("lightcyan4", [122, 139, 139]), - ("lightgoldenrod", [238, 221, 130]), - ("lightgoldenrod1", [255, 236, 139]), - ("lightgoldenrod2", [238, 220, 130]), - ("lightgoldenrod3", [205, 190, 112]), - ("lightgoldenrod4", [139, 129, 76]), - ("lightgoldenrodyellow", [250, 250, 210]), - ("lightgray", [211, 211, 211]), - ("lightgreen", [144, 238, 144]), - ("lightgrey", [211, 211, 211]), - ("lightpink", [255, 182, 193]), - ("lightpink1", [255, 174, 185]), - ("lightpink2", [238, 162, 173]), - ("lightpink3", [205, 140, 149]), - ("lightpink4", [139, 95, 101]), - ("lightsalmon", [255, 160, 122]), - ("lightsalmon1", [255, 160, 122]), - ("lightsalmon2", [238, 149, 114]), - ("lightsalmon3", [205, 129, 98]), - ("lightsalmon4", [139, 87, 66]), - ("lightseagreen", [32, 178, 170]), - ("lightskyblue", [135, 206, 250]), - ("lightskyblue1", [176, 226, 255]), - ("lightskyblue2", [164, 211, 238]), - ("lightskyblue3", [141, 182, 205]), - ("lightskyblue4", [96, 123, 139]), - ("lightslateblue", [132, 112, 255]), - ("lightslategray", [119, 136, 153]), - ("lightslategrey", [119, 136, 153]), - ("lightsteelblue", [176, 196, 222]), - ("lightsteelblue1", [202, 225, 255]), - ("lightsteelblue2", [188, 210, 238]), - ("lightsteelblue3", [162, 181, 205]), - ("lightsteelblue4", [110, 123, 139]), - ("lightyellow", [255, 255, 224]), - ("lightyellow1", [255, 255, 224]), - ("lightyellow2", [238, 238, 209]), - ("lightyellow3", [205, 205, 180]), - ("lightyellow4", [139, 139, 122]), - ("limegreen", [50, 205, 50]), - ("linen", [250, 240, 230]), - ("magenta", [255, 0, 255]), - ("magenta1", [255, 0, 255]), - ("magenta2", [238, 0, 238]), - ("magenta3", [205, 0, 205]), - ("magenta4", [139, 0, 139]), - ("maroon", [176, 48, 96]), - ("maroon1", [255, 52, 179]), - ("maroon2", [238, 48, 167]), - ("maroon3", [205, 41, 144]), - ("maroon4", [139, 28, 98]), - ("mediumaquamarine", [102, 205, 170]), - ("mediumblue", [0, 0, 205]), - ("mediumorchid", [186, 85, 211]), - ("mediumorchid1", [224, 102, 255]), - ("mediumorchid2", [209, 95, 238]), - ("mediumorchid3", [180, 82, 205]), - ("mediumorchid4", [122, 55, 139]), - ("mediumpurple", [147, 112, 219]), - ("mediumpurple1", [171, 130, 255]), - ("mediumpurple2", [159, 121, 238]), - ("mediumpurple3", [137, 104, 205]), - ("mediumpurple4", [93, 71, 139]), - ("mediumseagreen", [60, 179, 113]), - ("mediumslateblue", [123, 104, 238]), - ("mediumspringgreen", [0, 250, 154]), - ("mediumturquoise", [72, 209, 204]), - ("mediumvioletred", [199, 21, 133]), - ("midnightblue", [25, 25, 112]), - ("mintcream", [245, 255, 250]), - ("mistyrose", [255, 228, 225]), - ("mistyrose1", [255, 228, 225]), - ("mistyrose2", [238, 213, 210]), - ("mistyrose3", [205, 183, 181]), - ("mistyrose4", [139, 125, 123]), - ("moccasin", [255, 228, 181]), - ("navajowhite", [255, 222, 173]), - ("navajowhite1", [255, 222, 173]), - ("navajowhite2", [238, 207, 161]), - ("navajowhite3", [205, 179, 139]), - ("navajowhite4", [139, 121, 94]), - ("navy", [0, 0, 128]), - ("navyblue", [0, 0, 128]), - ("oldlace", [253, 245, 230]), - ("olivedrab", [107, 142, 35]), - ("olivedrab1", [192, 255, 62]), - ("olivedrab2", [179, 238, 58]), - ("olivedrab3", [154, 205, 50]), - ("olivedrab4", [105, 139, 34]), - ("orange", [255, 165, 0]), - ("orange1", [255, 165, 0]), - ("orange2", [238, 154, 0]), - ("orange3", [205, 133, 0]), - ("orange4", [139, 90, 0]), - ("orangered", [255, 69, 0]), - ("orangered1", [255, 69, 0]), - ("orangered2", [238, 64, 0]), - ("orangered3", [205, 55, 0]), - ("orangered4", [139, 37, 0]), - ("orchid", [218, 112, 214]), - ("orchid1", [255, 131, 250]), - ("orchid2", [238, 122, 233]), - ("orchid3", [205, 105, 201]), - ("orchid4", [139, 71, 137]), - ("palegoldenrod", [238, 232, 170]), - ("palegreen", [152, 251, 152]), - ("palegreen1", [154, 255, 154]), - ("palegreen2", [144, 238, 144]), - ("palegreen3", [124, 205, 124]), - ("palegreen4", [84, 139, 84]), - ("paleturquoise", [175, 238, 238]), - ("paleturquoise1", [187, 255, 255]), - ("paleturquoise2", [174, 238, 238]), - ("paleturquoise3", [150, 205, 205]), - ("paleturquoise4", [102, 139, 139]), - ("palevioletred", [219, 112, 147]), - ("palevioletred1", [255, 130, 171]), - ("palevioletred2", [238, 121, 159]), - ("palevioletred3", [205, 104, 137]), - ("palevioletred4", [139, 71, 93]), - ("papayawhip", [255, 239, 213]), - ("peachpuff", [255, 218, 185]), - ("peachpuff1", [255, 218, 185]), - ("peachpuff2", [238, 203, 173]), - ("peachpuff3", [205, 175, 149]), - ("peachpuff4", [139, 119, 101]), - ("peru", [205, 133, 63]), - ("pink", [255, 192, 203]), - ("pink1", [255, 181, 197]), - ("pink2", [238, 169, 184]), - ("pink3", [205, 145, 158]), - ("pink4", [139, 99, 108]), - ("plum", [221, 160, 221]), - ("plum1", [255, 187, 255]), - ("plum2", [238, 174, 238]), - ("plum3", [205, 150, 205]), - ("plum4", [139, 102, 139]), - ("powderblue", [176, 224, 230]), - ("purple", [160, 32, 240]), - ("purple1", [155, 48, 255]), - ("purple2", [145, 44, 238]), - ("purple3", [125, 38, 205]), - ("purple4", [85, 26, 139]), - ("red", [255, 0, 0]), - ("red1", [255, 0, 0]), - ("red2", [238, 0, 0]), - ("red3", [205, 0, 0]), - ("red4", [139, 0, 0]), - ("rosybrown", [188, 143, 143]), - ("rosybrown1", [255, 193, 193]), - ("rosybrown2", [238, 180, 180]), - ("rosybrown3", [205, 155, 155]), - ("rosybrown4", [139, 105, 105]), - ("royalblue", [65, 105, 225]), - ("royalblue1", [72, 118, 255]), - ("royalblue2", [67, 110, 238]), - ("royalblue3", [58, 95, 205]), - ("royalblue4", [39, 64, 139]), - ("saddlebrown", [139, 69, 19]), - ("salmon", [250, 128, 114]), - ("salmon1", [255, 140, 105]), - ("salmon2", [238, 130, 98]), - ("salmon3", [205, 112, 84]), - ("salmon4", [139, 76, 57]), - ("sandybrown", [244, 164, 96]), - ("seagreen", [46, 139, 87]), - ("seagreen1", [84, 255, 159]), - ("seagreen2", [78, 238, 148]), - ("seagreen3", [67, 205, 128]), - ("seagreen4", [46, 139, 87]), - ("seashell", [255, 245, 238]), - ("seashell1", [255, 245, 238]), - ("seashell2", [238, 229, 222]), - ("seashell3", [205, 197, 191]), - ("seashell4", [139, 134, 130]), - ("sienna", [160, 82, 45]), - ("sienna1", [255, 130, 71]), - ("sienna2", [238, 121, 66]), - ("sienna3", [205, 104, 57]), - ("sienna4", [139, 71, 38]), - ("skyblue", [135, 206, 235]), - ("skyblue1", [135, 206, 255]), - ("skyblue2", [126, 192, 238]), - ("skyblue3", [108, 166, 205]), - ("skyblue4", [74, 112, 139]), - ("slateblue", [106, 90, 205]), - ("slateblue1", [131, 111, 255]), - ("slateblue2", [122, 103, 238]), - ("slateblue3", [105, 89, 205]), - ("slateblue4", [71, 60, 139]), - ("slategray", [112, 128, 144]), - ("slategray1", [198, 226, 255]), - ("slategray2", [185, 211, 238]), - ("slategray3", [159, 182, 205]), - ("slategray4", [108, 123, 139]), - ("slategrey", [112, 128, 144]), - ("snow", [255, 250, 250]), - ("snow1", [255, 250, 250]), - ("snow2", [238, 233, 233]), - ("snow3", [205, 201, 201]), - ("snow4", [139, 137, 137]), - ("springgreen", [0, 255, 127]), - ("springgreen1", [0, 255, 127]), - ("springgreen2", [0, 238, 118]), - ("springgreen3", [0, 205, 102]), - ("springgreen4", [0, 139, 69]), - ("steelblue", [70, 130, 180]), - ("steelblue1", [99, 184, 255]), - ("steelblue2", [92, 172, 238]), - ("steelblue3", [79, 148, 205]), - ("steelblue4", [54, 100, 139]), - ("tan", [210, 180, 140]), - ("tan1", [255, 165, 79]), - ("tan2", [238, 154, 73]), - ("tan3", [205, 133, 63]), - ("tan4", [139, 90, 43]), - ("thistle", [216, 191, 216]), - ("thistle1", [255, 225, 255]), - ("thistle2", [238, 210, 238]), - ("thistle3", [205, 181, 205]), - ("thistle4", [139, 123, 139]), - ("tomato", [255, 99, 71]), - ("tomato1", [255, 99, 71]), - ("tomato2", [238, 92, 66]), - ("tomato3", [205, 79, 57]), - ("tomato4", [139, 54, 38]), - ("turquoise", [64, 224, 208]), - ("turquoise1", [0, 245, 255]), - ("turquoise2", [0, 229, 238]), - ("turquoise3", [0, 197, 205]), - ("turquoise4", [0, 134, 139]), - ("violet", [238, 130, 238]), - ("violetred", [208, 32, 144]), - ("violetred1", [255, 62, 150]), - ("violetred2", [238, 58, 140]), - ("violetred3", [205, 50, 120]), - ("violetred4", [139, 34, 82]), - ("wheat", [245, 222, 179]), - ("wheat1", [255, 231, 186]), - ("wheat2", [238, 216, 174]), - ("wheat3", [205, 186, 150]), - ("wheat4", [139, 126, 102]), - ("white", [255, 255, 255]), - ("whitesmoke", [245, 245, 245]), - ("yellow", [255, 255, 0]), - ("yellow1", [255, 255, 0]), - ("yellow2", [238, 238, 0]), - ("yellow3", [205, 205, 0]), - ("yellow4", [139, 139, 0]), - ("yellowgreen", [154, 205, 50]), -]; diff --git a/crates/codecs/src/image.rs b/crates/codecs/src/image.rs index 138181f40a..f9d238ba82 100644 --- a/crates/codecs/src/image.rs +++ b/crates/codecs/src/image.rs @@ -140,10 +140,10 @@ pub struct Metadata { /// Free-form key/value text (PNG tEXt/iTXt, TIFF ASCII tags). pub text: Vec<(String, String)>, /// Photoshop image resources (`8BIM` resource blocks): TIFF tag 34377. Kept opaque here; - /// `photocraft-io` reads and writes them through `photocraft-psd`. + /// `photocraft-io` reads and writes them through `craft-psd`. pub photoshop_resources: Option>, /// Photoshop layer data (TIFF tag 37724 `ImageSourceData`): a layered TIFF's layers. Kept - /// opaque here; `photocraft-io` reads and writes it through `photocraft-psd`. + /// opaque here; `photocraft-io` reads and writes it through `craft-psd`. pub photoshop_layers: Option>, /// Samples per pixel beyond the colour channels and the one alpha sample. TIFF extra /// samples (spot colours, extra alpha channels) the pixel layout does not hold. Each entry @@ -373,69 +373,24 @@ impl ExrPartInfo { } } -/// One selection policy for header ranking/probing and flat decoding: never synthesize -/// RGB(A) or YA from separate layers. OpenEXR layers use the full prefix before the last -/// dot, including nested layers; a leading or trailing dot alone does not name a layer. +/// One selection policy for header ranking/probing and flat decoding (craft-exr's): never +/// synthesize RGB(A) or YA from separate layers. pub(crate) fn exr_color_channels<'a>(names: impl IntoIterator) -> Option<(ChannelLayout, Vec)> { - #[derive(Default)] - struct Group { - r: Option, - g: Option, - b: Option, - a: Option, - y: Option, - } - - // Sorted prefixes make rank ties deterministic independently of channel order, with - // the empty (unprefixed) group first. Unsupported channels cannot complete a group. - let mut groups = std::collections::BTreeMap::<&str, Group>::new(); - let mut count = 0usize; - for (index, name) in names.into_iter().enumerate() { - count = count.saturating_add(1); - let (prefix, base) = name.rsplit_once('.').filter(|(prefix, base)| !prefix.is_empty() && !base.is_empty()).unwrap_or(("", name)); - if !matches!(base, "R" | "G" | "B" | "A" | "Y") { - continue; - } - let group = groups.entry(prefix).or_default(); - let component = match base { - "R" => &mut group.r, - "G" => &mut group.g, - "B" => &mut group.b, - "A" => &mut group.a, - "Y" => &mut group.y, - _ => continue, + use craft_exr::channels::ColorLayout; + craft_exr::channels::color_channels(names).map(|(layout, indices)| { + let layout = match layout { + ColorLayout::Y => ChannelLayout::Gray, + ColorLayout::YA => ChannelLayout::GrayA, + ColorLayout::Rgb => ChannelLayout::Rgb, + ColorLayout::Rgba => ChannelLayout::Rgba, }; - component.get_or_insert(index); - } - - let mut best = None; - let mut best_rank = 0; - for group in groups.values() { - let candidate = if let (Some(r), Some(g), Some(b)) = (group.r, group.g, group.b) { - match group.a { - Some(a) => (ChannelLayout::Rgba, vec![r, g, b, a]), - None => (ChannelLayout::Rgb, vec![r, g, b]), - } - } else if let Some(y) = group.y { - match group.a { - Some(a) => (ChannelLayout::GrayA, vec![y, a]), - None => (ChannelLayout::Gray, vec![y]), - } - } else { - continue; - }; - let rank = candidate.0.channels(); - if rank > best_rank { - best = Some(candidate); - best_rank = rank; - } - } - best.or_else(|| (count == 1).then(|| (ChannelLayout::Gray, vec![0]))) + (layout, indices) + }) } /// Strip an optional `layer.` prefix from a channel name (`diffuse.R` → `R`). pub(crate) fn base_channel_name(name: &str) -> &str { - name.rsplit('.').next().unwrap_or(name) + craft_exr::channels::base_channel_name(name) } /// One Cryptomatte layer of an EXR file (Cryptomatte specification 1.2): per-pixel object or diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index 0664a11e0d..591320c663 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -210,7 +210,7 @@ pub fn probe_size(bytes: &[u8]) -> Result<(u32, u32), CodecError> { /// The colour table of a GIF's first frame (its Local Color Table, else the Global one) and the /// entry its Graphic Control Extension makes transparent, read without decoding pixels. pub fn gif_palette(bytes: &[u8]) -> Option<(Vec<[u8; 3]>, Option)> { - crate::codecs::gif_palette::palette(bytes) + craft_gif::palette(bytes) } /// Returns the embedded colour table for an indexed BMP, if it has one. diff --git a/crates/codecs/src/options.rs b/crates/codecs/src/options.rs index 354bbe36b9..c33fe10269 100644 --- a/crates/codecs/src/options.rs +++ b/crates/codecs/src/options.rs @@ -235,60 +235,8 @@ impl DpxBits { } } -/// How a DDS texture stores its pixels. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum DdsCompression { - /// Uncompressed, 8 bits per channel: BGRA (BGRX without alpha), or luminance with or - /// without alpha for grayscale. Lossless. - #[default] - None, - /// BC1 (DXT1): 4 bits per pixel. Alpha is on or off: texels under half opacity become - /// transparent black. - Bc1, - /// BC2 (DXT3): 8 bits per pixel, with 4 bits of explicit alpha per texel. - Bc2, - /// BC3 (DXT5): 8 bits per pixel, with smooth interpolated alpha. - Bc3, -} - -impl DdsCompression { - pub const ALL: [DdsCompression; 4] = [DdsCompression::None, DdsCompression::Bc1, DdsCompression::Bc2, DdsCompression::Bc3]; - - /// The name scripts and the CLI use: `none`, `bc1`, `bc2` or `bc3`. - pub fn name(self) -> &'static str { - match self { - DdsCompression::None => "none", - DdsCompression::Bc1 => "bc1", - DdsCompression::Bc2 => "bc2", - DdsCompression::Bc3 => "bc3", - } - } - - /// [`Self::name`] back to a compression, also taking the DXT names (`dxt1`, `dxt3`, - /// `dxt5`), in any case. Anything else is `None`. - pub fn from_name(name: &str) -> Option { - match name.to_ascii_lowercase().as_str() { - "none" => Some(DdsCompression::None), - "bc1" | "dxt1" => Some(DdsCompression::Bc1), - "bc2" | "dxt3" => Some(DdsCompression::Bc2), - "bc3" | "dxt5" => Some(DdsCompression::Bc3), - _ => None, - } - } - - /// A block compression (lossy), not uncompressed pixels. - pub fn is_block(self) -> bool { - self != DdsCompression::None - } -} - -/// What a DDS file is written with. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub struct DdsOptions { - pub compression: DdsCompression, - /// Write the full mip chain down to 1×1, each level a box filter of the one above. - pub mipmaps: bool, -} +/// How a DDS texture is written: from craft-raster-codecs, which writes it. +pub use craft_raster_codecs::dds::{DdsCompression, DdsOptions}; /// The longer side, in pixels, at which a TIFF image pyramid stops: the last level written is /// the first one no longer than this ([`EncodeOptions::tiff_pyramid`]). diff --git a/crates/codecs/src/resolution.rs b/crates/codecs/src/resolution.rs index 9efc4659d5..8428f624a0 100644 --- a/crates/codecs/src/resolution.rs +++ b/crates/codecs/src/resolution.rs @@ -526,18 +526,118 @@ pub fn xmp_with_resolution(xmp: &str, ppi: (f32, f32)) -> Cow<'_, str> { fn exif_without_thumbnail(exif: &[u8]) -> Option> { let body = tiff_body(exif); let prefix = exif.len() - body.len(); - let (_, first, count, entry_bytes, big_tiff) = ifd0_entries(body)?; + let (order, first, count, entry_bytes, big_tiff) = ifd0_entries(body)?; let next = prefix.checked_add(first)?.checked_add(count.checked_mul(entry_bytes)?)?; let width = if big_tiff { 8 } else { 4 }; // In bounds: `ifd0_entries` checked that the whole pointer is present. if exif.get(next..next.checked_add(width)?)?.iter().all(|b| *b == 0) { return None; } + // Classic TIFF: also blank the thumbnail JPEG itself (IFD1's JPEGInterchangeFormat/Length), + // which stays recoverable in the block once nothing points at it. + // Only a range clear of the TIFF header, IFD0's table and values, and its Exif/GPS sub-IFDs: one + // that covers them is not a thumbnail. + let thumb = (!big_tiff) + .then(|| thumbnail_range(order, body, next - prefix)) + .flatten() + .filter(|&(off, len)| off >= 8 && !overlaps_ifd0(order, body, first - 2, count, off, len)); let mut out = exif.to_vec(); out.get_mut(next..next + width)?.fill(0); + if let Some((off, len)) = thumb + && let Some(jpeg) = prefix.checked_add(off).and_then(|a| out.get_mut(a..a.checked_add(len)?)) + { + jpeg.fill(0); + } Some(out) } +/// Most IFD entries `overlaps_ifd0` examines in total: a hostile block with thousands of Exif/GPS +/// pointers to large sub-IFDs would otherwise cost billions of checks. +const MAX_OVERLAP_ENTRIES: usize = 1 << 20; + +/// Whether `off..off + len` of `body` covers part of classic IFD0 (`ifd0` is its entry count's +/// offset) or of its Exif / GPS sub-IFDs. Past [`MAX_OVERLAP_ENTRIES`] checks it answers `true` +/// (the range is not trusted as a thumbnail, so its bytes stay). +fn overlaps_ifd0(order: Order, body: &[u8], ifd0: usize, count: usize, off: usize, len: usize) -> bool { + let mut budget = MAX_OVERLAP_ENTRIES; + overlaps_ifd(order, body, ifd0, count, off, len, &mut budget) + || (0..count).any(|i| { + let e = ifd0 + 2 + i * 12; + // A LONG pointer (tag 0x8769 ExifIFD, 0x8825 GPSIFD) to a sub-IFD, whose own count says its size. + matches!(order.u16(body, e), Some(0x8769 | 0x8825)) + && order.u32(body, e + 8).and_then(|v| usize::try_from(v).ok()).is_some_and(|sub| overlaps_sub_ifd(order, body, sub, off, len, &mut budget)) + }) +} + +/// [`overlaps_ifd`] for the Exif / GPS sub-IFD at `sub`, and for the Interoperability IFD (tag +/// 0xA005) it points to, which `jpeg.fill(0)` would otherwise erase from under its pointer. +fn overlaps_sub_ifd(order: Order, body: &[u8], sub: usize, off: usize, len: usize, budget: &mut usize) -> bool { + let Some(n) = order.u16(body, sub).map(usize::from) else { return false }; + if overlaps_ifd(order, body, sub, n, off, len, budget) { + return true; + } + (0..n).any(|i| { + let Some(left) = budget.checked_sub(1) else { return true }; + *budget = left; + let e = sub + 2 + i * 12; + matches!(order.u16(body, e), Some(0xA005)) + && order + .u32(body, e + 8) + .and_then(|v| usize::try_from(v).ok()) + .is_some_and(|interop| order.u16(body, interop).is_some_and(|m| overlaps_ifd(order, body, interop, usize::from(m), off, len, budget))) + }) +} + +/// Whether `off..off + len` of `body` covers the table of the classic IFD at `ifd` (its entry +/// count's offset) with the next-IFD pointer, or an out-of-line value of one of its entries. Each +/// entry examined is charged to `budget`; when it runs out the answer is `true`. +fn overlaps_ifd(order: Order, body: &[u8], ifd: usize, count: usize, off: usize, len: usize, budget: &mut usize) -> bool { + let end = off.saturating_add(len); + let hits = |a: usize, size: usize| a < end && off < a.saturating_add(size); + if hits(ifd, 2 + count * 12 + 4) { + return true; + } + (0..count).any(|i| { + let Some(left) = budget.checked_sub(1) else { return true }; + *budget = left; + let e = ifd + 2 + i * 12; + let unit = match order.u16(body, e + 2) { + Some(1 | 2 | 6 | 7) => 1, + Some(3 | 8) => 2, + Some(4 | 9 | 11) => 4, + Some(5 | 10 | 12) => 8, + _ => return false, + }; + let size = usize::try_from(order.u32(body, e + 4).unwrap_or(0)).unwrap_or(usize::MAX).saturating_mul(unit); + size > 4 && order.u32(body, e + 8).and_then(|v| usize::try_from(v).ok()).is_some_and(|v| hits(v, size)) + }) +} + +/// IFD1's thumbnail JPEG as (offset, length) in `body`, from the next-IFD pointer at `ptr`. +fn thumbnail_range(order: Order, body: &[u8], ptr: usize) -> Option<(usize, usize)> { + let ifd1 = usize::try_from(order.u32(body, ptr)?).ok()?; + let (mut off, mut len) = (None, None); + for i in 0..usize::from(order.u16(body, ifd1)?) { + let e = ifd1.checked_add(2)?.checked_add(i.checked_mul(12)?)?; + let tag = order.u16(body, e)?; + if !matches!(tag, 0x0201 | 0x0202) { + continue; + } + // One SHORT or LONG value; anything else holds an unrelated number. + let ty = order.u16(body, e + 2)?; + if order.u32(body, e + 4)? != 1 || !matches!(ty, 3 | 4) { + return None; + } + let value = if ty == 3 { usize::from(order.u16(body, e + 8)?) } else { usize::try_from(order.u32(body, e + 8)?).ok()? }; + if tag == 0x0201 { + off = Some(value); + } else { + len = Some(value); + } + } + Some((off?, len?)) +} + /// The EXIF to write next to upright pixels at resolution `ppi`: Orientation 1 (see /// [`upright_exif`]), no thumbnail of the source image (see [`exif_without_thumbnail`]) and, /// when `ppi` is known, the resolution (see [`exif_with_resolution`]). diff --git a/crates/codecs/src/web.rs b/crates/codecs/src/web.rs index dfd0cd9b90..301e67a9b2 100644 --- a/crates/codecs/src/web.rs +++ b/crates/codecs/src/web.rs @@ -227,7 +227,7 @@ fn put_multibyte(out: &mut Vec, v: u32) { /// WBMP type 0 (1 bit per pixel, rows padded to bytes, 1 = white). `white[i]` per pixel. pub fn encode_wbmp(width: u32, height: u32, white: &[bool]) -> Result, CodecError> { let (w, h) = (width as usize, height as usize); - if width == 0 || height == 0 || white.len() != w * h { + if width == 0 || height == 0 || w.checked_mul(h) != Some(white.len()) { return Err(CodecError::InvalidImage("WBMP size must match the pixel data".into())); } let mut out = vec![0u8, 0u8]; @@ -304,7 +304,7 @@ pub fn encode_jpeg_rgb8( let (Ok(w16), Ok(h16)) = (u16::try_from(width), u16::try_from(height)) else { return Err(CodecError::encode(Format::Jpeg, "JPEG dimensions are limited to 65535")); }; - if rgb.len() != width as usize * height as usize * 3 { + if (width as usize).checked_mul(height as usize).and_then(|n| n.checked_mul(3)) != Some(rgb.len()) { return Err(CodecError::InvalidImage("RGB data does not match the size".into())); } let mut out = Vec::new(); diff --git a/crates/codecs/tests/it/dpx.rs b/crates/codecs/tests/it/dpx.rs index 3ec8978247..2f005efce9 100644 --- a/crates/codecs/tests/it/dpx.rs +++ b/crates/codecs/tests/it/dpx.rs @@ -82,19 +82,27 @@ impl Fixture { (8, _) => out.extend(codes.iter().map(|&c| c as u8)), (16, _) => out.extend(codes.iter().flat_map(|&c| self.u16(c))), (10, 1 | 2) => { - let base = if self.packing == 1 { 22 } else { 20 }; + // Method A pads the bottom two bits, method B the top two. The first sample sits in + // the high bits, except in a luma element, which fills each word from its low end + // (as FFmpeg and ImageMagick read and write it). + let pad = if self.packing == 1 { 2 } else { 0 }; + let luma = self.descriptor == 6; for chunk in codes.chunks(3) { - let w = chunk.iter().enumerate().fold(0u32, |w, (i, &c)| w | (u32::from(c) << (base - 10 * i as u32))); + let w = chunk.iter().enumerate().fold(0u32, |w, (i, &c)| { + let slot = if luma { i as u32 } else { 2 - i as u32 }; + w | (u32::from(c) << (pad + 10 * slot)) + }); out.extend(self.u32(w)); } } (12, 1) => out.extend(codes.iter().flat_map(|&c| self.u16(c << 4))), _ => { - // One bit stream, high bits first, cut into 32-bit words. - let mut bits: Vec = codes.iter().flat_map(|&c| (0..self.bits).rev().map(move |b| (c >> b) & 1 == 1)).collect(); + // Packing 0: the samples follow each other through the line's 32-bit words, the + // first in the low bits (as FFmpeg and ImageMagick read it). + let mut bits: Vec = codes.iter().flat_map(|&c| (0..self.bits).map(move |b| (c >> b) & 1 == 1)).collect(); bits.resize(bits.len().div_ceil(32) * 32, false); for word in bits.chunks(32) { - out.extend(self.u32(word.iter().fold(0u32, |w, &b| (w << 1) | u32::from(b)))); + out.extend(self.u32(word.iter().rev().fold(0u32, |w, &b| (w << 1) | u32::from(b)))); } } } @@ -177,6 +185,8 @@ fn written_codes(b: &[u8]) -> (u8, u16, Vec) { for i in 0..per_line { codes.push(match bits { 8 => u16::from(line[i]), + // A luma element fills each word from its low end. + 10 if nc == 1 => ((be32_at(line, i / 3 * 4) >> (2 + 10 * (i % 3) as u32)) & 0x3FF) as u16, 10 => ((be32_at(line, i / 3 * 4) >> (22 - 10 * (i % 3) as u32)) & 0x3FF) as u16, 12 => u16::from_be_bytes([line[i * 2], line[i * 2 + 1]]) >> 4, _ => u16::from_be_bytes([line[i * 2], line[i * 2 + 1]]), @@ -405,9 +415,10 @@ fn unsupported_and_damaged_files_error_instead_of_panicking() { let mut float = Fixture::new(50, 16, 0, 2, 2).bytes(); float[ELEMENT0 + 23] = 32; unsupported(float, "32-bit float"); + // 12-bit method B (the value in the low bits of each 16-bit word) is read since craft-dpx. let mut method_b = Fixture::new(50, 12, 1, 2, 2).bytes(); method_b[ELEMENT0 + 24..ELEMENT0 + 26].copy_from_slice(&2u16.to_be_bytes()); - unsupported(method_b, "12-bit method B"); + assert!(decode(&method_b).is_ok(), "12-bit method B"); let good = Fixture::new(51, 10, 1, 9, 9).bytes(); let mut no_elements = good.clone(); @@ -438,9 +449,13 @@ fn cineon_bytes(channels: u8, width: u32, height: u32, codes: &[u16]) -> Vec b[0..4].copy_from_slice(&0x802A_5FD7u32.to_be_bytes()); b[4..8].copy_from_slice(&2048u32.to_be_bytes()); b[193] = channels; - b[198] = 10; - b[200..204].copy_from_slice(&width.to_be_bytes()); - b[204..208].copy_from_slice(&height.to_be_bytes()); + // One descriptor per channel, all alike. + for c in 0..usize::from(channels) { + let at = 196 + 28 * c; + b[at + 2] = 10; + b[at + 4..at + 8].copy_from_slice(&width.to_be_bytes()); + b[at + 8..at + 12].copy_from_slice(&height.to_be_bytes()); + } for line in codes.chunks(width as usize * usize::from(channels)) { for chunk in line.chunks(3) { let w = chunk.iter().enumerate().fold(0u32, |w, (i, &c)| w | (u32::from(c) << (22 - 10 * i as u32))); diff --git a/crates/codecs/tests/it/exr_cryptomatte.rs b/crates/codecs/tests/it/exr_cryptomatte.rs index 28ad71e191..012f631818 100644 --- a/crates/codecs/tests/it/exr_cryptomatte.rs +++ b/crates/codecs/tests/it/exr_cryptomatte.rs @@ -269,3 +269,59 @@ fn hostile_input_never_panics() { let e = cryptomatte_layers(&bytes, &Limits { max_alloc: 8, ..Limits::default() }).unwrap_err(); assert!(e.to_string().contains("exceed"), "{e}"); } + +/// Many keys naming the same layer (in different spellings) list it once, so the listing +/// stays proportional to the channels rather than keys * channels. +#[test] +fn keys_naming_one_layer_list_it_once() { + let (w, h) = (4usize, 4usize); + let mk = |n: &str, v: f32| AnyChannel::new(n, FlatSamples::F32(vec![v; w * h])); + let list = vec![mk("crypto_asset00.red", cryptomatte_id("cube")), mk("crypto_asset00.green", 1.0)]; + let mut attrs = LayerAttributes::named("crypto_asset"); + let spellings = ["CryptoAsset", "crypto_asset", "Crypto-Asset", "CRYPTO_ASSET", "crypto__asset"]; + for i in 0..200 { + let name = spellings[i % spellings.len()]; + attrs.other.insert(text(&format!("cryptomatte/k{i:04}/name")), AttributeValue::Text(text(name))); + } + let layer = Layer::new( + (w, h), + attrs, + Encoding { compression: Compression::Uncompressed, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing }, + AnyChannels::sort(list.into_iter().collect()), + ); + let image = exr::image::Image::from_layers(ImageAttributes::new(IntegerBounds::new((0, 0), (w, h))), vec![layer]); + let mut out = std::io::Cursor::new(Vec::new()); + image.write().to_buffered(&mut out).expect("synthetic cryptomatte exr writes"); + let bytes = out.into_inner(); + let found = cryptomatte_layers(&bytes, &Limits::default()).unwrap(); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(found[0].channels, ["crypto_asset00"]); + let buf = decode_cryptomatte(&bytes, &found[0].name, &Limits::default()).unwrap(); + assert_eq!(buf.at(0, 0).len(), 1); +} + +/// Of keys naming one layer, the first with a usable manifest lists it, not an earlier one +/// whose manifest is missing. +#[test] +fn a_later_key_with_a_manifest_beats_an_earlier_one_without() { + let (w, h) = (4usize, 4usize); + let mk = |n: &str, v: f32| AnyChannel::new(n, FlatSamples::F32(vec![v; w * h])); + let list = vec![mk("crypto_asset00.red", cryptomatte_id("cube")), mk("crypto_asset00.green", 1.0)]; + let mut attrs = LayerAttributes::named("crypto_asset"); + attrs.other.insert(text("cryptomatte/a/name"), AttributeValue::Text(text("CryptoAsset"))); + attrs.other.insert(text("cryptomatte/b/name"), AttributeValue::Text(text("crypto_asset"))); + attrs.other.insert(text("cryptomatte/b/manifest"), AttributeValue::Text(text("{\"cube\":\"3f800000\"}"))); + let layer = Layer::new( + (w, h), + attrs, + Encoding { compression: Compression::Uncompressed, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing }, + AnyChannels::sort(list.into_iter().collect()), + ); + let image = exr::image::Image::from_layers(ImageAttributes::new(IntegerBounds::new((0, 0), (w, h))), vec![layer]); + let mut out = std::io::Cursor::new(Vec::new()); + image.write().to_buffered(&mut out).expect("synthetic cryptomatte exr writes"); + let found = cryptomatte_layers(&out.into_inner(), &Limits::default()).unwrap(); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(found[0].key, "b"); + assert_eq!(found[0].manifest.len(), 1); +} diff --git a/crates/codecs/tests/it/resolution.rs b/crates/codecs/tests/it/resolution.rs index 28c8203c96..af5165b848 100644 --- a/crates/codecs/tests/it/resolution.rs +++ b/crates/codecs/tests/it/resolution.rs @@ -511,10 +511,12 @@ fn exports_drop_the_source_exif_thumbnail() { assert!(out.windows(6).any(|w| w == b"NIKON\0"), "the rest of the EXIF is kept"); near(exif_resolution(&out), ppi.map_or(300.0, |p| p.0)); } - // Only the pointer changes. + // Only the pointer and the thumbnail's own bytes (the JPEG at the end) change. let out = export_exif(&exif, None); + let thumb_len = b"\xFF\xD8stale thumbnail\xFF\xD9".len(); let differing: Vec = (0..exif.len()).filter(|&i| exif[i] != out[i]).collect(); - assert!(differing.iter().all(|&i| (8 + 2 + 4 * 12..8 + 2 + 4 * 12 + 4).contains(&i)), "{differing:?}"); + assert!(differing.iter().all(|&i| (8 + 2 + 4 * 12..8 + 2 + 4 * 12 + 4).contains(&i) || i >= exif.len() - thumb_len), "{differing:?}"); + assert!(!out.windows(5).any(|w| w == b"stale"), "the thumbnail bytes are blanked, not just unlinked"); // With a JPEG-style prefix too. let prefixed = [b"Exif\0\0".as_slice(), &exif].concat(); assert_eq!(next_ifd(e, &export_exif(&prefixed, None)[6..]), 0); @@ -534,6 +536,44 @@ fn exports_drop_the_source_exif_thumbnail() { } } +/// A thumbnail range that covers IFD0, or tags that are not one SHORT/LONG value, are not blanked. +#[test] +fn thumbnail_blanking_keeps_ifd0_and_ignores_malformed_tags() { + for e in [&LE, &BE] { + let exif = exif_with_thumbnail(e); + let ifd1 = camera_exif(e).len(); + let table = 8..8 + 2 + 4 * 12; + // Offset 8, length 60: the range covers IFD0's table. + let mut over = exif.clone(); + over[ifd1 + 2 + 8..ifd1 + 2 + 12].copy_from_slice(&e.u32(8)); + over[ifd1 + 2 + 12 + 8..ifd1 + 2 + 12 + 12].copy_from_slice(&e.u32(60)); + let out = export_exif(&over, None); + assert_eq!(next_ifd(e, &out), 0, "IFD1 is still unlinked"); + assert_eq!(out[table.start..table.end], over[table.start..table.end], "IFD0's table is untouched"); + // Offset 0, length 8: the range covers the TIFF header, which must stay parseable. + let mut header = exif.clone(); + header[ifd1 + 2 + 8..ifd1 + 2 + 12].copy_from_slice(&e.u32(0)); + header[ifd1 + 2 + 12 + 8..ifd1 + 2 + 12 + 12].copy_from_slice(&e.u32(8)); + let out = export_exif(&header, None); + assert_eq!(out[..8], header[..8], "the TIFF header is untouched"); + // IFD0's last entry (Unit) turned into an ExifIFD pointer at IFD1's table: that range is not a thumbnail. + let mut sub = exif.clone(); + let entry = 8 + 2 + 3 * 12; + sub[entry..entry + 2].copy_from_slice(&e.u16(0x8769)); + sub[entry + 2..entry + 4].copy_from_slice(&e.u16(LONG)); + sub[entry + 4..entry + 8].copy_from_slice(&e.u32(1)); + sub[entry + 8..entry + 12].copy_from_slice(&e.u32(ifd1 as u32)); + sub[ifd1 + 2 + 8..ifd1 + 2 + 12].copy_from_slice(&e.u32(ifd1 as u32 + 2)); + sub[ifd1 + 2 + 12 + 8..ifd1 + 2 + 12 + 12].copy_from_slice(&e.u32(4)); + let out = export_exif(&sub, None); + assert_eq!(out[ifd1 + 2..ifd1 + 6], sub[ifd1 + 2..ifd1 + 6], "the sub-IFD's table is untouched"); + // A count of 2 on the offset tag: the thumbnail bytes are not blanked. + let mut counted = exif.clone(); + counted[ifd1 + 2 + 4..ifd1 + 2 + 8].copy_from_slice(&e.u32(2)); + assert!(export_exif(&counted, None).windows(5).any(|w| w == b"stale")); + } +} + #[test] fn thumbnail_removal_never_panics_on_truncated_exif() { for e in [&LE, &BE] { @@ -544,3 +584,75 @@ fn thumbnail_removal_never_panics_on_truncated_exif() { } } } + +/// Many Exif pointers to one huge sub-IFD must not cost a full scan each: past the scan budget the +/// thumbnail bytes are left alone (the IFD1 pointer is still cleared). +#[test] +fn thumbnail_overlap_scan_is_bounded_by_a_budget() { + let e = &LE; + let (pointers, sub_entries) = (100usize, 65_535usize); + let sub = 8 + 2 + pointers * 12 + 4; + let ifd1 = sub + 2 + sub_entries * 12 + 4; + let thumb = b"\xFF\xD8stale thumbnail\xFF\xD9"; + let mut v = b"II*\0".to_vec(); + v.extend_from_slice(&e.u32(8)); + v.extend_from_slice(&e.u16(pointers as u16)); + for _ in 0..pointers { + v.extend_from_slice(&[e.u16(0x8769), e.u16(LONG)].concat()); + v.extend_from_slice(&[e.u32(1), e.u32(sub as u32)].concat()); + } + v.extend_from_slice(&e.u32(ifd1 as u32)); + v.extend_from_slice(&e.u16(sub_entries as u16)); + v.resize(ifd1, 0); // the sub-IFD's entries are type 0: nothing to hit + v.extend_from_slice(&e.u16(2)); + for (tag, value) in [(0x0201u16, (ifd1 + 2 + 2 * 12 + 4) as u32), (0x0202, thumb.len() as u32)] { + v.extend_from_slice(&[e.u16(tag), e.u16(LONG)].concat()); + v.extend_from_slice(&[e.u32(1), e.u32(value)].concat()); + } + v.extend_from_slice(&e.u32(0)); + v.extend_from_slice(thumb); + let out = export_exif(&v, None); + assert_eq!(next_ifd_at(e, &out, 8 + 2 + pointers * 12), 0, "IFD1 is unlinked"); + assert!(out.windows(5).any(|w| w == b"stale"), "over the scan budget the thumbnail bytes stay"); +} + +fn next_ifd_at(e: &Exif, exif: &[u8], at: usize) -> u32 { + let b: [u8; 4] = exif[at..at + 4].try_into().unwrap(); + if e.big { u32::from_be_bytes(b) } else { u32::from_le_bytes(b) } +} + +/// A thumbnail range that covers the Interoperability IFD (an Exif sub-IFD's 0xA005 target) is not +/// blanked: its pointer would stay behind, aimed at zeroes. +#[test] +fn thumbnail_blanking_keeps_the_interoperability_ifd() { + for e in [&LE, &BE] { + let (ifd0, sub, interop, ifd1) = (8usize, 8 + 2 + 12 + 4, 8 + 2 + 12 + 4 + 2 + 12 + 4, 8 + 2 + 12 + 4 + 2 + 12 + 4 + 2 + 12 + 4); + let mut v = if e.big { b"MM\0*".to_vec() } else { b"II*\0".to_vec() }; + v.extend_from_slice(&e.u32(ifd0 as u32)); + // IFD0: one ExifIFD pointer, then IFD1. + v.extend_from_slice(&e.u16(1)); + v.extend_from_slice(&[e.u16(0x8769), e.u16(LONG)].concat()); + v.extend_from_slice(&[e.u32(1), e.u32(sub as u32)].concat()); + v.extend_from_slice(&e.u32(ifd1 as u32)); + // The Exif IFD: one Interoperability pointer. + v.extend_from_slice(&e.u16(1)); + v.extend_from_slice(&[e.u16(0xA005), e.u16(LONG)].concat()); + v.extend_from_slice(&[e.u32(1), e.u32(interop as u32)].concat()); + v.extend_from_slice(&e.u32(0)); + // The Interoperability IFD: one inline ASCII entry (InteroperabilityIndex). + v.extend_from_slice(&e.u16(1)); + v.extend_from_slice(&[e.u16(1), e.u16(ASCII)].concat()); + v.extend_from_slice(&[e.u32(4), b"R98\0".to_vec().try_into().unwrap_or([0; 4])].concat()); + v.extend_from_slice(&e.u32(0)); + assert_eq!(v.len(), ifd1); + // IFD1: a thumbnail whose range is the Interoperability IFD. + v.extend_from_slice(&e.u16(2)); + for (tag, value) in [(0x0201u16, interop as u32), (0x0202, 18)] { + v.extend_from_slice(&[e.u16(tag), e.u16(LONG)].concat()); + v.extend_from_slice(&[e.u32(1), e.u32(value)].concat()); + } + v.extend_from_slice(&e.u32(0)); + let out = export_exif(&v, None); + assert_eq!(out[interop..interop + 18], v[interop..interop + 18], "the Interoperability IFD is untouched"); + } +} diff --git a/crates/compose/src/effects/distance.rs b/crates/compose/src/effects/distance.rs index ed92d9f973..1b93cd8ac6 100644 --- a/crates/compose/src/effects/distance.rs +++ b/crates/compose/src/effects/distance.rs @@ -158,7 +158,9 @@ impl Dt1Scratch { pub(super) fn edt_nearest(inside: &[bool], w: usize, h: usize) -> (Vec, Vec) { const INF: f32 = 1e20; let total = w.saturating_mul(h); - if total != inside.len() || total > u32::MAX as usize { + // No pixels: nothing to transform, and the scratch below is sized from the larger + // dimension, which a zero-by-huge plane would still allocate. + if total != inside.len() || total > u32::MAX as usize || total == 0 { return (vec![INF; inside.len()], vec![0; inside.len()]); } let n = w.max(h); diff --git a/crates/compose/src/effects/paint.rs b/crates/compose/src/effects/paint.rs index 99b0c6aa0b..3403ebddb9 100644 --- a/crates/compose/src/effects/paint.rs +++ b/crates/compose/src/effects/paint.rs @@ -180,7 +180,11 @@ struct PreparedGradient { impl PreparedGradient { fn new(g: &Gradient) -> Self { - Self { color: g.stops.iter().map(|(p, c)| (*p, rgb(c))).collect(), opacity: g.opacity_stops.iter().map(|(p, a)| (*p, [*a; 3])).collect() } + let mut color: Vec<_> = g.stops.iter().map(|(p, c)| (*p, rgb(c))).collect(); + color.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut opacity: Vec<_> = g.opacity_stops.iter().map(|(p, a)| (*p, [*a; 3])).collect(); + opacity.sort_by(|a, b| a.0.total_cmp(&b.0)); + Self { color, opacity } } fn sample(&self, t: f32) -> [f32; 4] { @@ -198,13 +202,15 @@ fn sample_stops(stops: &[(f32, [f32; 3])], t: f32) -> [f32; 3] { if t <= stops[0].0 { return stops[0].1; } - for w in stops.windows(2) { - if t <= w[1].0 { - let k = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 }; - return std::array::from_fn(|i| w[0].1[i] + (w[1].1[i] - w[0].1[i]) * k); - } + // Sorted in `new`: bisect rather than scan the stops for every covered pixel. + let j = stops.partition_point(|s| s.0 < t); + // j == 0 for a NaN position: the last stop, as a scan gave. + if j >= stops.len() || j == 0 { + return stops[stops.len() - 1].1; } - stops[stops.len() - 1].1 + let (a, b) = (&stops[j - 1], &stops[j]); + let k = if b.0 > a.0 { (t - a.0) / (b.0 - a.0) } else { 0.0 }; + std::array::from_fn(|i| a.1[i] + (b.1[i] - a.1[i]) * k) } } } diff --git a/crates/compose/src/effects/tests.rs b/crates/compose/src/effects/tests.rs index 83cef453ca..9795262ed2 100644 --- a/crates/compose/src/effects/tests.rs +++ b/crates/compose/src/effects/tests.rs @@ -1048,6 +1048,14 @@ fn shifting_by_hostile_distances_does_not_overflow() { } } +/// A plane with no pixels but a huge other dimension must not size scratch from it. +#[test] +fn an_empty_distance_transform_allocates_nothing() { + let (d, n) = edt_nearest(&[], 0, 1 << 30); + assert!(d.is_empty() && n.is_empty()); + assert!(edt(&[], 1 << 30, 0).is_empty()); +} + /// #8639 review: a Stroke Emboss whose stroke lies wholly inside shades with the layer, so its /// non-Normal highlight or shadow counts as an interior blend, as an Inner Bevel's does; with the /// stroke reaching outside, or no stroke, it doesn't. diff --git a/crates/compose/src/fx_cache.rs b/crates/compose/src/fx_cache.rs index e1cd209002..02dc8b21cc 100644 --- a/crates/compose/src/fx_cache.rs +++ b/crates/compose/src/fx_cache.rs @@ -275,6 +275,13 @@ fn evict_fx_cache_over_budget(key: u64) { c.bytes = c.bytes.saturating_sub(s.get().map_or(0, |e| e.bytes)); } } + // The current entry alone over the budget: its callers hold the maps, the cache must not. + if c.bytes > budget + && let Some(s) = c.map.remove(&key) + { + c.order.retain(|k| *k != key); + c.bytes = c.bytes.saturating_sub(s.get().map_or(0, |e| e.bytes)); + } } /// The layer's effect maps from the global cache, built on a miss. diff --git a/crates/compose/src/gradient_fill.rs b/crates/compose/src/gradient_fill.rs index 0e7fe319e3..21a7401b6a 100644 --- a/crates/compose/src/gradient_fill.rs +++ b/crates/compose/src/gradient_fill.rs @@ -72,15 +72,17 @@ fn sample_color(stops: &[(f32, [f32; N])], mids: &[f32], t: f32) if t <= first.0 { return first.1; } - for (i, w) in stops.windows(2).enumerate() { - let (a, b) = (&w[0], &w[1]); - if t <= b.0 { - let u = if b.0 > a.0 { (t - a.0) / (b.0 - a.0) } else { 0.0 }; - let k = midpoint_remap(u, mids.get(i).copied().unwrap_or(0.5)); - return std::array::from_fn(|c| a.1[c] + (b.1[c] - a.1[c]) * k); - } + // The stops are sorted: the segment is found by bisection, not a scan per pixel (a + // document can carry thousands of stops). + let j = stops.partition_point(|s| s.0 < t); + // A NaN position leaves `j` at 0 (no stop compares below it): the last stop, as a scan gave. + if j >= stops.len() || j == 0 { + return last.1; } - last.1 + let (a, b) = (&stops[j - 1], &stops[j]); + let u = if b.0 > a.0 { (t - a.0) / (b.0 - a.0) } else { 0.0 }; + let k = midpoint_remap(u, mids.get(j - 1).copied().unwrap_or(0.5)); + std::array::from_fn(|c| a.1[c] + (b.1[c] - a.1[c]) * k) } fn sample_opacity(stops: &[(f32, f32)], t: f32) -> f32 { @@ -88,13 +90,13 @@ fn sample_opacity(stops: &[(f32, f32)], t: f32) -> f32 { if t <= first.0 { return first.1; } - for w in stops.windows(2) { - if t <= w[1].0 { - let u = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 }; - return w[0].1 + (w[1].1 - w[0].1) * u; - } + let j = stops.partition_point(|s| s.0 < t); + if j >= stops.len() || j == 0 { + return last.1; } - last.1 + let (a, b) = (&stops[j - 1], &stops[j]); + let u = if b.0 > a.0 { (t - a.0) / (b.0 - a.0) } else { 0.0 }; + a.1 + (b.1 - a.1) * u } /// Adds one level of the shared dither noise to a colour (as the Gradient tool does). @@ -248,6 +250,38 @@ pub fn from_handles(style: GradientStyle, from: [f32; 2], to: [f32; 2], frame: R #[cfg(test)] mod tests { use super::*; + + /// A NaN position (from a non-finite angle in a file) returns the last stop and does not panic. + #[test] + fn nan_position_gives_the_last_stop() { + let stops = [(0.0f32, [1.0f32]), (1.0, [2.0])]; + assert_eq!(sample_color(&stops, &[], f32::NAN), [2.0]); + assert_eq!(sample_opacity(&[(0.0, 0.25), (1.0, 0.75)], f32::NAN), 0.75); + } + + /// Bisection over many stops picks the same segment as a scan, including repeated positions. + #[test] + fn bisected_stop_lookup_matches_a_scan() { + let stops: Vec<(f32, [f32; 1])> = (0..1000).map(|i| ((i / 2) as f32 / 500.0, [i as f32])).collect(); + let scan = |t: f32| { + if t <= stops[0].0 { + return stops[0].1; + } + for w in stops.windows(2) { + if t <= w[1].0 { + let u = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 }; + return [w[0].1[0] + (w[1].1[0] - w[0].1[0]) * u]; + } + } + stops[stops.len() - 1].1 + }; + for k in 0..=2000 { + let t = k as f32 / 2000.0 * 1.1 - 0.05; + assert_eq!(sample_color(&stops, &[], t), scan(t), "t = {t}"); + } + let opacity: Vec<(f32, f32)> = stops.iter().map(|(p, c)| (*p, c[0])).collect(); + assert_eq!(sample_opacity(&opacity, 0.5), sample_color(&stops, &[], 0.5)[0]); + } use photocraft_doc::Color; const STYLES: [GradientStyle; 5] = [GradientStyle::Linear, GradientStyle::Radial, GradientStyle::Angle, GradientStyle::Reflected, GradientStyle::Diamond]; diff --git a/crates/doc/src/vector.rs b/crates/doc/src/vector.rs index 9dc8edf258..0f6b4af7e2 100644 --- a/crates/doc/src/vector.rs +++ b/crates/doc/src/vector.rs @@ -303,8 +303,8 @@ pub enum LiveShape { rect: [f64; 4], }, /// Regular polygon or star inscribed in `rect`; `star_ratio` = inner/outer radius (1 = polygon). - /// `corner_radius` rounds every vertex (0 = sharp), each within what its edges allow; the - /// Triangle tool draws a 3-sided one. + /// `corner_radius` rounds every vertex of a polygon and the outer points of a star (0 = sharp), + /// each within what its edges allow. Polygon { rect: [f64; 4], sides: u32, @@ -312,6 +312,15 @@ pub enum LiveShape { #[serde(default)] corner_radius: f64, }, + /// Isosceles triangle filling `rect`: the apex at the centre of the top edge, then the bottom + /// right and the bottom left corner (the Triangle tool, Create Triangle). `corner_radius` + /// rounds all three corners (0 = sharp), each within what its edges allow. Triangles saved + /// before this kind existed are 3-sided `Polygon`s and keep that geometry. + Triangle { + rect: [f64; 4], + #[serde(default)] + corner_radius: f64, + }, /// Line from `from` to `to` drawn as a filled bar `weight` px thick. Line { from: [f64; 2], diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index b5b814b1a2..51f652c77c 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -30,7 +30,7 @@ photocraft-algo = { workspace = true } photocraft-text = { workspace = true } photocraft-vector = { workspace = true } photocraft-io = { workspace = true } -photocraft-psd = { workspace = true } +craft-psd = { workspace = true } photocraft-format = { workspace = true } photocraft-plugins = { workspace = true } base64 = "0.22" diff --git a/crates/engine/src/allocation.rs b/crates/engine/src/allocation.rs index bf5dc177f6..db9344d9a7 100644 --- a/crates/engine/src/allocation.rs +++ b/crates/engine/src/allocation.rs @@ -15,6 +15,23 @@ pub(crate) fn filled(len: usize, value: T, purpose: &str) -> Result, max: u64) -> std::io::Result> { + use std::io::{Error, ErrorKind, Read}; + let file = std::fs::File::open(path)?; + if !file.metadata()?.is_file() { + return Err(Error::new(ErrorKind::InvalidInput, "not a regular file")); + } + let mut out = Vec::new(); + file.take(max.saturating_add(1)).read_to_end(&mut out)?; + if out.len() as u64 > max { + return Err(Error::new(ErrorKind::InvalidData, format!("file is larger than {max} bytes"))); + } + Ok(out) +} + /// Reserve a vector for a known number of operation results. pub(crate) fn capacity(len: usize, purpose: &str) -> Result> { let bytes = len.checked_mul(std::mem::size_of::()).ok_or_else(|| error(purpose, "requested size overflowed"))?; @@ -61,6 +78,29 @@ pub(crate) fn read_region(surface: &photocraft_raster::Surface, area: photocraft Ok(out) } +/// Most bytes of dense working buffers one command may hold while it expands sparse content (or +/// the canvas) into flat arrays: the allowance Image Size resamples within. A document stores +/// only the tiles it holds, so two distant tiles, or a huge empty canvas, make a small file whose +/// content bounds would need far more than any machine has. +pub(crate) const MAX_DENSE_BYTES: u64 = crate::image_cmds::MAX_RESAMPLE_BYTES; + +/// Refuses, before anything is allocated, an operation that would hold `bytes_per_px` bytes of +/// dense buffers for every pixel of `area` at once. +pub(crate) fn check_dense(area: photocraft_geom::Rect, bytes_per_px: u64, purpose: &str) -> Result<()> { + let px = u64::from(area.width()).saturating_mul(u64::from(area.height())); + let bytes = px.saturating_mul(bytes_per_px); + if bytes <= MAX_DENSE_BYTES { + return Ok(()); + } + Err(EngineError::Other(format!( + "{purpose} would need {} MB of working memory for a {} x {} px area (limit {} MB); the document was not changed", + bytes >> 20, + area.width(), + area.height(), + MAX_DENSE_BYTES >> 20 + ))) +} + pub(crate) fn error(purpose: &str, detail: &str) -> EngineError { EngineError::Other(format!("not enough memory for {purpose} ({detail}); the document was not changed")) } @@ -102,6 +142,17 @@ fn failpoint_hits() -> bool { mod tests { use super::*; + #[test] + fn dense_area_past_the_budget_is_refused() { + use photocraft_geom::Rect; + assert!(check_dense(Rect::from_xywh(0, 0, 4096, 4096), 16, "test").is_ok()); + // Two tiles a million pixels apart: content bounds of a trillion pixels. + let far = Rect::new(0, 0, 1 << 20, 1 << 20); + assert!(check_dense(far, 16, "test").is_err_and(|e| e.to_string().contains("working memory"))); + // Overflowing sizes saturate instead of wrapping into a small number. + assert!(check_dense(Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX), u64::MAX, "test").is_err()); + } + #[test] fn allocation_failure_is_reported_without_panicking() { fail_next_for_test(); @@ -131,4 +182,30 @@ mod tests { assert!(filled::(4, 0, "counted").is_err_and(|e| e.to_string().contains("not enough memory for counted"))); assert!(filled::(4, 0, "done").is_ok()); } + + #[test] + fn read_file_within_bounds_the_bytes_and_refuses_special_files() { + let path = std::env::temp_dir().join(format!("pc-read-within-{}", std::process::id())); + std::fs::write(&path, [7u8; 10]).unwrap(); + let p = path.to_str().unwrap(); + assert_eq!(read_file_within(p, 10).unwrap(), vec![7u8; 10]); + assert!(read_file_within(p, 9).is_err_and(|e| e.kind() == std::io::ErrorKind::InvalidData)); + std::fs::remove_file(&path).unwrap(); + // A directory (and on unix a device that never ends) is not a regular file. + assert!(read_file_within(std::env::temp_dir().to_str().unwrap(), 10).is_err()); + #[cfg(unix)] + assert!(read_file_within("/dev/zero", 1 << 30).is_err_and(|e| e.kind() == std::io::ErrorKind::InvalidInput)); + } + + #[cfg(unix)] + #[test] + fn read_file_within_reads_a_path_that_is_not_utf8() { + use std::os::unix::ffi::OsStrExt; + let dir = std::env::temp_dir().join(format!("pc-read-within-nonutf8-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(std::ffi::OsStr::from_bytes(b"frame-\xff.png")); + std::fs::write(&path, [3u8; 4]).unwrap(); + assert_eq!(read_file_within(&path, 10).unwrap(), vec![3u8; 4]); + std::fs::remove_dir_all(&dir).unwrap(); + } } diff --git a/crates/engine/src/canvas_geom.rs b/crates/engine/src/canvas_geom.rs index 795ba9d1bb..c3e3254ac2 100644 --- a/crates/engine/src/canvas_geom.rs +++ b/crates/engine/src/canvas_geom.rs @@ -305,6 +305,18 @@ pub(crate) fn transform_doc_marks(doc: &mut Document, a: &Affine) { } } +/// Runs `f` (Image Size, Canvas Size, Image Rotation) and puts the count points back where they +/// were: they keep their document coordinates, also where they end up off the canvas, as in the +/// reference application (#11762). Other marks follow the map as `f` applies it. +pub(crate) fn keeping_count_points(doc: &mut Document, f: impl FnOnce(&mut Document) -> R) -> R { + let saved: Vec> = doc.measurement.count_groups.iter().map(|g| g.points.clone()).collect(); + let r = f(doc); + for (g, points) in doc.measurement.count_groups.iter_mut().zip(saved) { + g.points = points; + } + r +} + /// Applies `a` to all non-pixel geometry of the document (layers and document marks). pub(crate) fn transform_geometry(doc: &mut Document, a: &Affine) { let dpi = doc.resolution_dpi; diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index a17fdec405..d44758cd52 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -27,6 +27,11 @@ pub struct CommandSpec { pub journal: bool, } +/// Image › Adjustments › Desaturate: Hue/Saturation with saturation at -100. +pub(crate) fn desaturate_adjustment() -> Adjustment { + Adjustment::HueSaturation { hue: 0.0, saturation: -100.0, lightness: 0.0, colorize: false, ranges: photocraft_doc::adjust::HueRange::defaults() } +} + /// Image › Image Rotation by a right angle or a flip (pixels, vectors, guides, … all move). fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result { if let Some(d) = s.active() { @@ -37,7 +42,7 @@ fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result Vec { ["Image", "Adjustments"], Some("Cmd+Shift+U"), r##"{"target":"pixels"|"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active}"##, - has_pixel_layer, + crate::adjust_cmds::has_adjustable, |s, p| { - destructive_adjust( - s, - "Desaturate", - Adjustment::HueSaturation { - hue: 0.0, - saturation: -100.0, - lightness: 0.0, - colorize: false, - ranges: photocraft_doc::adjust::HueRange::defaults(), - }, - p, - ) + if crate::adjust_cmds::adjust_as_smart_filter(s, "desaturate", "Desaturate", p)? { + return Ok(Value::Null); + } + destructive_adjust(s, "Desaturate", desaturate_adjustment(), p) } ), // Paint diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index b72254ba3b..c854dfa631 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -136,6 +136,9 @@ pub struct ActionsFile { pub const MAX_PLAYBACK_STEPS: u64 = 100_000; +/// How deep batches and droplets may run inside one another (a droplet whose steps run a droplet). +pub const MAX_BATCH_DEPTH: u8 = 4; + /// Actions list and the recording / playback flags. Only `list` is persisted. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default)] @@ -156,6 +159,14 @@ pub struct ActionState { /// Number of steps executed by the current top-level playback tree. #[serde(skip)] pub playback_steps: u64, + /// Set for a batch nested in a played action or another batch: the playback counter it carries + /// is shared by every input, so a played action inside it does not restart the count. + #[serde(skip)] + pub budget_shared: bool, + /// How many batches (`file.automate.batch`, and droplets through it) are running inside one + /// another: each runs its steps in a scratch session that carries this on, plus one. + #[serde(skip)] + pub batch_depth: u8, /// How many scripts (`file.scripts.browse`) are running inside one another. #[serde(skip)] pub script_depth: u8, @@ -303,6 +314,22 @@ pub fn consume_playback_step(s: &mut Session) -> bool { true } } + +/// Steps of the playback tree the next `actions.play` starts in has charged so far: a top-level +/// call starts a new tree ([`begin_playback`] resets the counter). +fn playback_steps_used(s: &Session) -> u64 { + if s.actions.playing > 0 || s.actions.budget_shared { s.actions.playback_steps } else { 0 } +} + +/// Steps of `action` playback walks past without running them: the ones before `from` and the +/// disabled ones after it. [`begin_playback`] charges them, so every stored step costs one unit +/// of the playback budget once per call, run or not. +fn skipped_steps(action: &Action, from: usize) -> u64 { + let len = action.steps.len(); + let from = from.min(len); + let disabled = action.disabled.range(from..len).count(); + u64::try_from(from.saturating_add(disabled)).unwrap_or(u64::MAX) +} /// View-only menu commands recorded by the desktop shell. Headless playback reports /// them as unsupported instead of silently dropping them; Batch and droplets skip them. pub fn shell_view_command(id: &str) -> bool { @@ -315,6 +342,14 @@ pub fn playback_plan(s: &Session, p: &Value) -> Result<(Action, usize)> { return Err(bad("actions.play", "an action is already playing")); } let idx = resolve(&s.actions.list, p, "actions.play")?; + // Every stored step of the call is charged to the playback tree (run, disabled or skipped), + // so refuse a call whose steps no longer fit before copying it: repeated calls to a large + // action would otherwise copy and walk it each time for free. + let len = s.actions.list.get(idx).map_or(0, |a| a.steps.len()); + if playback_steps_used(s).saturating_add(u64::try_from(len).unwrap_or(u64::MAX)) > MAX_PLAYBACK_STEPS { + // A limit, not a bad parameter: an enclosing batch must fail the input instead of saving it. + return Err(EngineError::BatchLimit(format!("invalid parameters for `actions.play`: action playback exceeded the {MAX_PLAYBACK_STEPS}-step limit"))); + } let action = s.actions.list.get(idx).cloned().ok_or_else(|| bad("actions.play", "no such action"))?; if s.actions.playback_stack.iter().any(|name| name == &action.name) || s.actions.recording.is_some_and(|(_, i)| i == idx) { return Err(bad("actions.play", format!("recursive action call to `{}`", action.name))); @@ -751,7 +786,7 @@ fn run_recorded(s: &mut Session, action: &Action, from: usize) -> (u64, Option (u64, Option { + // A nested batch or action that stopped at a limit stops this action too. + if let Some(error) = limit_stop(&value) { + // The child result stays, so the files a nested batch wrote before the stop are visible. + let mut failure = json!({"step": i, "id": id, "error": error, "limit": true}); + failure["result"] = value; + failed = Some(failure); + break; + } if let Some(error) = nested_failure(id, &value) { // Like Scripts, retain the child result so partial Batch outputs remain visible. let mut failure = json!({"step": i, "id": id, "error": error}); @@ -779,6 +822,11 @@ fn run_recorded(s: &mut Session, action: &Action, from: usize) -> (u64, Option { failed = Some(json!({"step": i, "id": id, "error": e.to_string()})); + if matches!(e, EngineError::BatchLimit(_)) + && let Some(f) = failed.as_mut() + { + f["limit"] = json!(true); + } break; } } @@ -789,10 +837,31 @@ fn run_recorded(s: &mut Session, action: &Action, from: usize) -> (u64, Option Result> { + begin_playback_from(s, action, 0) +} + +/// [`begin_playback`] for a call that starts at step `from`: the steps before it are charged to the +/// playback budget too. +pub fn begin_playback_from(s: &mut Session, action: &Action, from: usize) -> Result> { flush_recording(s)?; + // The steps that run are charged one by one as they run; the ones walked past are charged + // here ([`playback_plan`] checked that the whole action fits). Refused before the history + // scope opens, so a rejected call leaves none behind. + let skipped = skipped_steps(action, from); + let max = crate::automate_cmds::MAX_SCRIPT_STEPS; + if s.actions.script_depth > 0 && s.actions.script_steps.saturating_add(skipped) > max { + return Err(bad("actions.play", format!("the script ran more than {max} steps in all"))); + } if s.actions.playing == 0 { history::begin(s, &action.name); - s.actions.playback_steps = 0; + // A batch nested in a played action or another batch carries the shared count on. + if !s.actions.budget_shared { + s.actions.playback_steps = 0; + } + } + s.actions.playback_steps = s.actions.playback_steps.saturating_add(skipped); + if s.actions.script_depth > 0 { + s.actions.script_steps = s.actions.script_steps.saturating_add(skipped); } let recording = s.actions.recording.take(); s.actions.playing = s.actions.playing.saturating_add(1); @@ -822,6 +891,16 @@ pub fn restore_recording(s: &mut Session, idx: usize, action: &str, from: usize) s.journal.push(("actions.play".into(), params)); } +/// The message of a nesting or playback-limit stop reported by `value`, the result of a step: an +/// input of a nested batch or droplet marked `"limit": true` in `errors`, or a played action whose +/// failed step carries it. Such a stop fails the enclosing input rather than being swallowed. +pub fn limit_stop(value: &Value) -> Option { + let flagged = |v: &Value| v.get("limit") == Some(&json!(true)); + let found = + value.get("errors").and_then(Value::as_array).and_then(|a| a.iter().find(|e| flagged(e))).or_else(|| value.get("failed").filter(|f| flagged(f)))?; + Some(found.get("error").and_then(Value::as_str).unwrap_or("batch limit reached").to_string()) +} + /// What stops the caller of a Batch even where per-file errors don't (a direct Batch in a script /// or a CLI command list): the script ran out of steps inside it, it was cancelled, or its /// requested error log could not be written. @@ -874,7 +953,7 @@ pub fn nested_failure(id: &str, value: &Value) -> Option { /// recording while a gate is installed marks the recorded action ([`note_automation_step`]). fn play(s: &mut Session, p: &Value) -> Result { let (action, from) = playback_plan(s, p)?; - let recording = begin_playback(s, &action)?; + let recording = begin_playback_from(s, &action, from)?; // Nested calls and commands the steps run on their own behalf see the kept gate too. let kept = kept_gate(s, &action); if kept.is_some() { @@ -1319,4 +1398,62 @@ mod security_tests { assert!(consume_playback_step(&mut session)); assert!(!consume_playback_step(&mut session)); } + + /// A played action inside a nested batch (no enclosing playback) continues the shared count the + /// batch carries instead of restarting it for each input. + #[test] + fn a_nested_batch_input_does_not_reset_the_shared_playback_count() { + let mut session = Session::new(); + session.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + session.actions.list.push(Action::new("A", vec![("select.all".to_string(), json!({}))])); + session.actions.budget_shared = true; + session.actions.playback_steps = MAX_PLAYBACK_STEPS; + let r = session.execute("actions.play", json!({"action": "A"})); + assert!(matches!(r, Err(EngineError::BatchLimit(_))), "the carried count leaves no room for the action: {r:?}"); + session.actions.budget_shared = false; + let r = session.execute("actions.play", json!({"action": "A"})).unwrap(); + assert_eq!(r["ran"], 1, "a top-level call starts its own count"); + } + + /// An action of mostly disabled steps, called over and over from a parent, is charged for + /// every step it stores, so the calls stop at the shared limit instead of each copying and + /// walking the whole action for free. + #[test] + fn disabled_steps_are_charged_to_the_playback_budget() { + let mut session = Session::new(); + let mut child = Action::new("Child", (0..1000).map(|_| ("select.all".to_string(), json!({}))).collect()); + child.disabled = (0..1000).collect(); + let calls = MAX_PLAYBACK_STEPS as usize / 1000 * 2; + let parent = Action::new("Parent", (0..calls).map(|_| ("actions.play".to_string(), json!({"action": "Child"}))).collect()); + session.actions.list.push(child); + session.actions.list.push(parent); + let r = session.execute("actions.play", json!({"action": "Parent"})).unwrap(); + let failed = r["failed"]["error"].as_str().unwrap(); + assert!(failed.contains("step limit"), "{failed}"); + // Each call charges its 1000 stored steps plus the Play step itself. + let ran = r["ran"].as_u64().unwrap(); + assert!(ran < MAX_PLAYBACK_STEPS / 1000, "{ran}"); + } + + /// Limit stops are recognised from a nested batch's `errors` and from a played action's `failed`; + /// an ordinary failure is not one. + #[test] + fn limit_stops_are_found_in_nested_results() { + let batch = json!({"files": [], "errors": [{"file": "a", "error": "x"}, {"file": "b", "error": "too deep", "limit": true}]}); + assert_eq!(limit_stop(&batch).as_deref(), Some("too deep")); + let played = json!({"action": "A", "failed": {"step": 2, "id": "x", "error": "over", "limit": true}}); + assert_eq!(limit_stop(&played).as_deref(), Some("over")); + assert_eq!(limit_stop(&json!({"errors": [{"file": "a", "error": "x"}], "failed": {"step": 0, "error": "y"}})), None); + } + + #[test] + fn steps_before_from_are_charged() { + let action = Action::new("A", (0..10).map(|_| ("select.all".to_string(), json!({}))).collect()); + assert_eq!(skipped_steps(&action, 7), 7); + assert_eq!(skipped_steps(&action, 50), 10); + let mut disabled = action.clone(); + disabled.disabled = [1, 8, 9, 40].into_iter().collect(); + assert_eq!(skipped_steps(&disabled, 7), 9); + assert_eq!(skipped_steps(&disabled, 0), 3); + } } diff --git a/crates/engine/src/cmd/actions_cmds/tests.rs b/crates/engine/src/cmd/actions_cmds/tests.rs index ef755b1954..97e0cbebab 100644 --- a/crates/engine/src/cmd/actions_cmds/tests.rs +++ b/crates/engine/src/cmd/actions_cmds/tests.rs @@ -1601,6 +1601,18 @@ fn record_keeps_an_empty_loaded_sets_exact_name() { assert_eq!(s.execute("actions.save", json!({"set": " Web "})).unwrap()["actions"], json!(["First"])); } +#[test] +fn skipped_steps_count_against_the_script_limit() { + let mut s = Session::new(); + s.actions.list.push(Action::new("A", (0..3).map(|_| ("select.all".to_string(), json!({}))).collect())); + s.actions.script_depth = 1; + s.actions.script_steps = crate::automate_cmds::MAX_SCRIPT_STEPS - 1; + let e = s.execute("actions.play", json!({"action": "A", "from": 3})).err().map(|e| e.to_string()); + assert!(e.is_some_and(|e| e.contains("the script ran more than"))); + assert_eq!(s.actions.playing, 0); + assert!(s.action_history.is_none(), "a rejected call leaves no history scope open"); +} + /// A droplet capturing two actions of one name (sets A and B) keeps each call on the action it /// reached: an index or set-qualified call to B's action still reaches B's copy, a name-only call /// still reaches A's, and a call to a uniquely named action stays a name. diff --git a/crates/engine/src/cmd/adjust_cmds.rs b/crates/engine/src/cmd/adjust_cmds.rs index f6e1351dad..c63edf3608 100644 --- a/crates/engine/src/cmd/adjust_cmds.rs +++ b/crates/engine/src/cmd/adjust_cmds.rs @@ -245,7 +245,7 @@ pub fn folder_luts(_: &str) -> Vec<(String, String)> { #[cfg(not(target_arch = "wasm32"))] fn read_file(path: &str) -> Option> { - std::fs::read(path).ok() + crate::allocation::read_file_within(path, MAX_FOLDER_LUT_BYTES).ok() } #[cfg(target_arch = "wasm32")] fn read_file(_: &str) -> Option> { @@ -266,19 +266,23 @@ pub fn update_adjustment(existing: &Adjustment, p: &Value) -> Option, f: &mut dyn FnMut(&mut Vec<[f32; 4]>, Rect)) { +/// the result through the selection. Refused before reading when the dense buffers over the +/// content bounds (which span the gaps between distant tiles) would pass the working budget. +fn process_surface(surf: &mut Surface, selection: Option<&Surface>, f: &mut dyn FnMut(&mut Vec<[f32; 4]>, Rect)) -> Result<()> { let r = surf.content_bounds(); if r.is_empty() { - return; + return Ok(()); } let fmt = surf.format(); let n = fmt.channels(); + // The native read and the blended output (`n` f32 each), and the edited and original RGBA. + crate::allocation::check_dense(r, (n as u64).saturating_mul(8).saturating_add(32), "this adjustment")?; let raw = surf.read_region(r); let mut px: Vec<[f32; 4]> = raw.chunks_exact(n).map(|q| to_rgba(&fmt, q)).collect(); let orig = px.clone(); f(&mut px, r); surf.write_region(r, &crate::pixels::mix_through_selection(&fmt, r, &orig, &px, selection)); + Ok(()) } /// One history step running `f` on the active pixel layer (or targeted channel or layer mask). @@ -288,7 +292,7 @@ fn rgba_edit(s: &mut Session, label: &str, p: &Value, mut f: impl FnMut(&mut Vec return s.edit(label, |doc, _| { let sel = doc.selection.clone(); if let Some(surf) = crate::channel_cmds::channel_surface_for_filter(doc, id, p)? { - process_surface(surf, sel.as_ref(), &mut f); + process_surface(surf, sel.as_ref(), &mut f)?; surf.prune(); } Ok(Value::Null) @@ -298,7 +302,7 @@ fn rgba_edit(s: &mut Session, label: &str, p: &Value, mut f: impl FnMut(&mut Vec s.edit(label, |doc, _| { let sel = doc.selection.clone(); let surf = crate::commands::paint_surface(doc, id, &Value::Null)?; - process_surface(surf, sel.as_ref(), &mut f); + process_surface(surf, sel.as_ref(), &mut f)?; Ok(Value::Null) }) } @@ -331,20 +335,25 @@ pub(crate) fn has_adjustable(s: &Session) -> std::result::Result<(), String> { } } +/// The smart object an adjustment's pixels would go to: the layer the params resolve to (the +/// active one by default), when the command edits its pixels and that layer is a smart object. +/// `None` for a mask or channel target, or a layer that is not a smart object. +pub(crate) fn smart_pixel_target(s: &Session, p: &Value) -> Result> { + if crate::commands::is_mask_target(p) || crate::channel_cmds::is_channel_target(p) || crate::color_channels::target(s, p)?.is_some() { + return Ok(None); + } + let Ok(id) = crate::commands::layer_param(s, p) else { return Ok(None) }; + let smart = s.active().is_some_and(|d| matches!(d.doc.layer(id).map(|l| &l.content), Some(LayerContent::Smart(_)))); + Ok(smart.then_some(id)) +} + /// Image › Adjustments on a smart object record `image.adjustments.` as a smart filter /// (Photoshop): the adjustment re-runs from the source whenever the object re-renders, through /// [`adjust_as_filter`]. `Ok(true)` when it was recorded (one history step, the selection becomes /// the filter mask); `Ok(false)` when the command should edit pixels instead (a mask or channel /// target, or the active layer is not a smart object). pub(crate) fn adjust_as_smart_filter(s: &mut Session, kind: &str, label: &str, p: &Value) -> Result { - if crate::commands::is_mask_target(p) || crate::channel_cmds::is_channel_target(p) || crate::color_channels::target(s, p)?.is_some() { - return Ok(false); - } - let Ok(id) = crate::commands::layer_param(s, p) else { return Ok(false) }; - let smart = s.active().is_some_and(|d| matches!(d.doc.layer(id).map(|l| &l.content), Some(LayerContent::Smart(_)))); - if !smart { - return Ok(false); - } + let Some(id) = smart_pixel_target(s, p)? else { return Ok(false) }; // A pixel or full lock refuses the smart filter, as for `filter.*` on a smart object. crate::commands::check_pixels_unlocked(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?; // The recorded params are the command's own, minus the engine's private `__kind` key. @@ -372,30 +381,50 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { /// Image › Adjustments run as a smart filter (`image.adjustments.` recorded on a smart /// object): the adjustment applied to a copy of `surf`. `None` for kinds or params it can't run. -pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface) -> Option { +pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface, histogram_mask: Option<&photocraft_doc::LayerMask>) -> Result> { // A Color Lookup filter re-reads its LUT `file`, a path stored in the document: followed only // as `doc_path` allows, else the filter can't run (like a missing file). let resolved; let p = match p.get("file").and_then(Value::as_str).filter(|f| kind == "colorLookup" && !f.is_empty()) { Some(file) => { let mut q = p.clone(); - q["file"] = json!(crate::doc_path::resolve(file).ok()?.to_str()?); + let Some(path) = crate::doc_path::resolve(file).ok().and_then(|p| p.to_str().map(str::to_owned)) else { return Ok(None) }; + q["file"] = json!(path); resolved = q; &resolved } None => p, }; let mut out = surf.clone(); - if kind == "shadowsHighlights" { + if kind == "replaceColor" { + let Ok((c, fuzz, h, sat, l)) = replace_color_params("image.adjustments.replaceColor", p, [0.0, 0.0, 0.0, 1.0]) else { return Ok(None) }; + process_surface(&mut out, None, &mut |px, _| { + tone::replace_color(px, [c[0], c[1], c[2]], fuzz, h, sat, l); + })?; + } else if kind == "desaturate" { + let mode = surf.format().mode; + if crate::pixels::adjust_surface(&mut out, &crate::commands::desaturate_adjustment(), None, mode).is_err() { + return Ok(None); + } + } else if kind == "equalize" { + process_surface(&mut out, None, &mut |px, area| { + let width = area.width() as usize; + let cover = + (0..px.len()).map(|i| histogram_mask.map_or(1.0, |m| m.value(area.x0 + (i % width) as i32, area.y0 + (i / width) as i32))).collect::>(); + crate::extra_cmds::equalize_pixels(px, &cover); + })?; + } else if kind == "shadowsHighlights" { let sh = shadows_highlights_params(p); - process_surface(&mut out, None, &mut |px, r| tone::shadows_highlights(px, r.width() as usize, r.height() as usize, &sh)); + process_surface(&mut out, None, &mut |px, r| tone::shadows_highlights(px, r.width() as usize, r.height() as usize, &sh))?; } else { let mode = surf.format().mode; - let adj = crate::adjust_params::from_params(kind, p, None, mode).ok()?; - crate::pixels::adjust_surface(&mut out, &adj, None, mode).ok()?; + let Ok(adj) = crate::adjust_params::from_params(kind, p, None, mode) else { return Ok(None) }; + if crate::pixels::adjust_surface(&mut out, &adj, None, mode).is_err() { + return Ok(None); + } } out.prune(); - Some(out) + Ok(Some(out)) } fn shadows_highlights(s: &mut Session, p: &Value) -> Result { @@ -422,15 +451,56 @@ fn shadows_highlights_params(p: &Value) -> ShadowsHighlights { } } -/// Recorded Lab bounds use native profile matching; ordinary RGB samples keep their existing path. +fn replace_color_params(cmd: &str, p: &Value, default_color: [f32; 4]) -> Result<([f32; 4], f32, f32, f32, f32)> { + match given(p, "color") { + None => {} + Some(Value::String(s)) if crate::commands::parse_hex(s).is_some() => {} + Some(Value::Array(a)) if (3..=4).contains(&a.len()) && a.iter().all(Value::is_number) => {} + Some(_) => return Err(bad(cmd, "`color` must be a hex colour or an array of 3 or 4 finite numbers")), + } + let c = crate::commands::color_param(cmd, p, "color", default_color)?; + let fuzz = num(p, "fuzziness", 40.0).clamp(0.0, 200.0); + let (h, sat, l) = (num(p, "hue", 0.0).clamp(-180.0, 180.0), num(p, "saturation", 0.0).clamp(-100.0, 100.0), num(p, "lightness", 0.0).clamp(-100.0, 100.0)); + Ok((c, fuzz, h, sat, l)) +} + fn replace_color(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "image.adjustments.replaceColor"; + let localized_requested = p.get("localized").and_then(Value::as_bool).unwrap_or(false); + // Only the smart object's own pixels are restricted: a mask, alpha channel or Quick Mask over + // it edits as for any layer. + let on_smart = smart_pixel_target(s, p)?.is_some(); + // Recorded Lab bounds use native profile matching and edit pixels in place; ordinary RGB + // samples keep their existing path. A smart object has no pixels to edit that way. + if on_smart && (p.get("labMinimum").is_some() || p.get("labMaximum").is_some()) { + return Err(bad(CMD, "Lab bounds require a pixel layer, not a smart object")); + } if let Some(result) = replace_color_range::apply(s, p)? { return Ok(result); } - const CMD: &str = "image.adjustments.replaceColor"; - let c = crate::commands::color_param(CMD, p, "color", s.tools.foreground)?; - let fuzz = num(p, "fuzziness", 40.0).clamp(0.0, 200.0); - let (h, sat, l) = (num(p, "hue", 0.0).clamp(-180.0, 180.0), num(p, "saturation", 0.0).clamp(-100.0, 100.0), num(p, "lightness", 0.0).clamp(-100.0, 100.0)); + if localized_requested && on_smart { + return Err(bad(CMD, "Localized Color Clusters are not available as a smart filter yet")); + } + // Several samples (Add/Subtract from Sample) edit pixels through Color Range's matcher; the + // smart filter replays one colour only, so recording it would silently drop the extra samples. + if on_smart { + let multi = p.get("points").and_then(Value::as_array).is_some_and(|a| a.len() > 1); + let subtracted = p.get("subtractPoints").and_then(Value::as_array).is_some_and(|a| !a.is_empty()); + if multi || subtracted { + return Err(bad(CMD, "Add/Subtract from Sample are not available as a smart filter yet")); + } + } + let (c, fuzz, h, sat, l) = replace_color_params(CMD, p, s.tools.foreground)?; + if !localized_requested { + // Resolve and validate before recording, including the null foreground fallback. + let mut q = Value::Object(p.as_object().cloned().unwrap_or_default()); + if let Value::Object(m) = &mut q { + m.insert("color".into(), json!(c)); + } + if adjust_as_smart_filter(s, "replaceColor", "Replace Color", &q)? { + return Ok(Value::Null); + } + } // Localized Color Clusters, as in Select › Color Range: the colour only matches within Range // (a percentage of the canvas's longer side) of where it was picked. let points = sample_points(p).map_err(|m| bad(CMD, m))?; @@ -615,7 +685,7 @@ pub fn specs() -> Vec { "Replace Color…", ["Image", "Adjustments"], r##"{"localized":bool=false,"color":color,"fuzziness":0..200=40,"range":0..100=100,"hue":-180..180=0,"saturation":-100..100=0,"lightness":-100..100=0,"points":[[x,y],…]?,"subtractPoints":[[x,y],…]?,"order":["+"|"-",…]?,"labMinimum":[L,a,b]?,"labMaximum":[L,a,b]?} (Lab bounds: a finite ordered D50 box, mutually exclusive with color/points/subtractPoints/order/localized/range; composite pixel-layer target only. Otherwise color ("#rrggbb") defaults to the foreground; localized points use range % of the longer side; several "points" (Add to Sample) or any "subtractPoints" (Subtract from Sample) match as select.colorRange does for the same samples, "order" the click order.)"##, - has_pixels, + has_adjustable, replace_color ), spec!( @@ -634,6 +704,16 @@ pub fn specs() -> Vec { has_doc, hdr_toning ), + CommandSpec { + id: "image.adjustments.blackWhite.auto", + label: "Black & White Auto", + menu: &[], + shortcut: None, + params: r##"{"layer":id?,"filter":index?} → {"reds","yellows","greens","cyans","blues","magentas"} (%: the Auto mix for the image a Black & White adjustment layer sees, a smart object's pixels below its smart filter `filter`, or a pixel layer's own pixels; nothing changes)"##, + enabled: has_doc, + run: black_white_auto, + journal: false, + }, CommandSpec { id: "image.adjustments.colorLookup.list", label: "List Color Lookup Looks", @@ -647,5 +727,129 @@ pub fn specs() -> Vec { ] } +/// At most this many pixels are sampled for [`auto_black_white`]. +const AUTO_BW_SAMPLES: usize = 1 << 16; +/// Grey levels [`auto_black_white`] tells apart. +const AUTO_BW_BINS: usize = 32; + +/// Black & White's Auto (#9269): the colour weights (%, in [`crate::adjust_params::HUE_RANGES`] +/// order) that spread the image's greys over the most grey levels. PhotoCraft's own search, not +/// Photoshop's: from the default mix, each weight in turn steps through 0..=150 % to the value +/// that most raises the entropy of the greys' histogram ([`AUTO_BW_BINS`] levels), less a pull +/// back towards the default, until a pass changes nothing. So colours the default mix turns into +/// the same grey are told apart, with the mildest change that does it; colours the image lacks +/// keep their default weight. +pub fn auto_black_white(px: &[[f32; 3]]) -> [f32; 6] { + let defaults = crate::adjust_params::BW_DEFAULTS; + let score = |w: &[f32; 6]| -> f32 { + if px.is_empty() { + return 0.0; + } + let mut bins = [0u32; AUTO_BW_BINS]; + for c in px { + let g = photocraft_compose::adjust::black_white_gray(*c, w).clamp(0.0, 1.0); + if let Some(b) = bins.get_mut(((g * AUTO_BW_BINS as f32) as usize).min(AUTO_BW_BINS - 1)) { + *b += 1; + } + } + let n = px.len() as f32; + let entropy: f32 = bins.iter().filter(|&&k| k > 0).map(|&k| k as f32 / n).map(|q| -q * q.log2()).sum(); + let pull: f32 = w.iter().zip(defaults).map(|(v, d)| (v - d).abs()).sum::() / 100.0; + entropy - 0.05 * pull + }; + let mut w = defaults; + let mut best = score(&w); + for _ in 0..4 { + let mut changed = false; + for k in 0..6 { + for step in 0..=15 { + let mut t = w; + t[k] = step as f32 * 10.0; + let s = score(&t); + if s > best + 1e-6 { + (best, w, changed) = (s, t, true); + } + } + } + if !changed { + break; + } + } + w +} + +/// At most [`AUTO_BW_SAMPLES`] of the pixels with alpha: one from each run of `stride` of them, at +/// a position that varies from run to run (Fibonacci hashing of the run's index), so a pattern +/// whose period divides `stride` (alternating columns on an even-width canvas) isn't only ever +/// sampled in one phase. +fn auto_bw_sample(rgba: &[[f32; 4]]) -> Vec<[f32; 3]> { + let covered = || rgba.iter().filter(|c| c[3] > 0.0); + let stride = covered().count().div_ceil(AUTO_BW_SAMPLES).max(1); + let pick = |run: usize| ((run as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 32) as usize % stride; + covered().enumerate().filter(|(i, _)| i % stride == pick(i / stride)).map(|(_, c)| [c[0], c[1], c[2]]).collect() +} + +/// Hides `id` and everything composited above it. Returns whether `id` is in `layers`. +fn hide_from(layers: &mut [Layer], id: photocraft_doc::LayerId) -> bool { + let mut found = false; + for l in layers.iter_mut() { + if found || l.id == id { + found = true; + l.visible = false; + } else if l.children_mut().is_some_and(|c| hide_from(c, id)) { + found = true; + } + } + found +} + +/// `image.adjustments.blackWhite.auto`: [`auto_black_white`] for `layer` (default the active one): +/// the composite of what lies below a Black & White adjustment layer (what it adjusts), a smart +/// object's pixels below smart filter `filter` (what that filter edits), or a pixel layer's own +/// pixels (what Image › Adjustments › Black & White changes). As in the reference application, +/// the whole canvas counts: a selection, the adjustment's mask and its clip base don't narrow it. +fn black_white_auto(s: &mut Session, p: &Value) -> Result { + let cmd = "image.adjustments.blackWhite.auto"; + let st = s.active().ok_or(EngineError::NoDocument)?; + let id = match p.get("layer") { + None | Some(Value::Null) => st.active_layer.ok_or_else(|| EngineError::Other("no active layer".into()))?, + Some(v) => photocraft_doc::LayerId(v.as_u64().ok_or_else(|| bad(cmd, "`layer` must be a layer id"))?), + }; + let filter = match p.get("filter") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(cmd, "`filter` must be a smart filter index"))?), + }; + let layer = st.doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let area = st.doc.bounds(); + // Rendering or reading a canvas past the render limit gives nothing to sample: say so rather + // than answer with the default mix. + if u64::from(area.width()) * u64::from(area.height()) > photocraft_compose::MAX_RENDER_PIXELS { + return Err(bad(cmd, "the canvas is too large to analyse")); + } + let read = |surf: &Surface| -> Vec<[f32; 4]> { + let fmt = surf.format(); + surf.read_region(area).chunks_exact(fmt.channels()).map(|c| to_rgba(&fmt, c)).collect() + }; + let rgba: Vec<[f32; 4]> = match (&layer.content, filter) { + (LayerContent::Smart(sm), Some(i)) => { + if i >= sm.smart_filters.len() { + return Err(bad(cmd, format!("layer \"{}\" has no smart filter {i}", layer.name))); + } + let below = crate::smart_cmds::render_below_filter(&st.doc, sm, i)? + .ok_or_else(|| EngineError::Other("the smart object's contents are unavailable".into()))?; + read(&below) + } + (_, Some(_)) => return Err(bad(cmd, "`filter` needs a smart object layer")), + (LayerContent::Adjustment(_), None) => { + let mut below = (*st.doc).clone(); + hide_from(&mut below.layers, id); + photocraft_compose::render(&below, area).into_px() + } + (_, None) => read(layer.surface().ok_or_else(|| EngineError::Other(format!("layer \"{}\" has no pixels", layer.name)))?), + }; + let w = auto_black_white(&auto_bw_sample(&rgba)); + Ok(Value::Object(crate::adjust_params::HUE_RANGES.iter().zip(w).map(|(k, v)| ((*k).to_string(), json!(v))).collect())) +} + #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/adjust_cmds/tests.rs b/crates/engine/src/cmd/adjust_cmds/tests.rs index 162524367d..62bbad6c09 100644 --- a/crates/engine/src/cmd/adjust_cmds/tests.rs +++ b/crates/engine/src/cmd/adjust_cmds/tests.rs @@ -578,7 +578,7 @@ fn locked_smart_objects_refuse_adjustment_smart_filters() { } /// A wrong-typed value errors before anything is recorded (never a panic), and the adjustments -/// that can't re-render from a source (Replace Color, Match Color) stay off a smart object. +/// that can't re-render from a source (Match Color) stays off a smart object. #[test] fn a_bad_adjustment_param_on_a_smart_object_is_an_error() { let mut s = smart_session(); @@ -588,10 +588,63 @@ fn a_bad_adjustment_param_on_a_smart_object_is_an_error() { assert_eq!(smart_filters_of(&s).len(), filters, "nothing recorded"); assert_eq!(s.active().unwrap().history.past_len(), steps, "no history step"); assert_eq!(flatten(&s), flat, "pixels untouched"); - assert!(!s.is_enabled("image.adjustments.replaceColor"), "only adjustments that re-render become smart filters"); assert!(!s.is_enabled("image.adjustments.matchColor"), "only adjustments that re-render become smart filters"); } +/// Add/Subtract from Sample edit through Color Range's matcher, which the one-colour smart filter +/// cannot replay: refused on a smart object instead of recording a filter that drops the samples. +#[test] +fn multi_sample_replace_color_is_refused_on_a_smart_object() { + let mut s = smart_session(); + let (filters, steps) = (smart_filters_of(&s).len(), s.active().unwrap().history.past_len()); + for p in [json!({"points": [[1, 1], [2, 2]]}), json!({"subtractPoints": [[1, 1]]})] { + let e = s.execute("image.adjustments.replaceColor", p).unwrap_err(); + assert!(e.to_string().contains("smart filter"), "{e}"); + } + assert_eq!(smart_filters_of(&s).len(), filters, "nothing recorded"); + assert_eq!(s.active().unwrap().history.past_len(), steps, "no history step"); +} + +/// Localized Replace Color is refused only for the smart object's own pixels: an alpha channel, +/// or an explicit `layer` that is not a smart object, edits as usual while a smart object is active. +#[test] +fn localized_replace_color_is_refused_only_for_the_smart_objects_pixels() { + let mut s = smart_session(); + let (filters, steps) = (smart_filters_of(&s).len(), s.active().unwrap().history.past_len()); + let own = json!({"localized": true, "points": [[3, 3]]}); + let e = s.execute("image.adjustments.replaceColor", own).unwrap_err(); + assert!(e.to_string().contains("smart filter"), "{e}"); + assert_eq!(smart_filters_of(&s).len(), filters); + s.execute("channel.new", json!({"name": "Alpha", "fill": "white"})).unwrap(); + let channel = json!({"localized": true, "points": [[3, 3]], "target": {"channel": 0}}); + s.execute("image.adjustments.replaceColor", channel).expect("a channel under a smart object is not refused"); + assert_eq!(smart_filters_of(&s).len(), filters, "no smart filter for a channel edit"); + assert!(s.active().unwrap().history.past_len() > steps); + // The smart object is active, but the command names the Background. + let background = doc(&s).layers.iter().find(|l| !matches!(l.content, LayerContent::Smart(_))).unwrap().id; + let other = json!({"localized": true, "points": [[3, 3]], "layer": background.0}); + s.execute("image.adjustments.replaceColor", other).expect("an explicit pixel layer is not refused"); + assert_eq!(smart_filters_of(&s).len(), filters); +} + +/// Equalize Entire Image Based On Selected Area needs the selection for the histogram only, which +/// a smart filter's output mask cannot express: refused rather than recorded as "selected area only". +#[test] +fn equalize_entire_image_is_refused_on_a_smart_object_with_a_selection() { + let mut s = smart_session(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 24, "height": 32})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + let e = s.execute("image.adjustments.equalize", json!({"selectedAreaOnly": false})).unwrap_err(); + assert!(e.to_string().contains("smart object"), "{e}"); + assert!(smart_filters_of(&s).is_empty(), "nothing recorded"); + assert_eq!(s.active().unwrap().history.past_len(), steps); + s.execute("image.adjustments.equalize", json!({"selectedAreaOnly": true})).unwrap(); + assert_eq!(smart_filters_of(&s).len(), 1, "the selected area itself still records a filter"); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("image.adjustments.equalize", json!({"selectedAreaOnly": false})).unwrap(); + assert_eq!(smart_filters_of(&s).len(), 2, "without a selection it is plain Equalize"); +} + /// #780: a targeted mask enables Invert (and filters) on layers without pixels, such as an /// adjustment layer; viewing the mask (⌥-click) targets it too. #[test] @@ -625,6 +678,67 @@ fn a_targeted_mask_enables_editing_it_on_any_layer() { assert_eq!(rgba(&s, 23, 3), pixels); } +/// Desaturate, Equalize and Replace Color on a smart object record a smart filter that renders +/// what the destructive command bakes into the same pixels (they used to be refused). +#[test] +fn desaturate_equalize_and_replace_color_record_smart_filters() { + let replace = json!({"color": "#ff0000", "fuzziness": 120, "hue": 90}); + for (id, params) in [("image.adjustments.desaturate", json!({})), ("image.adjustments.equalize", json!({})), ("image.adjustments.replaceColor", replace)] { + let mut plain = session(8, "rgb"); + let original = flatten(&plain); + plain.execute(id, params.clone()).unwrap(); + let baked = flatten(&plain); + assert!(max_diff(&original, &baked) > 0.02, "{id}: the control changes the pixels"); + + let mut s = smart_session(); + assert!(s.is_enabled(id), "{id} runs on a smart object"); + s.execute(id, params).unwrap(); + let sf = smart_filters_of(&s); + assert_eq!(sf.len(), 1, "{id}"); + assert_eq!(sf[0].command, id); + assert_eq!(max_diff(&flatten(&s), &baked), 0.0, "{id}: the smart filter renders the destructive result"); + s.undo(); + assert!(smart_filters_of(&s).is_empty(), "{id}: undo removes the filter"); + } +} + +/// Replace Color without `color` samples the foreground: the smart filter records that colour, so +/// changing the foreground afterwards and re-rendering the filter leaves its result unchanged. +#[test] +fn replace_color_smart_filter_keeps_the_foreground_it_was_run_with() { + let picked = [0.27, 0.6, 0.52, 1.0]; + let params = json!({"fuzziness": 60, "hue": 90}); + let mut plain = session(8, "rgb"); + plain.tools.foreground = picked; + plain.execute("image.adjustments.replaceColor", params.clone()).unwrap(); + let baked = flatten(&plain); + + let mut s = smart_session(); + let original = flatten(&s); + s.tools.foreground = picked; + s.execute("image.adjustments.replaceColor", params).unwrap(); + assert!(smart_filters_of(&s)[0].params.get("color").is_some(), "the foreground colour is recorded"); + assert_eq!(max_diff(&flatten(&s), &baked), 0.0, "the filter replaces the foreground colour"); + assert!(max_diff(&original, &baked) > 0.02, "the control changes the pixels"); + // A new foreground, then a re-render (hide and show the filter): the result stays put. + s.tools.foreground = [1.0, 0.0, 0.0, 1.0]; + s.execute("layer.smartFilter.setVisible", json!({"index": 0})).unwrap(); + s.execute("layer.smartFilter.setVisible", json!({"index": 0})).unwrap(); + assert!(smart_filters_of(&s)[0].visible); + assert_eq!(max_diff(&flatten(&s), &baked), 0.0, "changing the foreground leaves the filter unchanged"); +} + +/// Lab bounds edit pixels in place; a smart object keeps its pixels, so they are refused there. +#[test] +fn replace_color_lab_bounds_are_refused_on_a_smart_object() { + let mut s = smart_session(); + let before = flatten(&s); + let r = s.execute("image.adjustments.replaceColor", json!({"labMinimum": [0, -128, -128], "labMaximum": [100, 127, 127], "hue": 90})); + assert!(r.is_err(), "Lab bounds on a smart object must be refused"); + assert!(smart_filters_of(&s).is_empty()); + assert_eq!(max_diff(&flatten(&s), &before), 0.0); +} + /// #5335: Curves (⌘M) edits the targeted layer mask, saved channel or Quick Mask at every depth. #[test] fn curves_apply_to_non_colour_targets_at_every_depth() { @@ -1043,6 +1157,49 @@ fn invert_turns_the_black_of_quick_mask_and_alpha_channels_white() { } } +#[test] +fn equalize_smart_filter_uses_selected_pixels_for_its_histogram() { + for depth in DEPTHS { + let mut plain = session(depth, "rgb"); + let mut smart = session(depth, "rgb"); + smart.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + for s in [&mut plain, &mut smart] { + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 12, "height": 32})).unwrap(); + s.execute("image.adjustments.equalize", json!({})).unwrap(); + } + assert!(max_diff(&flatten(&plain), &flatten(&smart)) < 2.0 / 255.0, "depth={depth}"); + // Disabling the filter mask changes the histogram too: no stale cached stage. + let mut full = session(depth, "rgb"); + full.execute("image.adjustments.equalize", json!({})).unwrap(); + smart.execute("select.deselect", json!({})).unwrap(); + smart.execute("layer.smartFilter.disableFilterMask", json!({"enabled": false})).unwrap(); + assert!(max_diff(&flatten(&full), &flatten(&smart)) < 2.0 / 255.0, "disabled mask, depth={depth}"); + } +} + +#[test] +fn replace_color_null_records_foreground_and_bad_color_does_not_edit() { + for depth in DEPTHS { + let mut plain = session(depth, "rgb"); + let mut smart = session(depth, "rgb"); + smart.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let params = json!({"color": null, "fuzziness": 200, "hue": 90}); + for s in [&mut plain, &mut smart] { + s.tools.foreground = [0.27, 0.6, 0.52, 1.0]; + s.execute("image.adjustments.replaceColor", params.clone()).unwrap(); + } + assert_eq!(max_diff(&flatten(&plain), &flatten(&smart)), 0.0); + assert_eq!(smart_filters_of(&smart)[0].params["color"], json!([0.27_f32, 0.6_f32, 0.52_f32, 1.0_f32])); + let before = smart.active().unwrap().doc.clone(); + let steps = smart.active().unwrap().history.past_len(); + for color in [json!(3), json!("wrong"), json!([1, 2]), json!([1e300, 0, 0]), json!(["red", 0, 0])] { + assert!(smart.execute("image.adjustments.replaceColor", json!({"color": color})).is_err()); + assert!(std::sync::Arc::ptr_eq(&smart.active().unwrap().doc, &before)); + assert_eq!(smart.active().unwrap().history.past_len(), steps); + } + } +} + /// #6558: a LUT folder lists its LUT files by name, case-insensitively, and nothing else. #[test] fn folder_luts_lists_lut_files_by_name() { @@ -1062,3 +1219,134 @@ fn folder_luts_lists_lut_files_by_name() { assert!(folder_luts("").is_empty()); assert!(folder_luts(dir.path().join("missing").to_str().unwrap()).is_empty()); } + +/// #9269: Black & White's Auto spreads an image's greys wider than the default mix, leaves the +/// weights of colours the image lacks at their defaults, and changes nothing in the document. +#[test] +fn black_white_auto_spreads_the_greys() { + use crate::adjust_params::{BW_DEFAULTS, HUE_RANGES}; + // A red and a blue the default mix turns into the same grey (0.43). + let (red, blue) = ([0.776, 0.2, 0.2], [0.29, 0.29, 1.0]); + let gray = |c: [f32; 3], w: &[f32; 6]| photocraft_compose::adjust::black_white_gray(c, w); + let w = auto_black_white(&[red, blue]); + let gap = |w: &[f32; 6]| (gray(red, w) - gray(blue, w)).abs(); + assert!(gap(&BW_DEFAULTS) < 0.01); + assert!(gap(&w) > 1.0 / 32.0, "{w:?}: {}", gap(&w)); + assert!(w.iter().all(|v| (0.0..=150.0).contains(v)), "{w:?}"); + // Yellows, greens, cyans and magentas aren't in the image: they keep their defaults. + for k in [1, 2, 3, 5] { + assert_eq!(w[k], BW_DEFAULTS[k], "{}", HUE_RANGES[k]); + } + // A grey image (and no pixels at all) keeps the default mix. + assert_eq!(auto_black_white(&[[0.2; 3], [0.7; 3]]), BW_DEFAULTS); + assert_eq!(auto_black_white(&[]), BW_DEFAULTS); + + // The command: an adjustment layer reads the image under it; the document is unchanged. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); + paint(&mut s, |x, _| if x < 10 { [0.776, 0.2, 0.2, 1.0] } else { [0.29, 0.29, 1.0, 1.0] }); + let id = s.execute("layer.newAdjustmentLayer.blackWhite", json!({})).unwrap()["layer"].as_u64().unwrap(); + let rev = s.active().unwrap().revision; + let r = s.execute("image.adjustments.blackWhite.auto", json!({"layer": id})).unwrap(); + let got: Vec = HUE_RANGES.iter().map(|k| r[*k].as_f64().unwrap() as f32).collect(); + assert_eq!(got, w.to_vec()); + assert_eq!(s.active().unwrap().revision, rev, "nothing changes"); + assert!(s.execute("image.adjustments.blackWhite.auto", json!({"layer": 999})).is_err()); + assert!(s.execute("image.adjustments.blackWhite.auto", json!({"layer": "x"})).is_err()); + + // A layer above the adjustment isn't part of what it adjusts. + s.execute("layer.new.layer", json!({})).unwrap(); + paint(&mut s, |_, _| [0.5, 0.5, 0.5, 1.0]); + assert_eq!(s.execute("image.adjustments.blackWhite.auto", json!({"layer": id})).unwrap(), r); + + // Sampling a big canvas still finds a thin painted stripe. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 512, "height": 512, "background": "transparent"})).unwrap(); + paint(&mut s, |x, y| match (x, y < 256) { + (1, true) => [0.776, 0.2, 0.2, 1.0], + (1, false) => [0.29, 0.29, 1.0, 1.0], + _ => [0.0; 4], + }); + let r = s.execute("image.adjustments.blackWhite.auto", json!({})).unwrap(); + let got: Vec = HUE_RANGES.iter().map(|k| r[*k].as_f64().unwrap() as f32).collect(); + assert_eq!(got, w.to_vec()); + + // Columns alternating with a period that divides the sampling stride (4 here): both colours + // are still sampled, not only the even columns. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 512, "height": 512})).unwrap(); + paint(&mut s, |x, _| if x % 2 == 0 { [0.776, 0.2, 0.2, 1.0] } else { [0.29, 0.29, 1.0, 1.0] }); + let r = s.execute("image.adjustments.blackWhite.auto", json!({})).unwrap(); + let got: Vec = HUE_RANGES.iter().map(|k| r[*k].as_f64().unwrap() as f32).collect(); + assert_ne!(got, BW_DEFAULTS.to_vec(), "only one colour was sampled"); + assert!(gap(&got.clone().try_into().unwrap()) > 1.0 / 32.0, "{got:?}"); +} + +/// #9301 review: as in the reference application, Auto reads the whole canvas whatever the +/// selection, the adjustment's mask or its clip base; a smart filter's Auto reads the pixels below +/// that filter, not the filtered result; a canvas too large to analyse is an error, not the +/// default mix. +#[test] +fn black_white_auto_reads_the_whole_input() { + use crate::adjust_params::{BW_DEFAULTS, HUE_RANGES}; + let (red, blue) = ([0.776, 0.2, 0.2, 1.0], [0.29, 0.29, 1.0, 1.0]); + let mix = auto_black_white(&[[red[0], red[1], red[2]], [blue[0], blue[1], blue[2]]]); + assert_ne!(mix, BW_DEFAULTS); + let auto = |s: &mut Session, p: Value| -> Vec { + let r = s.execute("image.adjustments.blackWhite.auto", p).unwrap(); + HUE_RANGES.iter().map(|k| r[*k].as_f64().unwrap() as f32).collect() + }; + let split = |x: i32, _| if x < 10 { red } else { blue }; + + // A selection over the red half doesn't narrow Image › Adjustments' Auto. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); + paint(&mut s, split); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + assert_eq!(auto(&mut s, json!({})), mix.to_vec()); + + // Nor does an adjustment layer's mask hiding the blue half. + s.execute("select.deselect", json!({})).unwrap(); + let id = s.execute("layer.newAdjustmentLayer.blackWhite", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.edit("mask", |doc, _| { + let b = doc.bounds(); + let mut m = photocraft_doc::LayerMask::reveal_all(); + m.surface.write_region(Rect::new(10, 0, b.x1, b.y1), &vec![0.0; 10 * 10]); + doc.layer_mut(photocraft_doc::LayerId(id)).unwrap().mask = Some(m); + Ok(()) + }) + .unwrap(); + assert_eq!(auto(&mut s, json!({"layer": id})), mix.to_vec()); + + // Nor clipping it to a layer that only covers the red half. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); + paint(&mut s, |_, _| blue); + s.execute("layer.new.layer", json!({})).unwrap(); + paint(&mut s, |x, _| if x < 10 { red } else { [0.0; 4] }); + let id = s.execute("layer.newAdjustmentLayer.blackWhite", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.createClippingMask", json!({})).unwrap(); + assert!(s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().clipped); + assert_eq!(auto(&mut s, json!({"layer": id})), mix.to_vec()); + + // A Black & White smart filter: its own result is grey, its input is the colours. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); + paint(&mut s, split); + s.execute("filter.convertForSmartFilters", json!({})).unwrap(); + s.execute("image.adjustments.blackWhite", json!({})).unwrap(); + let smart = s.active().unwrap().active_layer.unwrap().0; + assert_eq!(auto(&mut s, json!({"layer": smart})), BW_DEFAULTS.to_vec(), "the filtered result is grey"); + assert_eq!(auto(&mut s, json!({"layer": smart, "filter": 0})), mix.to_vec()); + for bad in [json!({"layer": smart, "filter": 1}), json!({"layer": smart, "filter": "x"}), json!({"layer": smart, "filter": -1})] { + assert!(s.execute("image.adjustments.blackWhite.auto", bad).is_err()); + } + s.execute("file.new", json!({"width": 20, "height": 10})).unwrap(); + assert!(s.execute("image.adjustments.blackWhite.auto", json!({"filter": 0})).is_err(), "not a smart object"); + + // Past the render limit there is nothing to sample. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40000, "height": 30000, "background": "transparent"})).unwrap(); + let id = s.execute("layer.newAdjustmentLayer.blackWhite", json!({})).unwrap()["layer"].as_u64().unwrap(); + assert!(s.execute("image.adjustments.blackWhite.auto", json!({"layer": id})).is_err()); +} diff --git a/crates/engine/src/cmd/align_cmds.rs b/crates/engine/src/cmd/align_cmds.rs index 485c2085f6..67da0dd793 100644 --- a/crates/engine/src/cmd/align_cmds.rs +++ b/crates/engine/src/cmd/align_cmds.rs @@ -171,9 +171,12 @@ fn auto_align(s: &mut Session, p: &Value) -> Result { const MAX_BLEND_BYTES: u64 = 4 << 30; /// What Auto-Blend's buffers hold per work-area pixel, as f32: each layer's pixels, luminance, -/// alpha and mask weight, plus the merged picture and the depth map. -fn blend_bytes_per_pixel(layers: u64, channels: u64) -> u64 { - layers.saturating_mul(channels.saturating_add(3)).saturating_add(channels.saturating_mul(2)).saturating_mul(4) +/// alpha and mask weight, plus the merged picture and the depth map. A `stack` blend also holds +/// `fuse_stack`'s pyramids when `fuse` (a `stack` blend with Seamless Tones; 4/3 of a level 0 +/// each): the accumulated and the current image's (`channels` each), and about seven single-channel ones (luma, alpha, energies, winners, halo). +fn blend_bytes_per_pixel(layers: u64, channels: u64, fuse: bool) -> u64 { + let pyramids = if fuse { channels.saturating_mul(2).saturating_add(7).saturating_mul(4).div_ceil(3) } else { 0 }; + layers.saturating_mul(channels.saturating_add(3)).saturating_add(channels.saturating_mul(2)).saturating_add(pyramids).saturating_mul(4) } /// Auto-Blend's buffers, for allocation errors. @@ -218,12 +221,23 @@ fn auto_blend(s: &mut Session, p: &Value) -> Result { // whose buffers would exceed `MAX_BLEND_BYTES`, keep to the canvas. let canvas = doc.bounds(); let channels = ids.iter().filter_map(|id| doc.layer(*id).and_then(|l| l.surface()).map(|s| s.channels() as u64)).max().unwrap_or(4); - let per_px = blend_bytes_per_pixel(ids.len() as u64, channels); + let per_px = blend_bytes_per_pixel(ids.len() as u64, channels, method == "stack" && seamless); let fits = px_of(&union).saturating_mul(per_px) <= MAX_BLEND_BYTES && px_of(&union) <= content_px.max(px_of(&canvas)).saturating_mul(2); let area = if fits { union } else { union.intersect(&canvas) }; if area.is_empty() { return Err(EngineError::Other("the selected layers are empty".into())); } + // The fallback (the canvas) can still be past the budget: a huge canvas, or sparse layers + // whose content bounds fill it. Refuse before any layer is expanded into dense buffers. + if px_of(&area).saturating_mul(per_px) > MAX_BLEND_BYTES { + return Err(EngineError::Other(format!( + "Auto-Blend would need more than {} MB for {} layers over {} x {} px; blend fewer or smaller layers", + MAX_BLEND_BYTES >> 20, + ids.len(), + area.width(), + area.height() + ))); + } let (w, h) = (area.width() as usize, area.height() as usize); let mut imgs: Vec> = Vec::new(); let mut luma: Vec> = Vec::new(); diff --git a/crates/engine/src/cmd/align_cmds/tests.rs b/crates/engine/src/cmd/align_cmds/tests.rs index e456a70814..f8217b3cae 100644 --- a/crates/engine/src/cmd/align_cmds/tests.rs +++ b/crates/engine/src/cmd/align_cmds/tests.rs @@ -357,11 +357,17 @@ fn auto_blend_sparse_huge_bounds_keep_to_the_canvas() { #[test] fn auto_blend_budget_counts_layers_and_channels() { // Two RGBA layers: 4 bytes × (2 layers × (4 channels + luma, alpha, weight) + merged + depth). - assert_eq!(blend_bytes_per_pixel(2, 4), 88); - assert!(blend_bytes_per_pixel(5, 4) > blend_bytes_per_pixel(2, 4)); + assert_eq!(blend_bytes_per_pixel(2, 4, false), 88); + assert!(blend_bytes_per_pixel(5, 4, false) > blend_bytes_per_pixel(2, 4, false)); + // A stack blend adds the fusion pyramids: (2 × 4 + 7) × 4/3 = 20 more f32 per pixel. + assert_eq!(blend_bytes_per_pixel(2, 4, true), 88 + 80); + // Without Seamless Tones `fuse_stack` never runs, so its pyramids are not budgeted: two RGBA + // layers over 6000 x 6000 px fit the limit only then. + assert!(36_000_000 * blend_bytes_per_pixel(2, 4, false) <= MAX_BLEND_BYTES); + assert!(36_000_000 * blend_bytes_per_pixel(2, 4, true) > MAX_BLEND_BYTES); // A 2^27-pixel area would need about 11 GiB for just two RGBA layers: it keeps to the canvas. - assert!((1u64 << 27).saturating_mul(blend_bytes_per_pixel(2, 4)) > MAX_BLEND_BYTES); - assert_eq!(blend_bytes_per_pixel(u64::MAX, 4), u64::MAX, "saturates instead of overflowing"); + assert!((1u64 << 27).saturating_mul(blend_bytes_per_pixel(2, 4, false)) > MAX_BLEND_BYTES); + assert_eq!(blend_bytes_per_pixel(u64::MAX, 4, true), u64::MAX, "saturates instead of overflowing"); } #[test] diff --git a/crates/engine/src/cmd/analysis_cmds.rs b/crates/engine/src/cmd/analysis_cmds.rs index ee51e9e2d0..451cdeaf67 100644 --- a/crates/engine/src/cmd/analysis_cmds.rs +++ b/crates/engine/src/cmd/analysis_cmds.rs @@ -795,7 +795,14 @@ fn straighten(s: &mut Session, p: &Value) -> Result { let (w0, h0) = (f64::from(d.size.width), f64::from(d.size.height)); compound(s, "Straighten", |s| { if crop { - s.execute("image.rotation.arbitrary", json!({"angle": rot, "direction": "cw"}))?; + // Count points turn with the image here, since the crop after it moves them too. + // Called directly rather than through `execute`, so an untrusted session's gate is + // asked here, as dispatch would have asked it for the nested rotation. + let rotation = json!({"angle": rot, "direction": "cw"}); + if let Some(gate) = s.authorize { + gate("image.rotation.arbitrary", &rotation)?; + } + crate::mode_cmds::rotate_arbitrary_with(s, &rotation, false)?; let nd = doc(s)?; let (cw, ch) = inscribed(w0, h0, rot.to_radians()); let (nw, nh) = (f64::from(nd.size.width), f64::from(nd.size.height)); @@ -1179,6 +1186,18 @@ fn log_delete(s: &mut Session, p: &Value) -> Result { fn csv_field(v: &Value) -> String { let s = match v { + // A text cell a spreadsheet would read as a formula gets a leading apostrophe (OWASP CSV + // injection); plain numbers in text keep their sign. + // Leading spaces do not hide it: a spreadsheet that trims them still reads a formula. + Value::String(s) + if { + let t = s.trim_start_matches(' '); + t.starts_with(['=', '@', '\t', '\r', '\n', '\u{ff1d}', '\u{ff20}']) + || (t.starts_with(['+', '-', '\u{ff0b}', '\u{ff0d}']) && t.parse::().is_err()) + } => + { + format!("'{s}") + } Value::String(s) => s.clone(), Value::Array(a) => a.iter().map(|x| x.to_string()).collect::>().join(" "), Value::Null => String::new(), diff --git a/crates/engine/src/cmd/analysis_cmds/tests.rs b/crates/engine/src/cmd/analysis_cmds/tests.rs index 6978b4d059..73a0202b30 100644 --- a/crates/engine/src/cmd/analysis_cmds/tests.rs +++ b/crates/engine/src/cmd/analysis_cmds/tests.rs @@ -556,6 +556,28 @@ fn iso_from_unix_matches_the_old_cycle_conversion_including_beyond_chrono() { assert_eq!(iso_from_unix(i64::MIN), "-292277022657-01-27T08:29:52Z"); } +#[test] +fn csv_text_cells_that_read_as_formulas_are_neutralised() { + for (cell, want) in [ + ("=1+1", "'=1+1"), + ("@SUM(A1)", "'@SUM(A1)"), + ("-2+3", "'-2+3"), + ("+cmd|x", "'+cmd|x"), + ("-5.5", "-5.5"), + ("px", "px"), + ("\n=1+1", "\"'\n=1+1\""), + ("\u{ff1d}1+1", "'\u{ff1d}1+1"), + ("\u{ff0b}1", "'\u{ff0b}1"), + ("\u{ff20}SUM(A1)", "'\u{ff20}SUM(A1)"), + (" =1+1", "' =1+1"), + (" -2+3", "' -2+3"), + (" -5.5", " -5.5"), + ] { + assert_eq!(csv_field(&json!(cell)), want, "{cell}"); + } + assert_eq!(csv_field(&json!(-5.5)), "-5.5", "numbers are not text cells"); +} + #[test] fn geometric_features_match_full_measurements_without_gray() { let mask = [true, true, false, false, false, false, false, true, true]; diff --git a/crates/engine/src/cmd/atn_cmds.rs b/crates/engine/src/cmd/atn_cmds.rs index c0f716fe93..feb8a1a3dd 100644 --- a/crates/engine/src/cmd/atn_cmds.rs +++ b/crates/engine/src/cmd/atn_cmds.rs @@ -3,7 +3,7 @@ //! (Photoshop's Insert Stop) and `actions.photoshopStep` (a step PhotoCraft has no command for //! yet, kept verbatim so Save Actions writes it back unchanged). //! -//! Parsing and writing live in `photocraft-psd` (`atn`); this module maps Photoshop *events* +//! Parsing and writing live in `craft-psd` (`atn`); this module maps Photoshop *events* //! (`gaussianBlur` with `Rds`, `make` of an adjustment layer, `set` of the selection…) onto //! PhotoCraft commands and back. An event is keyed by both its four-character code (`GsnB`, //! older files) and its string name (`gaussianBlur`, Photoshop 2024 and later), as the two are @@ -18,8 +18,8 @@ //! {"offset"}`, the document that many places from the active one in opening order, not dragged //! tab order (#7103). -use photocraft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; -use photocraft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; +use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; +use craft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; use serde_json::{Map, Value, json}; use crate::actions_cmds::Action; @@ -35,6 +35,8 @@ mod files; mod menu_item; mod steps_artboard; +mod steps_artboard_section; +mod steps_automate; mod steps_batch; mod steps_calculations; mod steps_channels; @@ -43,6 +45,7 @@ mod steps_direct_adjustments; mod steps_distort; mod steps_doc; mod steps_droplet; +mod steps_frame_section; mod steps_gallery; mod steps_gradient; mod steps_image; @@ -188,6 +191,9 @@ mod layer_props_tests; #[cfg(test)] mod layer_list_tests; +#[cfg(test)] +mod automate_tests; + #[cfg(test)] mod stylize_tests; @@ -200,5 +206,14 @@ mod selection_tests; #[cfg(test)] mod render_tests; +#[cfg(test)] +mod frame_section_tests; + #[cfg(test)] mod recorded_tools_tests; + +#[cfg(test)] +mod artboard_section_tests; + +#[cfg(test)] +mod fade_step_tests; diff --git a/crates/engine/src/cmd/atn_cmds/artboard_section_tests.rs b/crates/engine/src/cmd/atn_cmds/artboard_section_tests.rs new file mode 100644 index 0000000000..28bc3fc0cc --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/artboard_section_tests.rs @@ -0,0 +1,313 @@ +//! #10723: Layer › New › Artboard and Layer › New › Artboard from Layers, recorded as a Make of +//! class `artboardSection` (`docs/atn.md`, "Recorded through the menus"). + +use super::*; +use photocraft_doc::{Layer, LayerId}; +use photocraft_geom::Rect; + +const NEW: &str = "layer.new.artboard"; +const FROM_LAYERS: &str = "layer.new.artboardFromLayers"; +const SOURCE: &str = "_atnArtboardSectionDescriptor"; + +/// `artboardRect` with its edges in the recorded order, built here independently of the +/// converter. +fn board_rect(cls: &str, [top, left, bottom, right]: [f64; 4]) -> D { + D::Descriptor( + Descriptor::new(cls).with("Top ", D::Double(top)).with("Left", D::Double(left)).with("Btom", D::Double(bottom)).with("Rght", D::Double(right)), + ) +} + +/// The `null` reference: the class `artboardSection`. +fn section_class() -> D { + D::Reference(vec![ReferenceItem::Class(class("artboardSection"))]) +} + +/// The measured Layer › New › Artboard step, session ids included. +fn new_board(name: &str, edges: [f64; 4]) -> Descriptor { + Descriptor::new("null") + .with("null", section_class()) + .with("layerSectionStart", D::Integer(7)) + .with("layerSectionEnd", D::Integer(8)) + .with("Nm ", D::Text(UnicodeString::new_nul(name))) + .with("artboardRect", board_rect("classFloatRect", edges)) +} + +/// The measured Layer › New › Artboard from Layers step, session ids included. +fn from_layers(name: &str) -> Descriptor { + let target = D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: Id::new("Ordn"), value: Id::new("Trgt") }]); + Descriptor::new("null") + .with("null", section_class()) + .with("From", target) + .with("layerSectionStart", D::Integer(12)) + .with("layerSectionEnd", D::Integer(13)) + .with("Nm ", D::Text(UnicodeString::new_nul(name))) +} + +/// `d` with the value of its first `key` replaced by `v`. +fn replaced(mut d: Descriptor, key: &str, v: D) -> Descriptor { + if let Some(slot) = d.items.iter_mut().find(|(k, _)| k.is(key)) { + slot.1 = v; + } + d +} + +/// A Make step holding `d`. +fn make_item(d: Descriptor) -> AtnItem { + AtnItem { event: AtnEvent::Code(*b"Mk "), dictionary: b"Make".to_vec(), descriptor: Some(d), ..Default::default() } +} + +/// Load `items` as action "A" through `actions.load`. +fn load(items: Vec) -> (Session, Value) { + let file = AtnFile { + name: UnicodeString::new_nul("Boards"), + actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }], + ..Default::default() + }; + let mut s = Session::new(); + let r = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&atn::write(&file).unwrap())})).unwrap(); + (s, r) +} + +/// Action "A" written by `actions.save` and parsed back. +fn saved(s: &mut Session) -> Vec { + let r = s.execute("actions.save", json!({"action": "A"})).unwrap(); + assert_eq!(r["skipped"], json!([]), "{r}"); + atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap().actions.remove(0).items +} + +/// The descriptor `id` with `p` saves as, if it saves. +fn exported(id: &str, p: &Value) -> Option { + export_item(id, p, "S").and_then(|item| item.descriptor) +} + +/// The document's artboards as (name, rect). +fn boards(s: &Session) -> Vec<(String, Rect)> { + s.active().unwrap().doc.artboards().into_iter().map(|(_, name, board)| (name.to_string(), board.rect)).collect() +} + +/// Recorded steps load as their command with the exact rectangle and name, and save back byte for +/// byte: with session ids, in another key order, with another rectangle class, with an empty name +/// and in the canonical form. +#[test] +fn recorded_steps_load_and_save_back_unchanged() { + let mut reordered = new_board("Wide", [-20.0, 300.0, 380.0, 940.0]); + reordered.items.reverse(); + let mut no_ids = from_layers("Cards"); + no_ids.items.retain(|(k, _)| !k.is("layerSectionStart") && !k.is("layerSectionEnd")); + let cases = [ + (new_board("Hero", [20.0, 10.0, 70.0, 110.0]), NEW, json!({"rect": [10, 20, 100, 50], "name": "Hero"})), + (reordered, NEW, json!({"rect": [300, -20, 640, 400], "name": "Wide"})), + ( + replaced(new_board("", [0.0, 0.0, 80.0, 100.0]), "artboardRect", board_rect("Rctn", [0.0, 0.0, 80.0, 100.0])), + NEW, + json!({"rect": [0, 0, 100, 80], "name": ""}), + ), + // Edges in the 32-bit range, a width past it. + (new_board("Span", [0.0, -2e9, 10.0, 2e9]), NEW, json!({"rect": [-2_000_000_000_i64, 0, 4_000_000_000_i64, 10], "name": "Span"})), + // The canonical form but for an edge of -0.0, which only the bytes tell apart from 0.0. + ( + { + let mut d = new_board("Zero", [-0.0, 10.0, 70.0, 110.0]); + d.items.retain(|(k, _)| !k.is("layerSectionStart") && !k.is("layerSectionEnd")); + d + }, + NEW, + json!({"rect": [10, 0, 100, 70], "name": "Zero"}), + ), + (from_layers("Cards"), FROM_LAYERS, json!({"name": "Cards"})), + (no_ids, FROM_LAYERS, json!({"name": "Cards"})), + ]; + for (d, id, params) in cases { + let (mut s, r) = load(vec![make_item(d.clone())]); + assert_eq!(r["unsupported"], json!([]), "{r}"); + let (got, p) = &s.actions.list[0].steps[0]; + let mut p = p.clone(); + p.as_object_mut().unwrap().remove(SOURCE); + assert_eq!((got.as_str(), &p), (id, ¶ms)); + let back = saved(&mut s); + assert_eq!((&back[0].event, back[0].descriptor.as_ref().map(Descriptor::to_bytes)), (&AtnEvent::Code(*b"Mk "), Some(d.to_bytes()))); + } +} + +/// A loaded New Artboard step makes the recorded board, as one undoable edit. +#[test] +fn a_loaded_artboard_step_plays_and_undoes() { + let (mut s, _) = load(vec![make_item(new_board("Hero", [20.0, 10.0, 70.0, 110.0]))]); + s.execute("file.new", json!({"width": 200, "height": 100})).unwrap(); + let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + assert_eq!(boards(&s), vec![("Hero".to_string(), Rect::new(10, 20, 110, 70))]); + s.execute("history.undo", json!({})).unwrap(); + assert_eq!(boards(&s), vec![]); +} + +/// A loaded Artboard from Layers step puts the selected layer into a board around its pixels, as +/// one undoable edit. +#[test] +fn a_loaded_artboard_from_layers_step_plays_and_undoes() { + let (mut s, _) = load(vec![make_item(from_layers("Cards"))]); + s.execute("file.new", json!({"width": 100, "height": 80})).unwrap(); + let square = s + .edit("square", |doc, active| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster("Square", fmt); + l.surface_mut().unwrap().fill_rect(Rect::new(10, 15, 30, 45), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + let id = doc.insert_above(None, l); + *active = Some(id); + Ok(id) + }) + .unwrap(); + let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + assert_eq!(boards(&s), vec![("Cards".to_string(), Rect::new(10, 15, 30, 45))]); + let doc = &s.active().unwrap().doc; + let board: LayerId = doc.artboards()[0].0; + assert_eq!(doc.artboard_of(square), Some(board)); + s.execute("history.undo", json!({})).unwrap(); + assert_eq!(boards(&s), vec![]); + assert_eq!(s.active().unwrap().doc.artboard_of(square), None); +} + +/// A step recorded in PhotoCraft writes the measured keys without the session ids, `Nm ` only +/// for a name of its own, and loads back to the same settings. +#[test] +fn native_steps_save_the_measured_keys() { + let no_ids = |mut d: Descriptor| { + d.items.retain(|(k, _)| !k.is("layerSectionStart") && !k.is("layerSectionEnd")); + d + }; + let mut unnamed = no_ids(new_board("", [20.0, 10.0, 70.0, 110.0])); + unnamed.items.retain(|(k, _)| !k.is("Nm ")); + let mut unnamed_from = no_ids(from_layers("")); + unnamed_from.items.retain(|(k, _)| !k.is("Nm ")); + let cases = [ + (NEW, json!({"rect": [10, 20, 100, 50], "name": "Hero"}), no_ids(new_board("Hero", [20.0, 10.0, 70.0, 110.0]))), + ( + NEW, + json!({"x": 10, "y": 20, "width": 100, "height": 50, "name": "Hero", "preset": "", "background": "white", "takeBackground": false}), + no_ids(new_board("Hero", [20.0, 10.0, 70.0, 110.0])), + ), + (NEW, json!({"rect": [10.0, 20, 100, 50], "name": ""}), unnamed.clone()), + (NEW, json!({"rect": [10, 20, 100, 50]}), unnamed), + (FROM_LAYERS, json!({"name": "Cards"}), no_ids(from_layers("Cards"))), + (FROM_LAYERS, json!({"name": "", "width": 0, "height": 0, "background": "white"}), unnamed_from.clone()), + (FROM_LAYERS, json!({}), unnamed_from), + (NEW, json!({"rect": [-2_000_000_000_i64, 0, 4_000_000_000_i64, 10], "name": "Span"}), no_ids(new_board("Span", [0.0, -2e9, 10.0, 2e9]))), + ]; + for (id, p, d) in cases { + assert_eq!(exported(id, &p).as_ref(), Some(&d), "{id} {p}"); + let (s, _) = load(vec![make_item(d)]); + let (got, back) = &s.actions.list[0].steps[0]; + assert_eq!(got, id); + assert!(back.get(SOURCE).is_none(), "{back}"); + assert_eq!(exported(id, back).map(|d| d.to_bytes()), exported(id, &p).map(|d| d.to_bytes()), "{back}"); + } +} + +/// A native step the event can't hold is refused: a board without a position (it lands beside +/// the last one), a fractional or empty size, an edge past the 32-bit range, a preset, another +/// background or colour, the Background taken into the first board, a size of its own for +/// Artboard from Layers, a layer target, or a name that isn't text. +#[test] +fn settings_the_event_cannot_hold_are_refused() { + for (id, p) in [ + (NEW, json!({})), + (NEW, json!({"width": 100, "height": 50, "name": "", "preset": "", "background": "white"})), + (NEW, json!({"x": 10, "y": 20, "width": 100})), + (NEW, json!({"rect": [10, 20, 100]})), + (NEW, json!({"rect": [10, 20, 100.5, 50]})), + (NEW, json!({"rect": [10, 20, 0, 50]})), + (NEW, json!({"rect": [10, 20, 100, -50]})), + (NEW, json!({"rect": [2_147_483_600, 0, 100, 50]})), + (NEW, json!({"rect": [-2_147_483_649_i64, 0, 100, 50]})), + (NEW, json!({"rect": [0, 0, 4_294_967_296_i64, 50]})), + (NEW, json!({"rect": [10, 20, 100, 50], "x": 5})), + (NEW, json!({"rect": [10, 20, 100, 50], "preset": "iPhone 14"})), + (NEW, json!({"rect": [10, 20, 100, 50], "background": "black"})), + (NEW, json!({"rect": [10, 20, 100, 50], "background": "custom", "color": "#00ff00"})), + (NEW, json!({"rect": [10, 20, 100, 50], "color": "#ffffff"})), + (NEW, json!({"rect": [10, 20, 100, 50], "takeBackground": true})), + (NEW, json!({"rect": [10, 20, 100, 50], "name": 3})), + (FROM_LAYERS, json!({"width": 1080, "height": 0})), + (FROM_LAYERS, json!({"height": 1350})), + (FROM_LAYERS, json!({"background": "transparent"})), + (FROM_LAYERS, json!({"layer": "Square"})), + (FROM_LAYERS, json!({"rect": [10, 20, 100, 50]})), + ] { + assert!(exported(id, &p).is_none(), "{id} {p}"); + } +} + +/// Any other form keeps the reference step: both or neither of `artboardRect` and `From`, another +/// `From` target, a repeated or extra key, values of another type, a fractional or empty +/// rectangle, or another `null` class. +#[test] +fn other_forms_keep_the_photoshop_step() { + let mut no_rect = new_board("Hero", [20.0, 10.0, 70.0, 110.0]); + no_rect.items.pop(); + let three_edges = Descriptor::new("classFloatRect").with("Top ", D::Double(0.0)).with("Left", D::Double(0.0)).with("Btom", D::Double(10.0)); + let board = new_board("Hero", [20.0, 10.0, 70.0, 110.0]); + let named_layer = D::Reference(vec![ReferenceItem::Name { class: class("Lyr "), name: UnicodeString::new_nul("Square") }]); + let forms = [ + no_rect, + board.clone().with("From", from_layers("Cards").get("From").unwrap().clone()), + replaced(from_layers("Cards"), "From", named_layer), + board.clone().with("Nm ", D::Text(UnicodeString::new_nul("Again"))), + board.clone().with("artboardBackgroundType", D::Integer(1)), + from_layers("Cards").with("Wdth", D::Double(1080.0)), + replaced(board.clone(), "layerSectionStart", D::Double(7.0)), + replaced(board.clone(), "Nm ", D::Integer(1)), + replaced(board.clone(), "null", D::Reference(vec![ReferenceItem::Class(class("artboard"))])), + replaced(board.clone(), "artboardRect", D::Integer(0)), + new_board("Hero", [20.0, 10.5, 70.0, 110.0]), + new_board("Hero", [20.0, 10.0, 20.0, 110.0]), + new_board("Hero", [20.0, 110.0, 70.0, 10.0]), + new_board("Hero", [20.0, 10.0, 70.0, 1e12]), + replaced(board.clone(), "artboardRect", board_rect("classFloatRect", [20.0, 10.0, 70.0, f64::NAN])), + replaced(board.clone(), "artboardRect", D::Descriptor(three_edges.clone())), + replaced(board.clone(), "artboardRect", D::Descriptor(three_edges.clone().with("Rght", D::UnitFloat { unit: PX, value: 110.0 }))), + replaced(board.clone(), "artboardRect", D::Descriptor(three_edges.clone().with("Rght", D::Double(110.0)).with("Rght", D::Double(110.0)))), + ]; + for d in forms { + let (mut s, r) = load(vec![make_item(d.clone())]); + assert_eq!(r["unsupported"].as_array().map(Vec::len), Some(1), "{d:?}"); + assert_eq!(s.actions.list[0].steps[0].0, PHOTOSHOP_STEP, "{d:?}"); + assert_eq!(saved(&mut s)[0].descriptor.as_ref().map(Descriptor::to_bytes), Some(d.to_bytes())); + } +} + +/// A loaded step whose board was changed saves the new settings, not the stale recording; one +/// whose recording is damaged still saves its settings. +#[test] +fn changed_or_damaged_steps_save_their_settings() { + let (s, _) = load(vec![make_item(new_board("Hero", [20.0, 10.0, 70.0, 110.0])), make_item(from_layers("Cards"))]); + let steps = &s.actions.list[0].steps; + let (mut board, mut cards) = (steps[0].1.clone(), steps[1].1.clone()); + assert!(board.get(SOURCE).is_some() && cards.get(SOURCE).is_some(), "{board} {cards}"); + board["rect"] = json!([0, 0, 10, 10]); + cards["name"] = json!(""); + let mut unnamed = from_layers(""); + unnamed.items.retain(|(k, _)| k.is("null") || k.is("From")); + let mut small = new_board("Hero", [0.0, 0.0, 10.0, 10.0]); + small.items.retain(|(k, _)| !k.is("layerSectionStart") && !k.is("layerSectionEnd")); + assert_eq!(exported(NEW, &board), Some(small.clone())); + assert_eq!(exported(FROM_LAYERS, &cards), Some(unnamed)); + board[SOURCE] = json!("not base64!"); + assert_eq!(exported(NEW, &board), Some(small)); +} + +/// A recording too large to keep whole stays a kept step, and a stored recording past that size +/// is never decoded on save: the step's settings are written instead. +#[test] +fn oversized_recordings_are_not_kept_or_parsed() { + let long = "N".repeat(40_000); + let huge = new_board(&long, [20.0, 10.0, 70.0, 110.0]); + let (mut s, r) = load(vec![make_item(huge.clone())]); + assert_eq!(r["unsupported"].as_array().map(Vec::len), Some(1), "{r}"); + assert_eq!(saved(&mut s)[0].descriptor.as_ref().map(Descriptor::to_bytes), Some(huge.to_bytes())); + // The same recording stored by hand: it matches the settings, but it is past the bound. + let p = json!({"rect": [10, 20, 100, 50], "name": long, SOURCE: photocraft_paint::tile::b64_encode(&huge.to_bytes())}); + let mut canonical = huge; + canonical.items.retain(|(k, _)| !k.is("layerSectionStart") && !k.is("layerSectionEnd")); + assert_eq!(exported(NEW, &p), Some(canonical)); +} diff --git a/crates/engine/src/cmd/atn_cmds/automate_tests.rs b/crates/engine/src/cmd/atn_cmds/automate_tests.rs new file mode 100644 index 0000000000..dc778e1142 --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/automate_tests.rs @@ -0,0 +1,249 @@ +//! #10723: File › Automate › Fit Image steps, the script event measured in the reference +//! application: class `cjsp`, then `Msge`, `Hght` and `Wdth` in pixels, `limit` (Don't Enlarge). + +use super::steps_automate::{FIT_IMAGE, FIT_IMAGE_EVENT}; +use super::*; + +const SOURCE: &str = "_atnFitImageDescriptor"; + +/// The measured descriptor, built here independently of the converter. +fn recorded(message: &str, width: f64, height: f64, dont_enlarge: bool) -> Descriptor { + Descriptor::new("cjsp") + .with("Msge", D::Text(UnicodeString::new_nul(message))) + .with("Hght", D::UnitFloat { unit: *b"#Pxl", value: height }) + .with("Wdth", D::UnitFloat { unit: *b"#Pxl", value: width }) + .with("limit", D::Boolean(dont_enlarge)) +} + +/// A Fit Image step as the reference application records it. +fn fit_item(d: Descriptor) -> AtnItem { + AtnItem { event: AtnEvent::name(FIT_IMAGE_EVENT), dictionary: b"Fit Image".to_vec(), descriptor: Some(d), ..Default::default() } +} + +/// Load `items` as action "A" through `actions.load`. +fn load(items: Vec) -> (Session, Value) { + let file = AtnFile { + name: UnicodeString::new_nul("Automate"), + actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items, ..Default::default() }], + ..Default::default() + }; + let mut s = Session::new(); + let r = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&atn::write(&file).unwrap())})).unwrap(); + (s, r) +} + +/// Action "A" written by `actions.save` and parsed back. +fn saved(s: &mut Session) -> Vec { + let r = s.execute("actions.save", json!({"action": "A"})).unwrap(); + assert_eq!(r["skipped"], json!([]), "{r}"); + atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap().actions.remove(0).items +} + +/// The recorded step loads as `file.automate.fitImage` with its three settings and saves back +/// byte for byte: the message, the descriptor class and the key order are the recording's. +#[test] +fn a_recorded_fit_image_step_loads_and_saves_back_unchanged() { + let mut other_class = recorded("Recorded message", 1200.0, 900.0, true); + other_class.class_id = Id::new("null"); + let mut reordered = recorded("", 640.5, 480.0, false); + reordered.items.reverse(); + for (d, width, height, dont_enlarge) in [ + (recorded("Recorded message", 1200.0, 900.0, true), 1200.0, 900.0, true), + (other_class, 1200.0, 900.0, true), + (reordered, 640.5, 480.0, false), + (recorded("", 300.0, 200.0, false), 300.0, 200.0, false), + ] { + let (mut s, r) = load(vec![fit_item(d.clone())]); + assert_eq!(r["unsupported"], json!([]), "{r}"); + let (id, p) = &s.actions.list[0].steps[0]; + assert_eq!(id, FIT_IMAGE); + assert_eq!((p["width"].as_f64(), p["height"].as_f64(), &p["dontEnlarge"]), (Some(width), Some(height), &json!(dont_enlarge)), "{p}"); + let back = saved(&mut s); + assert_eq!(back.len(), 1); + assert_eq!(back[0].event, AtnEvent::name(FIT_IMAGE_EVENT)); + assert_eq!(back[0].dictionary, b"Fit Image"); + assert_eq!(back[0].descriptor.as_ref().map(Descriptor::to_bytes), Some(d.to_bytes())); + } +} + +/// The empty-message form in the measured key order is what a step recorded in PhotoCraft saves +/// as, so loading it keeps no descriptor of its own. +#[test] +fn the_canonical_form_carries_only_the_settings() { + let (s, _) = load(vec![fit_item(recorded("", 300.0, 200.0, false))]); + assert_eq!(s.actions.list[0].steps[0].1, json!({"width": 300, "height": 200, "dontEnlarge": false})); + let item = export_item(FIT_IMAGE, &json!({"width": 300, "height": 200, "dontEnlarge": false}), "S").unwrap(); + assert_eq!(item.descriptor.map(|d| d.to_bytes()), Some(recorded("", 300.0, 200.0, false).to_bytes())); +} + +/// A step recorded in PhotoCraft writes the measured descriptor byte for byte: an empty class name, +/// class `cjsp`, then `Msge` TEXT, `Hght` and `Wdth` UntF `#Pxl`, `limit` bool under a long key; the +/// step is enabled, without its dialog, with a descriptor (flag -1). +#[test] +fn a_step_recorded_in_photocraft_writes_the_measured_descriptor() { + let item = export_item(FIT_IMAGE, &json!({"width": 250, "height": 180, "dontEnlarge": true}), "S").unwrap(); + assert_eq!((item.enabled, item.with_dialog, &item.event), (true, false, &AtnEvent::name(FIT_IMAGE_EVENT))); + let mut expected = Vec::new(); + expected.extend_from_slice(&0u32.to_be_bytes()); // class name: no UTF-16 units + expected.extend_from_slice(b"\0\0\0\0cjsp"); // class id as a 4-character code + expected.extend_from_slice(&4u32.to_be_bytes()); + expected.extend_from_slice(b"\0\0\0\0MsgeTEXT\0\0\0\x01\0\0"); // one UTF-16 unit: the NUL + expected.extend_from_slice(b"\0\0\0\0HghtUntF#Pxl"); + expected.extend_from_slice(&180f64.to_be_bytes()); + expected.extend_from_slice(b"\0\0\0\0WdthUntF#Pxl"); + expected.extend_from_slice(&250f64.to_be_bytes()); + expected.extend_from_slice(b"\0\0\0\x05limitbool\x01"); + assert_eq!(item.descriptor.as_ref().map(Descriptor::to_bytes), Some(expected)); +} + +/// The reference plays the step alike whatever its `Msge` holds, or without one (measured on a new +/// 400 x 300 document with a 250 x 180 box and Don't Enlarge: 240 x 180 every time). Each of those +/// forms loads as the native step, plays to that size and saves back byte for byte. +#[test] +fn every_measured_message_form_maps_and_plays_alike() { + let mut removed = recorded("", 250.0, 180.0, true); + removed.items.retain(|(k, _)| !k.is("Msge")); + for d in + [recorded("Fit Image action settings", 250.0, 180.0, true), recorded("", 250.0, 180.0, true), removed, recorded("unrelated text", 250.0, 180.0, true)] + { + let (mut s, r) = load(vec![fit_item(d.clone())]); + assert_eq!(r["unsupported"], json!([]), "{d:?}"); + let (id, p) = &s.actions.list[0].steps[0]; + assert_eq!((id.as_str(), p["width"].as_f64(), p["height"].as_f64(), &p["dontEnlarge"]), (FIT_IMAGE, Some(250.0), Some(180.0), &json!(true)), "{d:?}"); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + let size = s.active().unwrap().doc.size; + assert_eq!((size.width, size.height), (240, 180), "{d:?}"); + assert_eq!(saved(&mut s)[0].descriptor.as_ref().map(Descriptor::to_bytes), Some(d.to_bytes())); + } +} + +/// A loaded step fits the document into the recorded box, and Don't Enlarge keeps a smaller +/// document as it is. +#[test] +fn a_loaded_fit_image_step_plays() { + for (box_w, box_h, dont_enlarge, expected) in [ + (300.0, 300.0, false, (300, 200)), + (300.0, 300.0, true, (300, 200)), + (1200.0, 1200.0, false, (1200, 800)), + (1200.0, 1200.0, true, (600, 400)), + (900.0, 100.0, false, (150, 100)), + ] { + let (mut s, _) = load(vec![fit_item(recorded("Recorded message", box_w, box_h, dont_enlarge))]); + s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); + let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + let size = s.active().unwrap().doc.size; + assert_eq!((size.width, size.height), expected, "box {box_w}×{box_h}, don't enlarge {dont_enlarge}"); + } +} + +/// Any other form keeps the reference step as it was: a missing, repeated or extra key, a side in +/// another unit or type, a side of zero (the native command reads it as "keep that side"), a +/// non-finite side, a message that isn't text, a limit that isn't a boolean. +#[test] +fn other_forms_keep_the_photoshop_step() { + let with = |key: &str, v: D| { + let mut d = recorded("m", 300.0, 200.0, false); + if let Some(slot) = d.items.iter_mut().find(|(k, _)| k.is(key)) { + slot.1 = v; + } + d + }; + let mut missing = recorded("m", 300.0, 200.0, false); + missing.items.retain(|(k, _)| !k.is("limit")); + let mut repeated = recorded("m", 300.0, 200.0, false); + repeated.items[3] = (Id::new("Hght"), D::UnitFloat { unit: *b"#Pxl", value: 200.0 }); + let forms = [ + missing, + repeated, + recorded("m", 300.0, 200.0, false).with("Rslt", D::UnitFloat { unit: *b"#Rsl", value: 72.0 }), + with("Wdth", D::UnitFloat { unit: *b"#Prc", value: 50.0 }), + with("Hght", D::UnitFloat { unit: *b"#Rlt", value: 200.0 }), + with("Wdth", D::Double(300.0)), + with("Hght", D::Integer(200)), + with("Wdth", D::UnitFloat { unit: *b"#Pxl", value: 0.0 }), + with("Hght", D::UnitFloat { unit: *b"#Pxl", value: -5.0 }), + with("Wdth", D::UnitFloat { unit: *b"#Pxl", value: f64::INFINITY }), + with("Msge", D::Integer(1)), + with("limit", D::Integer(1)), + recorded("m", 300.0, 200.0, false).with("Msge", D::Text(UnicodeString::new_nul("again"))), + Descriptor::new("cjsp").with("Hght", D::UnitFloat { unit: *b"#Pxl", value: 200.0 }).with("Wdth", D::UnitFloat { unit: *b"#Pxl", value: 300.0 }), + Descriptor::new("cjsp"), + ]; + for d in forms { + let (mut s, r) = load(vec![fit_item(d.clone())]); + assert_eq!(r["unsupported"].as_array().map(Vec::len), Some(1), "{d:?}"); + assert_eq!(s.actions.list[0].steps[0].0, PHOTOSHOP_STEP, "{d:?}"); + let back = saved(&mut s); + assert_eq!((&back[0].event, back[0].descriptor.as_ref().map(Descriptor::to_bytes)), (&AtnEvent::name(FIT_IMAGE_EVENT), Some(d.to_bytes()))); + } +} + +/// A native step saves only when the event holds all of it: both sides set, Don't Enlarge as a +/// boolean, and the default resampling, since the event has no key for another method. +#[test] +fn settings_the_event_cannot_hold_are_refused() { + let saves = |p: Value| export_item(FIT_IMAGE, &p, "S").and_then(|item| item.descriptor); + assert_eq!(saves(json!({"width": 800, "height": 600})), Some(recorded("", 800.0, 600.0, false))); + assert_eq!(saves(json!({"width": 800, "height": 600, "dontEnlarge": true, "resample": "bicubic"})), Some(recorded("", 800.0, 600.0, true))); + assert_eq!(saves(json!({"width": 800, "height": 600, "dontEnlarge": null, "resample": null})), Some(recorded("", 800.0, 600.0, false))); + for p in [ + json!({"width": 800, "height": 600, "resample": "nearest"}), + json!({"width": 800, "height": 600, "resample": "bicubicAutomatic"}), + json!({"width": 800}), + json!({"width": 800, "height": 0}), + json!({"width": null, "height": 600}), + json!({"width": "800", "height": 600}), + json!({"width": 800, "height": 600, "dontEnlarge": "true"}), + json!({"width": 800, "height": 600, "scaleStyles": true}), + ] { + assert_eq!(saves(p.clone()), None, "{p}"); + } +} + +/// A loaded step whose settings were changed saves the new settings in the recorded descriptor +/// (its message or lack of one, class and key order), not the stale recorded settings; an +/// unchanged one saves the recording. +#[test] +fn changed_settings_save_with_the_recorded_message() { + let without_message = |mut d: Descriptor| { + d.items.retain(|(k, _)| !k.is("Msge")); + d + }; + let mut other_class = recorded("Recorded message", 1200.0, 900.0, true); + other_class.class_id = Id::new("null"); + let mut changed_other_class = recorded("Recorded message", 500.0, 900.0, false); + changed_other_class.class_id = Id::new("null"); + for (original, changed) in [ + (recorded("Recorded message", 1200.0, 900.0, true), recorded("Recorded message", 500.0, 900.0, false)), + (without_message(recorded("", 1200.0, 900.0, true)), without_message(recorded("", 500.0, 900.0, false))), + (other_class, changed_other_class), + ] { + let (s, _) = load(vec![fit_item(original.clone())]); + let mut p = s.actions.list[0].steps[0].1.clone(); + assert!(p.get(SOURCE).is_some(), "{p}"); + assert_eq!(export_item(FIT_IMAGE, &p, "S").and_then(|item| item.descriptor), Some(original)); + p["width"] = json!(500); + p["dontEnlarge"] = json!(false); + assert_eq!(export_item(FIT_IMAGE, &p, "S").and_then(|item| item.descriptor), Some(changed)); + } +} + +/// A damaged recorded descriptor doesn't stop a step with valid settings from saving: it saves +/// as a step recorded in PhotoCraft would (CodeRabbit review on steps_automate.rs:87-95). +#[test] +fn a_damaged_recorded_descriptor_saves_the_settings() { + let other_event = photocraft_paint::tile::b64_encode(&desc("null").with("Rds ", px(2.0)).to_bytes()); + // A message beside a broken Fit Image field: neither the descriptor nor its message is kept. + let mut missing_limit = recorded("Recorded message", 800.0, 600.0, true); + missing_limit.items.retain(|(k, _)| !k.is("limit")); + let missing_limit = photocraft_paint::tile::b64_encode(&missing_limit.to_bytes()); + for damaged in + [json!("not base64!"), json!(photocraft_paint::tile::b64_encode(b"not a descriptor")), json!(other_event), json!(missing_limit), json!(7), json!(null)] + { + let p = json!({"width": 800, "height": 600, "dontEnlarge": true, SOURCE: damaged}); + assert_eq!(export_item(FIT_IMAGE, &p, "S").and_then(|item| item.descriptor), Some(recorded("", 800.0, 600.0, true)), "{p}"); + } +} diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index d98c17fbe4..97292737a4 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -856,10 +856,13 @@ pub(super) const EVENTS: &[Event] = &[ "image.calculations", "type.convertToShape", "type.createWorkPath", + super::steps_frame_section::COMMAND, "layer.new.layer", "layer.layerStyle.createLayer", "layer.new.group", "layer.groupLayers", + super::steps_artboard_section::NEW, + super::steps_artboard_section::FROM_LAYERS, "layer.duplicate", "layer.new.layerViaCopy", "layer.new.layerViaCut", @@ -1205,6 +1208,15 @@ pub(super) const EVENTS: &[Event] = &[ from: super::steps_batch::batch_from, to: super::steps_batch::batch_to, }, + // File › Automate › Fit Image: the script event recorded after the Image Size it runs (#10723). + Event { + code: "", + name: super::steps_automate::FIT_IMAGE_EVENT, + label: "Fit Image", + ids: &[super::steps_automate::FIT_IMAGE], + from: super::steps_automate::fit_image_from, + to: super::steps_automate::fit_image_to, + }, // Create Droplet (#10710): Photoshop has no string ID for it. Event { code: "CrtD", diff --git a/crates/engine/src/cmd/atn_cmds/fade_step_tests.rs b/crates/engine/src/cmd/atn_cmds/fade_step_tests.rs new file mode 100644 index 0000000000..83c82f078f --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/fade_step_tests.rs @@ -0,0 +1,99 @@ +use super::*; + +/// One action with a single recorded Fade step. +fn fade_file(descriptor: Descriptor) -> Vec { + atn::write(&AtnFile { + name: UnicodeString::new_nul("Fade"), + actions: vec![AtnAction { + name: UnicodeString::new_nul("Step"), + items: vec![AtnItem { event: AtnEvent::Code(*b"Fade"), dictionary: b"Fade".to_vec(), descriptor: Some(descriptor), ..Default::default() }], + ..Default::default() + }], + ..Default::default() + }) + .unwrap() +} + +/// The command, opacity and mode a recorded Fade step imports as. +fn imported(descriptor: Descriptor) -> (String, f64, String) { + let loaded = import(&fade_file(descriptor)).unwrap(); + assert!(loaded.unsupported.is_empty()); + let (id, params) = &loaded.actions[0].steps[0]; + (id.clone(), params["opacity"].as_f64().unwrap(), params["mode"].as_str().unwrap().to_owned()) +} + +/// An 8 x 8 image, inverted so there is an edit to fade. +fn inverted(depth: u8) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width":8,"height":8,"depth":depth,"background":"transparent"})).unwrap(); + s.execute("edit.fill", json!({"contents":"color","color":"#4080c0"})).unwrap(); + s.execute("image.adjustments.invert", json!({})).unwrap(); + s +} + +/// The pixel a recorded Fade step leaves after the Invert it fades. +fn played(depth: u8, descriptor: Descriptor) -> Value { + let mut s = inverted(depth); + let loaded = s.execute("actions.load", json!({"data":photocraft_paint::tile::b64_encode(&fade_file(descriptor))})).unwrap(); + assert_eq!(loaded["unsupported"], json!([])); + let result = s.execute("actions.play", json!({"action":loaded["actions"][0]})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + s.execute("document.pixel", json!({"x":3,"y":3})).unwrap() +} + +/// The pixel `edit.fade` leaves when run directly with these params. +fn faded(depth: u8, params: Value) -> Value { + let mut s = inverted(depth); + s.execute("edit.fade", params).unwrap(); + s.execute("document.pixel", json!({"x":3,"y":3})).unwrap() +} + +/// A step with no keys plays at 100 % Normal; with one key, the other takes its default. +#[test] +fn fade_step_missing_keys_take_fixed_defaults() { + assert_eq!(imported(desc("null")), ("edit.fade".into(), 100.0, "Normal".into())); + assert_eq!(imported(desc("null").with("Opct", pct(40.0))), ("edit.fade".into(), 40.0, "Normal".into())); + assert_eq!(imported(desc("null").with("Md ", enm("BlnM", "Mltp"))), ("edit.fade".into(), 100.0, "Multiply".into())); + for depth in [8, 16, 32] { + assert_eq!(played(depth, desc("null")), faded(depth, json!({"opacity":100,"mode":"normal"}))); + assert_eq!(played(depth, desc("null").with("Md ", enm("BlnM", "Mltp"))), faded(depth, json!({"opacity":100,"mode":"multiply"}))); + } +} + +/// Opacity less than 100 out of range wraps modulo 100 and fractions round; whole values in range +/// are unchanged, and unmeasured values further out keep the clamp. +#[test] +fn fade_step_opacity_wraps_and_rounds() { + for (recorded, expected) in [ + (150.0, 50.0), + (-5.0, 95.0), + (50.5, 51.0), + (0.0, 0.0), + (37.0, 37.0), + (100.0, 100.0), + (-0.4, 0.0), + (199.0, 99.0), + (200.0, 100.0), + (1e9, 100.0), + (-100.0, 0.0), + (-105.0, 0.0), + ] { + let (id, opacity, _) = imported(desc("null").with("Opct", pct(recorded)).with("Md ", enm("BlnM", "Nrml"))); + assert_eq!(id, "edit.fade"); + assert_eq!(opacity, expected, "{recorded}"); + assert!(opacity.is_sign_positive(), "{recorded}"); + } + for depth in [8, 16, 32] { + let recorded = desc("null").with("Opct", pct(150.0)).with("Md ", enm("BlnM", "Nrml")); + assert_eq!(played(depth, recorded), faded(depth, json!({"opacity":50,"mode":"normal"}))); + } +} + +/// Recording still writes both keys, so a step imported without them saves them explicitly. +#[test] +fn fade_step_saves_both_keys() { + let loaded = import(&fade_file(desc("null"))).unwrap(); + let saved = export("Fade", &[&loaded.actions[0]], &[], false).unwrap().0; + let d = atn::parse(&saved).unwrap().actions[0].items[0].descriptor.clone().unwrap(); + assert_eq!(d, desc("null").with("Opct", pct(100.0)).with("Md ", enm("BlnM", "Nrml"))); +} diff --git a/crates/engine/src/cmd/atn_cmds/files.rs b/crates/engine/src/cmd/atn_cmds/files.rs index 6b051778fb..3f342194ab 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_with_encoding}; +use super::convert::{UniqueNames, clip_name, export, import_with_encoding}; use super::{Action, DEFAULT_SET, EngineError, Result, Session, Value, bad, json}; /// `actions.load`: add the actions of an `.atn` file (`path` or `data`) to the list, retargeting @@ -22,7 +22,8 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result { match p.get("set") { None | Some(Value::Null) => {} Some(Value::String(n)) if !n.trim().is_empty() => { - imp.set = n.trim().to_string(); + // Held to the importer's name limit: the set name is copied into every action. + imp.set = clip_name(n.trim()).trim_end().to_string(); for a in &mut imp.actions { a.set = Some(imp.set.clone()); } diff --git a/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs b/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs new file mode 100644 index 0000000000..873ace6627 --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs @@ -0,0 +1,254 @@ +//! #10723: Layer › New › Frame from Layers, recorded as a Make of class `framedGroupSection` +//! (`docs/atn.md`, "Recorded through the menus"). + +use super::*; +use photocraft_doc::{Layer, LayerId}; +use photocraft_geom::Rect; + +const FRAME: &str = "layer.new.frameFromLayers"; +const SOURCE: &str = "_atnFrameSectionDescriptor"; + +/// `From`: the layer `name`, by name. +fn by_name(name: &str) -> D { + D::Reference(vec![ReferenceItem::Name { class: class("Lyr "), name: UnicodeString::new_nul(name) }]) +} + +/// The measured step, session ids included, built here independently of the converter. +fn recorded(from: D, name: &str) -> Descriptor { + Descriptor::new("null") + .with("null", D::Reference(vec![ReferenceItem::Class(class("framedGroupSection"))])) + .with("From", from) + .with("layerSectionStart", D::Integer(4)) + .with("layerSectionEnd", D::Integer(5)) + .with("Nm ", D::Text(UnicodeString::new_nul(name))) +} + +/// `d` without the keys `drop`. +fn without(mut d: Descriptor, drop: &[&str]) -> Descriptor { + d.items.retain(|(k, _)| !drop.iter().any(|key| k.is(key))); + d +} + +/// The step PhotoCraft writes: the measured keys without the session ids. +fn canonical(from: D, name: Option<&str>) -> Descriptor { + let d = without(recorded(from, name.unwrap_or("")), &["layerSectionStart", "layerSectionEnd"]); + if name.is_some() { d } else { without(d, &["Nm "]) } +} + +/// The target layer, the `From` of a step recorded in PhotoCraft without a layer of its own. +fn target_layer() -> D { + D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: Id::new("Ordn"), value: Id::new("Trgt") }]) +} + +/// Load the Make steps holding `ds` as action "A" through `actions.load`. +fn load(ds: Vec) -> (Session, Value) { + let items = ds.into_iter().map(|d| AtnItem { event: AtnEvent::Code(*b"Mk "), dictionary: b"Make".to_vec(), descriptor: Some(d), ..Default::default() }); + let file = AtnFile { + name: UnicodeString::new_nul("Frames"), + actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items: items.collect(), ..Default::default() }], + ..Default::default() + }; + let mut s = Session::new(); + let r = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&atn::write(&file).unwrap())})).unwrap(); + (s, r) +} + +/// The descriptor of the first step of action "A" as `actions.save` writes it. +fn saved(s: &mut Session) -> Option> { + let r = s.execute("actions.save", json!({"action": "A"})).unwrap(); + assert_eq!(r["skipped"], json!([]), "{r}"); + let mut items = atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap().actions.remove(0).items; + assert_eq!(items[0].event, AtnEvent::Code(*b"Mk ")); + items.remove(0).descriptor.as_ref().map(Descriptor::to_bytes) +} + +/// The descriptor a native Frame from Layers step with `p` saves as, if it saves. +fn exported(p: &Value) -> Option { + export_item(FRAME, p, "S").and_then(|item| item.descriptor) +} + +/// A 100 × 80 document with "Photo" (pixels at (10, 15)–(40, 45)) under "Other" (pixels at +/// (60, 5)–(90, 25)), "Other" selected. +fn two_layers(s: &mut Session) -> (LayerId, LayerId) { + s.execute("file.new", json!({"width": 100, "height": 80})).unwrap(); + let mut add = |name: &str, r: Rect| { + s.edit(name, |doc, active| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster(name, fmt); + l.surface_mut().unwrap().fill_rect(r, &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + let id = doc.insert_above(None, l); + *active = Some(id); + Ok(id) + }) + .unwrap() + }; + let photo = add("Photo", Rect::new(10, 15, 40, 45)); + let other = add("Other", Rect::new(60, 5, 90, 25)); + s.execute("layer.select", json!({"layer": other.0, "mode": "replace"})).unwrap(); + (photo, other) +} + +/// The frame layers named `name`, as (group id, frame `[x, y, w, h]`). +fn frames(s: &Session, name: &str) -> Vec<(LayerId, [f64; 4])> { + let doc = &s.active().unwrap().doc; + doc.walk() + .into_iter() + .filter(|(_, _, l)| l.name == name) + .filter_map(|(_, _, l)| l.frame.as_ref().map(|f| (l.id, [f.transform.m[4], f.transform.m[5], f.transform.m[0], f.transform.m[3]]))) + .collect() +} + +/// Recorded steps load with the exact layer and name and save back byte for byte: the measured +/// form, another key order, no session ids, no name, and the target-layer form. +#[test] +fn recorded_steps_load_and_save_back_unchanged() { + let mut reordered = recorded(by_name("Photo"), "Frame 1"); + reordered.items.reverse(); + let cases = [ + (recorded(by_name("Photo"), "Frame 1"), json!({"layer": "Photo", "name": "Frame 1"})), + (reordered, json!({"layer": "Photo", "name": "Frame 1"})), + (without(recorded(by_name("Ébène"), "Cadre"), &["layerSectionStart", "layerSectionEnd"]), json!({"layer": "Ébène", "name": "Cadre"})), + (without(recorded(by_name("Photo"), ""), &["Nm "]), json!({"layer": "Photo"})), + (recorded(by_name("Photo"), ""), json!({"layer": "Photo", "name": ""})), + (canonical(target_layer(), Some("Frame 1")), json!({"name": "Frame 1"})), + ]; + for (d, params) in cases { + let (mut s, r) = load(vec![d.clone()]); + assert_eq!(r["unsupported"], json!([]), "{r}"); + let (id, p) = &s.actions.list[0].steps[0]; + let mut p = p.clone(); + p.as_object_mut().unwrap().remove(SOURCE); + assert_eq!((id.as_str(), &p), (FRAME, ¶ms)); + assert_eq!(saved(&mut s), Some(d.to_bytes())); + } +} + +/// A loaded step frames the layer it names, not the selected one: the frame fits that layer's +/// pixels, the other layer stays where it was, and one Undo takes the frame back. +#[test] +fn a_loaded_step_frames_the_named_layer_and_undoes() { + let (mut s, _) = load(vec![recorded(by_name("Photo"), "Frame 1")]); + let (photo, other) = two_layers(&mut s); + let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + assert_eq!(frames(&s, "Frame 1").into_iter().map(|f| f.1).collect::>(), vec![[10.0, 15.0, 30.0, 30.0]]); + let doc = &s.active().unwrap().doc; + assert!(doc.layer(photo).is_none(), "Photo went into the frame"); + assert!(doc.layers.iter().any(|l| l.id == other), "Other stays a top-level layer"); + s.execute("history.undo", json!({})).unwrap(); + assert!(frames(&s, "Frame 1").is_empty()); + let doc = &s.active().unwrap().doc; + assert!(doc.layers.iter().any(|l| l.id == photo) && doc.layers.iter().any(|l| l.id == other)); +} + +/// A step that names its layer plays with no layer selected: the command is admitted on the +/// named layer, not the (empty) selection. +#[test] +fn a_loaded_step_plays_with_no_layer_selected() { + let (mut s, _) = load(vec![recorded(by_name("Photo"), "Frame 1")]); + let (photo, other) = two_layers(&mut s); + s.execute("select.deselectLayers", json!({})).unwrap(); + let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + assert_eq!(frames(&s, "Frame 1").into_iter().map(|f| f.1).collect::>(), vec![[10.0, 15.0, 30.0, 30.0]]); + // The frame took in Photo, not Other. + let doc = &s.active().unwrap().doc; + assert!(doc.layer(photo).is_none(), "Photo went into the frame"); + assert!(doc.layers.iter().any(|l| l.id == other), "Other stays a top-level layer"); +} + +/// Without a layer of its own the command still frames the selected layers. +#[test] +fn without_a_layer_the_selected_layers_are_framed() { + let mut s = Session::new(); + let (photo, other) = two_layers(&mut s); + s.execute(FRAME, json!({"name": "Frame 1"})).unwrap(); + assert_eq!(frames(&s, "Frame 1").into_iter().map(|f| f.1).collect::>(), vec![[60.0, 5.0, 30.0, 20.0]]); + let doc = &s.active().unwrap().doc; + assert!(doc.layer(other).is_none() && doc.layers.iter().any(|l| l.id == photo)); +} + +/// A step recorded in PhotoCraft writes the measured keys without the session ids: the layer by +/// name (the target layer without one) and `Nm ` for a name that isn't blank. It loads back to +/// the same settings. +#[test] +fn native_steps_save_the_measured_keys() { + for (p, d, back) in [ + (json!({"layer": "Photo", "name": "Frame 1"}), canonical(by_name("Photo"), Some("Frame 1")), json!({"layer": "Photo", "name": "Frame 1"})), + (json!({"layer": "Photo"}), canonical(by_name("Photo"), None), json!({"layer": "Photo"})), + (json!({"name": "Frame 1"}), canonical(target_layer(), Some("Frame 1")), json!({"name": "Frame 1"})), + (json!({"name": " ", "layer": null}), canonical(target_layer(), None), json!({})), + (json!({}), canonical(target_layer(), None), json!({})), + ] { + assert_eq!(exported(&p), Some(d.clone()), "{p}"); + let (s, _) = load(vec![d]); + assert_eq!(s.actions.list[0].steps[0], (FRAME.to_string(), back), "{p}"); + } +} + +/// A native step the event can't hold is refused: a layer by id or selector, a name that isn't +/// text, or the group options the command passes on (colour, mode, opacity), which the step +/// doesn't record. +#[test] +fn settings_the_event_cannot_hold_are_refused() { + for p in [ + json!({"layer": 3}), + json!({"layer": {"index": 2}}), + json!({"layer": {"background": true}}), + json!({"name": 4}), + json!({"name": "Frame 1", "color": "red"}), + json!({"mode": "multiply"}), + json!({"opacity": 50}), + json!({"name": "Frame 1", "width": 200}), + ] { + assert!(exported(&p).is_none(), "{p}"); + } +} + +/// Any other form keeps the reference step: no `From`, another `From`, a repeated or extra key, +/// values of another type, or another `null`. +#[test] +fn other_forms_keep_the_photoshop_step() { + let measured = recorded(by_name("Photo"), "Frame 1"); + let replaced = |key: &str, v: D| { + let mut d = measured.clone(); + d.items.iter_mut().filter(|(k, _)| k.is(key)).for_each(|slot| slot.1 = v.clone()); + d + }; + let forms = [ + without(measured.clone(), &["From"]), + replaced("From", D::Reference(vec![ReferenceItem::Index { class: class("Lyr "), index: 2 }])), + replaced("From", D::Reference(vec![ReferenceItem::Name { class: class("Chnl"), name: UnicodeString::new_nul("Photo") }])), + replaced("From", D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: Id::new("Ordn"), value: Id::new("Al ") }])), + replaced("From", D::Text(UnicodeString::new_nul("Photo"))), + replaced("Nm ", D::Integer(1)), + replaced("layerSectionEnd", D::Double(5.0)), + replaced("null", D::Reference(vec![ReferenceItem::Class(class("frame"))])), + measured.clone().with("Nm ", D::Text(UnicodeString::new_nul("Again"))), + measured.clone().with("From", by_name("Other")), + measured.clone().with("Wdth", D::UnitFloat { unit: PX, value: 200.0 }), + ]; + for d in forms { + let (mut s, r) = load(vec![d.clone()]); + assert_eq!(r["unsupported"].as_array().map(Vec::len), Some(1), "{d:?}"); + assert_eq!(s.actions.list[0].steps[0].0, PHOTOSHOP_STEP, "{d:?}"); + assert_eq!(saved(&mut s), Some(d.to_bytes())); + } +} + +/// A loaded step whose layer or name was changed saves the new settings, not the stale +/// recording; one whose recording is damaged still saves its settings. +#[test] +fn changed_or_damaged_steps_save_their_settings() { + let (s, _) = load(vec![recorded(by_name("Photo"), "Frame 1")]); + let mut p = s.actions.list[0].steps[0].1.clone(); + assert!(p.get(SOURCE).is_some(), "{p}"); + p["layer"] = json!("Other"); + assert_eq!(exported(&p), Some(canonical(by_name("Other"), Some("Frame 1")))); + p["layer"] = json!("Photo"); + p["name"] = json!(" "); + assert_eq!(exported(&p), Some(canonical(by_name("Photo"), None))); + p["name"] = json!("Frame 1"); + p[SOURCE] = json!("not base64!"); + assert_eq!(exported(&p), Some(canonical(by_name("Photo"), Some("Frame 1")))); +} diff --git a/crates/engine/src/cmd/atn_cmds/layer_list_tests.rs b/crates/engine/src/cmd/atn_cmds/layer_list_tests.rs index 4f6f1c6a47..089d96b2bb 100644 --- a/crates/engine/src/cmd/atn_cmds/layer_list_tests.rs +++ b/crates/engine/src/cmd/atn_cmds/layer_list_tests.rs @@ -1,6 +1,6 @@ use super::*; -use photocraft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; -use photocraft_psd::descriptor::{Descriptor, ReferenceItem, UnicodeString, Value as D}; +use craft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; +use craft_psd::descriptor::{Descriptor, ReferenceItem, UnicodeString, Value as D}; use serde_json::json; fn item(event: &str, label: &str, d: Option) -> AtnItem { diff --git a/crates/engine/src/cmd/atn_cmds/selection_tests.rs b/crates/engine/src/cmd/atn_cmds/selection_tests.rs index 66c99248c6..7611baae17 100644 --- a/crates/engine/src/cmd/atn_cmds/selection_tests.rs +++ b/crates/engine/src/cmd/atn_cmds/selection_tests.rs @@ -56,7 +56,7 @@ fn fixtures() -> Vec<(&'static str, Option<&'static str>, Descriptor)> { ellipse.items.last_mut().unwrap().1 = D::Boolean(false); cases.push(("AddT", Some("addTo"), ellipse)); for mode in ["Scrn", "H", "linearDodge"] { - cases.push(("Fade", Some("fade"), desc("null").with("Opct", pct(25.5)).with("Md ", enm("BlnM", mode)))); + cases.push(("Fade", Some("fade"), desc("null").with("Opct", pct(25.0)).with("Md ", enm("BlnM", mode)))); } for edge in ["AdCH", "AdRg", "AdTp", "AdCV", "AdBt"] { cases.push(("Dstr", Some("distribute"), desc("null").with("null", target_ref("Lyr ")).with("Usng", enm("ADSt", edge)))); @@ -262,12 +262,12 @@ fn noncanonical_group_f_enums_keep_their_bytes_and_flags() { } } -/// Fade writes native defaults and clamps only its documented opacity range. +/// Fade writes native defaults; a recorded opacity just outside 0..=100 wraps modulo 100 on import. #[test] fn fade_defaults_and_opacity_limits_are_explicit() { let native = export_item("edit.fade", &json!({}), "S").unwrap().descriptor.unwrap(); assert_eq!(native, desc("null").with("Opct", pct(100.0)).with("Md ", enm("BlnM", "Nrml"))); - for (opacity, expected) in [(-5.0, 0.0), (0.0, 0.0), (100.0, 100.0), (105.0, 100.0)] { + for (opacity, expected) in [(-5.0, 95.0), (0.0, 0.0), (100.0, 100.0), (105.0, 5.0), (250.0, 100.0)] { let bytes = file(AtnEvent::Code(*b"Fade"), desc("null").with("Opct", pct(opacity)).with("Md ", enm("BlnM", "Nrml"))); let loaded = import(&bytes).unwrap(); assert!(loaded.unsupported.is_empty()); @@ -302,7 +302,6 @@ fn group_f_unsupported_settings_are_not_silently_replaced() { (*b"AddT", wrong_ref), (*b"PstI", desc("null").with("AntA", enm("Annt", "Unknown")).with("As ", D::Class(class("Pxel")))), (*b"PstO", desc("null").with("AntA", enm("Annt", "Anno")).with("As ", D::Class(class("Other")))), - (*b"Fade", desc("null").with("Opct", pct(50.0))), (*b"Fade", desc("null").with("Opct", px(50.0)).with("Md ", enm("BlnM", "Nrml"))), (*b"Dstr", desc("null").with("null", target_ref("Lyr ")).with("Usng", enm("ADSt", "Unknown"))), (*b"RmvL", desc("null").with("apply", D::Boolean(true))), diff --git a/crates/engine/src/cmd/atn_cmds/steps_artboard_section.rs b/crates/engine/src/cmd/atn_cmds/steps_artboard_section.rs new file mode 100644 index 0000000000..eb5aa76010 --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/steps_artboard_section.rs @@ -0,0 +1,222 @@ +//! Layer › New › Artboard and Layer › New › Artboard from Layers, recorded as a Make of class +//! `artboardSection`, as `docs/atn.md` ("Recorded through the menus") measures them (#10723): +//! +//! - Artboard: `layerSectionStart`, `layerSectionEnd` (longs), `Nm ` (text) and `artboardRect` +//! (`Top `, `Left`, `Btom`, `Rght` doubles, in pixels); +//! - Artboard from Layers: `From` = the target layer, `layerSectionStart`, `layerSectionEnd` and +//! `Nm `. The dialog's size and background are not in the step. +//! +//! `layerSectionStart` and `layerSectionEnd` are ids of the recording session, so they are not +//! settings: a loaded step keeps them only inside its recorded descriptor. + +use super::descriptors::{class_ref, desc, jstr, target_ref, text}; +use super::fields::{Mapped, step}; +use super::{D, Descriptor, ReferenceItem, Value, json}; + +/// Layer › New › Artboard. +pub(super) const NEW: &str = "layer.new.artboard"; +/// Layer › New › Artboard from Layers. +pub(super) const FROM_LAYERS: &str = "layer.new.artboardFromLayers"; +/// The recorded descriptor, kept when it differs from the one [`to`] would write (session ids, +/// key order, classes), so a load and save keeps the step unchanged. +const SOURCE: &str = "_atnArtboardSectionDescriptor"; +/// The most bytes a recorded descriptor may take to be kept in [`SOURCE`]: far above any measured +/// step (a few keys and a name), so a stored value is never parsed at any size on save. +const MAX_SOURCE_BYTES: usize = 64 * 1024; +/// The rectangle's edges in the order the step records them, with the `[x, y, w, h]` slot each +/// one comes from. +const EDGES: [&str; 4] = ["Top ", "Left", "Btom", "Rght"]; + +/// What one step makes. +#[derive(Debug, PartialEq)] +enum Section { + /// A new, empty artboard at `[x, y, width, height]`. + Board([i64; 4]), + /// An artboard around the selected layers. + FromLayers, +} + +/// The settings a step holds: what it makes and the board's name (`None`: no `Nm `, so the +/// board takes the next free "Artboard N"). +#[derive(Debug, PartialEq)] +struct Settings { + section: Section, + name: Option, +} + +/// How many times `d` holds `key`. +fn count(d: &Descriptor, key: &str) -> usize { + d.items.iter().filter(|(k, _)| k.is(key)).count() +} + +/// `null`: a reference to the class `artboardSection`. +fn is_section_class(v: &D) -> bool { + matches!(v, D::Reference(r) if matches!(r.as_slice(), [ReferenceItem::Class(c)] if c.class_id.is("artboardSection"))) +} + +/// `From`: the target layer, `Lyr ` `Ordn.Trgt`. +fn is_target_layer(v: &D) -> bool { + matches!(v, D::Reference(r) if matches!(r.as_slice(), + [ReferenceItem::Enumerated { class, type_id, value }] if class.class_id.is("Lyr ") && type_id.is("Ordn") && value.is("Trgt"))) +} + +/// An edge of `artboardRect`: a double holding a whole number of pixels in the 32-bit range. +fn edge(v: Option<&D>) -> Option { + let D::Double(v) = v? else { return None }; + (v.is_finite() && v.fract() == 0.0 && (f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(v)).then_some(*v as i64) +} + +/// `artboardRect` as `[x, y, width, height]`: the four edges exactly once, nothing else, and a +/// board of positive size. +fn rect(r: &Descriptor) -> Option<[i64; 4]> { + if r.items.len() != EDGES.len() || EDGES.iter().any(|key| count(r, key) != 1) { + return None; + } + let [top, left, bottom, right] = EDGES.map(|key| edge(r.get(key))); + let (top, left, bottom, right) = (top?, left?, bottom?, right?); + (right > left && bottom > top).then_some([left, top, right - left, bottom - top]) +} + +/// The measured forms only: `null` = class `artboardSection`, then either `artboardRect` (a new +/// artboard) or `From` = the target layer (Artboard from Layers), optional session ids (longs) +/// and an optional `Nm `, each key at most once and nothing else. +fn recorded(d: &Descriptor) -> Option { + const KEYS: [&str; 6] = ["null", "From", "layerSectionStart", "layerSectionEnd", "Nm ", "artboardRect"]; + if d.items.iter().any(|(k, _)| !KEYS.iter().any(|key| k.is(key))) || KEYS.iter().any(|key| count(d, key) > 1) { + return None; + } + if !d.get("null").is_some_and(is_section_class) + || ["layerSectionStart", "layerSectionEnd"].iter().any(|key| d.get(key).is_some_and(|v| !matches!(v, D::Integer(_)))) + { + return None; + } + let name = match d.get("Nm ") { + None => None, + Some(D::Text(t)) => Some(String::from_utf16(t.0.strip_suffix(&[0]).unwrap_or(&t.0)).ok()?), + Some(_) => return None, + }; + let section = match (d.get("From"), d.get("artboardRect")) { + (Some(from), None) if is_target_layer(from) => Section::FromLayers, + (None, Some(D::Descriptor(r))) => Section::Board(rect(r)?), + _ => return None, + }; + Some(Settings { section, name }) +} + +/// The descriptor a step recorded in PhotoCraft saves as: the measured keys without the session +/// ids, `Nm ` only for a name of the step's own. +fn canonical(settings: &Settings) -> Descriptor { + let mut d = desc("null").with("null", class_ref("artboardSection")); + if settings.section == Section::FromLayers { + d = d.with("From", target_ref("Lyr ")); + } + if let Some(name) = &settings.name { + d = d.with("Nm ", text(name)); + } + if let Section::Board([x, y, w, h]) = settings.section { + let edges = [y, x, y + h, x + w]; + let r = EDGES.iter().zip(edges).fold(desc("classFloatRect"), |r, (key, v)| r.with(key, D::Double(v as f64))); + d = d.with("artboardRect", D::Descriptor(r)); + } + d +} + +/// Map the measured forms; any other stays a complete kept step. +pub(super) fn from(d: &Descriptor) -> Mapped { + let Some(settings) = recorded(d) else { return Mapped::Unsupported { harmless: false } }; + let bytes = d.to_bytes(); + // A step too large to keep whole stays a kept step rather than lose its bytes on save. + if bytes.len() > MAX_SOURCE_BYTES { + return Mapped::Unsupported { harmless: false }; + } + let (id, mut p) = match settings.section { + Section::Board(r) => (NEW, json!({"rect": r})), + Section::FromLayers => (FROM_LAYERS, json!({})), + }; + if let Some(name) = &settings.name { + p["name"] = name.as_str().into(); + } + // Bytes, not descriptor equality: that takes an edge of -0.0 for 0.0, which would save + // another value than the one recorded. + if bytes != canonical(&settings).to_bytes() { + p[SOURCE] = photocraft_paint::tile::b64_encode(&bytes).into(); + } + step(id, p) +} + +/// Whether `p` leaves `key` unset or at `default`. +fn unset_or(p: &Value, key: &str, default: &Value) -> bool { + p.get(key).is_none_or(|v| v.is_null() || v == default) +} + +/// A whole number of pixels, small enough that a position plus a size can't overflow. +fn whole(v: &Value) -> Option { + let v = v.as_f64().filter(|v| v.is_finite() && v.fract() == 0.0 && v.abs() <= f64::from(u32::MAX))?; + Some(v as i64) +} + +/// The board a native New Artboard step makes, when the step says where: `rect`, or all of `x`, +/// `y`, `width` and `height`, in whole pixels, of positive size and with every edge in the +/// 32-bit range, as the command and [`rect`] take it (so the size itself may pass `i32::MAX`). +/// Without a position the board lands beside the last one at playback, which the event's fixed +/// rectangle can't say. +fn native_rect(p: &Value) -> Option<[i64; 4]> { + let v: [i64; 4] = match p.get("rect") { + Some(Value::Array(a)) if ["x", "y", "width", "height"].iter().all(|k| p.get(*k).is_none_or(Value::is_null)) => { + a.iter().map(whole).collect::>>()?.try_into().ok()? + } + None | Some(Value::Null) => ["x", "y", "width", "height"].map(|k| p.get(k).and_then(whole)).into_iter().collect::>>()?.try_into().ok()?, + _ => return None, + }; + let [x, y, w, h] = v; + let fits = |a: i64, len: i64| len > 0 && i32::try_from(a).is_ok() && i32::try_from(a + len).is_ok(); + (fits(x, w) && fits(y, h)).then_some(v) +} + +/// A native step the event holds. New Artboard needs its position and size, and neither form may +/// set what the step doesn't record: a preset, a background other than the default white, a +/// colour, the Background taken into the first board, or (Artboard from Layers) a size of its +/// own. Those refuse export rather than play differently. +fn native(id: &str, p: &Value) -> Option { + let m = p.as_object()?; + let allowed: &[&str] = if id == NEW { + &["rect", "x", "y", "width", "height", "name", "preset", "background", "takeBackground", SOURCE] + } else { + &["name", "width", "height", "background", SOURCE] + }; + if m.keys().any(|key| !allowed.contains(&key.as_str())) || !unset_or(p, "background", &json!("white")) { + return None; + } + let name = match m.get("name") { + None | Some(Value::Null) => None, + Some(Value::String(n)) if n.is_empty() => None, + Some(Value::String(n)) => Some(n.clone()), + Some(_) => return None, + }; + let section = if id == NEW { + if !unset_or(p, "preset", &json!("")) || !unset_or(p, "takeBackground", &json!(false)) { + return None; + } + Section::Board(native_rect(p)?) + } else { + if !["width", "height"].iter().all(|k| p.get(*k).is_none_or(|v| v.is_null() || v.as_f64() == Some(0.0))) { + return None; + } + Section::FromLayers + }; + Some(Settings { section, name }) +} + +/// Save the recorded descriptor while the step still makes the same board, otherwise the +/// canonical form of the step's settings. +pub(super) fn to(id: &str, p: &Value) -> Option { + let settings = native(id, p)?; + // Only a value no larger than a kept recording is decoded and parsed at all. + let source = jstr(p, SOURCE) + .filter(|text| text.len() <= MAX_SOURCE_BYTES.div_ceil(3) * 4) + .and_then(photocraft_paint::tile::b64_decode) + .filter(|bytes| bytes.len() <= MAX_SOURCE_BYTES) + .and_then(|bytes| Descriptor::from_bytes(&bytes).ok()) + .filter(|d| recorded(d).is_some_and(|r| r.section == settings.section && r.name.as_deref().unwrap_or("") == settings.name.as_deref().unwrap_or(""))); + Some(source.unwrap_or_else(|| canonical(&settings))) +} diff --git a/crates/engine/src/cmd/atn_cmds/steps_automate.rs b/crates/engine/src/cmd/atn_cmds/steps_automate.rs new file mode 100644 index 0000000000..0dacb7d6aa --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/steps_automate.rs @@ -0,0 +1,121 @@ +//! File › Automate › Fit Image, recorded as the script event `3caa3434-cb67-11d1-bc43-0060b0a13dc4` +//! after the Image Size it runs, as measured in the reference application (#10723): class `cjsp` +//! with an empty class name, then `Msge` text, `Hght` and `Wdth` in pixels and `limit` +//! (Don't Enlarge, a long key), in that order. `Msge` isn't needed to play the step: the +//! reference plays it the same with the key removed. + +use super::descriptors::{PX, desc, jstr, px, text}; +use super::fields::{Mapped, step}; +use super::{D, Descriptor, Value, json}; + +/// The script event's string ID. +pub(super) const FIT_IMAGE_EVENT: &str = "3caa3434-cb67-11d1-bc43-0060b0a13dc4"; +/// The native command the event plays as. +pub(super) const FIT_IMAGE: &str = "file.automate.fitImage"; +/// The class the reference application records the event's descriptor with. +const CLASS: &str = "cjsp"; +/// The recorded descriptor, kept when it differs from the one [`fit_image_to`] would write +/// (its message, class, key order or ID encoding), so a load and save keeps the step unchanged. +const SOURCE: &str = "_atnFitImageDescriptor"; + +/// The Fit Image settings the event holds. +#[derive(Debug, PartialEq)] +struct Fit { + width: f64, + height: f64, + dont_enlarge: bool, +} + +/// A recorded box side: a pixel unit float the native command reads as set (positive, finite). +fn side(v: &D) -> Option { + match v { + D::UnitFloat { unit, value } if *unit == PX && value.is_finite() && *value > 0.0 => Some(*value), + _ => None, + } +} + +/// The measured form only: `Hght`, `Wdth` and `limit` exactly once, `Msge` at most once (the +/// reference plays a step without it), and nothing else. Another unit, a box side of zero (which +/// the native command reads as "keep that side") or an extra key keeps the whole step as recorded. +fn recorded(d: &Descriptor) -> Option { + let count = |key: &str| d.items.iter().filter(|(k, _)| k.is(key)).count(); + let messages = count("Msge"); + if messages > 1 || d.items.len() != 3 + messages || ["Hght", "Wdth", "limit"].iter().any(|key| count(key) != 1) { + return None; + } + if !matches!(d.get("Msge"), None | Some(D::Text(_))) { + return None; + } + let D::Boolean(dont_enlarge) = d.get("limit")? else { return None }; + Some(Fit { width: side(d.get("Wdth")?)?, height: side(d.get("Hght")?)?, dont_enlarge: *dont_enlarge }) +} + +/// The descriptor a step recorded in PhotoCraft saves as: the measured class and key order. The +/// message is empty: it is the script's own text, not a setting, and no text of the reference +/// application is copied. +fn canonical(fit: &Fit) -> Descriptor { + desc(CLASS).with("Msge", text("")).with("Hght", px(fit.height)).with("Wdth", px(fit.width)).with("limit", D::Boolean(fit.dont_enlarge)) +} + +/// The recorded descriptor `d` holding `fit`'s settings instead of its own. Everything else stays +/// the recording's: its class, its message or the lack of one, and its key order and encoding. +fn with_settings(mut d: Descriptor, fit: &Fit) -> Descriptor { + for (key, value) in &mut d.items { + if key.is("Hght") { + *value = px(fit.height); + } else if key.is("Wdth") { + *value = px(fit.width); + } else if key.is("limit") { + *value = D::Boolean(fit.dont_enlarge); + } + } + d +} + +/// Map the measured form; any other stays a complete kept step. +pub(super) fn fit_image_from(d: &Descriptor) -> Mapped { + let Some(fit) = recorded(d) else { return Mapped::Unsupported { harmless: false } }; + let mut p = json!({"width": fit.width, "height": fit.height, "dontEnlarge": fit.dont_enlarge}); + if *d != canonical(&fit) { + p[SOURCE] = photocraft_paint::tile::b64_encode(&d.to_bytes()).into(); + } + step(FIT_IMAGE, p) +} + +/// The settings of a native step, when the event can hold all of them: both box sides set, and +/// the default resampling, since the event has no key for another method. A missing, zero or +/// `null` side plays as the document's own size, which the event cannot carry either. +fn native(p: &Value) -> Option { + let m = p.as_object()?; + if m.keys().any(|key| !["width", "height", "dontEnlarge", "resample", SOURCE].contains(&key.as_str())) { + return None; + } + if !matches!(m.get("resample"), None | Some(Value::Null)) && jstr(p, "resample") != Some("bicubic") { + return None; + } + let side = |key: &str| m.get(key).and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0); + let dont_enlarge = match m.get("dontEnlarge") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool()?, + }; + Some(Fit { width: side("width")?, height: side("height")?, dont_enlarge }) +} + +/// The recorded descriptor carried in `SOURCE`, when it decodes to the measured form. +fn source(p: &Value) -> Option<(Descriptor, Fit)> { + let d = Descriptor::from_bytes(&photocraft_paint::tile::b64_decode(jstr(p, SOURCE)?)?).ok()?; + let fit = recorded(&d)?; + Some((d, fit)) +} + +/// Save the recorded descriptor while the step still holds its settings; once they were +/// changed, write the new settings into the recorded descriptor. The settings decide whether the +/// step saves: a recorded descriptor that is missing or damaged only loses its message. +pub(super) fn fit_image_to(_: &str, p: &Value) -> Option { + let fit = native(p)?; + Some(match source(p) { + Some((d, recorded)) if recorded == fit => d, + Some((d, _)) => with_settings(d, &fit), + None => canonical(&fit), + }) +} diff --git a/crates/engine/src/cmd/atn_cmds/steps_frame_section.rs b/crates/engine/src/cmd/atn_cmds/steps_frame_section.rs new file mode 100644 index 0000000000..e2340988e6 --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/steps_frame_section.rs @@ -0,0 +1,121 @@ +//! Layer › New › Frame from Layers, recorded as a Make of class `framedGroupSection`, as +//! `docs/atn.md` ("Recorded through the menus") measures it (#10723): `From` = the layer **by +//! name**, `layerSectionStart`, `layerSectionEnd` (longs) and `Nm ` (text). The dialog's width +//! and height are not in the step. +//! +//! `layerSectionStart` and `layerSectionEnd` are ids of the recording session, so they are not +//! settings: a loaded step keeps them only inside its recorded descriptor. + +use super::descriptors::{class_ref, desc, jstr, name_ref, target_ref, text}; +use super::fields::{Mapped, step}; +use super::{D, Descriptor, ReferenceItem, Value, json}; + +/// The native command the step plays as. +pub(super) const COMMAND: &str = "layer.new.frameFromLayers"; +/// The recorded descriptor, kept when it differs from the one [`to`] would write (session ids, +/// key order), so a load and save keeps the step unchanged. +const SOURCE: &str = "_atnFrameSectionDescriptor"; + +/// The settings a step holds: the layer it frames (`None`: the selected layers) and the frame's +/// name (`None`: no `Nm `, so the frame takes the command's default name). +#[derive(Debug, PartialEq)] +struct Settings { + layer: Option, + name: Option, +} + +/// Text without the trailing NUL the format may carry. +fn plain(t: &super::UnicodeString) -> Option { + String::from_utf16(t.0.strip_suffix(&[0]).unwrap_or(&t.0)).ok() +} + +/// `From`: a layer by name, or the target layer (`Lyr ` `Ordn.Trgt`), the form a step recorded +/// in PhotoCraft without a layer of its own writes. +fn source_layer(v: &D) -> Option> { + let D::Reference(r) = v else { return None }; + match r.as_slice() { + [ReferenceItem::Name { class, name }] if class.class_id.is("Lyr ") => Some(Some(plain(name)?)), + [ReferenceItem::Enumerated { class, type_id, value }] if class.class_id.is("Lyr ") && type_id.is("Ordn") && value.is("Trgt") => Some(None), + _ => None, + } +} + +/// The measured form only: `null` = class `framedGroupSection`, `From`, optional session ids +/// (longs) and an optional `Nm `, each key at most once and nothing else. +fn recorded(d: &Descriptor) -> Option { + const KEYS: [&str; 5] = ["null", "From", "layerSectionStart", "layerSectionEnd", "Nm "]; + let once = |key: &str| d.items.iter().filter(|(k, _)| k.is(key)).count() <= 1; + if d.items.iter().any(|(k, _)| !KEYS.iter().any(|key| k.is(key))) || !KEYS.iter().all(|key| once(key)) { + return None; + } + let section = matches!(d.get("null")?, D::Reference(r) if matches!(r.as_slice(), [ReferenceItem::Class(c)] if c.class_id.is("framedGroupSection"))); + if !section || ["layerSectionStart", "layerSectionEnd"].iter().any(|key| d.get(key).is_some_and(|v| !matches!(v, D::Integer(_)))) { + return None; + } + let name = match d.get("Nm ") { + None => None, + Some(D::Text(t)) => Some(plain(t)?), + Some(_) => return None, + }; + Some(Settings { layer: source_layer(d.get("From")?)?, name }) +} + +/// The descriptor a step recorded in PhotoCraft saves as: the measured keys without the session +/// ids, `Nm ` only for a name of the step's own (not blank). +fn canonical(settings: &Settings) -> Descriptor { + let from = settings.layer.as_deref().map_or_else(|| target_ref("Lyr "), |layer| name_ref("Lyr ", layer)); + let d = desc("null").with("null", class_ref("framedGroupSection")).with("From", from); + match &settings.name { + Some(name) => d.with("Nm ", text(name)), + None => d, + } +} + +/// Map the measured form; any other stays a complete kept step. +pub(super) fn from(d: &Descriptor) -> Mapped { + let Some(settings) = recorded(d) else { return Mapped::Unsupported { harmless: false } }; + let mut p = json!({}); + if let Some(layer) = &settings.layer { + p["layer"] = layer.as_str().into(); + } + if let Some(name) = &settings.name { + p["name"] = name.as_str().into(); + } + if *d != canonical(&settings) { + p[SOURCE] = photocraft_paint::tile::b64_encode(&d.to_bytes()).into(); + } + step(COMMAND, p) +} + +/// A native step the event holds: the selected layers or a layer by name, and a name. A layer by +/// id (meaningless in another document) and the group options the command passes on to the +/// group it frames (colour, mode, opacity) refuse export: the step records none of them. +fn native(p: &Value) -> Option { + let m = p.as_object()?; + if m.keys().any(|key| !["layer", "name", SOURCE].contains(&key.as_str())) { + return None; + } + let layer = match m.get("layer") { + None | Some(Value::Null) => None, + Some(Value::String(layer)) => Some(layer.clone()), + Some(_) => return None, + }; + let name = match m.get("name") { + None | Some(Value::Null) => None, + // A blank name is no name to the command either. + Some(Value::String(n)) => Some(n.clone()).filter(|n| !n.trim().is_empty()), + Some(_) => return None, + }; + Some(Settings { layer, name }) +} + +/// Save the recorded descriptor while the step still frames the same layer with the same name, +/// otherwise the canonical form of the step's settings. +pub(super) fn to(p: &Value) -> Option { + let settings = native(p)?; + let source = jstr(p, SOURCE) + .and_then(photocraft_paint::tile::b64_decode) + .and_then(|bytes| Descriptor::from_bytes(&bytes).ok()) + .filter(|d| recorded(d).is_some_and(|r| r.layer == settings.layer && r.name.filter(|n| !n.trim().is_empty()) == settings.name)); + Some(source.unwrap_or_else(|| canonical(&settings))) +} diff --git a/crates/engine/src/cmd/atn_cmds/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs index 63a5c831eb..0e16f09c8f 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_make.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -540,16 +540,30 @@ fn type_shape_descriptor() -> Descriptor { desc("null").with("null", class_ref("contentLayer")).with("Usng", target_ref("textLayer")) } +/// Make events another module maps: a type path, an artboard, a layer style or a frame, +/// tried in that order. +fn delegated_make_from(d: &Descriptor) -> Option { + let class = get_ref(d, "null").and_then(ref_class); + match class.as_deref() { + Some("Path") => return Some(super::steps_type_path::from(d)), + // Layer › New › Artboard and Artboard from Layers (#10723). + Some("artboardSection") => return Some(super::steps_artboard_section::from(d)), + _ => {} + } + if let Some(mapped) = super::steps_layer_style::create_from_descriptor(d) { + return Some(mapped); + } + // Layer › New › Frame from Layers (#10723). + (class.as_deref() == Some("framedGroupSection")).then(|| super::steps_frame_section::from(d)) +} + /// Import Make events only when their geometry and options can be represented faithfully, /// including the exact target-text-to-content-layer references. pub(super) fn make_from(d: &Descriptor) -> Mapped { if let Some(mapped) = super::steps_calculations::from_descriptor(d) { return mapped; } - if get_ref(d, "null").and_then(ref_class).as_deref() == Some("Path") { - return super::steps_type_path::from(d); - } - if let Some(mapped) = super::steps_layer_style::create_from_descriptor(d) { + if let Some(mapped) = delegated_make_from(d) { return mapped; } if d.items == type_shape_descriptor().items { @@ -717,9 +731,15 @@ pub(super) fn make_to(id: &str, p: &Value) -> Option { if id == super::steps_type_path::COMMAND { return super::steps_type_path::to(p); } + if matches!(id, super::steps_artboard_section::NEW | super::steps_artboard_section::FROM_LAYERS) { + return super::steps_artboard_section::to(id, p); + } if id == super::steps_layer_style::CREATE { return super::steps_layer_style::style_to(id, p); } + if id == super::steps_frame_section::COMMAND { + return super::steps_frame_section::to(p); + } if id == "type.convertToShape" { return p.as_object().filter(|p| p.is_empty()).map(|_| type_shape_descriptor()); } diff --git a/crates/engine/src/cmd/atn_cmds/steps_selection.rs b/crates/engine/src/cmd/atn_cmds/steps_selection.rs index 1c30dc93ab..4755ce94fb 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_selection.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_selection.rs @@ -151,22 +151,49 @@ pub(super) fn paste_to(_: &str, p: &Value) -> Option { Some(desc("null").with("AntA", enm("Annt", "Anno")).with("As ", D::Class(class("Pxel")))) } -/// Fade requires the settings recorded after the edit it fades, not guessed factory values. +/// Fade plays the recorded settings; a missing key takes the reference application's fixed default +/// (100 % opacity, Normal mode), not the dialog's last values. Opacity is rounded to a whole percent. pub(super) fn fade_from(d: &Descriptor) -> Mapped { let mapped = || { if !keys(d, &["Opct", "Md "]) { return None; } - let mode = blend_label(&enumeration(d, "Md ", "BlnM")?)?; - // An accepted alias would be rewritten to the exporter's preferred blend identifier. - if d.get("Md ") != Some(&enm("BlnM", blend_ps(mode)?)) { - return None; - } - Some(json!({"opacity":unit(d,"Opct",b"#Prc")?.clamp(0.0,100.0),"mode":mode})) + let mode = match d.get("Md ") { + None => "Normal", + Some(recorded) => { + let mode = blend_label(&enumeration(d, "Md ", "BlnM")?)?; + // An accepted alias would be rewritten to the exporter's preferred blend identifier. + if *recorded != enm("BlnM", blend_ps(mode)?) { + return None; + } + mode + } + }; + let opacity = match d.get("Opct") { + None => 100.0, + Some(_) => fade_opacity(unit(d, "Opct", b"#Prc")?), + }; + Some(json!({"opacity":opacity,"mode":mode})) }; mapped().map_or(Mapped::Unsupported { harmless: false }, |p| step("edit.fade", p)) } +/// A recorded Fade opacity less than 100 past either end wraps modulo 100 (150 plays as 50, -5 as +/// 95), as measured in the reference application. Values further out (200, -100, -105) were not +/// measured and keep the clamp to 0..=100. +fn fade_opacity(recorded: f64) -> f64 { + let rounded = recorded.round(); + let played = if rounded > 100.0 && rounded < 200.0 { + rounded - 100.0 + } else if rounded < 0.0 && rounded > -100.0 { + rounded + 100.0 + } else { + rounded.clamp(0.0, 100.0) + }; + // -0.4 rounds to -0.0; adding zero stores it as 0. + played + 0.0 +} + /// Native omitted Fade settings retain the command's 100% Normal behavior. pub(super) fn fade_to(_: &str, p: &Value) -> Option { if !params(p, &["opacity", "mode"]) { diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index be6f071b2e..cbbb23f6cc 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -1,6 +1,6 @@ use super::*; -use photocraft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; -use photocraft_psd::descriptor::{Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; +use craft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; +use craft_psd::descriptor::{Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; use serde_json::json; /// A wire key has one mapper; distinct wire aliases may still name the same command. @@ -508,6 +508,21 @@ fn load_renames_play_targets_longer_than_the_name_limit() { assert_eq!(caller.steps[0].1["action"], renamed.as_str()); } +/// The `set` override is copied into every loaded action, so it is held to the same limit as a +/// set name read from the file. +#[test] +fn load_clips_an_overlong_set_override() { + let mut s = Session::new(); + let actions: Vec = (0..3).map(|i| Action::new(format!("A{i}"), vec![])).collect(); + let refs: Vec<&Action> = actions.iter().collect(); + let (bytes, _) = export("File", &refs, &[], false).unwrap(); + let long = "s".repeat(super::convert::MAX_NAME_CHARS * 4); + s.execute("actions.load", json!({"data": b64(&bytes), "set": long})).unwrap(); + let clipped = "s".repeat(super::convert::MAX_NAME_CHARS); + assert_eq!(s.actions.list.len(), 3); + assert!(s.actions.list.iter().all(|a| a.set.as_deref() == Some(clipped.as_str()))); +} + #[test] fn load_many_duplicate_names_get_sequential_suffixes() { // Several actions share one base name. Deduplication must stay O(n) overall and produce @@ -691,7 +706,10 @@ fn every_mapped_command_exports_and_imports_back() { "rotationAdaptation":"none","scale":true,"mirror":false,"output":"new"}), ), ("edit.fade", json!({"opacity":50,"mode":"Multiply"})), + ("layer.new.frameFromLayers", json!({"layer": "Photo", "name": "Frame 1"})), ("layer.linkLayers", json!({})), + ("layer.new.artboard", json!({"rect": [10, 20, 100, 50], "name": "Hero"})), + ("layer.new.artboardFromLayers", json!({"name": "Cards"})), ("layer.smartObjects.stackMode.range", json!({})), ("layer.smartObjects.stackMode.entropy", json!({})), ("layer.smartObjects.stackMode.kurtosis", json!({})), @@ -865,6 +883,7 @@ fn every_mapped_command_exports_and_imports_back() { ("layer.videoLayers.deleteFrame", json!({})), ("file.automate.cropAndStraightenPhotos", json!({})), ("file.automate.cropAndStraightenPhotos", json!({"_atnNoTarget": true})), + ("file.automate.fitImage", json!({"width": 800, "height": 600, "dontEnlarge": true})), ("layer.new.artboardFromGroup", json!({})), ("layer.new.artboardFromGroup", json!({"background":"white","color":[1,1,1],"preset":"","guideIDs":[],"changeBackground":1})), ( diff --git a/crates/engine/src/cmd/automate_cmds.rs b/crates/engine/src/cmd/automate_cmds.rs index 9a5f94f68c..785ed90f37 100644 --- a/crates/engine/src/cmd/automate_cmds.rs +++ b/crates/engine/src/cmd/automate_cmds.rs @@ -433,6 +433,8 @@ fn write_shim(_: &str) -> Result { /// Runs a droplet file on inputs (files and/or folders). fn run_droplet(s: &mut Session, p: &Value) -> Result { let cmd = "file.automate.runDroplet"; + // Checked before the droplet file is read, so a droplet that runs itself stops at the limit. + crate::file_cmds::check_batch_depth(s, cmd)?; let path = p.get("droplet").or_else(|| p.get("path")).and_then(Value::as_str).ok_or_else(|| bad(cmd, "missing \"droplet\""))?; let v: Value = serde_json::from_slice(&read_file(path)?).map_err(|e| bad(cmd, format!("{path}: {e}")))?; if v.get("photocraftDroplet").is_none() { diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 6858b35e22..82abc3d436 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -12,7 +12,7 @@ use photocraft_paint::mixer::{MixerSettings, MixerState}; use photocraft_paint::replace::{Limits, ReplaceMode, ReplaceSettings, Sampling, apply_color_replacement, color_replacement_effect}; use photocraft_paint::tile::PREVIEW_SIDE; use photocraft_paint::{ - BrushPreset, BrushSettings, GrayTile, Pattern, PresetCaptures, StoredTile, Stroke, StrokePoint, StrokeRenderer, TipShape, render_stroke, + BrushPreset, BrushSettings, GrayTile, Pattern, PresetCaptures, StoredTile, Stroke, StrokePoint, StrokeRenderer, TipShape, render_stroke_clipped, }; use photocraft_raster::Surface; use serde_json::{Value, json}; @@ -90,6 +90,12 @@ pub(crate) fn check_coords(pts: &[StrokePoint], cmd: &str) -> Result<()> { Ok(()) } +/// Where a stroke can change pixels: the canvas plus any pixels the layer already holds past its +/// edge (a moved layer keeps them, #5067). Dabs that reach neither are not rasterized. +fn paintable_area(canvas: Rect, surf: &Surface) -> Rect { + canvas.union(&surf.tile_bounds()) +} + /// Deep-merge `patch` into `base` (objects merge key by key; anything else replaces). fn merge(base: &mut Value, patch: &Value) { match (base, patch) { @@ -291,7 +297,9 @@ fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushS } let sel = doc.selection.clone(); let table = crate::mode_cmds::paint_color_table(doc, p); + let canvas = doc.bounds(); let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?; + let clip = paintable_area(canvas, surf); let mut brush = brush; erase_locked(&mut brush, lock, bg); if auto_erase { @@ -307,23 +315,23 @@ fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushS .iter() .filter(|p| crate::symmetry_cmds::SymmetryAxis::has_distinct_mirror(&pts, p)) .map(|p| { - let mut renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom); + let mut renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom).with_clip(clip); renderer.push(p); renderer.finish(); renderer }) .collect(); if copies.is_empty() { - render_stroke(surf, &brush, &pts, sel.as_ref(), lock, zoom) + render_stroke_clipped(surf, &brush, &pts, sel.as_ref(), lock, zoom, Some(clip)) } else { let pre = surf.clone(); - let mut original = StrokeRenderer::new(&brush, Some(surf.format()), zoom); + let mut original = StrokeRenderer::new(&brush, Some(surf.format()), zoom).with_clip(clip); original.push(&pts); original.finish(); original.composite_union_many(&copies, &pre, surf, sel.as_ref(), lock) } } else { - render_stroke(surf, &brush, &pts, sel.as_ref(), lock, zoom) + render_stroke_clipped(surf, &brush, &pts, sel.as_ref(), lock, zoom, Some(clip)) }; if let (Some(table), Some(pre)) = (&table, &unpainted) { crate::mode_cmds::keep_in_color_table(table, pre, surf, damage); @@ -341,12 +349,23 @@ fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushS /// Pencil Auto Erase: a stroke that starts on a pixel of the foreground colour paints the /// background colour instead (Photoshop). The match is exact (#11966): the foreground as the /// layer would store it (its mode and depth) against the pixel, its alpha aside, so one level -/// off paints the foreground. +/// off paints the foreground. In a CMYK layer a foreground picked as CMYK is probed as the inks +/// the stroke paints (#13060), not as its RGB stand-in converted back. fn apply_auto_erase(brush: &mut BrushSettings, surf: &Surface, start: Option<&StrokePoint>, fg: [f32; 4], bg: [f32; 4]) { let Some(p0) = start else { return }; let c = surf.rgba(p0.x.floor() as i32, p0.y.floor() as i32); - let mut probe = Surface::new(surf.format()); - probe.write_pixel(0, 0, &photocraft_raster::from_rgba(&surf.format(), [fg[0], fg[1], fg[2], 1.0])); + let format = surf.format(); + let mut px = photocraft_raster::from_rgba(&format, [fg[0], fg[1], fg[2], 1.0]); + // The renderer's condition for painting the picked inks (`StrokeRenderer::composite`), keyed + // on the foreground being probed. + if let (photocraft_color::ColorMode::Cmyk, Some((rgb, inks))) = (format.mode, brush.color_cmyk) + && rgb == [fg[0], fg[1], fg[2]] + && let Some(channels) = px.get_mut(..4) + { + channels.copy_from_slice(&inks); + } + let mut probe = Surface::new(format); + probe.write_pixel(0, 0, &px); let stored = probe.rgba(0, 0); // Far below one 8-bit level: only the float noise of the conversion. if c[3] > 0.0 && (0..3).all(|i| (c[i] - stored[i]).abs() < 1e-5) { @@ -626,16 +645,19 @@ impl LiveStroke { let mut doc = (*st.doc).clone(); let sel = doc.selection.clone(); let table = crate::mode_cmds::paint_color_table(&doc, p); + let canvas = doc.bounds(); let (surf, lock) = crate::channel_cmds::target_surface(&mut doc, layer, p)?; + let clip = paintable_area(canvas, surf); let bg = crate::color_cmds::swatch_in_doc(s, s.tools.background); erase_locked(&mut brush, lock, bg); if pencil && flag(p, "autoErase", false) { let fg = table.as_ref().map_or(fg, |t| crate::mode_cmds::table_color(t, fg)); apply_auto_erase(&mut brush, surf, pts.first(), fg, s.tools.background); } - let renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom); + let renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom).with_clip(clip); let symmetry = s.active().and_then(|st| st.symmetry.clone()); - let mirrors: Vec<_> = (0..symmetry.as_ref().map_or(0, |s| s.mirror_count())).map(|_| StrokeRenderer::new(&brush, Some(surf.format()), zoom)).collect(); + let mirrors: Vec<_> = + (0..symmetry.as_ref().map_or(0, |s| s.mirror_count())).map(|_| StrokeRenderer::new(&brush, Some(surf.format()), zoom).with_clip(clip)).collect(); let mirror_distinct = vec![false; mirrors.len()]; let pre = surf.clone(); let mut live = Self { @@ -913,7 +935,7 @@ fn color_replacement(s: &mut Session, p: &Value) -> Result { let sel = doc.selection.clone(); let lock = doc.effective_locks(id).transparency; let surf = paint_surface(doc, id, &json!({}))?; - Ok(apply_color_replacement(surf, &stroke, &rs, sel.as_ref(), lock)) + apply_color_replacement(surf, &stroke, &rs, sel.as_ref(), lock).map_err(|e| bad("paint.colorReplacement", e.to_string())) })?; Ok(damage_json(s, dmg)) } diff --git a/crates/engine/src/cmd/brush_cmds/mixer_live_tests.rs b/crates/engine/src/cmd/brush_cmds/mixer_live_tests.rs index 20447a627f..d2aeb8560d 100644 --- a/crates/engine/src/cmd/brush_cmds/mixer_live_tests.rs +++ b/crates/engine/src/cmd/brush_cmds/mixer_live_tests.rs @@ -110,7 +110,8 @@ fn mixer_live_current_layer_matches_reference_and_cancels() { &mut state, None, false, - ); + ) + .unwrap(); let live = LiveMixer::begin(&s, &p).unwrap(); let id = s.active().unwrap().active_layer.unwrap(); let actual = live.doc.layer(id).unwrap().surface().unwrap().read_region(s.active().unwrap().doc.bounds()); diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index 7a424e2f03..3de4871031 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -32,6 +32,23 @@ fn stroke_backwards_compatible() { assert!(rgba(&s, 30, 5)[3] > 0.9 && rgba(&s, 30, 8)[3] < 0.01); } +#[test] +fn a_stroke_from_far_off_the_canvas_paints_only_what_reaches_it() { + // Dabs that cannot reach the canvas are not rasterized (their coverage is never read). + let mut s = session(80, 80); + let r = s + .execute( + "paint.stroke", + json!({"points": [[-100_000, 20], [70, 20], [70, 60]], "size": 6, "color": "#0000ff", "brush": {"hardness": 0.5, "smoothing": {"amount": 0.0}}}), + ) + .unwrap(); + assert!(rgba(&s, 40, 20)[3] > 0.9, "the part on the canvas is painted: {:?} {r}", rgba(&s, 40, 20)); + assert!(rgba(&s, 70, 50)[3] > 0.9); + assert_eq!(rgba(&s, 40, 40)[3], 0.0); + let d: Vec = r["damage"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(); + assert!(d[0] > -100, "the damage does not span the off-canvas path: {r}"); +} + #[test] fn fill_fills_the_enclosed_region_not_the_outline() { // #3659: a closed gesture with `fill` paints the interior, not a ring. @@ -212,6 +229,35 @@ fn pencil_is_aliased_and_auto_erases() { assert_eq!(rgba(&s, 40, 26), [0.0, 0.0, 0.0, 1.0]); } +/// #13060: in a CMYK document a foreground picked as CMYK inks (a rich black, which its sRGB +/// stand-in does not convert back to) is painted as those inks, and Pencil Auto Erase recognises +/// them: a stroke that starts on it paints the background colour, live and committed. +#[test] +fn pencil_auto_erase_probes_a_cmyk_pick_with_the_picked_inks() { + let rich_black = [0.6f32, 0.4, 0.4, 1.0]; + let rgb = photocraft_color::convert::cmyk_to_rgb(rich_black).map(|c| c.clamp(0.0, 1.0)); + let mut s = session(40, 20); + s.execute("image.mode.cmyk", json!({})).unwrap(); + s.execute("tools.setColors", json!({"foreground": rgb, "foregroundCmyk": rich_black, "background": "#ffffff"})).unwrap(); + s.execute("paint.pencil", json!({"points": [[5, 10], [35, 10]], "size": 5})).unwrap(); + let pixel = |s: &Session, x: i32, y: i32| -> Vec { surface(s).read_region(Rect::new(x, y, x + 1, y + 1)).into_iter().take(4).collect() }; + let painted = pixel(&s, 20, 10); + assert!(painted.iter().zip(rich_black).all(|(a, b)| (a - b).abs() < 0.01), "the stroke paints the picked inks: {painted:?}"); + let white = [1.0f32, 1.0, 1.0, 1.0]; + + // Live: the stroke that starts on the rich black paints the background. + let p = json!({"points": [[12, 10]], "autoErase": true, "smoothing": 0.0}); + let mut live = LiveStroke::begin_with(&s, "paint.pencil", &p).unwrap(); + live.push(&[StrokePoint::new(12.0, 18.0, 1.0)]).unwrap(); + let shown = live.doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().rgba(12, 17); + assert!(shown.iter().zip(white).all(|(a, b)| (a - b).abs() < 1e-3), "live: {shown:?}"); + + // Committed: the same. + s.execute("paint.pencil", json!({"points": [[20, 10], [20, 18]], "size": 3, "autoErase": true})).unwrap(); + let erased = rgba(&s, 20, 17); + assert!(erased.iter().zip(white).all(|(a, b)| (a - b).abs() < 1e-3), "committed: {erased:?}"); +} + #[test] fn mixer_brush_reservoir_and_cleaning() { let mut s = session(200, 30); @@ -1157,12 +1203,15 @@ fn out_of_range_scatter_is_rejected_and_the_maximum_still_paints() { assert!(s.execute("tools.setBrush", json!({ "brush": scatter(1e38) })).is_err()); assert!(s.execute("paint.stroke", stroke.clone()).is_ok()); // The maximum (1000 %) is accepted and paints a finite, well-formed dab. - for patch in [scatter(10.0), dual(10.0)] { + for (patch, primary_on_canvas) in [(scatter(10.0), false), (dual(10.0), true)] { let mut s = new(); s.execute("tools.setBrush", json!({ "brush": patch })).unwrap(); let r = s.execute("paint.stroke", stroke.clone()).unwrap(); let d: Vec = r["damage"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(); - assert!(d[0].abs() < 1000 && d[1].abs() < 1000 && d[2] > 0 && d[3] > 0, "{r}"); + // A dab scattered clear of the canvas is not rasterized, so its damage is empty. The dual + // brush scatters only its own tip: the primary dab stays on the canvas and always paints. + let off_canvas = !primary_on_canvas && d[2] == 0 && d[3] == 0; + assert!(off_canvas || (d[0].abs() < 1000 && d[1].abs() < 1000 && d[2] > 0 && d[3] > 0), "{r}"); } // Control: 200 % scatter paints where it did before the cap (the soft default tip reaches a // little past its radius). diff --git a/crates/engine/src/cmd/brush_preset_cmds.rs b/crates/engine/src/cmd/brush_preset_cmds.rs index cd54b1ff61..6cfe6365c7 100644 --- a/crates/engine/src/cmd/brush_preset_cmds.rs +++ b/crates/engine/src/cmd/brush_preset_cmds.rs @@ -30,7 +30,7 @@ fn always(_: &Session) -> std::result::Result<(), String> { /// Longest preset or group name accepted. pub const MAX_NAME: usize = 255; /// Deepest folder path accepted inside a group (matches the `.abr` reader's limit). -pub const MAX_FOLDER_DEPTH: usize = photocraft_psd::abr::MAX_FOLDER_DEPTH; +pub const MAX_FOLDER_DEPTH: usize = craft_psd::abr::MAX_FOLDER_DEPTH; fn text(p: &Value, k: &str, cmd: &str) -> Result { let v = p.get(k).and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, format!("missing `{k}`")))?; diff --git a/crates/engine/src/cmd/channel_cmds/refs.rs b/crates/engine/src/cmd/channel_cmds/refs.rs index a9552e6d62..39a56e1928 100644 --- a/crates/engine/src/cmd/channel_cmds/refs.rs +++ b/crates/engine/src/cmd/channel_cmds/refs.rs @@ -93,6 +93,10 @@ pub(super) fn native_pixels(doc: &Document, layer: Option) -> Result<(V let r = doc.bounds(); let fmt = doc.pixel_format(); let n = fmt.channels(); + // The source is read as dense samples over the whole canvas, whatever tiles it stores, then + // returned as `n` native f32 samples per pixel. Refuse a canvas past the working budget + // before reading (an empty canvas can be 300000 px a side). + let out = (n as u64).saturating_mul(4); match layer { Some(id) => { let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; @@ -105,6 +109,7 @@ pub(super) fn native_pixels(doc: &Document, layer: Option) -> Result<(V return Err(EngineError::Other(format!("layer \"{}\" has no pixels", l.name))); } }; + crate::allocation::check_dense(r, (s.channels() as u64).saturating_mul(4).saturating_add(out), "reading this channel source")?; if s.format() == fmt { return Ok((s.read_region(r), n)); } @@ -113,6 +118,8 @@ pub(super) fn native_pixels(doc: &Document, layer: Option) -> Result<(V Ok((raw.chunks_exact(sf.channels()).flat_map(|p| from_rgba(&fmt, to_rgba(&sf, p))).collect(), n)) } None => { + // The composite is straight RGBA f32. + crate::allocation::check_dense(r, 16u64.saturating_add(out), "reading this channel source")?; let buf = photocraft_compose::render(doc, r); Ok((buf.px.iter().flat_map(|p| from_rgba(&fmt, *p)).collect(), n)) } @@ -152,6 +159,13 @@ fn ref_planes(doc: &Document, layer: Option, active: Option, r let colors = color_count(doc); Ok(match r { ChanRef::Composite | ChanRef::Color(_) => { + // After `native_pixels` returns its `n` samples per pixel, the colour planes (and for + // one channel the toned plane) are built beside them: check that peak first, as + // `native_pixels` only checks its own. + let n = doc.pixel_format().channels() as u64; + let toned = u64::from(matches!(r, ChanRef::Color(_))); + let planes = (colors as u64).saturating_add(toned).saturating_mul(4); + crate::allocation::check_dense(area, n.saturating_mul(4).saturating_add(planes), "reading this channel source")?; let (px, n) = native_pixels(doc, layer)?; let planes: Vec> = (0..colors).map(|c| px.chunks_exact(n).map(|p| p[c]).collect()).collect(); match r { diff --git a/crates/engine/src/cmd/color_cmds.rs b/crates/engine/src/cmd/color_cmds.rs index e0bf17a271..de14c9f420 100644 --- a/crates/engine/src/cmd/color_cmds.rs +++ b/crates/engine/src/cmd/color_cmds.rs @@ -988,19 +988,8 @@ pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result Result<(Vec, usize)> { let check = GamutCheck::new(&composite_profile(doc), &setup.profile, threshold).map_err(cms_err)?; let buf = photocraft_compose::flatten(doc); - let mut count = 0; - let mask = buf - .px - .iter() - .map(|p| { - if p[3] > 0.0 && check.out_of_gamut(&p[..3]) { - count += 1; - 255 - } else { - 0 - } - }) - .collect(); + let mut mask = vec![0u8; buf.px.len()]; + let count = check.mask_rgba(&buf.px, &mut mask).map_err(cms_err)?; Ok((mask, count)) } diff --git a/crates/engine/src/cmd/contour_lib_cmds.rs b/crates/engine/src/cmd/contour_lib_cmds.rs index 370c4da5cf..36ba5ac209 100644 --- a/crates/engine/src/cmd/contour_lib_cmds.rs +++ b/crates/engine/src/cmd/contour_lib_cmds.rs @@ -5,7 +5,7 @@ //! The library is [`PresetState::contours`](crate::presets::PresetState); like the other preset //! sets it lives in the preferences document and changes the preferences, not a document's //! history. A user contour is applied to an effect as a `contour` curve object (see -//! [`contour_param`]); `.shc` files go through `photocraft_psd::shc` (see [`contours_from_shc`]). +//! [`contour_param`]); `.shc` files go through `craft_psd::shc` (see [`contours_from_shc`]). use photocraft_doc::Contour; use photocraft_doc::adjust::CurvePoint; @@ -47,7 +47,9 @@ fn named(c: Contour, name: &str) -> Contour { /// `base`, or `base 2`, `base 3`… so a name is neither a standard contour's nor a user contour's /// (a name alone selects a standard contour, so a user contour may not shadow one). fn unique(lib: &[Contour], base: &str) -> String { - let taken = |n: &str| builtin_contour(n).is_some() || lib.iter().any(|c| name_of(c) == n); + // One pass over the library, not one per suffix tried. + let used: std::collections::HashSet<&str> = lib.iter().map(name_of).collect(); + let taken = |n: &str| builtin_contour(n).is_some() || used.contains(n); if !taken(base) { return base.to_string(); } diff --git a/crates/engine/src/cmd/count_resize_tests.rs b/crates/engine/src/cmd/count_resize_tests.rs new file mode 100644 index 0000000000..7648ed0051 --- /dev/null +++ b/crates/engine/src/cmd/count_resize_tests.rs @@ -0,0 +1,94 @@ +//! #11762: count points keep their document coordinates through Image Size, Canvas Size and Image +//! Rotation (right angles, flips and arbitrary), also off the new canvas; other marks still follow +//! the image, and Crop keeps today's behaviour. + +use serde_json::{Value, json}; + +use crate::Session; + +const POINT: [f64; 2] = [99.3, 99.7]; + +fn doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); + s.execute("count.add", json!({"x": POINT[0], "y": POINT[1]})).unwrap(); + s.execute("notes.add", json!({"x": 100, "y": 100})).unwrap(); + s +} + +fn count_point(s: &Session) -> [f64; 2] { + s.active().unwrap().doc.measurement.count_groups[0].points[0] +} + +fn note(s: &Session) -> [f64; 2] { + s.active().unwrap().doc.notes[0].position +} + +#[test] +fn count_points_keep_their_coordinates() { + // The note at [100, 100] on the 600×400 canvas, where each command moves it. + let steps: [(&str, Value, [f64; 2]); 8] = [ + ("image.imageSize", json!({"width": 300, "height": 200}), [50.0, 50.0]), + ("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"}), [0.0, 50.0]), + ("image.imageRotation.90cw", json!({}), [300.0, 100.0]), + ("image.imageRotation.90ccw", json!({}), [100.0, 500.0]), + ("image.imageRotation.180", json!({}), [500.0, 300.0]), + ("image.imageRotation.flipCanvasHorizontal", json!({}), [500.0, 100.0]), + ("image.imageRotation.flipCanvasVertical", json!({}), [100.0, 300.0]), + ("image.rotation.arbitrary", json!({"angle": 30}), [236.794_919_243_112_3, 136.897_459_621_556_2]), + ]; + for (cmd, p, moved) in steps { + let mut s = doc(); + let before = note(&s); + s.execute(cmd, p).unwrap(); + assert_eq!(count_point(&s), POINT, "{cmd}"); + let n = note(&s); + assert!((n[0] - moved[0]).abs() < 1e-6 && (n[1] - moved[1]).abs() < 1e-6, "{cmd}: note at {n:?}, expected {moved:?}"); + s.undo(); + assert_eq!((count_point(&s), note(&s)), (POINT, before), "{cmd}: undo"); + } +} + +#[test] +fn all_three_in_a_row_leave_the_point_where_it_was() { + let mut s = doc(); + s.execute("image.imageSize", json!({"width": 300, "height": 200})).unwrap(); + s.execute("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"})).unwrap(); + s.execute("image.imageRotation.90cw", json!({})).unwrap(); + assert_eq!(count_point(&s), POINT); +} + +#[test] +fn crop_still_moves_count_points() { + let mut s = doc(); + s.execute("image.crop", json!({"x": 50, "y": 50, "width": 300, "height": 200})).unwrap(); + assert_ne!(count_point(&s), POINT, "not measured: Crop keeps today's behaviour"); +} + +#[test] +fn ruler_straighten_with_crop_moves_count_points_with_the_image() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); + s.execute("count.add", json!({"x": 250, "y": 150})).unwrap(); + s.execute("notes.add", json!({"x": 250, "y": 150})).unwrap(); + // Straighten Layer is off for the Background (#12033). + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [100, 10]})).unwrap(); + s.execute("image.analysis.straightenLayer", json!({"crop": true})).unwrap(); + let (c, n) = (count_point(&s), note(&s)); + assert!((c[0] - n[0]).abs() < 1e-6 && (c[1] - n[1]).abs() < 1e-6, "count {c:?} vs note {n:?}"); +} + +#[test] +fn ruler_straighten_with_crop_asks_the_gate_for_its_rotation() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); + // Straighten Layer is off for the Background (#12033). + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [100, 10]})).unwrap(); + let size = s.active().unwrap().doc.size; + s.authorize = Some(|id, _| if id == "image.rotation.arbitrary" { Err(crate::EngineError::Other("denied".into())) } else { Ok(()) }); + assert!(s.execute("image.analysis.straightenLayer", json!({"crop": true})).is_err(), "the nested rotation is denied"); + s.authorize = None; + assert_eq!(s.active().unwrap().doc.size, size, "nothing turned"); +} diff --git a/crates/engine/src/cmd/direct_select_history_names_tests.rs b/crates/engine/src/cmd/direct_select_history_names_tests.rs new file mode 100644 index 0000000000..09d9082862 --- /dev/null +++ b/crates/engine/src/cmd/direct_select_history_names_tests.rs @@ -0,0 +1,88 @@ +//! #13205: the History names of Direct Selection's path edits, as in the reference: "Drag Anchor +//! Point" for one anchor, "Drag Anchor Points" for two or more, "Drag Control Point" for a +//! handle and "Drag Segment" for a segment. The Convert Point and Curvature Pen names stay. + +use serde_json::{Value, json}; + +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200, "background": "white"})).unwrap(); + // Knot 1 at (120, 40) is smooth, with handles at (100, 40) and (140, 40). + let path = json!({"subpaths": [{"closed": true, "knots": [ + [40, 40], + {"anchor": [120, 40], "in": [100, 40], "out": [140, 40], "smooth": true}, + [120, 120], + [40, 120], + ]}]}); + s.execute("path.set", json!({"path": path})).unwrap(); + s +} + +/// The History step `id` with `params` adds. +fn step(s: &mut Session, id: &str, params: Value) -> String { + let n = s.active().unwrap().history.entries().len(); + s.execute(id, params).unwrap(); + let names = s.active().unwrap().history.entries(); + assert_eq!(names.len(), n + 1, "{id} adds one step: {names:?}"); + names[n].clone() +} + +#[test] +fn one_anchor_is_drag_anchor_point_and_more_are_drag_anchor_points() { + let mut s = session(); + let one = json!({"anchors": [[0, 2]], "move": [5, 0], "stepName": "Drag Anchor Point"}); + assert_eq!(step(&mut s, "path.moveAnchors", one), "Drag Anchor Point"); + assert_eq!(step(&mut s, "path.moveAnchors", json!({"anchors": [[0, 2], [0, 3]], "move": [5, 0]})), "Drag Anchor Points"); +} + +#[test] +fn a_handle_drag_is_drag_control_point() { + let mut s = session(); + for independent in [false, true] { + let p = json!({"subpath": 0, "knot": 1, "handle": "out", "to": [150, 60], "independent": independent}); + assert_eq!(step(&mut s, "path.moveHandle", p), "Drag Control Point", "independent: {independent}"); + } +} + +#[test] +fn a_segment_drag_stays_drag_segment() { + let mut s = session(); + assert_eq!(step(&mut s, "path.bendSegment", json!({"subpath": 0, "knot": 2, "move": [0, 10]})), "Drag Segment"); +} + +#[test] +fn other_tools_keep_their_names() { + let mut s = session(); + let corner = json!({"subpath": 0, "knot": 1, "handle": "out", "to": [150, 60], "independent": true, "stepName": "Corner Drag"}); + assert_eq!(step(&mut s, "path.moveHandle", corner), "Corner Drag"); + assert_eq!(step(&mut s, "path.convertPoint", json!({"subpath": 0, "knot": 2, "stepName": "Change Anchor Point"})), "Change Anchor Point"); + let whole = json!({"anchors": [[0, 0], [0, 1], [0, 2], [0, 3]], "move": [1, 1], "stepName": "Drag Path"}); + assert_eq!(step(&mut s, "path.moveAnchors", whole), "Drag Path"); + // The Curvature Pen's drag, and a one-anchor move that names no step (an arrow-key nudge). + assert_eq!(step(&mut s, "path.moveAnchors", json!({"anchors": [[0, 1]], "move": [0, 5], "curvature": true})), "Drag Anchor Points"); + assert_eq!(step(&mut s, "path.moveAnchors", json!({"anchors": [[0, 1]], "move": [1, 0]})), "Drag Anchor Points"); +} + +#[test] +fn an_unknown_step_name_is_refused_and_changes_nothing() { + let mut s = session(); + let before = (s.active().unwrap().doc.work_path.clone(), s.active().unwrap().history.entries()); + for bad in [json!("Drag Anchor Points"), json!("Drag Control Point"), json!("drag anchor point"), json!(""), json!(1), json!(["Drag Path"])] { + let e = s.execute("path.moveAnchors", json!({"anchors": [[0, 1]], "move": [1, 0], "stepName": bad})).unwrap_err().to_string(); + assert!(e.contains("\"Drag Path\" or \"Drag Anchor Point\""), "{bad}: {e}"); + let e = s.execute("path.moveHandle", json!({"subpath": 0, "knot": 1, "handle": "out", "to": [150, 60], "stepName": bad})).unwrap_err().to_string(); + assert!(e.contains("stepName") && e.contains("\"Corner Drag\""), "{bad}: {e}"); + } + assert_eq!((s.active().unwrap().doc.work_path.clone(), s.active().unwrap().history.entries()), before); +} + +#[test] +fn the_command_list_says_the_new_names() { + let specs = crate::command_specs(); + let spec = |id: &str| specs.iter().find(|c| c.id == id).unwrap(); + assert_eq!(spec("path.moveHandle").label, "Drag Control Point"); + assert!(spec("path.moveHandle").params.contains("default \"Drag Control Point\"")); + assert!(spec("path.moveAnchors").params.contains("\"Drag Anchor Point\" when it drags one anchor")); +} diff --git a/crates/engine/src/cmd/distort_cmds.rs b/crates/engine/src/cmd/distort_cmds.rs index 1b71aed4a0..0f74916c5d 100644 --- a/crates/engine/src/cmd/distort_cmds.rs +++ b/crates/engine/src/cmd/distort_cmds.rs @@ -160,14 +160,24 @@ fn interp(p: &Value) -> Interp { // ---------- pixel operations ---------- /// Mixes `new` over `old` by the selection's coverage (premultiplied when there is alpha). -fn mix_by_selection(old: &Surface, new: &Surface, sel: &Surface) -> Surface { - let area = old.content_bounds().union(&new.content_bounds()); - let mut out = new.clone(); +/// +/// Where the selection covers nothing the result is `old`, so only the part of the content +/// bounds the selection reaches is blended into a copy of `old`: a small selection over distant +/// sparse content no longer expands the empty space between them. Refused, before any dense +/// buffer, when that part would still pass the working budget. +fn mix_by_selection(old: &Surface, new: &Surface, sel: &Surface) -> Result { + let content = old.content_bounds().union(&new.content_bounds()); + // Outside its tiles the selection's coverage is its default: an empty default lets the + // blend keep to the selection's bounds. + let sel_default_empty = sel.default_pixel().first().is_none_or(|v| *v <= 0.0); + let area = if sel_default_empty { content.intersect(&sel.content_bounds()) } else { content }; + let mut out = old.clone(); if area.is_empty() { - return out; + return Ok(out); } let fmt = old.format(); let n = fmt.channels(); + crate::allocation::check_dense(area, (n as u64).saturating_mul(12), "blending Liquify through the selection")?; let (o, w) = (old.read_region(area), new.read_region(area)); let mut r = vec![0.0f32; o.len()]; let aw = area.width() as usize; @@ -189,7 +199,7 @@ fn mix_by_selection(old: &Surface, new: &Surface, sel: &Surface) -> Surface { } out.write_region(area, &r); out.prune(); - out + Ok(out) } /// Liquifies a surface over `canvas` (the field's extent). @@ -344,7 +354,7 @@ fn liquify(s: &mut Session, p: &Value) -> Result { &|surf, sel, _| { let out = apply_liquify(surf, &field); Ok(match sel { - Some(sel) => mix_by_selection(surf, &out, sel), + Some(sel) => mix_by_selection(surf, &out, sel)?, None => out, }) }, diff --git a/crates/engine/src/cmd/edit_menu_cmds.rs b/crates/engine/src/cmd/edit_menu_cmds.rs index 98ea8b4619..b021ce0cc5 100644 --- a/crates/engine/src/cmd/edit_menu_cmds.rs +++ b/crates/engine/src/cmd/edit_menu_cmds.rs @@ -23,8 +23,12 @@ use crate::{EngineError, Result, Session}; #[derive(Clone, Debug, PartialEq)] pub struct FadeSource { pub doc: DocId, - /// Document revision right after the command; any later change disables Fade. + /// Document revision right after the command, or after a later step that only showed or hid + /// other layers (#13805); any other change disables Fade. pub revision: u64, + /// History id of the state before the command, which Fade blends back towards. Steps that only + /// showed or hid other layers can sit between that state and the current one. + pub before: Option, pub target: FadeTarget, pub label: String, } @@ -70,10 +74,12 @@ fn fadeable(id: &str) -> bool { /// Called after every successful command: remember a fadeable result. pub(crate) fn after_command(s: &mut Session, id: &str, params: &Value) { if !fadeable(id) { + keep_after_visibility(s, id, params); return; } let Some(st) = s.active() else { return }; let label = st.history.undo_label().unwrap_or(id).to_string(); + let before = st.history.past_len().checked_sub(1).and_then(|i| st.history.row_id(i)); let prev = st.history.state(st.history.past_len().wrapping_sub(1)); let prev = prev.as_deref(); let surf_eq = |a: Option<&Surface>, b: Option<&Surface>| match (a, b) { @@ -100,7 +106,7 @@ pub(crate) fn after_command(s: &mut Session, id: &str, params: &Value) { } let channel = channel.filter(|target| prev.is_none_or(|prev| !surf_eq(channel_surface(&st.doc, target), channel_surface(prev, target)))); if let Some(target) = channel { - s.edit_state.fade = Some(FadeSource { doc: st.doc.id, revision: st.revision, target, label }); + s.edit_state.fade = Some(FadeSource { doc: st.doc.id, revision: st.revision, before, target, label }); return; } let Some(layer) = st.active_layer else { return }; @@ -113,7 +119,35 @@ pub(crate) fn after_command(s: &mut Session, id: &str, params: &Value) { && !surf_eq(now.and_then(|l| l.mask.as_ref().map(|m| &m.surface)), was.and_then(|l| l.mask.as_ref().map(|m| &m.surface))) }); let target = if mask { FadeTarget::Mask(layer) } else { FadeTarget::Pixels(layer) }; - s.edit_state.fade = Some(FadeSource { doc: st.doc.id, revision: st.revision, target, label }); + s.edit_state.fade = Some(FadeSource { doc: st.doc.id, revision: st.revision, before, target, label }); +} + +/// Hiding or showing another layer right after a fadeable step keeps Fade available, as in +/// Photoshop (#13805): Fade still blends the step back towards the state before it. A step that +/// shows or hides the faded layer itself leaves Fade disabled. +fn keep_after_visibility(s: &mut Session, id: &str, params: &Value) { + let only_visibility = match id { + "layer.hideLayers" | "layer.showLayers" | "layer.showOnly" => true, + // The Layers panel's eye. + "layer.setProps" => { + params.as_object().is_some_and(|o| o.contains_key("visible") && o.keys().all(|k| matches!(k.as_str(), "layer" | "layers" | "visible" | "coalesce"))) + } + _ => false, + }; + let (Some(st), Some(f)) = (s.active(), s.edit_state.fade.as_ref()) else { return }; + let (FadeTarget::Pixels(layer) | FadeTarget::Mask(layer)) = f.target else { return }; + // Each of these commands changes the document once, so Fade was available right before it. + if !only_visibility || f.doc != st.doc.id || f.revision.checked_add(1) != Some(st.revision) { + return; + } + let visible = |doc: &Document| doc.layer(layer).map(|l| l.visible); + if fade::before_state(st, f).is_none_or(|before| visible(&before) != visible(&st.doc)) { + return; + } + let revision = st.revision; + if let Some(f) = s.edit_state.fade.as_mut() { + f.revision = revision; + } } /// Tile identity of a surface (pointer equality of its COW tiles). @@ -329,7 +363,7 @@ pub fn specs() -> Vec { "Fade…", ["Edit"], Some("Cmd+Shift+F"), - r##"{"opacity":0..100=100,"mode":"normal|multiply|screen|overlay|softLight|hardLight|darken|lighten|difference|color|luminosity"}"##, + r##"{"opacity":0..100=100,"mode":"normal|dissolve|darken|multiply|colorBurn|linearBurn|darkerColor|lighten|screen|colorDodge|linearDodge|lighterColor|overlay|softLight|hardLight|vividLight|linearLight|pinLight|hardMix|difference|exclusion|subtract|divide|hue|saturation|color|luminosity"}"##, can_fade, fade ), @@ -415,3 +449,7 @@ pub fn custom_shapes(s: &Session) -> &[CustomShape] { #[cfg(test)] #[path = "edit_menu_cmds/tests.rs"] mod tests; + +#[cfg(test)] +#[path = "edit_menu_cmds/fade_visibility_tests.rs"] +mod fade_visibility_tests; diff --git a/crates/engine/src/cmd/edit_menu_cmds/fade.rs b/crates/engine/src/cmd/edit_menu_cmds/fade.rs index ad767c584c..e8c797b212 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/fade.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/fade.rs @@ -1,6 +1,6 @@ use super::{ - BlendMode, Document, EngineError, FadeTarget, Rect, Result, Session, Surface, Value, bad, blend_from_str, f32_or, from_rgba_into, json, str_or, surface_of, - surface_of_mut, to_rgba, + BlendMode, Document, EngineError, FadeSource, FadeTarget, Rect, Result, Session, Surface, Value, bad, blend_from_str, f32_or, from_rgba_into, json, str_or, + surface_of, surface_of_mut, to_rgba, }; // ------------------------------------------------------------------ Fade @@ -8,7 +8,7 @@ use super::{ pub(super) fn can_fade(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; let f = s.edit_state.fade.as_ref().ok_or("nothing to fade")?; - if f.doc != st.doc.id || f.revision != st.revision || !st.history.can_undo() { + if f.doc != st.doc.id || f.revision != st.revision || before_state(st, f).is_none() { return Err("Fade is only available right after a filter, adjustment or painting step".into()); } if surface_of(&st.doc, f.target).is_none() { @@ -20,17 +20,38 @@ pub(super) fn can_fade(s: &Session) -> std::result::Result<(), String> { Ok(()) } +/// The state before the faded step, which Fade blends back towards, while the history holds it. +pub(super) fn before_state(st: &crate::DocState, f: &FadeSource) -> Option> { + let i = st.history.row_of(f.before?)?; + if i < st.history.past_len() { st.history.state(i) } else { None } +} + /// Blend `after` back towards `before` over `area`: `before + opacity × (B(before, after) − before)` -/// with blend mode `mode` (premultiplied, so alpha changes fade too). +/// with blend mode `mode` (premultiplied, so alpha changes fade too). Dissolve instead takes, per +/// pixel, `after` or `before` whole, with `opacity` as the odds of `after`. pub fn fade_surface(before: &Surface, after: &mut Surface, area: Rect, mode: BlendMode, opacity: f32) -> Result<()> { let fmt = after.format(); let n = fmt.channels(); - if area.is_empty() || n == 0 { + let k = opacity.clamp(0.0, 1.0); + // Dissolve at 100 % keeps every pixel of the step's result. + if area.is_empty() || n == 0 || (mode == BlendMode::Dissolve && k >= 1.0) { return Ok(()); } let b = crate::allocation::read_region(before, area, "fading pixels")?; let mut a = crate::allocation::read_region(after, area, "fading pixels")?; - let k = opacity.clamp(0.0, 1.0); + if mode == BlendMode::Dissolve { + // Dissolve: each pixel is the step's result or the pixel before it, alpha included, never + // a mix; the opacity is the odds of the result. The noise follows the pixel's position, + // so the pick is the same across tiles and between the preview and OK (#13809). + let at = (area.y0..area.y1).flat_map(|y| (area.x0..area.x1).map(move |x| (x, y))); + for ((pa, pb), (x, y)) in a.chunks_exact_mut(n).zip(b.chunks_exact(n)).zip(at) { + if photocraft_color::dither_noise(x, y) >= k { + pa.copy_from_slice(pb); + } + } + after.try_write_region(area, &a)?; + return Ok(()); + } let lerp_premul = |pb: &[f32], pa: &[f32], out: &mut [f32], alpha: bool| { let m = out.len(); if !alpha { @@ -84,7 +105,7 @@ fn fade_job(s: &Session, p: &Value) -> Result { let opacity = f32_or(p, "opacity", 100.0).clamp(0.0, 100.0) / 100.0; let mode = blend_from_str(str_or(p, "mode", "normal")).ok_or_else(|| bad(cmd, "unknown blend mode"))?; let st = s.active().ok_or(EngineError::NoDocument)?; - let prev = st.history.past_len().checked_sub(1).and_then(|i| st.history.state(i)).ok_or_else(|| bad(cmd, "no previous state"))?; + let prev = before_state(st, &src).ok_or_else(|| bad(cmd, "no previous state"))?; let before = surface_of(&prev, src.target).cloned().ok_or_else(|| EngineError::Other("the layer or channel did not exist before this step".into()))?; let now = surface_of(&st.doc, src.target).ok_or_else(|| EngineError::Other("the faded layer or channel no longer exists".into()))?; if now.format() != before.format() { @@ -135,3 +156,7 @@ pub fn fade_preview(s: &Session, p: &Value) -> Result { let doc = Document::clone(&s.active().ok_or(EngineError::NoDocument)?.doc); Ok(FadePreview { doc, job }) } + +#[cfg(test)] +#[path = "fade_dissolve_tests.rs"] +mod dissolve_tests; diff --git a/crates/engine/src/cmd/edit_menu_cmds/fade_dissolve_tests.rs b/crates/engine/src/cmd/edit_menu_cmds/fade_dissolve_tests.rs new file mode 100644 index 0000000000..012b7cbc8f --- /dev/null +++ b/crates/engine/src/cmd/edit_menu_cmds/fade_dissolve_tests.rs @@ -0,0 +1,130 @@ +//! #13809: Edit › Fade in Dissolve picks, per pixel, the pixel before the step or the step's +//! result, never a mix of the two; the opacity is the odds of the result. + +use super::*; + +const W: i32 = 400; +const H: i32 = 300; + +fn bounds() -> Rect { + Rect::new(0, 0, W, H) +} + +/// The issue's test document: white Background plus an opaque layer `Paint` of four blocks and a +/// yellow square. +fn blocks_session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": W, "height": H, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap(); + s.edit("paint", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(Rect::new(0, 0, 200, 150), &[1.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(200, 0, 400, 150), &[0.0, 128.0 / 255.0, 1.0, 1.0]); + surf.fill_rect(Rect::new(0, 150, 200, 300), &[64.0 / 255.0, 200.0 / 255.0, 64.0 / 255.0, 1.0]); + surf.fill_rect(Rect::new(200, 150, 400, 300), &[128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]); + surf.fill_rect(Rect::new(50, 50, 150, 150), &[1.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +/// The active layer's pixels over the canvas, one `channels`-long run per pixel. +fn layer_pixels(doc: &Document, s: &Session) -> (Vec, usize) { + let surf = doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap(); + let mut out = vec![0.0; (W * H) as usize * surf.channels()]; + surf.read_region_into(bounds(), &mut out); + (out, surf.channels()) +} + +fn active_pixels(s: &Session) -> (Vec, usize) { + layer_pixels(&s.active().unwrap().doc, s) +} + +/// How many pixels are exactly the step's result; panics on a pixel that is neither the base +/// nor the result. +fn count_picks(base: &[f32], top: &[f32], faded: &[f32], n: usize, what: &str) -> usize { + let mut picked = 0; + for (i, ((b, t), f)) in base.chunks_exact(n).zip(top.chunks_exact(n)).zip(faded.chunks_exact(n)).enumerate() { + if f == t { + picked += 1; + } else { + assert_eq!(f, b, "{what}: pixel ({}, {}) is a mix of {b:?} and {t:?}", i % W as usize, i / W as usize); + } + } + picked +} + +#[test] +fn dissolve_picks_the_base_or_the_inverted_pixel_at_every_depth() { + for depth in [8, 16, 32] { + let mut s = blocks_session(depth); + let (base, n) = active_pixels(&s); + s.execute("image.adjustments.invert", json!({})).unwrap(); + let (top, _) = active_pixels(&s); + s.execute("edit.fade", json!({"opacity": 37, "mode": "dissolve"})).unwrap(); + let (faded, _) = active_pixels(&s); + let picked = count_picks(&base, &top, &faded, n, &format!("depth {depth}")); + let share = picked as f64 / f64::from(W * H); + assert!((share - 0.37).abs() <= 0.03, "depth {depth}: {:.1} % of the pixels took the inverted value", share * 100.0); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Fade Invert")); + } +} + +#[test] +fn dissolve_at_100_is_normal_at_100_and_at_0_leaves_the_base() { + for depth in [8, 16, 32] { + let faded = |opacity: u32, mode: &str| { + let mut s = blocks_session(depth); + let (base, _) = active_pixels(&s); + s.execute("image.adjustments.invert", json!({})).unwrap(); + let (top, _) = active_pixels(&s); + s.execute("edit.fade", json!({"opacity": opacity, "mode": mode})).unwrap(); + (base, top, active_pixels(&s).0) + }; + let (_, top, dissolve_full) = faded(100, "dissolve"); + assert!(dissolve_full == top, "depth {depth}: Dissolve 100 % is the step's result"); + assert!(dissolve_full == faded(100, "normal").2, "depth {depth}: Dissolve 100 % equals Normal 100 %"); + let (base, _, dissolve_none) = faded(0, "dissolve"); + assert!(dissolve_none == base, "depth {depth}: Dissolve 0 % leaves the base"); + } +} + +/// A blurred red square on a transparent layer: each pixel takes the blurred value, alpha +/// included, or keeps the one before the blur, so the soft edge never becomes half as opaque. +#[test] +fn dissolve_picks_alpha_with_the_colour() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": W, "height": H, "depth": 8, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "T"})).unwrap(); + s.edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(150, 100, 250, 200), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + let (base, n) = active_pixels(&s); + s.execute("filter.blur.gaussianBlur", json!({"radius": 10})).unwrap(); + let (top, _) = active_pixels(&s); + s.execute("edit.fade", json!({"opacity": 50, "mode": "dissolve"})).unwrap(); + let (faded, _) = active_pixels(&s); + count_picks(&base, &top, &faded, n, "blurred square"); + // Along y = 150, outside the square's left edge: alpha 0 or the blur's, both seen. + let alpha = |px: &[f32], x: usize| px[(150 * W as usize + x) * n + n - 1]; + let row: Vec = (130..150).map(|x| alpha(&faded, x)).collect(); + assert!(row.iter().zip(130..150).all(|(&a, x)| a == 0.0 || a == alpha(&top, x)), "{row:?}"); + assert!(row.contains(&0.0) && row.iter().any(|&a| a > 0.0), "both picks along the edge: {row:?}"); +} + +/// The pick depends only on the pixel's position, so the dialog's preview is what OK applies +/// and the same params give the same pattern again. +#[test] +fn dissolve_preview_is_what_ok_applies() { + let mut s = blocks_session(8); + s.execute("image.adjustments.invert", json!({})).unwrap(); + let p = json!({"opacity": 37, "mode": "dissolve"}); + let preview = fade_preview(&s, &p).and_then(FadePreview::render).unwrap(); + let again = fade_preview(&s, &p).and_then(FadePreview::render).unwrap(); + assert!(layer_pixels(&preview, &s).0 == layer_pixels(&again, &s).0, "the same params give the same pattern"); + s.execute("edit.fade", p).unwrap(); + assert!(layer_pixels(&preview, &s).0 == active_pixels(&s).0, "the preview is what OK applies"); +} diff --git a/crates/engine/src/cmd/edit_menu_cmds/fade_visibility_tests.rs b/crates/engine/src/cmd/edit_menu_cmds/fade_visibility_tests.rs new file mode 100644 index 0000000000..a534a927e0 --- /dev/null +++ b/crates/engine/src/cmd/edit_menu_cmds/fade_visibility_tests.rs @@ -0,0 +1,119 @@ +//! #13805: hiding or showing another layer after a fadeable step keeps Edit › Fade available, as in +//! Photoshop; other steps in between still disable it. + +use super::*; +use photocraft_doc::LayerId; + +/// A command and its params, given the Background and the faded layer. +type Step = (&'static str, fn(LayerId, LayerId) -> Value); + +/// A white Background and a layer `Paint` with a black square, made active and blurred: +/// (session, Background, Paint, Paint's edge pixel before the blur). +fn blurred() -> (Session, LayerId, LayerId, Vec) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "depth": 8, "background": "white"})).unwrap(); + let bg = s.active().unwrap().active_layer.unwrap(); + let paint = LayerId(s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap()["layer"].as_u64().unwrap()); + s.execute("select.rect", json!({"x": 16, "y": 16, "width": 16, "height": 16})).unwrap(); + s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + let sharp = pixel(&s, paint); + s.execute("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap(); + assert_ne!(pixel(&s, paint), sharp, "the blur changed the edge pixel"); + assert!(s.is_enabled("edit.fade"), "Fade follows the blur"); + (s, bg, paint, sharp) +} + +fn pixel(s: &Session, layer: LayerId) -> Vec { + s.active().unwrap().doc.layer(layer).unwrap().surface().unwrap().pixel(16, 20) +} + +fn visible(s: &Session, layer: LayerId) -> bool { + s.active().unwrap().doc.layer(layer).unwrap().visible +} + +/// Hiding the Background after the blur, by each way of hiding it, with visibility changes +/// recorded in History or not: Fade stays available and fades the blur towards the square as it +/// was before the blur, and the Background stays hidden. +#[test] +fn hiding_another_layer_keeps_fade() { + let hides: [Step; 3] = [ + ("layer.hideLayers", |bg, _| json!({"layer": bg.0})), + ("layer.setProps", |bg, _| json!({"layer": bg.0, "visible": false})), + ("layer.showOnly", |_, _| json!({})), + ]; + for undoable in [true, false] { + for (hide, params) in hides { + let (mut s, bg, paint, sharp) = blurred(); + s.execute("history.options", json!({"makeLayerVisibilityChangesUndoable": undoable})).unwrap(); + assert!(s.is_enabled("edit.fade"), "History Options don't touch the document"); + let steps = s.active().unwrap().history.past_len(); + + s.execute(hide, params(bg, paint)).unwrap(); + assert!(!visible(&s, bg), "{hide} undoable={undoable}: the Background is hidden"); + assert_eq!(s.active().unwrap().history.past_len(), steps + usize::from(undoable), "{hide} undoable={undoable}"); + assert!(s.is_enabled("edit.fade"), "{hide} undoable={undoable}: Fade stays available"); + let preview = fade_preview(&s, &json!({"opacity": 0})).and_then(FadePreview::render).unwrap(); + assert_eq!(preview.layer(paint).unwrap().surface().unwrap().pixel(16, 20), sharp, "{hide} undoable={undoable}: the preview fades the blur"); + + s.execute("edit.fade", json!({"opacity": 0})).unwrap(); + assert_eq!(pixel(&s, paint), sharp, "{hide} undoable={undoable}: 0 % fades the blur away"); + assert!(!visible(&s, bg), "{hide} undoable={undoable}: Fade leaves the Background hidden"); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Fade Gaussian Blur")); + assert!(!s.is_enabled("edit.fade"), "{hide} undoable={undoable}: Fade can't repeat"); + } + } +} + +/// Showing the hidden layer again keeps Fade available too, and Fade at 50 % lands halfway +/// between the square before the blur and after it. +#[test] +fn hiding_and_showing_another_layer_keeps_fade() { + let (mut s, bg, paint, sharp) = blurred(); + let blurred_px = pixel(&s, paint); + s.execute("layer.hideLayers", json!({"layer": bg.0})).unwrap(); + s.execute("layer.showLayers", json!({"layer": bg.0})).unwrap(); + assert!(s.is_enabled("edit.fade")); + s.execute("edit.fade", json!({"opacity": 50})).unwrap(); + let half = pixel(&s, paint); + for c in 0..half.len() { + assert!((half[c] - (sharp[c] + blurred_px[c]) / 2.0).abs() < 0.01, "channel {c}: {half:?} between {sharp:?} and {blurred_px:?}"); + } +} + +/// Selecting another layer, or a step that is neither fadeable nor a visibility change, disables +/// Fade as before. +#[test] +fn other_steps_still_disable_fade() { + let steps: [Step; 4] = [ + ("layer.select", |bg, _| json!({"layer": bg.0})), + ("select.all", |_, _| json!({})), + ("view.colorSamplers.add", |_, _| json!({"x": 15, "y": 15})), + ("layer.setProps", |_, paint| json!({"layer": paint.0, "opacity": 0.5})), + ]; + for (step, params) in steps { + let (mut s, bg, paint, _) = blurred(); + s.execute(step, params(bg, paint)).unwrap(); + assert!(!s.is_enabled("edit.fade"), "{step}: Fade is disabled"); + assert!(s.execute("edit.fade", json!({})).is_err(), "{step}"); + // A visibility change afterwards doesn't bring it back. + s.execute("layer.hideLayers", json!({"layer": bg.0})).unwrap(); + assert!(!s.is_enabled("edit.fade"), "{step}, then a hide: Fade stays disabled"); + } + // A hide together with another property is not a visibility change only. + let (mut s, bg, _, _) = blurred(); + s.execute("layer.setProps", json!({"layer": bg.0, "visible": false, "name": "Back"})).unwrap(); + assert!(!s.is_enabled("edit.fade"), "a hide with a rename disables Fade"); +} + +/// Hiding the faded layer itself was not measured in the reference: Fade stays disabled, by itself +/// and when a later step shows the layer again. +#[test] +fn hiding_the_faded_layer_disables_fade() { + let (mut s, _, paint, _) = blurred(); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(!visible(&s, paint), "Hide Layers hid the active, faded layer"); + assert!(!s.is_enabled("edit.fade")); + s.execute("layer.showLayers", json!({"layer": paint.0})).unwrap(); + assert!(!s.is_enabled("edit.fade"), "showing it again doesn't bring Fade back"); +} diff --git a/crates/engine/src/cmd/eraser_cmds.rs b/crates/engine/src/cmd/eraser_cmds.rs index 473699aa63..4887228dfc 100644 --- a/crates/engine/src/cmd/eraser_cmds.rs +++ b/crates/engine/src/cmd/eraser_cmds.rs @@ -7,6 +7,10 @@ //! layers with locked transparency; the Background Eraser erases them to transparency and leaves //! the lock on. Both respect the selection, work in the layer's own colour model and depth, and are //! one undo step per click / stroke. +//! +//! The Magic Eraser refuses Indexed Color and Bitmap documents with the reference's alerts +//! ([`MAGIC_ERASER_INDEXED_ERROR`] and [`MAGIC_ERASER_BITMAP_ERROR`], #12032), before it samples +//! anything, so a refused click leaves the document exactly as it was. use photocraft_algo::selection as sel; use photocraft_color::{ColorMode, SampleType}; @@ -79,6 +83,28 @@ fn damage(s: &mut Session, dmg: Rect, erased: bool) -> Value { json!({ "erased": erased, "damage": [dmg.x0, dmg.y0, dmg.width(), dmg.height()] }) } +/// The reference's alert for a Magic Eraser click in an Indexed Color document (#12032), measured: +/// one alert with an OK button. The UI shows this text through `tl!` (English is the catalog +/// source); the command returns it as its error. +pub const MAGIC_ERASER_INDEXED_ERROR: &str = + "Could not use the magic eraser because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +/// The same alert for a Bitmap document (#12032), which points at Grayscale instead. +pub const MAGIC_ERASER_BITMAP_ERROR: &str = + "Could not use the magic eraser because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// The alert `doc` gets instead of a Magic Eraser click, or `None` when the click may erase +/// (#12032). Indexed Color and Bitmap are the two measured refusals, at every bit depth; Duotone +/// and Multichannel are not measured and keep erasing, as do RGB, Grayscale, CMYK and Lab. +/// The text is exactly what `paint.magicEraser` answers with, so the tool can refuse the press with +/// what the command would refuse. +pub fn magic_eraser_refusal(doc: &Document) -> Option<&'static str> { + match doc.mode { + ColorMode::Indexed => Some(MAGIC_ERASER_INDEXED_ERROR), + ColorMode::Bitmap => Some(MAGIC_ERASER_BITMAP_ERROR), + _ => None, + } +} + /// `paint.magicEraser`: erase the wand region around `(x, y)`. fn magic_eraser(s: &mut Session, p: &Value) -> Result { const CMD: &str = "paint.magicEraser"; @@ -89,6 +115,13 @@ fn magic_eraser(s: &mut Session, p: &Value) -> Result { let tolerance = number(p, CMD, "tolerance", 32.0, 0.0..=255.0)? as f32; let opacity = number(p, CMD, "opacity", 100.0, 1.0..=100.0)? as f32 / 100.0; let (anti_alias, contiguous, sample_all) = (flag(p, "antiAlias", true), flag(p, "contiguous", true), flag(p, "sampleAllLayers", false)); + // #12032: an Indexed Color or a Bitmap document gets the reference's alert before anything is + // sampled or edited, so the click changes nothing: no pixels, no selection, no History step, + // and the Background stays a Background. The tool refuses the press with this same text + // (`eraser_ui::click`), which is why the check belongs to the command. + if let Some(msg) = s.active().and_then(|st| magic_eraser_refusal(&st.doc)) { + return Err(EngineError::Other(msg.into())); + } let id = active_pixel_layer(s, p, CMD)?; { let d = s.active().ok_or(EngineError::NoDocument)?; @@ -187,9 +220,10 @@ fn background_eraser(s: &mut Session, p: &Value) -> Result { let surf = l.surface_mut().ok_or_else(|| bad(CMD, "not a pixel layer"))?; if let Some(colors) = colors { let effect = selected_background_effect(surf, &bs, colors, bg); - Ok(photocraft_paint::retouch::apply_dab_stroke(surf, &background_eraser_stroke(&stroke), selection.as_ref(), false, 0, effect)) + photocraft_paint::retouch::apply_dab_stroke(surf, &background_eraser_stroke(&stroke), selection.as_ref(), false, 0, effect) + .map_err(|e| bad(CMD, e.to_string())) } else { - Ok(apply_background_eraser(surf, &stroke, &bs, selection.as_ref())) + apply_background_eraser(surf, &stroke, &bs, selection.as_ref()).map_err(|e| bad(CMD, e.to_string())) } })?; Ok(damage(s, dmg, true)) @@ -279,7 +313,7 @@ pub fn specs() -> Vec { label: "Magic Eraser", menu: &[], shortcut: None, - params: r##"{"x":px,"y":px,"tolerance":0..255=32,"antiAlias":bool=true,"contiguous":bool=true,"sampleAllLayers":bool=false,"opacity":1..100=100}"##, + params: r##"{"x":px,"y":px,"tolerance":0..255=32,"antiAlias":bool=true,"contiguous":bool=true,"sampleAllLayers":bool=false,"opacity":1..100=100} (one undo step; a click off the canvas erases nothing and records no step; refused with the tool's alert and nothing changes: an Indexed Color document answers "Could not use the magic eraser because it does not work with Indexed Color images (convert image to RGB Color mode to edit).", a Bitmap document "Could not use the magic eraser because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; Duotone and Multichannel erase as before)"##, enabled: has_pixel_layer, run: magic_eraser, journal: true, @@ -297,6 +331,8 @@ pub fn specs() -> Vec { ] } +#[cfg(test)] +mod magic_eraser_mode_refusal_tests; #[cfg(test)] mod magic_eraser_tolerance_tests; #[cfg(test)] diff --git a/crates/engine/src/cmd/eraser_cmds/magic_eraser_mode_refusal_tests.rs b/crates/engine/src/cmd/eraser_cmds/magic_eraser_mode_refusal_tests.rs new file mode 100644 index 0000000000..b56d839310 --- /dev/null +++ b/crates/engine/src/cmd/eraser_cmds/magic_eraser_mode_refusal_tests.rs @@ -0,0 +1,104 @@ +//! #12032: the Magic Eraser refuses Indexed Color and Bitmap documents with the reference's +//! alerts, and refuses them *before* it samples or edits anything: no History step, the Background +//! stays a Background, the pixels and the selection stay as they were. Duotone and Multichannel +//! are not measured, so they keep today's behaviour; the modes and depths the issue lists as +//! working (RGB, Grayscale, CMYK and Lab at 8 bits, RGB at 16 and 32 bits) still erase. + +use super::*; +use photocraft_doc::{Color, SampleType, Size}; + +/// The reference's alert for an Indexed Color document, measured (#12032); the alert has one OK +/// button. Spelled out here rather than taken from the command, so the test fails if the text the +/// app shows ever drifts from what was measured. +const INDEXED: &str = "Could not use the magic eraser because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +/// Its alert for a Bitmap document, measured (#12032). +const BITMAP: &str = "Could not use the magic eraser because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// A 64x48 document in `mode` at `depth`: a white Background - one flat colour, so a Magic Eraser +/// click on it would wipe the canvas out - with a live selection. Both must survive a refusal. +fn session(mode: photocraft_color::ColorMode, depth: SampleType) -> Session { + let d = Document::with_background("palette", Size::new(64, 48), mode, depth, Color::WHITE); + let mut s = Session::new(); + s.add_document(d, None); + s.execute("select.rect", json!({"x": 4, "y": 4, "width": 20, "height": 20, "antiAlias": false})).unwrap(); + s +} + +/// What a refused click must leave exactly as it was: the document itself, the History depth, one +/// pixel, and the selection. +fn snapshot(s: &Session) -> (std::sync::Arc, usize, Vec, Option) { + let st = s.active().unwrap(); + let pixels = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(2, 2).to_vec(); + (st.doc.clone(), st.history.past_len(), pixels, st.doc.selection.clone()) +} + +/// The text `paint.magicEraser` answers this click with, panicking with `case` in its message when +/// it erases or answers something else. +fn alert(s: &mut Session, case: &str, want: &str, p: Value) -> String { + match s.execute("paint.magicEraser", p.clone()) { + Err(e) if e.to_string() == want => e.to_string(), + Err(e) => panic!("{case}: refused with the wrong text: {e}"), + Ok(r) => panic!("{case}: the click erased instead of being refused: {r}"), + } +} + +#[test] +fn magic_eraser_refuses_indexed_and_bitmap_with_the_reference_alerts() { + for (case, mode, want) in [("Indexed", photocraft_color::ColorMode::Indexed, INDEXED), ("Bitmap", photocraft_color::ColorMode::Bitmap, BITMAP)] { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + // The refusal is the same whatever else the click asks for: sampling every layer or + // only this one, the whole canvas or one colour, inside the selection or not. + for p in [ + json!({"x": 2, "y": 2, "antiAlias": false}), + json!({"x": 12, "y": 12, "antiAlias": false}), + json!({"x": 2, "y": 2, "antiAlias": false, "sampleAllLayers": true}), + json!({"x": 2, "y": 2, "antiAlias": false, "contiguous": false, "tolerance": 255, "opacity": 1}), + ] { + let name = format!("{case} {depth:?} {p}"); + let mut s = session(mode, depth); + let (doc, steps, pixels, selection) = snapshot(&s); + let id = s.active().unwrap().active_layer.unwrap(); + assert_eq!(alert(&mut s, &name, want, p), want.to_string()); + let st = s.active().unwrap(); + // Nothing at all happened: not a History step, not a pixel, not the selection, and + // the Background is still a Background rather than the "Layer 0" the erase makes. + assert!(std::sync::Arc::ptr_eq(&doc, &st.doc), "{name}: the document is untouched"); + assert_eq!(st.history.past_len(), steps, "{name}: no History step"); + assert_eq!(st.doc.layer(id).unwrap().name, "Background", "{name}: the layer name"); + assert!(st.doc.is_background(id), "{name}: still a Background"); + assert_eq!(st.doc.layer(id).unwrap().surface().unwrap().rgba(2, 2).to_vec(), pixels, "{name}: pixels unchanged"); + assert_eq!(st.doc.selection, selection, "{name}: the selection is unchanged"); + } + } + } +} + +#[test] +fn magic_eraser_still_erases_the_measured_modes_and_depths() { + for (mode, depth) in [("rgb", 8), ("gray", 8), ("cmyk", 8), ("lab", 8), ("rgb", 16), ("rgb", 32)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "mode": mode, "depth": depth})).unwrap(); + let h = s.active().unwrap().history.past_len(); + let id = s.active().unwrap().active_layer.unwrap(); + let r = s.execute("paint.magicEraser", json!({"x": 2, "y": 2, "antiAlias": false})).unwrap(); + assert_eq!(r["erased"], true, "{mode} {depth}: still erases"); + assert_eq!(s.active().unwrap().history.past_len(), h + 1, "{mode} {depth}: one undo step"); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer(id).unwrap().name, "Layer 0", "{mode} {depth}: the Background became a layer"); + assert_eq!(st.doc.layer(id).unwrap().surface().unwrap().rgba(2, 2)[3], 0.0, "{mode} {depth}: erased to transparency"); + } +} + +/// Duotone and Multichannel are *not measured* (#12032), so they keep today's behaviour: the click +/// erases, and neither of the two alerts appears. +#[test] +fn duotone_and_multichannel_keep_todays_behaviour() { + for (case, mode) in [("Duotone", photocraft_color::ColorMode::Duotone), ("Multichannel", photocraft_color::ColorMode::Multichannel)] { + let mut s = session(mode, SampleType::U8); + let id = s.active().unwrap().active_layer.unwrap(); + let r = s.execute("paint.magicEraser", json!({"x": 2, "y": 2, "antiAlias": false})); + assert!(r.is_ok(), "{case}: keeps today's behaviour, answers {r:?}"); + assert_eq!(r.unwrap()["erased"], true, "{case}"); + assert_eq!(s.active().unwrap().doc.layer(id).unwrap().name, "Layer 0", "{case}"); + } +} diff --git a/crates/engine/src/cmd/extra_cmds.rs b/crates/engine/src/cmd/extra_cmds.rs index 96ac6d88c3..30bedcec9f 100644 --- a/crates/engine/src/cmd/extra_cmds.rs +++ b/crates/engine/src/cmd/extra_cmds.rs @@ -242,7 +242,23 @@ fn equalize(s: &mut Session, p: &Value) -> Result { Some(Value::Bool(only)) => !only, Some(_) => return Err(EngineError::BadParams { cmd: "image.adjustments.equalize".into(), msg: "selectedAreaOnly must be true or false".into() }), }; - map_pixels_in(s, "Equalize", p, whole, |_, px, cover| { + // A smart filter's selection is its output mask, so it cannot also stand for "histogram from + // the selection, applied to everything": refuse instead of quietly leaving the rest unchanged. + if whole && s.active().is_some_and(|d| d.doc.selection.is_some()) && crate::adjust_cmds::smart_pixel_target(s, p)?.is_some() { + return Err(EngineError::BadParams { + cmd: "image.adjustments.equalize".into(), + msg: "Equalize Entire Image Based On Selected Area is not available on a smart object yet".into(), + }); + } + if crate::adjust_cmds::adjust_as_smart_filter(s, "equalize", "Equalize", p)? { + return Ok(Value::Null); + } + map_pixels_in(s, "Equalize", p, whole, |_, px, cover| equalize_pixels(px, cover)) +} + +/// [`equalize`] on straight RGBA pixels with a coverage weight each (also run as a smart filter). +pub(crate) fn equalize_pixels(px: &mut [[f32; 4]], cover: &[f32]) { + { let mut hist = [0f64; 256]; for (p, &k) in px.iter().zip(cover) { if k > 0.0 && p[3] > 0.0 { @@ -269,7 +285,7 @@ fn equalize(s: &mut Session, p: &Value) -> Result { *v = map(*v); } } - }) + } } // ---------- transform presets ---------- @@ -727,11 +743,20 @@ pub(crate) fn kind_of(s: &Session, id: LayerId) -> Option<&'static str> { }) } +fn has_vector_mask(s: &Session, id: LayerId, only: Option<&str>) -> bool { + only.is_none() && s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| l.vector_mask.is_some()) +} + +/// Whether `rasterize_one` has something to do for this layer. +fn has_rasterize_work(s: &Session, id: LayerId, only: Option<&str>) -> bool { + kind_of(s, id).is_some_and(|k| only.is_none_or(|o| o == k)) || has_vector_mask(s, id, only) +} + /// Rasterize one layer; `only` restricts it to one kind. Without `only` (Rasterize › Layer / All /// Layers: "all vector data") a vector mask becomes a pixel mask too; layer effects stay live, as /// in Photoshop (Rasterize › Layer Style bakes them). Returns false when there was nothing to do. pub(crate) fn rasterize_one(s: &mut Session, id: LayerId, only: Option<&str>, key: &str) -> Result { - let vector_mask = only.is_none() && s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| l.vector_mask.is_some()); + let vector_mask = has_vector_mask(s, id, only); let content = rasterize_content(s, id, only, key)?; if vector_mask { s.execute("layer.rasterize.vectorMask", json!({"layer": id.0, "coalesce": key}))?; @@ -800,36 +825,75 @@ fn rasterize_content(s: &mut Session, id: LayerId, only: Option<&str>, key: &str /// rasterize"), every selected layer the command applies to, in one history step. pub(crate) fn rasterize(s: &mut Session, p: &Value, only: Option<&'static str>) -> Result { let ids = crate::layer_multi_cmds::targets(s, p)?; - let many = ids.len() > 1; - let key = step_key(s, "rasterize"); - let mut done = Vec::new(); - for id in ids { - if rasterize_one(s, id, only, &key)? { - done.push(id.0); - } + rasterize_layers(s, ids, only, rasterize_one) +} + +/// The history label of a Rasterize step: the kind it was limited to, or plain "Rasterize". +fn rasterize_label(only: Option<&str>) -> &'static str { + match only { + Some("type") => "Rasterize Type", + Some("shape") => "Rasterize Shape", + Some("fill") => "Rasterize Fill Content", + Some("smart") => "Rasterize Smart Object", + _ => "Rasterize", } - let Some(&first) = done.first() else { - return Err(EngineError::Other(match (only, many) { - (Some(k), false) => format!("the layer is not a {k} layer"), - (Some(k), true) => format!("none of the selected layers is a {k} layer"), - (None, false) => "the layer has nothing to rasterize".into(), - (None, true) => "none of the selected layers has anything to rasterize".into(), - })); - }; +} + +fn nothing_to_rasterize(only: Option<&str>, many: bool) -> EngineError { + EngineError::Other(match (only, many) { + (Some(k), false) => format!("the layer is not a {k} layer"), + (Some(k), true) => format!("none of the selected layers is a {k} layer"), + (None, false) => "the layer has nothing to rasterize".into(), + (None, true) => "none of the selected layers has anything to rasterize".into(), + }) +} + +/// Convert `ids` with `convert` as one history step; a layer that fails takes back the ones +/// converted before it (#4974). +fn rasterize_layers( + s: &mut Session, + ids: Vec, + only: Option<&str>, + convert: impl Fn(&mut Session, LayerId, Option<&str>, &str) -> Result, +) -> Result { + let many = ids.len() > 1; + // Refused before a step starts: a failed `compound` still moves the revision, and a command + // that changes nothing must leave it alone. + if !ids.iter().any(|&id| has_rasterize_work(s, id, only)) { + return Err(nothing_to_rasterize(only, many)); + } + let key = step_key(s, "rasterize"); + let (first, done) = crate::analysis_cmds::compound(s, rasterize_label(only), |s| { + let mut done = Vec::new(); + for id in ids { + if convert(s, id, only, &key)? { + done.push(id.0); + } + } + let Some(&first) = done.first() else { return Err(nothing_to_rasterize(only, many)) }; + Ok((first, done)) + })?; let active = s.active().and_then(|d| d.active_layer).map(|id| id.0).filter(|id| done.contains(id)); Ok(json!({"layer": active.unwrap_or(first), "layers": done})) } pub(crate) fn rasterize_all(s: &mut Session) -> Result { let ids: Vec = s.active().map(|d| d.doc.walk().into_iter().map(|(_, _, l)| l.id).collect()).unwrap_or_default(); - let key = step_key(s, "rasterizeAll"); - let mut n = 0; - for id in ids { - // Every sub-step shares one history entry via the coalescing key. - if rasterize_one(s, id, None, &key)? { - n += 1; - } + let ids: Vec = ids.into_iter().filter(|&id| has_rasterize_work(s, id, None)).collect(); + if ids.is_empty() { + return Ok(json!({"rasterized": 0})); } + let key = step_key(s, "rasterizeAll"); + let n = crate::analysis_cmds::compound(s, "Rasterize All Layers", |s| { + let mut n = 0; + for id in ids { + // Every sub-step shares one history entry via the coalescing key. + if rasterize_one(s, id, None, &key)? { + n += 1; + } + } + Ok(n) + })?; Ok(json!({"rasterized": n})) } @@ -906,7 +970,7 @@ pub fn specs() -> Vec { &["Image", "Adjustments"], None, r#"{"selectedAreaOnly":bool=true (with a selection, false equalizes the layer within the canvas by the selection's histogram)}"#, - has_pixels, + crate::adjust_cmds::has_adjustable, equalize ), spec!("image.revealAll", "Reveal All", &["Image"], None, "{}", has_doc, |s, _| { diff --git a/crates/engine/src/cmd/extra_cmds/tests.rs b/crates/engine/src/cmd/extra_cmds/tests.rs index 647a585a23..d85e7c9585 100644 --- a/crates/engine/src/cmd/extra_cmds/tests.rs +++ b/crates/engine/src/cmd/extra_cmds/tests.rs @@ -94,6 +94,10 @@ fn active(s: &Session) -> &Layer { d.doc.layer(d.active_layer.unwrap()).unwrap() } +fn layer_of(s: &Session, id: u64) -> &Layer { + doc(s).layer(LayerId(id)).unwrap() +} + fn pixel(s: &Session, x: i32, y: i32) -> Vec { active(s).surface().unwrap().pixel(x, y) } @@ -1165,6 +1169,54 @@ fn rasterize_fill_and_all_in_one_step() { assert!(doc(&s).walk().iter().all(|(_, _, l)| !matches!(l.content, LayerContent::Fill(_)))); } +/// #4974: Rasterize converts its layers as one step, so a layer that fails after another was +/// converted leaves the document, history, journal and dirty state as they were. +#[test] +fn a_later_layer_failing_takes_back_the_rasterized_ones() { + let mut s = session(8); + let a = s.execute("layer.newFillLayer.solidColor", json!({"color": "#00ff00"})).unwrap()["layer"].as_u64().unwrap(); + let b = s.execute("layer.newFillLayer.solidColor", json!({"color": "#0000ff"})).unwrap()["layer"].as_u64().unwrap(); + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let before = s.active().unwrap().doc.clone(); + let steps = s.active().unwrap().history.past_len(); + let journal = s.journal.len(); + + let ids = vec![LayerId(a), LayerId(b)]; + let r = rasterize_layers(&mut s, ids.clone(), None, |s, id, only, key| { + if id.0 == b { Err(EngineError::Other("second layer failed".into())) } else { rasterize_one(s, id, only, key) } + }); + assert!(r.is_err()); + assert!(matches!(layer_of(&s, a).content, LayerContent::Fill(_))); + assert!(matches!(layer_of(&s, b).content, LayerContent::Fill(_))); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before)); + assert_eq!(s.active().unwrap().history.past_len(), steps); + assert!(!s.active().unwrap().history.can_redo()); + assert_eq!(s.journal.len(), journal); + assert!(!s.active().unwrap().is_dirty()); + + // Without the failure both are converted in a single step. + rasterize_layers(&mut s, ids, None, rasterize_one).unwrap(); + assert!(matches!(layer_of(&s, a).content, LayerContent::Raster(_))); + assert!(matches!(layer_of(&s, b).content, LayerContent::Raster(_))); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1); +} + +/// A refused Rasterize starts no step: the revision and the saved state do not move. +#[test] +fn rasterize_with_nothing_to_convert_changes_nothing() { + let mut s = session(8); + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let (revision, steps) = (s.active().unwrap().revision, s.active().unwrap().history.past_len()); + assert!(s.execute("layer.rasterize.layer", json!({})).is_err()); + assert!(s.execute("layer.rasterize.type", json!({})).is_err()); + assert_eq!(s.execute("layer.rasterize.allLayers", json!({})).unwrap()["rasterized"], 0); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.active().unwrap().history.past_len(), steps); + assert!(!s.active().unwrap().is_dirty()); +} + #[test] fn rasterize_smart_object_layer() { let mut s = session(8); diff --git a/crates/engine/src/cmd/face_cmds.rs b/crates/engine/src/cmd/face_cmds.rs index 0ae0af3d35..1d7ef45dd8 100644 --- a/crates/engine/src/cmd/face_cmds.rs +++ b/crates/engine/src/cmd/face_cmds.rs @@ -28,6 +28,9 @@ pub fn detect(px: &[[f32; 4]], w: usize, h: usize, min_score: f32) -> Result, all_layers: bool, min_score: f32) -> Result> { let area = doc.bounds(); + // Both paths hold the whole canvas as straight RGBA f32, however few tiles the layers store: + // refuse a canvas past the working budget before allocating it. + crate::allocation::check_dense(area, 16, "face detection")?; let (w, h) = (area.width() as usize, area.height() as usize); let surface = active.and_then(|id| doc.layer(id)).and_then(|l| l.surface()).filter(|_| !all_layers); let px = match surface { diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 572c70ae60..633b25ff11 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -33,6 +33,7 @@ mod save; pub use batch_naming::plan as plan_batch_names; use batch_run::batch; +pub(crate) use batch_run::check_batch_depth; pub use batch_run::same_format as batch_same_format; use batch_run::same_format; #[cfg(not(target_arch = "wasm32"))] @@ -435,6 +436,10 @@ pub fn specs() -> Vec { #[path = "file_cmds/tests.rs"] mod tests; +#[cfg(test)] +#[path = "file_cmds/export_clut_cube_header_tests.rs"] +mod export_clut_cube_header_tests; + #[cfg(test)] #[path = "file_cmds/place_job_tests.rs"] mod place_job_tests; diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index b8ad5a137d..5eb6543c86 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -222,6 +222,10 @@ impl FileFailure { fn value(&self, key: &str, input: &str) -> Value { let mut failure = json!({"error": self.error.to_string()}); failure[key] = json!(input); + // Marks a nesting or playback-budget stop, which an enclosing batch step must not swallow. + if matches!(self.error, EngineError::BatchLimit(_)) { + failure["limit"] = json!(true); + } if let Some(result) = &self.result { failure["result"] = result.clone(); } @@ -239,10 +243,13 @@ fn process_outputs<'a>( // The scratch sessions have default preferences; a raw opens at the user's Raw Defaults. let raw_ppi = s.prefs().raw_defaults.resolution; let action_prefs = s.prefs().actions.clone(); + let authorize = s.authorize; let mut files = Vec::new(); let mut errors = Vec::new(); let mut written = OutputClaims::default(); let run = |scratch: &mut Session, out: &str| { + // Nested commands answer to the initiating session's authorization hook. + scratch.authorize = authorize; scratch.prefs.edit(|prefs| prefs.actions = action_prefs.clone()); f(scratch, out).map_err(FileFailure::from) }; @@ -661,6 +668,18 @@ pub(crate) fn batch_keeps_step(id: &str) -> bool { (batch_save_point(id) || !crate::actions_cmds::shell_save_command(id)) && !crate::actions_cmds::shell_view_command(id) } +/// Refuses a batch or droplet nested past [`MAX_BATCH_DEPTH`](crate::actions_cmds::MAX_BATCH_DEPTH), +/// before it reads or decodes anything: each level keeps its parent's scratch document open. +pub(crate) fn check_batch_depth(s: &Session, cmd: &str) -> Result<()> { + if s.actions.batch_depth >= crate::actions_cmds::MAX_BATCH_DEPTH { + return Err(EngineError::BatchLimit(format!( + "invalid parameters for `{cmd}`: batches and droplets are nested more than {} deep", + crate::actions_cmds::MAX_BATCH_DEPTH + ))); + } + Ok(()) +} + pub(crate) fn batch_action(list: &[crate::actions_cmds::Action], p: &Value) -> Result { const CMD: &str = "file.automate.batch"; if let Some(set) = p.get("set").filter(|v| !v.is_null()) { @@ -680,6 +699,7 @@ pub(crate) fn batch_action(list: &[crate::actions_cmds::Action], p: &Value) -> R /// Named actions carry their recursion context and both routes normalize recorded parameters. pub(super) fn batch(s: &mut Session, p: &Value) -> Result { let cmd = "file.automate.batch"; + check_batch_depth(s, cmd)?; let quiet_raw = match p.get("suppressOpenOptions") { None | Some(Value::Null) => false, Some(Value::Bool(value)) => *value, @@ -810,17 +830,19 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // A batch inside a played action charges its inputs × steps (at least one each: an input is read, // decoded and saved even with no steps) to the playback tree it is in and // hands the count on, so nested batches cannot multiply past the limit. A top-level named - // action starts fresh; standalone explicit steps retain their existing behavior. + // action starts fresh; standalone explicit steps retain their existing behavior. A batch nested + // in another batch (a droplet a droplet runs) is charged the same way, so the levels share one budget. let named = called_name.is_some(); + let nested = s.actions.playing > 0 || s.actions.batch_depth > 0; let mut playback_steps = 0; - if s.actions.playing > 0 || named { - let spent = if s.actions.playing > 0 { s.actions.playback_steps } else { 0 }; + if nested || named { + let spent = if nested { s.actions.playback_steps } else { 0 }; playback_steps = spent.saturating_add((steps.len().max(1) as u64).saturating_mul(if source == "open" { s.documents().len() } else { inputs.len() } as u64)); if playback_steps > crate::actions_cmds::MAX_PLAYBACK_STEPS { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: "this batch would exceed the action playback step limit".into() }); + return Err(EngineError::BatchLimit(format!("invalid parameters for `{cmd}`: this batch would exceed the action playback step limit"))); } - if s.actions.playing > 0 { + if nested { s.actions.playback_steps = playback_steps; } } @@ -833,6 +855,8 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { playback_steps, script_depth: s.actions.script_depth, script_steps: s.actions.script_steps, + budget_shared: nested, + batch_depth: s.actions.batch_depth.saturating_add(1), ..Default::default() }; if source == "open" { @@ -849,6 +873,9 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { let previous_playing = std::mem::replace(&mut s.actions.playing, actions.playing); let previous_stack = std::mem::replace(&mut s.actions.playback_stack, actions.playback_stack); let previous_steps = std::mem::replace(&mut s.actions.playback_steps, actions.playback_steps); + // The nesting depth and shared budget of the levels above travel with the run too. + let previous_shared = std::mem::replace(&mut s.actions.budget_shared, actions.budget_shared); + let previous_depth = std::mem::replace(&mut s.actions.batch_depth, actions.batch_depth); let previous_list = p.get("calledActions").is_some_and(|value| !value.is_null()).then(|| std::mem::replace(&mut s.actions.list, actions.list)); let owns_history = s.action_history.is_none() && s.prefs().actions.create_single_history_state; if owns_history { @@ -860,10 +887,12 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { } s.actions.playing = previous_playing; s.actions.playback_stack = previous_stack; + s.actions.budget_shared = previous_shared; + s.actions.batch_depth = previous_depth; if let Some(previous) = previous_list { s.actions.list = previous; } - if previous_playing == 0 { + if previous_playing == 0 && !previous_shared { s.actions.playback_steps = previous_steps; } if named { @@ -902,7 +931,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { #[cfg(not(target_arch = "wasm32"))] validate_flat_outputs(&outputs)?; validate_error_log(&policy, outputs.iter().map(|(path, _)| path.clone()), outputs.iter().map(|(_, path)| path.clone()))?; - let was_playing = s.actions.playing > 0; + let was_playing = nested; #[cfg(test)] let history_observer = s.batch_history_observer; crate::jobs::run( @@ -1027,6 +1056,10 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { // A recorded Save is a step too: Batch writes the output for it. charge_script_step(scratch)?; if batch_save_point(id) { + // The scratch session never executes a save point, so the gate would not see it. + if let Some(gate) = scratch.authorize { + gate(id, params)?; + } let st = scratch.active_mut().ok_or(EngineError::NoDocument)?; saved = Some(st.doc.clone()); // Batch performs the action's Save / Save As (to its destination), so the @@ -1040,6 +1073,12 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { } let params = crate::actions_cmds::playback_params(scratch, id, params)?; let r = scratch.execute(id, params)?; + // A nested batch, droplet or played action that hit the nesting or shared playback + // limit fails this input too, instead of saving it unprocessed. + if let Some(limit) = crate::actions_cmds::limit_stop(&r) { + // The child result stays, so the files it wrote before the stop are reported. + return Err(FileFailure { error: EngineError::BatchLimit(limit), result: Some(r) }); + } ctx.publish_batch_preview(&source_path, scratch.active().map(|state| state.doc.clone())); // A failed step inside a called action makes this file an error, not a saved result. if let Some(error) = crate::actions_cmds::nested_failure(id, &r) { diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index 1f7f9677ff..404930f917 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -44,6 +44,10 @@ pub struct LayerExportReport { pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result { let cmd = "file.export.layersToFiles"; let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); + // The format becomes the file extension inside one filename component handed to `write`. + if format.is_empty() || !format.chars().all(|c| c.is_ascii_alphanumeric()) { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: "`format` must be a file extension such as png".into() }); + } let trim = p.get("trim").and_then(Value::as_bool).unwrap_or(false); let visible_only = p.get("visibleOnly").and_then(Value::as_bool).unwrap_or(true); // Callers outside `Session::execute` (headless workspace exports) carry the session's gate @@ -144,7 +148,7 @@ fn lut_layers<'a>(doc: &'a Document, ids: Option<&[LayerId]>) -> Result String { +fn bake_cube_layers(size: usize, title: &str, layers: &[&Layer], depth: photocraft_color::SampleType) -> String { let n = size; let (w, h) = ((n * n) as u32, n as u32); let mut lattice = Document::new("lut", photocraft_doc::Size::new(w, h), ColorMode::Rgb, photocraft_color::SampleType::F32); @@ -172,14 +176,24 @@ fn bake_cube_layers(size: usize, title: &str, layers: &[&Layer]) -> String { lattice.layers.push(a); } let out = photocraft_compose::flatten(&lattice); - let mut s = format!("TITLE \"{}\"\n# Created by PhotoCraft\nLUT_3D_SIZE {n}\nDOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n", title.replace('"', "'")); + // The reference application's comment layout. There is no Copyright input yet (#13748), so the + // `#Copyright:` line is never written. + let mut s = format!( + "#Created by: PhotoCraft\nTITLE \"{}\"\n\n#LUT size\nLUT_3D_SIZE {n}\n\n#data domain\nDOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n\n#LUT data points\n", + title.replace('"', "'") + ); + // 8- and 16-bit documents write values on 1/32768 steps; 32-bit stays unquantised. + let quantise = |v: f32| -> f32 { + let v = v.clamp(0.0, 1.0); + if matches!(depth, photocraft_color::SampleType::F32) { v } else { (v * 32768.0).round() / 32768.0 } + }; // .cube order: red changes fastest, then green, then blue. for b in 0..n { for g in 0..n { for r in 0..n { let (x, y) = (b * n + r, g); let px = out.px[y * w as usize + x]; - s.push_str(&format!("{:.6} {:.6} {:.6}\n", px[0].clamp(0.0, 1.0), px[1].clamp(0.0, 1.0), px[2].clamp(0.0, 1.0))); + s.push_str(&format!("{:.6} {:.6} {:.6}\n", quantise(px[0]), quantise(px[1]), quantise(px[2]))); } } } @@ -189,7 +203,7 @@ fn bake_cube_layers(size: usize, title: &str, layers: &[&Layer]) -> String { /// Backwards-compatible helper for exporting all visible top-level adjustments. pub fn bake_cube(doc: &Document, size: usize, title: &str) -> String { let layers: Vec<&Layer> = doc.layers.iter().filter(|l| l.visible && matches!(l.content, LayerContent::Adjustment(_))).collect(); - bake_cube_layers(size.clamp(2, photocraft_cms::lutfile::MAX_SIZE), title, &layers) + bake_cube_layers(size.clamp(2, photocraft_cms::lutfile::MAX_SIZE), title, &layers, doc.depth) } /// Export either the whole visible stack (backward-compatible default), the Layers panel's @@ -231,7 +245,7 @@ pub(super) fn color_lookup_tables(s: &mut Session, p: &Value) -> Result { let layers = lut_layers(&d.doc, explicit.as_deref())?; let count = layers.len(); let title = p.get("title").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); - let cube = bake_cube_layers(size as usize, &title, &layers); + let cube = bake_cube_layers(size as usize, &title, &layers, d.doc.depth); match p.get("path").and_then(Value::as_str) { Some(path) => { write_file(path, cube.as_bytes())?; diff --git a/crates/engine/src/cmd/file_cmds/export_clut_cube_header_tests.rs b/crates/engine/src/cmd/file_cmds/export_clut_cube_header_tests.rs new file mode 100644 index 0000000000..7c2cf2d7db --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/export_clut_cube_header_tests.rs @@ -0,0 +1,91 @@ +//! The exported CUBE file's comment layout and 1/32768 steps (#13750). + +use super::*; + +fn session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "depth": depth})).unwrap(); + s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + s +} + +fn cube(s: &mut Session, size: u32) -> String { + s.execute("file.export.colorLookupTables", json!({"size": size, "title": "My Look"})).unwrap()["cube"].as_str().unwrap().to_string() +} + +fn data_lines(cube: &str) -> Vec<&str> { + cube.lines().filter(|l| l.chars().next().is_some_and(|c| c.is_ascii_digit())).collect() +} + +fn values(cube: &str) -> Vec { + data_lines(cube).iter().flat_map(|l| l.split(' ').map(str::to_string)).collect() +} + +#[test] +fn header_follows_the_reference_comment_layout() { + let mut s = session(8); + let text = cube(&mut s, 3); + let head: Vec<&str> = text.lines().take(12).collect(); + assert_eq!( + head, + [ + "#Created by: PhotoCraft", + "TITLE \"My Look\"", + "", + "#LUT size", + "LUT_3D_SIZE 3", + "", + "#data domain", + "DOMAIN_MIN 0.0 0.0 0.0", + "DOMAIN_MAX 1.0 1.0 1.0", + "", + "#LUT data points", + data_lines(&text)[0], + ] + ); + assert_eq!(text.lines().count(), 11 + 27); +} + +#[test] +fn eight_and_sixteen_bit_values_sit_on_1_32768_steps() { + for depth in [8, 16] { + let mut s = session(depth); + // Inverted size-7 lattice: 1 - k/6 gives 5/6 and 1/6. + let v = values(&cube(&mut s, 7)); + assert!(v.contains(&"0.833344".to_string()), "depth {depth}"); + assert!(v.contains(&"0.166656".to_string()), "depth {depth}"); + assert!(!v.contains(&"0.833333".to_string()), "depth {depth}"); + // Inverted size-52 lattice: 1 - 19/51 = 32/51 = 160/255. + let v = values(&cube(&mut s, 52)); + assert!(v.contains(&"0.627441".to_string()), "depth {depth}"); + for x in v { + let f: f64 = x.parse().unwrap(); + assert!((f * 32768.0 - (f * 32768.0).round()).abs() < 32768.0 * 1e-6 + 1e-9, "{x}"); + } + } +} + +#[test] +fn thirty_two_bit_values_are_not_quantised() { + let mut s = session(32); + let v = values(&cube(&mut s, 7)); + assert!(v.contains(&"0.833333".to_string())); + assert!(v.contains(&"0.166667".to_string())); + assert!(!v.contains(&"0.833344".to_string())); +} + +#[test] +fn exported_text_parses_back_with_the_same_values() { + for depth in [8, 32] { + let mut s = session(depth); + let text = cube(&mut s, 5); + let lut = photocraft_cms::lutfile::parse_cube(&text).unwrap(); + assert_eq!(lut.size, 5); + assert_eq!(lut.title, "My Look"); + let written: Vec = values(&text).iter().map(|x| x.parse().unwrap()).collect(); + assert_eq!(lut.data.len(), written.len()); + for (a, b) in lut.data.iter().zip(&written) { + assert!((a - b).abs() < 1e-6, "{a} vs {b}"); + } + } +} diff --git a/crates/engine/src/cmd/file_cmds/place_steps.rs b/crates/engine/src/cmd/file_cmds/place_steps.rs index 8d35d54704..f449eaee8a 100644 --- a/crates/engine/src/cmd/file_cmds/place_steps.rs +++ b/crates/engine/src/cmd/file_cmds/place_steps.rs @@ -171,6 +171,19 @@ impl PlaceSteps { Some(c) if c.len() == 2 => (c[0].as_f64().unwrap_or(cw / 2.0), c[1].as_f64().unwrap_or(ch / 2.0)), _ => (cw / 2.0, ch / 2.0), }; + // `scale` is the caller's: bound the resampled size before allocating it (a frame's image + // renders through its smart object, which has its own budget). Resampling rounds the far + // output edges outward; an unresampled placement keeps its size. + if self.input.frame.is_none() { + let (ow, oh) = if (scale - 1.0).abs() > 1e-9 { ((w * scale).ceil(), (h * scale).ceil()) } else { (w, h) }; + let scaled = ow * oh; + if scaled.is_nan() || scaled > photocraft_compose::MAX_RENDER_PIXELS as f64 { + return Err(EngineError::BadParams { + cmd: self.input.command().into(), + msg: format!("scaling {w}×{h} by {scale} makes an image too large to place"), + }); + } + } let (dx, dy) = ((center.0 - w * scale / 2.0).round(), (center.1 - h * scale / 2.0).round()); self.plan = Plan { w, h, scale, dx, dy }; // A frame's image renders through its smart object, which refuses a placement past the diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 94680e496a..9b3207a8ee 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -1785,6 +1785,17 @@ fn dds_params_are_none_until_one_is_given() { assert_eq!(dds_param(&json!({"ddsCompression": "bc2"}), "file.saveAs").unwrap(), Some(DdsOptions { compression: DdsCompression::Bc2, mipmaps: false })); } +/// The layer export's `format` is an extension, never a path: separators and `..` are refused. +#[test] +fn layer_export_format_cannot_carry_path_components() { + let dir = tmp("fmt-path"); + let mut s = session(8, 8, 8); + for bad in ["png/../../x", "..\\x", "a/b", ""] { + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "format": bad})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{bad}: {r:?}"); + } +} + /// A `tgaBits` other than 24 or 32 is a bad parameter, reported before anything is written. #[test] fn bad_targa_bits_are_refused_before_writing() { @@ -1860,8 +1871,8 @@ fn image_previews_preference_controls_the_psd_thumbnail() { let dir = tmp("previews"); let mut s = session(300, 200, 16); let has_thumbnail = |path: &str| { - let file = photocraft_psd::PsdFile::from_bytes(&std::fs::read(path).unwrap()).unwrap(); - file.resources.iter().any(|r| r.id == photocraft_psd::resources::ids::THUMBNAIL) + let file = craft_psd::PsdFile::from_bytes(&std::fs::read(path).unwrap()).unwrap(); + file.resources.iter().any(|r| r.id == craft_psd::resources::ids::THUMBNAIL) }; for (ask, expect) in [(Ask::Always, true), (Ask::Never, false), (Ask::Ask, true)] { s.edit_prefs(|p| p.file_handling.image_previews = ask); @@ -1882,7 +1893,7 @@ fn maximize_compatibility_preference_controls_the_psd_merged_image() { let dir = tmp("maximize"); let mut s = session(300, 200, 16); s.execute("layer.new.layer", json!({})).unwrap(); - let real_merged = |path: &str| photocraft_psd::PsdFile::from_bytes(&std::fs::read(path).unwrap()).unwrap().has_real_merged_data(); + let real_merged = |path: &str| craft_psd::PsdFile::from_bytes(&std::fs::read(path).unwrap()).unwrap().has_real_merged_data(); for (ask, expect) in [(Ask::Always, true), (Ask::Never, false), (Ask::Ask, true)] { s.edit_prefs(|p| p.file_handling.maximize_psd_compatibility = ask); for ext in ["psd", "psb"] { @@ -1933,7 +1944,7 @@ fn maximize_compatibility_param_overrides_the_preference_for_one_save() { let dir = tmp("maximize-param"); let mut s = session(300, 200, 16); s.execute("layer.new.layer", json!({})).unwrap(); - let real_merged = |path: &str| photocraft_psd::PsdFile::from_bytes(&std::fs::read(path).unwrap()).unwrap().has_real_merged_data(); + let real_merged = |path: &str| craft_psd::PsdFile::from_bytes(&std::fs::read(path).unwrap()).unwrap().has_real_merged_data(); for (ask, param, expect) in [ (Ask::Always, json!(false), false), (Ask::Never, json!(true), true), @@ -2004,6 +2015,21 @@ fn place_embedded_centres_fits_and_embeds() { } } +/// A caller-chosen placement scale cannot ask for an image beyond the render limit. +#[test] +fn placing_refuses_a_scale_that_would_exceed_the_pixel_limit() { + let dir = tmp("place-huge-scale"); + let small = png(&dir, "small.png", 200, 100, "#ff0000"); + let mut s = session(100, 100, 8); + for scale in [1e9, 1e300, 1e308, 23170.25] { + assert!(matches!(s.execute("file.placeEmbedded", json!({"path": small, "scale": scale})), Err(EngineError::BadParams { .. })), "{scale}"); + } + assert!(s.execute("file.placeEmbedded", json!({"path": small, "scale": 50})).is_ok()); + // The error names the command that asked. + let linked = s.execute("file.placeLinked", json!({"path": small, "scale": 1e9})); + assert!(matches!(linked, Err(EngineError::BadParams { ref cmd, .. }) if cmd == "file.placeLinked"), "{linked:?}"); +} + /// Preferences ▸ General ▸ Always Create Smart Objects When Placing: unchecked, an embedded place /// lands as a plain pixel layer; a linked place is always a smart object and `"smartObject"` wins. #[test] @@ -2723,6 +2749,41 @@ fn trimming_an_empty_layer_keeps_a_valid_nonzero_canvas() { assert_eq!((back.size.width, back.size.height), (6, 7)); } +#[test] +fn image_processor_scratch_sessions_answer_to_the_authorization_gate() { + fn deny_image(id: &str, _: &Value) -> Result<()> { + if id.starts_with("image.") { Err(EngineError::Other(format!("automation command `{id}` is disabled"))) } else { Ok(()) } + } + let dir = tmp("proc-gate"); + let input = join(&dir, "in"); + std::fs::create_dir_all(&input).unwrap(); + png(&input, "a.png", 40, 20, "#ff0000"); + let mut s = Session::new(); + s.authorize = Some(deny_image); + let out = join(&dir, "out"); + let r = s.execute("file.scripts.imageProcessor", json!({"input": input, "output": out, "format": "jpg", "width": 20, "height": 20})).unwrap(); + assert!(r["files"].as_array().unwrap().is_empty(), "{r}"); + assert_eq!(r["errors"].as_array().unwrap().len(), 1, "{r}"); +} + +#[test] +fn batch_save_points_answer_to_the_authorization_gate() { + fn deny_save(id: &str, _: &Value) -> Result<()> { + if id == "file.save" { Err(EngineError::Other(format!("automation command `{id}` is disabled"))) } else { Ok(()) } + } + let dir = tmp("batch-save-gate"); + let input = join(&dir, "in"); + std::fs::create_dir_all(&input).unwrap(); + png(&input, "a.png", 8, 8, "#ff0000"); + let mut s = Session::new(); + s.authorize = Some(deny_save); + let out = join(&dir, "out"); + let r = s.execute("file.automate.batch", json!({"steps": [["file.save", {}]], "input": input, "output": out, "format": "png"})).unwrap(); + assert!(r["files"].as_array().unwrap().is_empty(), "{r}"); + assert_eq!(r["errors"].as_array().unwrap().len(), 1, "{r}"); + assert!(!std::path::Path::new(&join(&out, "a.png")).exists()); +} + #[test] fn load_files_into_stack_and_image_processor_and_batch() { let dir = tmp("batch"); @@ -3900,6 +3961,33 @@ fn sanitize_keeps_windows_device_names_off_the_disk() { } } +/// A droplet whose steps run the same droplet stops at the nesting limit with an error for the +/// input, rather than opening documents until the stack or memory runs out. +#[test] +fn a_droplet_that_runs_itself_stops_at_the_nesting_limit() { + let dir = tmp("droplet-recursion"); + let input = png(&dir, "a.png", 4, 4, "#ff0000"); + let droplet = join(&dir, "self.pcdroplet"); + let out = join(&dir, "out"); + let step = json!(["file.automate.runDroplet", {"droplet": droplet, "input": [input], "output": out}]); + std::fs::write(&droplet, json!({"photocraftDroplet": 1, "name": "self", "action": {"steps": [step]}, "options": {"format": "png"}}).to_string()).unwrap(); + let mut s = Session::new(); + // Each level runs the next in a scratch session; the innermost is refused, so this returns. + let r = s.execute("file.automate.runDroplet", json!({"droplet": droplet, "input": [input], "output": out})).unwrap(); + assert_eq!(s.actions.batch_depth, 0); + // The limit reaches the outermost result: the input failed, nothing was saved unprocessed. + assert!(r["errors"][0]["error"].as_str().unwrap().contains("nested more than"), "{r}"); + assert_eq!(r["files"], json!([]), "{r}"); + assert!(!std::path::Path::new(&out).join("a.png").exists()); + // At the limit, the droplet is refused before its file is read (this one doesn't exist). + s.actions.batch_depth = crate::actions_cmds::MAX_BATCH_DEPTH; + let missing = join(&dir, "missing.pcdroplet"); + let e = s.execute("file.automate.runDroplet", json!({"droplet": missing, "input": [input], "output": out})).unwrap_err(); + assert!(e.to_string().contains("nested more than"), "{e}"); + let e = s.execute("file.automate.batch", json!({"steps": [], "input": [input], "output": out})).unwrap_err(); + assert!(e.to_string().contains("nested more than"), "{e}"); +} + #[test] fn approve_memory_validates_parameters_and_unknown_ids() { let mut s = session(4, 4, 8); diff --git a/crates/engine/src/cmd/float_cmds.rs b/crates/engine/src/cmd/float_cmds.rs index 9cfa5d3f96..f5dfa28d2f 100644 --- a/crates/engine/src/cmd/float_cmds.rs +++ b/crates/engine/src/cmd/float_cmds.rs @@ -163,8 +163,22 @@ fn cut_piece(base: &Surface, sel: &Surface, b: photocraft_geom::Rect, with_alpha let alpha_off = dst_bpp - sb; let src_empty_default = same_fmt && base.default_bytes().iter().all(|&v| v == 0); let oom = |e| EngineError::Other(format!("not enough memory while floating selection ({e}); the document was not changed")); - let mut coords = crate::allocation::capacity(b.tiles().count(), "floating selection")?; - coords.extend(b.tiles()); + // Only tiles that can hold a piece of the result are visited. With an empty source default, + // that is the source's stored tiles; with an empty selection default, the selection's. Two + // distant tiles make `b` a grid of millions of tiles that hold nothing, so the full grid is + // walked only when neither default is empty, after checking what it could produce. + let sel_default_empty = sel.default_pixel().first().is_none_or(|v| *v <= 0.0); + let stored = |s: &Surface| s.tiles().map(|(c, _)| *c).filter(|c| !c.rect().intersect(&b).is_empty()).collect::>(); + let coords: Vec = if src_empty_default { + stored(base) + } else if sel_default_empty { + stored(sel) + } else { + crate::allocation::check_dense(b, dst_bpp as u64, "floating selection")?; + let mut coords = crate::allocation::capacity(usize::try_from(b.tile_count()).unwrap_or(usize::MAX), "floating selection")?; + coords.extend(b.tiles()); + coords + }; let tiles = coords .into_par_iter() .map(|tc| -> Result)>> { diff --git a/crates/engine/src/cmd/frame_cmds.rs b/crates/engine/src/cmd/frame_cmds.rs index 8e2ea786b5..9888b601dd 100644 --- a/crates/engine/src/cmd/frame_cmds.rs +++ b/crates/engine/src/cmd/frame_cmds.rs @@ -109,7 +109,9 @@ fn new_frame(s: &mut Session, p: &Value) -> Result { Some(child) } }; - let mut g = Layer::group(name.unwrap_or_else(|| doc.next_layer_name("Frame")), vec![]); + // A frame drawn around a layer is named after it ("Red Frame"); an empty one is "Frame N". + let name = name.unwrap_or_else(|| child.as_ref().map_or_else(|| doc.next_layer_name("Frame"), |c| format!("{} Frame", c.name))); + let mut g = Layer::group(name, vec![]); g.blend = BlendMode::Normal; g.frame = Some(Box::new(f)); refresh(&mut g); @@ -135,8 +137,11 @@ fn new_frame(s: &mut Session, p: &Value) -> Result { Ok(result) } fn frame_from_layers(s: &mut Session, p: &Value) -> Result { + // A `layer` of its own (a recorded step names its layer) is what the grouping below takes + // in, so the frame fits that layer, not whatever is selected. + let explicit = crate::commands::explicit_layer(s, p)?; let st = s.active().ok_or(EngineError::NoDocument)?; - let ids = st.selected_layers(); + let ids = explicit.map_or_else(|| st.selected_layers(), |id| vec![id]); let bounds = ids .iter() .filter_map(|id| st.doc.layer(*id)) @@ -181,8 +186,14 @@ fn set(s: &mut Session, p: &Value) -> Result { if !["transform", "stroke", "name"].iter().any(|key| p.get(key).is_some()) { return Err(bad("supply transform, stroke or name")); } + // The Frame tool moves a frame as a "Move" step (#13880); every other change is "Frame Properties". + let step = match p.get("historyName") { + None | Some(Value::Null) => "Frame Properties", + Some(v) if v.as_str() == Some("Move") => "Move", + Some(_) => return Err(bad("`historyName` must be \"Move\" or null")), + }; let id = frame_id(s, p)?; - s.edit("Frame Properties", |doc, _| { + s.edit(step, |doc, _| { check_lock(doc, id)?; let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; let f = l.frame.as_mut().ok_or_else(|| bad("not a frame"))?; @@ -359,8 +370,17 @@ pub fn specs() -> Vec { has_doc, new_frame, ), - CommandSpec { menu: &["Layer", "New"], ..spec("layer.new.frameFromLayers", "Frame from Layers", r#"{name?:str}"#, has_layer, frame_from_layers) }, - spec("layer.frame.set", "Frame Properties", r#"{"layer":id?,"transform":[a,b,c,d,x,y]?,"stroke":object|null?,"name":str?}"#, has_doc, set), + CommandSpec { + menu: &["Layer", "New"], + ..spec("layer.new.frameFromLayers", "Frame from Layers", r#"{"layer":id?,"name":str?}"#, has_layer, frame_from_layers) + }, + spec( + "layer.frame.set", + "Frame Properties", + r#"{"layer":id?,"transform":[a,b,c,d,x,y]?,"stroke":object|null?,"name":str?,"historyName":"Move"?}"#, + has_doc, + set, + ), CommandSpec { journal: false, ..spec("layer.frame.info", "Frame Info", r#"{"layer":id?}"#, has_doc, query) }, spec("layer.frame.convert", "Convert to Frame", r#"{"layer":id?,"name":str?,"width":px?,"height":px?}"#, has_doc, convert), spec( @@ -374,4 +394,6 @@ pub fn specs() -> Vec { ] } #[cfg(test)] +mod content_name_tests; +#[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/frame_cmds/content_name_tests.rs b/crates/engine/src/cmd/frame_cmds/content_name_tests.rs new file mode 100644 index 0000000000..70d28d988a --- /dev/null +++ b/crates/engine/src/cmd/frame_cmds/content_name_tests.rs @@ -0,0 +1,72 @@ +//! #13862: a frame made around a layer is named " Frame"; an empty frame keeps +//! "Frame N", and an explicit `name` wins over both. +use super::*; +use photocraft_doc::Layer; +use photocraft_geom::Rect; + +/// The issue's document: 600 x 400 px with a white Background, pixel layers Red (100 x 80 at +/// 50,50) and Blue, and an empty pixel layer on top. +fn session() -> (Session, LayerId, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); + let (red, blue) = s + .edit("setup", |doc, _| { + let fmt = doc.pixel_format(); + let mut red = Layer::raster("Red", fmt); + red.surface_mut().unwrap().fill_rect(Rect::new(50, 50, 150, 130), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + let mut blue = Layer::raster("Blue", fmt); + blue.surface_mut().unwrap().fill_rect(Rect::new(300, 200, 400, 280), &photocraft_raster::from_rgba(&fmt, [0.0, 0.0, 1.0, 1.0])); + let (r, b) = (red.id, blue.id); + doc.layers.push(red); + doc.layers.push(blue); + doc.layers.push(Layer::raster("Layer 1", fmt)); + Ok((r, b)) + }) + .unwrap(); + (s, red, blue) +} + +fn frame(s: &mut Session, params: Value) -> (String, Vec) { + let r = s.execute("layer.new.frame", params).unwrap(); + let g = s.active().unwrap().doc.layer(LayerId(r["layer"].as_u64().unwrap())).unwrap(); + (g.name.clone(), g.children().unwrap().iter().map(|l| l.name.clone()).collect()) +} + +#[test] +fn a_frame_around_a_layer_is_named_after_it() { + let (mut s, red, blue) = session(); + let (name, content) = frame(&mut s, json!({"x": 40, "y": 40, "width": 120, "height": 100, "layer": red.0})); + assert_eq!((name.as_str(), content), ("Red Frame", vec!["Red".to_string()]), "the content layer keeps its own name"); + let (name, _) = frame(&mut s, json!({"x": 290, "y": 190, "width": 120, "height": 100, "shape": "ellipse", "layer": blue.0})); + assert_eq!(name, "Blue Frame"); +} + +#[test] +fn empty_frames_keep_the_frame_counter() { + let (mut s, _, _) = session(); + let (first, content) = frame(&mut s, json!({"x": 10, "y": 10, "width": 30, "height": 30})); + assert_eq!((first.as_str(), content.len()), ("Frame 1", 0)); + let (second, _) = frame(&mut s, json!({"x": 500, "y": 300, "width": 30, "height": 30})); + assert_eq!(second, "Frame 2"); +} + +#[test] +fn an_explicit_name_wins_over_the_content_name() { + let (mut s, red, _) = session(); + let (name, content) = frame(&mut s, json!({"x": 40, "y": 40, "width": 120, "height": 100, "layer": red.0, "name": "Hero"})); + assert_eq!((name.as_str(), content), ("Hero", vec!["Red".to_string()])); + let (name, _) = frame(&mut s, json!({"x": 10, "y": 10, "width": 30, "height": 30, "name": "Empty"})); + assert_eq!(name, "Empty"); +} + +#[test] +fn undo_and_redo_keep_the_content_name() { + let (mut s, red, _) = session(); + let (name, _) = frame(&mut s, json!({"x": 40, "y": 40, "width": 120, "height": 100, "layer": red.0})); + assert_eq!(name, "Red Frame"); + assert!(s.undo()); + let names = |s: &Session| s.active().unwrap().doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect::>(); + assert!(!names(&s).contains(&"Red Frame".to_string()) && names(&s).contains(&"Red".to_string()), "undo takes the frame away and gives Red back"); + assert!(s.redo()); + assert!(names(&s).contains(&"Red Frame".to_string())); +} diff --git a/crates/engine/src/cmd/gradient_alpha_method_tests.rs b/crates/engine/src/cmd/gradient_alpha_method_tests.rs new file mode 100644 index 0000000000..2603061025 --- /dev/null +++ b/crates/engine/src/cmd/gradient_alpha_method_tests.rs @@ -0,0 +1,118 @@ +//! #12010: the transparency of a gradient drawn with the Gradient tool follows the interpolation +//! method (Smooth by default) instead of a straight line. Reference: Foreground to Transparent, +//! Smooth, dragged (100, 300) to (700, 300): alpha 255 / 179 / 100 / 35 / 0 at x 50 / 250 / 400 / +//! 550 / 750. + +use serde_json::{Value, json}; + +use crate::Session; + +fn drawn(extra: Value) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600, "background": "transparent"})).unwrap(); + let mut p = json!({"gradient": "Foreground to Transparent", "from": [100, 300], "to": [700, 300], "dither": false}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + s.execute("paint.gradient", p).unwrap(); + s +} + +fn alpha_at(s: &Session, x: i32) -> f32 { + let d = s.active().unwrap(); + let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); + let photocraft_doc::LayerContent::Raster(surface) = &l.content else { panic!("a pixel layer") }; + surface.pixel(x, 300)[3] * 255.0 +} + +#[test] +fn smooth_transparency_ramp_matches_the_reference() { + let s = drawn(json!({"method": "smooth"})); + for (x, want) in [(50, 255.0), (250, 179.0), (400, 100.0), (550, 35.0), (750, 0.0)] { + let got = alpha_at(&s, x); + assert!((got - want).abs() <= 2.0, "x={x}: alpha {got:.1}, want {want}"); + } +} + +#[test] +fn without_a_method_the_ramp_stays_straight() { + let s = drawn(json!({})); + for (x, want) in [(250, 191.0), (400, 128.0), (550, 64.0)] { + let got = alpha_at(&s, x); + assert!((got - want).abs() <= 2.0, "x={x}: alpha {got:.1}, want {want}"); + } +} + +#[test] +fn opaque_gradients_paint_the_same_with_a_method() { + let paint = |extra: Value| { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 8, "background": "white"})).unwrap(); + let mut p = json!({"colors": ["#000000", "#ffffff"], "from": [0, 4], "to": [64, 4], "dither": false}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + s.execute("paint.gradient", p).unwrap(); + (0..64).map(|x| alpha_and_red(&s, x)).collect::>() + }; + fn alpha_and_red(s: &Session, x: i32) -> Vec { + let d = s.active().unwrap(); + let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); + let photocraft_doc::LayerContent::Raster(surface) = &l.content else { panic!() }; + surface.pixel(x, 4) + } + // The colours still follow the method; the alpha stays opaque. + let smooth = paint(json!({"method": "smooth"})); + assert!(smooth.iter().all(|p| (p[3] - 1.0).abs() < 1e-3)); + assert_ne!(smooth, paint(json!({}))); +} + +// Not measured in the Gradient tool: the other methods, and Smooth below 100 % Smoothness, keep +// today's merged stops (each dense stop takes the nearest stop's alpha). +#[test] +fn unmeasured_methods_and_smoothness_keep_todays_ramp() { + for extra in [json!({"method": "classic"}), json!({"method": "perceptual"}), json!({"method": "linear"}), json!({"method": "smooth", "smoothness": 50})] { + let s = drawn(extra.clone()); + for (x, want) in [(250, 191.0), (400, 128.0), (550, 64.0)] { + let got = alpha_at(&s, x); + assert!((got - want).abs() <= 1.0, "{extra} x={x}: alpha {got:.1}, want {want}"); + } + } +} + +fn drawn_colors(colors: Value) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600, "background": "transparent"})).unwrap(); + let p = json!({"colors": colors, "transparency": [[0, 100], [1, 0]], "method": "smooth", "from": [100, 300], "to": [700, 300], "dither": false}); + s.execute("paint.gradient", p).unwrap(); + s +} + +#[test] +fn one_colour_with_a_transparency_ramp_follows_smooth() { + let s = drawn_colors(json!(["#ff0000"])); + for (x, want) in [(50, 255.0), (250, 179.0), (400, 100.0), (550, 35.0), (750, 0.0)] { + let got = alpha_at(&s, x); + assert!((got - want).abs() <= 2.0, "x={x}: alpha {got:.1}, want {want}"); + } +} + +#[test] +fn legacy_colours_keep_their_own_alpha() { + let s = drawn_colors(json!(["#ff000080", "#ff000080"])); + for (x, want) in [(50, 128.0), (400, 64.0), (750, 0.0)] { + let got = alpha_at(&s, x); + assert!((got - want).abs() <= 1.0, "x={x}: alpha {got:.1}, want {want}"); + } +} + +// paint_gradient scans the stops for every pixel: Smooth's colour and opacity bakes share their +// 97 positions and must not be cut into four per interval (385 stops). +#[test] +fn smooth_transparency_keeps_one_stop_per_sampled_position() { + use photocraft_color::Color; + let black = Color::rgb(0.0, 0.0, 0.0); + let stops = super::paint_cmds::smooth_split_stops((vec![(0.0, black), (1.0, black)], vec![(0.0, 1.0), (1.0, 0.0)])); + assert_eq!(stops.len(), 97); + assert!((stops[0].1[3] - 1.0).abs() < 1e-6 && stops[96].1[3].abs() < 1e-6); +} diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index 9eff784a42..318b5dbad2 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -318,7 +318,13 @@ fn image_size(s: &mut Session, p: &Value) -> Result { Method::Automatic if nw > ow || nh > oh => Resample::PreserveDetails, Method::Automatic => Resample::BicubicSharper, }; - resample_doc_with_styles(doc, "image.imageSize", nw, nh, filter, scale_styles) + // Resampling to a new pixel size drops the selection rather than scaling it, as Photoshop + // does (#13856); undo brings it back with the old size. Taken before the resample so it + // isn't scaled for nothing. A resolution-only change (returned above) keeps it. + if (nw, nh) != (ow, oh) { + doc.selection = None; + } + crate::canvas_geom::keeping_count_points(doc, |doc| resample_doc_with_styles(doc, "image.imageSize", nw, nh, filter, scale_styles)) })?; // The size the document has now: without resampling `width`/`height` are ignored (#1815). let size = s.active().ok_or(EngineError::NoDocument)?.doc.size; @@ -714,7 +720,7 @@ fn canvas_size(s: &mut Session, p: &Value) -> Result { let ext = extension_color(s, p); s.set_sampler_map(photocraft_geom::Affine::translate(f64::from(dx), f64::from(dy))); s.edit("Canvas Size", |doc, _| { - translate_doc(doc, "image.canvasSize", dx, dy)?; + crate::canvas_geom::keeping_count_points(doc, |doc| translate_doc(doc, "image.canvasSize", dx, dy))?; doc.size = Size::new(nw, nh); if nw > ow as u32 || nh > oh as u32 { drop_fill_caches(&mut doc.layers); @@ -1049,7 +1055,7 @@ fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool, content_awar Ok(()) })?; } - crate::mode_cmds::rotate_arbitrary(s, &json!({"angle": angle, "direction": "ccw"}))?; + crate::mode_cmds::rotate_arbitrary_with(s, &json!({"angle": angle, "direction": "ccw"}), false)?; // Color Sampler points follow the crop's origin shift too (the rotation moved them above). s.set_sampler_map(crop_target.sampler_map(target)); let extension = s.tools.background; @@ -1293,3 +1299,7 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "image_size_drops_selection_tests.rs"] +mod image_size_drops_selection_tests; diff --git a/crates/engine/src/cmd/image_cmds/tests.rs b/crates/engine/src/cmd/image_cmds/tests.rs index 4d0478eccb..5acec8b8ba 100644 --- a/crates/engine/src/cmd/image_cmds/tests.rs +++ b/crates/engine/src/cmd/image_cmds/tests.rs @@ -205,8 +205,20 @@ fn image_size_keeps_canvas_edges_opaque() { let mut s = Session::new(); s.execute("file.new", json!({"width": 30, "height": 20, "depth": depth, "background": "#336699"})).unwrap(); s.execute("select.all", json!({})).unwrap(); + // The Crop tool's W x H x Resolution mode still resamples the selection with the + // pixels: a full selection keeps reaching the canvas edges. + let mut cropped = (*doc(&s)).clone(); + let ch = (20 * w + 15) / 30; + resample_doc(&mut cropped, "test", w, ch, Resample::Bicubic).unwrap(); + let sel = cropped.selection.as_ref().unwrap(); + let (x1, y1) = (cropped.size.width as i32 - 1, cropped.size.height as i32 - 1); + for (x, y) in [(0, 0), (x1, 0), (0, y1), (x1, y1)] { + assert!(sel.pixel(x, y)[0] > 0.99, "{depth} {resample}: selection at ({x},{y})"); + } s.execute("image.imageSize", json!({"width": w, "resample": resample})).unwrap(); let d = doc(&s); + // Image Size drops the selection when it resamples (#13856). + assert!(d.selection.is_none(), "{depth} {resample}: Image Size dropped the selection"); let flat = photocraft_compose::flatten(d); let (w, h) = (flat.rect.width() as usize, flat.rect.height() as usize); let mid = flat.px[(h / 2) * w + w / 2]; @@ -215,11 +227,6 @@ fn image_size_keeps_canvas_edges_opaque() { let off = p.iter().zip(mid).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); assert!(off < 0.01, "{depth} {resample} {w}: {p:?} vs {mid:?}"); } - let sel = d.selection.as_ref().unwrap(); - let (x1, y1) = (d.size.width as i32 - 1, d.size.height as i32 - 1); - for (x, y) in [(0, 0), (x1, 0), (0, y1), (x1, y1)] { - assert!(sel.pixel(x, y)[0] > 0.99, "{depth} {resample}: selection at ({x},{y})"); - } } } } diff --git a/crates/engine/src/cmd/image_size_drops_selection_tests.rs b/crates/engine/src/cmd/image_size_drops_selection_tests.rs new file mode 100644 index 0000000000..825331a1a0 --- /dev/null +++ b/crates/engine/src/cmd/image_size_drops_selection_tests.rs @@ -0,0 +1,83 @@ +//! #13856: Fit Image and Image Size drop the active selection when they resample to a new pixel +//! size, as the reference application does; undo brings back the old size and selection in one +//! step. A Fit Image that changes nothing and a resolution-only Image Size keep the selection. + +use photocraft_geom::Rect; +use serde_json::{Value, json}; + +use crate::Session; + +/// The issue's document: 400 x 300 px with a 10,10 50 x 50 selection. +fn doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + s +} + +fn size(s: &Session) -> (u32, u32) { + let d = &s.active().unwrap().doc; + (d.size.width, d.size.height) +} + +fn selection(s: &Session) -> Option { + s.active().unwrap().doc.selection.as_ref().map(|sel| sel.content_bounds()) +} + +fn steps(s: &Session) -> usize { + s.active().unwrap().history.past_len() +} + +#[test] +fn fit_image_that_resizes_drops_the_selection_and_undo_restores_it() { + let mut s = doc(); + let before = selection(&s); + assert_eq!(before, Some(Rect::from_xywh(10, 10, 50, 50))); + let n = steps(&s); + let r = s.execute("file.automate.fitImage", json!({"width": 200, "height": 200})).unwrap(); + assert_eq!(r["changed"], Value::Bool(true)); + assert_eq!(size(&s), (200, 150)); + assert_eq!(selection(&s), None, "no selection after Fit Image"); + assert_eq!(steps(&s), n + 1, "one history step"); + s.undo(); + assert_eq!(size(&s), (400, 300), "undo restores the size"); + assert_eq!(selection(&s), before, "and the selection, in the same step"); +} + +#[test] +fn image_size_with_a_new_pixel_size_drops_the_selection_and_undo_restores_it() { + let mut s = doc(); + let before = selection(&s); + let n = steps(&s); + s.execute("image.imageSize", json!({"width": 200, "height": 150, "resample": "bicubic"})).unwrap(); + assert_eq!(size(&s), (200, 150)); + assert_eq!(selection(&s), None, "no selection after Image Size"); + assert_eq!(steps(&s), n + 1, "one history step"); + s.undo(); + assert_eq!(size(&s), (400, 300)); + assert_eq!(selection(&s), before); +} + +#[test] +fn fit_image_that_changes_nothing_keeps_the_selection_and_adds_no_step() { + for p in [json!({"width": 400, "height": 300}), json!({"width": 800, "height": 800, "dontEnlarge": true})] { + let mut s = doc(); + let before = selection(&s); + let n = steps(&s); + let r = s.execute("file.automate.fitImage", p.clone()).unwrap(); + assert_eq!(r["changed"], Value::Bool(false), "{p}"); + assert_eq!(size(&s), (400, 300), "{p}"); + assert_eq!(selection(&s), before, "{p}: selection kept"); + assert_eq!(steps(&s), n, "{p}: no history step"); + } +} + +#[test] +fn image_size_with_only_a_new_resolution_keeps_the_selection() { + let mut s = doc(); + let before = selection(&s); + s.execute("image.imageSize", json!({"resolution": 300, "resample": "none"})).unwrap(); + assert_eq!(size(&s), (400, 300)); + assert_eq!(s.active().unwrap().doc.resolution_dpi, 300.0); + assert_eq!(selection(&s), before, "a resolution-only change keeps the selection"); +} diff --git a/crates/engine/src/cmd/layer_menu_cmds.rs b/crates/engine/src/cmd/layer_menu_cmds.rs index 46aae07a71..58f253bb68 100644 --- a/crates/engine/src/cmd/layer_menu_cmds.rs +++ b/crates/engine/src/cmd/layer_menu_cmds.rs @@ -131,6 +131,17 @@ fn apply_mask(s: &mut Session, p: &Value) -> Result { // displays. LayerMask::values_into accounts for density but not feather (#3044). let feathered = { let layer = doc.layer(id).ok_or(EngineError::NoLayer(id))?; + // The pixels are read over their content bounds (distant tiles span the gaps between + // them) as native samples, straight RGBA, the mask's coverage and the re-encoded + // output; a feathered mask is also rendered over the canvas and those bounds. + if let Some(surf) = layer.surface() { + let r = surf.content_bounds(); + let n = surf.channels() as u64; + crate::allocation::check_dense(r, n.saturating_mul(8).saturating_add(20), "applying the layer mask")?; + if layer.mask.as_ref().is_some_and(|m| m.enabled && photocraft_compose::masks::feather_sigma(m.feather) > 0.0) { + crate::allocation::check_dense(doc.bounds().union(&r), 8, "applying the feathered layer mask")?; + } + } if layer.mask.as_ref().is_some_and(|m| m.enabled && photocraft_compose::masks::feather_sigma(m.feather) > 0.0) { // Do not bake an independent vector mask that remains attached after Apply. let mut mask_only = layer.clone(); diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index 218718ebd0..dcaf8a8f18 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -63,6 +63,12 @@ pub fn rotated_size(size: Size, deg: f64) -> Size { } pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result { + rotate_arbitrary_with(s, p, true) +} + +/// [`rotate_arbitrary`]; `keep_counts` leaves the count points where they were (Image Rotation, +/// #11762). The Crop tool's straighten turn moves them with the image, as before. +pub(crate) fn rotate_arbitrary_with(s: &mut Session, p: &Value, keep_counts: bool) -> Result { const CMD: &str = "image.rotation.arbitrary"; // At full precision: an f32 angle can grow the canvas 1 px past what `rotated_size` gives callers. let angle = p.get("angle").and_then(Value::as_f64).unwrap_or(0.0); @@ -132,7 +138,11 @@ pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result { // What Free Transform leaves alone: unlinked vector masks, gradient angles, artboards… crate::canvas_geom::transform_layer_geometry(l, &a, false, dpi); } - crate::canvas_geom::transform_doc_marks(doc, &a); + if keep_counts { + crate::canvas_geom::keeping_count_points(doc, |doc| crate::canvas_geom::transform_doc_marks(doc, &a)); + } else { + crate::canvas_geom::transform_doc_marks(doc, &a); + } for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) { ch.surface = crate::transform_cmds::warp_gray(&ch.surface, &h, interp)?; } diff --git a/crates/engine/src/cmd/multichannel_cmds.rs b/crates/engine/src/cmd/multichannel_cmds.rs index b0d46c2e4f..91570fc245 100644 --- a/crates/engine/src/cmd/multichannel_cmds.rs +++ b/crates/engine/src/cmd/multichannel_cmds.rs @@ -124,6 +124,19 @@ fn to_multichannel(s: &mut Session, _p: &Value) -> Result { return Err(EngineError::NoDocument); }; let names = s.edit("Multichannel", |doc, active| { + // Every ink is built as dense planes over the whole canvas (the flattened image, its + // colour planes, the inverted densities and each clamped channel), however few tiles + // the document stores: refuse a canvas past the working budget before allocating. + // Per pixel: the flattened image (16 B), its colour planes (4 B each), and per ink an f32 + // density and the stored plane (up to 4 B at F32). A Duotone has one colour channel but + // as many inks as it lists. + let cc = doc.pixel_format().mode.color_channels() as u64; + let inks = match (&doc.duotone, doc.mode) { + (Some(d), ColorMode::Duotone) if !d.inks.is_empty() => d.inks.len() as u64, + _ => cc, + }; + let per_px = cc.saturating_mul(4).saturating_add(inks.saturating_mul(8)).saturating_add(16); + crate::allocation::check_dense(doc.bounds(), per_px, "converting to Multichannel")?; let inks = inks_of(doc); let mut channels: Vec = inks .iter() @@ -189,8 +202,16 @@ pub(crate) fn convert_from(s: &mut Session, mode: ColorMode, _p: &Value) -> Resu let how = s.edit("Mode Change", |doc, active| { let (inks, others): (Vec, Vec) = std::mem::take(&mut doc.channels).into_iter().partition(|c| c.spot.is_some()); let canvas = doc.bounds(); - let n = canvas.width() as usize * canvas.height() as usize; + // The interleaved output, the rendered look (straight RGBA f32) and one ink plane at a + // time, all over the canvas: refuse a canvas past the working budget before allocating. + // The appearance branch also holds the stored surface (up to 4 B per sample) while `shown` + // and the interleaved output are alive; the reinterpret branch drops each plane first. + let out_cc = mode.color_channels() as u64; let reinterpret = matches!((mode, inks.len()), (ColorMode::Rgb | ColorMode::Lab, 3) | (ColorMode::Cmyk, 4) | (ColorMode::Grayscale, 1)); + let samples = out_cc.saturating_add(1).saturating_mul(4); + let stored = if reinterpret { 0 } else { samples }; + crate::allocation::check_dense(canvas, samples.saturating_add(20).saturating_add(stored), "converting from Multichannel")?; + let n = canvas.width() as usize * canvas.height() as usize; // The printed look, rendered before the inks leave the document. let shown = (!reinterpret).then(|| { let mut d = doc.clone(); diff --git a/crates/engine/src/cmd/multichannel_cmds/tests.rs b/crates/engine/src/cmd/multichannel_cmds/tests.rs index fc3cfd1cd6..99ad72d673 100644 --- a/crates/engine/src/cmd/multichannel_cmds/tests.rs +++ b/crates/engine/src/cmd/multichannel_cmds/tests.rs @@ -110,8 +110,8 @@ fn flattens_layers_and_keeps_alpha_channels() { assert_eq!(d.channels.len(), 4); assert!(d.channels[3].spot.is_none(), "the saved selection stays an alpha channel"); // The black fill on the upper layer is solid ink in all three plates. - for k in 0..3 { - assert!(d.channels[k].surface.pixel(1, 1)[0] > 0.99); + for c in &d.channels[..3] { + assert!(c.surface.pixel(1, 1)[0] > 0.99); } // Back to RGB: the alpha channel survives, the inks become colour channels. s.execute("image.mode.rgb", json!({})).unwrap(); diff --git a/crates/engine/src/cmd/paint_cmds.rs b/crates/engine/src/cmd/paint_cmds.rs index 505b74ba56..e4e0c2265a 100644 --- a/crates/engine/src/cmd/paint_cmds.rs +++ b/crates/engine/src/cmd/paint_cmds.rs @@ -55,6 +55,9 @@ fn fill_mode(p: &Value) -> Result { } } +/// The reference's alert for a Paint Bucket click in a Bitmap document (#12536). +pub const BITMAP_REFUSAL: &str = "Could not use the paint bucket because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + fn bucket(s: &mut Session, p: &Value) -> Result { let fg = s.tools.foreground; let c = color(p.get("color"), fg); @@ -63,6 +66,10 @@ fn bucket(s: &mut Session, p: &Value) -> Result { let opacity = opacity(p, "paint.bucket")?; let mode = fill_mode(p)?; let all = b(p, "sampleAllLayers", false) && crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels; + // Before the region, the target and the document copy: a Bitmap click changes nothing. + if s.active().is_some_and(|d| d.doc.mode == photocraft_color::ColorMode::Bitmap) { + return Err(EngineError::Other(BITMAP_REFUSAL.into())); + } // Other visible layers can define the region, but the fill still writes only to the target. let region = if all { let (area, img) = crate::selection_cmds::sample_rgba8(s, true)?; @@ -154,15 +161,26 @@ fn gradient(s: &mut Session, p: &Value) -> Result { // where straight stops give 0.0625. let stops = match p.get("method").and_then(Value::as_str).and_then(photocraft_io::GradientMethod::from_name) { Some(m) if stops.len() >= 2 => { - let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect(); - let mids = vec![0.5; stops.len() - 1]; - photocraft_io::bake_gradient(colors, &mids, (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0), m) - .into_iter() - .map(|(t, c)| { - let rgb = c.to_rgb(); - (t, [rgb[0], rgb[1], rgb[2], c.alpha]) - }) - .collect() + let smoothness = (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0); + // Smooth at 100 % Smoothness bakes the colour and opacity stops apart: the colours by + // the method, the opacity by Smooth's measured transparency curve (#12010). Merged + // stops would take the nearest stop's alpha. The other methods and Smoothness values + // were not measured in the Gradient tool and keep the merged stops. + let split = if m == photocraft_io::GradientMethod::Smooth && smoothness >= 1.0 { split_stops(s, p, fg)? } else { None }; + match split { + Some(split) => smooth_split_stops(split), + None => { + let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect(); + let mids = vec![0.5; stops.len() - 1]; + photocraft_io::bake_gradient(colors, &mids, smoothness, m) + .into_iter() + .map(|(t, c)| { + let rgb = c.to_rgb(); + (t, [rgb[0], rgb[1], rgb[2], c.alpha]) + }) + .collect() + } + } } _ => stops, }; @@ -181,6 +199,64 @@ fn gradient(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// Smooth's colour and opacity stops baked apart, then joined. Both bakes sample the same +/// positions, so the alpha is multiplied in at each one: [`gradients::apply_opacity`] would cut +/// every interval into four (385 stops instead of 97), and `paint_gradient` scans the stops for +/// every pixel. Positions that differ still go through `apply_opacity`. +pub(crate) fn smooth_split_stops((cs, os): gradients::FillStops) -> gradients::Stops { + let mids = vec![0.5; cs.len().saturating_sub(1)]; + let colours: gradients::Stops = photocraft_io::bake_gradient(cs, &mids, 1.0, photocraft_io::GradientMethod::Smooth) + .into_iter() + .map(|(t, c)| { + let rgb = c.to_rgb(); + (t, [rgb[0], rgb[1], rgb[2], 1.0]) + }) + .collect(); + let omids = vec![0.5; os.len().saturating_sub(1)]; + let opacity = photocraft_io::bake_gradient_smooth_opacity(os, &omids); + if colours.len() != opacity.len() || colours.iter().zip(&opacity).any(|(c, o)| (c.0 - o.0).abs() > 1e-6) { + return gradients::apply_opacity(colours, &opacity); + } + colours + .into_iter() + .zip(opacity) + .map(|((t, mut c), (_, a))| { + c[3] = if a.is_finite() { a.clamp(0.0, 1.0) } else { 1.0 }; + (t, c) + }) + .collect() +} + +/// The Gradient tool's colour stops (opaque) and opacity stops kept apart, for Smooth's own +/// transparency curve. `None` when the opacity is constant, or when legacy `colors` carry their +/// own alpha (that case keeps the merged stops). A single colour stop spans the whole gradient. +fn split_stops(s: &Session, p: &Value, fg: [f32; 4]) -> Result> { + let (mut cs, os) = match gradients::tool_fill_stops(s, p)? { + Some(split) => split, + None => { + // The legacy `colors` list, evenly spaced. + let colors: Vec<[f32; 4]> = p.get("colors").and_then(Value::as_array).map(|a| a.iter().map(|v| color(Some(v), fg)).collect()).unwrap_or_default(); + if colors.iter().any(|c| c[3] < 1.0) { + return Ok(None); + } + let n = colors.len(); + let cs = colors + .iter() + .enumerate() + .map(|(i, c)| (if n > 1 { i as f32 / (n - 1) as f32 } else { 0.0 }, photocraft_color::Color::rgb(c[0], c[1], c[2]))) + .collect(); + (cs, gradients::transparency_param(p, "paint.gradient")?.unwrap_or_default()) + } + }; + if os.iter().all(|o| (o.1 - 1.0).abs() < 1e-6) { + return Ok(None); + } + if let [(_, c)] = cs.as_slice() { + cs = vec![(0.0, *c), (1.0, *c)]; + } + Ok(if cs.is_empty() { None } else { Some((cs, os)) }) +} + /// Paint helper command specs. pub fn specs() -> Vec { vec![ @@ -212,3 +288,6 @@ mod tests; #[cfg(test)] mod bucket_no_op_history_tests; + +#[cfg(test)] +mod bucket_bitmap_tests; diff --git a/crates/engine/src/cmd/paint_cmds/bucket_bitmap_tests.rs b/crates/engine/src/cmd/paint_cmds/bucket_bitmap_tests.rs new file mode 100644 index 0000000000..5149067238 --- /dev/null +++ b/crates/engine/src/cmd/paint_cmds/bucket_bitmap_tests.rs @@ -0,0 +1,95 @@ +//! #12536: the Paint Bucket refuses a Bitmap document with the reference's alert text, before +//! anything else, and leaves the document and History unchanged. Grayscale, RGB, CMYK, Lab and +//! Indexed Color documents still fill; Duotone and Multichannel were not measured and keep +//! today's behaviour (no refusal). + +use super::*; + +fn bitmap() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap(); + s.execute("image.mode.grayscale", json!({})).unwrap(); + s.execute("image.mode.bitmap", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.mode, photocraft_color::ColorMode::Bitmap); + s.execute("tools.setColors", json!({"foreground": "#00ff00"})).unwrap(); + s +} + +fn assert_refused(s: &mut Session, params: Value, case: &str) { + let (doc, steps) = (s.active().unwrap().doc.clone(), s.active().unwrap().history.past_len()); + let err = s.execute("paint.bucket", params).unwrap_err().to_string(); + assert_eq!(err, BITMAP_REFUSAL, "{case}"); + assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc), "{case}: document unchanged"); + assert_eq!(s.active().unwrap().history.past_len(), steps, "{case}: no history state"); +} + +#[test] +fn the_refusal_is_the_reference_alert_text() { + assert_eq!(BITMAP_REFUSAL, "Could not use the paint bucket because it does not work with Bitmap images (convert image to Grayscale mode to edit)."); +} + +#[test] +fn a_bitmap_document_is_refused() { + let mut s = bitmap(); + assert_refused(&mut s, json!({"x": 32, "y": 32}), "foreground"); + assert_refused(&mut s, json!({"x": 32, "y": 32, "color": "#000000", "mode": "clear"}), "black, Clear"); + assert_refused(&mut s, json!({"x": 32, "y": 32, "contents": "pattern"}), "a pattern"); + assert_refused(&mut s, json!({"x": 32, "y": 32, "sampleAllLayers": true}), "all layers"); +} + +/// The mode comes first: a click that would fill nothing, or a target that would be refused, +/// gets the Bitmap alert as well. +#[test] +fn the_refusal_comes_before_the_click_and_the_target() { + let mut s = bitmap(); + assert_refused(&mut s, json!({"x": -5, "y": 32}), "off the canvas"); + assert_refused(&mut s, json!({"x": 32, "y": 32, "layer": 999_999}), "a missing layer"); + assert_refused(&mut s, json!({"x": 32, "y": 32, "target": "mask"}), "a missing mask"); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8, "antiAlias": false})).unwrap(); + assert_refused(&mut s, json!({"x": 32, "y": 32}), "outside the selection"); +} + +#[test] +fn other_modes_still_fill() { + for (mode, depth) in [ + ("grayscale", 8), + ("grayscale", 16), + ("grayscale", 32), + ("rgb", 8), + ("rgb", 16), + ("rgb", 32), + ("cmyk", 8), + ("cmyk", 16), + ("lab", 8), + ("lab", 16), + ("indexed", 8), + ] { + let mut s = Session::new(); + let new_mode = if mode == "indexed" { "rgb" } else { mode }; + s.execute("file.new", json!({"width": 64, "height": 64, "mode": new_mode, "depth": depth, "background": "white"})).unwrap(); + if mode == "indexed" { + s.execute("image.mode.indexedColor", json!({})).unwrap(); + assert_eq!(s.active().unwrap().doc.mode, photocraft_color::ColorMode::Indexed); + } + s.execute("tools.setColors", json!({"foreground": "#000000"})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + let r = s.execute("paint.bucket", json!({"x": 32, "y": 32})).unwrap_or_else(|e| panic!("{mode} {depth}: {e}")); + assert_eq!(r["filled"], true, "{mode} {depth}: {r}"); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "{mode} {depth}"); + } +} + +#[test] +fn unmeasured_modes_are_not_refused() { + let mut multi = Session::new(); + multi.execute("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap(); + multi.execute("image.mode.multichannel", json!({})).unwrap(); + let mut duotone = Session::new(); + duotone.execute("file.new", json!({"width": 64, "height": 64, "mode": "grayscale", "background": "white"})).unwrap(); + duotone.execute("image.mode.duotone", json!({"type": "monotone"})).unwrap(); + for (mut s, mode) in [(multi, photocraft_color::ColorMode::Multichannel), (duotone, photocraft_color::ColorMode::Duotone)] { + assert_eq!(s.active().unwrap().doc.mode, mode); + let r = s.execute("paint.bucket", json!({"x": 32, "y": 32})); + assert!(r.as_ref().err().is_none_or(|e| e.to_string() != BITMAP_REFUSAL), "{mode:?}: {r:?}"); + } +} diff --git a/crates/engine/src/cmd/paint_cmds/tests.rs b/crates/engine/src/cmd/paint_cmds/tests.rs index bbcc8f7012..7043373580 100644 --- a/crates/engine/src/cmd/paint_cmds/tests.rs +++ b/crates/engine/src/cmd/paint_cmds/tests.rs @@ -329,3 +329,101 @@ fn bucket_and_gradient_reject_non_numeric_opacity_without_editing() { assert!((px(&s, 5, 5)[0] - 128.0 / 255.0).abs() < 0.01, "{cmd}: null opacity is 100%"); } } + +/// #11311: a white layer (the Background made a normal layer), a selection cleared to +/// transparency, Deselect, then the Paint Bucket clicked in the hole with white at 100 %. Returns +/// the session after the fill and the layer's pixels right after the clear. +fn clear_then_bucket(depth: u32, selection: Value, bucket_aa: bool) -> (Session, Vec<[f32; 4]>) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 120, "height": 100, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + s.execute("select.rect", selection).unwrap(); + s.execute("edit.clear", json!({})).unwrap(); + let cleared = layer_rgba(&s); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("paint.bucket", json!({"x": 60, "y": 50, "color": "#ffffff", "antiAlias": bucket_aa})).unwrap(); + (s, cleared) +} + +/// The active layer's pixels over the canvas, row by row. +fn layer_rgba(s: &Session) -> Vec<[f32; 4]> { + let d = s.active().unwrap(); + let surf = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap(); + let b = d.doc.bounds(); + (b.y0..b.y1).flat_map(|y| (b.x0..b.x1).map(move |x| (x, y))).map(|(x, y)| surf.rgba(x, y)).collect() +} + +/// The first `n` pixels (as `x, y, rgba`) that aren't opaque white at 8 bits. +fn not_white(px: &[[f32; 4]], width: usize, n: usize) -> Vec<(usize, usize, [f32; 4])> { + let is_white = |p: &[f32; 4]| p.iter().all(|c| (c.clamp(0.0, 1.0) * 255.0).round() == 255.0); + px.iter().enumerate().filter(|(_, p)| !is_white(p)).take(n).map(|(i, p)| (i % width, i / width, *p)).collect() +} + +fn assert_all_white(s: &Session, what: &str) { + let doc = &s.active().unwrap().doc; + let width = doc.bounds().width() as usize; + let layer = layer_rgba(s); + assert_eq!(not_white(&layer, width, 8), vec![], "{what}: layer pixels left after the fill"); + let composite = photocraft_compose::render(doc, doc.bounds()).px.clone(); + assert_eq!(composite.len(), layer.len()); + assert_eq!(not_white(&composite, width, 8), vec![], "{what}: composite pixels left after the fill"); +} + +/// #11311 / #11354 review: after clearing an anti-aliased selection and bucket-filling the hole +/// white at 100 %, the hole and the hole's edge are opaque white and the opaque art is untouched. +/// The soft rim the Clear left (straight white at partial alpha) rises only partly, as in the +/// reference application: a pixel of the one-pixel ring 8-adjacent to the flood, at alpha `α`, +/// ends at `α + (1 − α)²`, and pixels further out keep their alpha, so a faint rim stays. Before the first round the hole's own edge stayed semi-transparent (a grey ring); +/// the first round filled the rim to 255 too, which the reference does not do. +#[test] +fn bucket_after_clearing_an_antialiased_selection_fills_the_hole_and_raises_the_rim_partly() { + let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32; + for depth in [8, 16, 32] { + let ellipse = json!({"x": 20, "y": 10, "width": 80, "height": 80, "ellipse": true, "antiAlias": true}); + let (s, cleared) = clear_then_bucket(depth, ellipse, true); + // A transparent hole (its RGB zeroed) inside a rim of straight white at partial alpha, + // which the bucket's similarity test (RGB 255 away from the hole's 0) leaves out. + assert_eq!(cleared[50 * 120 + 60], [0.0; 4], "depth {depth}: the hole is empty"); + let rim: Vec<&[f32; 4]> = cleared.iter().filter(|p| p[3] > 0.0 && p[3] < 1.0).collect(); + assert!(!rim.is_empty(), "depth {depth}: an anti-aliased clear leaves a soft rim"); + assert!(rim.iter().all(|p| p[..3].iter().all(|c| (c - 1.0).abs() < 1e-3)), "depth {depth}: the rim keeps its white"); + + let after = layer_rgba(&s); + // The flood is every pixel the 8-bit wand sees as empty; the ring is the pixels 8-adjacent to it. + let empty = |x: i64, y: i64| (0..120).contains(&x) && (0..100).contains(&y) && level(cleared[(y * 120 + x) as usize][3]) == 0; + let mut raised = 0; + for (i, (was, now)) in cleared.iter().zip(&after).enumerate() { + let at = (i % 120, i / 120); + let (x, y) = (at.0 as i64, at.1 as i64); + let next_to_flood = (-1..=1).any(|dy| (-1..=1).any(|dx| (dx, dy) != (0, 0) && empty(x + dx, y + dy))); + if level(was[3]) == 0 || was[3] >= 1.0 { + assert_eq!(level(now[3]), 255, "depth {depth} at {at:?}: hole, hole edge and opaque art end opaque: {now:?}"); + } else if next_to_flood { + raised += 1; + let want = was[3] + (1.0 - was[3]).powi(2); + assert!((now[3] - want).abs() < 1.5 / 255.0, "depth {depth} at {at:?}: rim {was:?} -> {now:?}, want alpha {want}"); + } else { + assert_eq!(now, was, "depth {depth} at {at:?}: a rim pixel beyond the ring next to the flood stays"); + } + assert!(now[..3].iter().all(|c| (c - 1.0).abs() < 1e-3), "depth {depth} at {at:?}: white: {now:?}"); + } + assert!(raised > 0, "depth {depth}: the fill reaches the rim"); + assert!(after.iter().any(|p| level(p[3]) < 255), "depth {depth}: a faint rim stays, as in the reference"); + } +} + +/// Controls for #11311: a hard-edged selection leaves no soft rim, but the bucket's own +/// anti-aliasing used to leave the hole's edge pixels partly transparent too, so hard edges end +/// white as well; with neither anti-aliased (the case that was always right) it stays white. +#[test] +fn bucket_after_clearing_a_hard_selection_leaves_no_ring() { + let hard_ellipse = json!({"x": 20, "y": 10, "width": 80, "height": 80, "ellipse": true, "antiAlias": false}); + let rect = json!({"x": 30, "y": 20, "width": 60, "height": 60}); + for depth in [8, 16, 32] { + for (selection, bucket_aa) in [(hard_ellipse.clone(), true), (rect.clone(), true), (rect.clone(), false)] { + let (s, cleared) = clear_then_bucket(depth, selection.clone(), bucket_aa); + assert!(cleared.iter().all(|p| p[3] == 0.0 || p[3] == 1.0), "depth {depth} {selection}: a hard clear leaves no rim"); + assert_all_white(&s, &format!("depth {depth} {selection}, bucket antiAlias {bucket_aa}")); + } + } +} diff --git a/crates/engine/src/cmd/path_delete_last_anchor_tests.rs b/crates/engine/src/cmd/path_delete_last_anchor_tests.rs index a9dfb310a9..d0b4cf7252 100644 --- a/crates/engine/src/cmd/path_delete_last_anchor_tests.rs +++ b/crates/engine/src/cmd/path_delete_last_anchor_tests.rs @@ -153,3 +153,21 @@ fn a_type_paths_last_anchor_is_still_refused() { assert_eq!(type_path(&s), Some(before)); assert_eq!(s.active().unwrap().history.entries().len(), steps); } + +/// ⌫ / Delete on the Delete Anchor Point tool's last anchor of a subpath among others (#12761) +/// takes the subpath as one Delete Selection step; the tool's click keeps Delete Anchor Point. +#[test] +fn deleting_a_subpaths_last_anchor_with_its_segments_is_delete_selection() { + let two = || json!({"subpaths": [{"closed": false, "knots": [[100, 300], [200, 300]]}, {"closed": false, "knots": [[400, 300]]}]}); + let s = &mut session(); + s.execute("path.set", json!({"name": "Path 1", "path": two()})).unwrap(); + let before = doc(s).paths[0].path.clone(); + let r = s.execute("path.deleteAnchor", json!({"name": "Path 1", "subpath": 1, "knot": 0, "segments": true})).unwrap(); + assert_eq!(r["subpathRemoved"], json!(true)); + assert_eq!(doc(s).paths[0].path.subpaths.len(), 1); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Delete Selection")); + assert!(s.undo()); + assert_eq!(doc(s).paths[0].path, before); + s.execute("path.deleteAnchor", json!({"name": "Path 1", "subpath": 1, "knot": 0})).unwrap(); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Delete Anchor Point"), "the click's label is unchanged"); +} diff --git a/crates/engine/src/cmd/path_edit_cmds.rs b/crates/engine/src/cmd/path_edit_cmds.rs index c07ee4d3c2..7a8a2b3de5 100644 --- a/crates/engine/src/cmd/path_edit_cmds.rs +++ b/crates/engine/src/cmd/path_edit_cmds.rs @@ -46,16 +46,22 @@ fn knot(cmd: &str, p: &Value) -> Result<[usize; 2]> { Ok([index(cmd, p, "subpath")?, index(cmd, p, "knot")?]) } -/// The History step name: `default`, or `named` when `stepName` asks for it (the Convert Point -/// tool names its steps as the reference does, #12736). Any other value is refused. -fn step_name(cmd: &str, p: &Value, default: &'static str, named: &'static str) -> Result<&'static str> { +/// The History step name: `default`, or one of `named` when `stepName` asks for it (the Convert +/// Point tool names its steps as the reference does, #12736; Direct Selection names a one-anchor +/// drag, #13205). Any other value is refused. +fn step_name(cmd: &str, p: &Value, default: &'static str, named: &[&'static str]) -> Result<&'static str> { match p.get("stepName") { None | Some(Value::Null) => Ok(default), - Some(Value::String(n)) if n == named => Ok(named), - Some(_) => Err(bad(cmd, format!("`stepName` must be \"{named}\""))), + Some(Value::String(n)) => named.iter().copied().find(|m| *m == n.as_str()).ok_or_else(|| bad(cmd, step_names_error(named))), + Some(_) => Err(bad(cmd, step_names_error(named))), } } +fn step_names_error(named: &[&str]) -> String { + let names: Vec = named.iter().map(|n| format!("\"{n}\"")).collect(); + format!("`stepName` must be {}", names.join(" or ")) +} + /// Applies `f` to the targeted path in one undoable step labelled `label`. fn edit_path(s: &mut Session, cmd: &str, p: &Value, label: &str, f: impl FnOnce(&mut Path) -> std::result::Result<(), String>) -> Result { // A malformed target is an error, never a silent edit of the Work Path or the active layer. @@ -116,10 +122,11 @@ fn move_anchors(s: &mut Session, p: &Value) -> Result { }) .collect::>()?; let d = offset(CMD, p)?; + let label = step_name(CMD, p, "Drag Anchor Points", &["Drag Path", "Drag Anchor Point"])?; if p.get("curvature").and_then(Value::as_bool).unwrap_or(false) { - return edit_path(s, CMD, p, "Drag Anchor Points", |path| edit::move_anchors_curvature(path, &anchors, d)); + return edit_path(s, CMD, p, label, |path| edit::move_anchors_curvature(path, &anchors, d)); } - edit_path(s, CMD, p, "Drag Anchor Points", |path| edit::move_anchors(path, &anchors, d)) + edit_path(s, CMD, p, label, |path| edit::move_anchors(path, &anchors, d)) } fn move_handle(s: &mut Session, p: &Value) -> Result { @@ -128,7 +135,7 @@ fn move_handle(s: &mut Session, p: &Value) -> Result { let h = p.get("handle").and_then(Value::as_str).and_then(Handle::parse).ok_or_else(|| bad(CMD, "`handle` must be \"in\" or \"out\""))?; let to = point(CMD, p, "to")?.ok_or_else(|| bad(CMD, "missing `to`"))?; let independent = p.get("independent").and_then(Value::as_bool).unwrap_or(false); - let label = step_name(CMD, p, "Drag Direction Point", "Corner Drag")?; + let label = step_name(CMD, p, "Drag Control Point", &["Corner Drag"])?; edit_path(s, CMD, p, label, |path| edit::move_handle(path, k, h, to, independent)) } @@ -146,7 +153,7 @@ fn bend_segment(s: &mut Session, p: &Value) -> Result { fn convert_point(s: &mut Session, p: &Value) -> Result { const CMD: &str = "path.convertPoint"; let k = knot(CMD, p)?; - let label = step_name(CMD, p, "Convert Point", "Change Anchor Point")?; + let label = step_name(CMD, p, "Convert Point", &["Change Anchor Point"])?; if p.get("curvature").and_then(Value::as_bool).unwrap_or(false) { return edit_path(s, CMD, p, label, |path| edit::toggle_curvature_point(path, k)); } @@ -192,6 +199,14 @@ fn delete_anchor(s: &mut Session, p: &Value) -> Result { }; Ok(()) })?; + // Delete / Backspace (`segments`) that takes a whole subpath is Delete Selection, as in + // Photoshop (#12761); the tool's click on a lone anchor stays Delete Anchor Point. + if removed + && segments + && let Some(st) = s.active_mut() + { + st.history.set_current_label("Delete Selection"); + } if let Some(o) = r.as_object_mut() { o.insert("subpathRemoved".into(), json!(removed)); } @@ -275,11 +290,11 @@ pub fn specs() -> Vec { journal: true, }; vec![ - spec("path.moveAnchors", "Drag Anchor Points", r#""anchors":[[subpath,knot],…],"move":[dx,dy],"curvature":bool=false (anchors move with their handles; Direct Selection drag. curvature = the Curvature Pen's drag: every smooth knot of the touched subpaths gets its handles recomputed so the curve flows through the anchors)"#.into(), move_anchors), + spec("path.moveAnchors", "Drag Anchor Points", r#""anchors":[[subpath,knot],…],"move":[dx,dy],"curvature":bool=false (anchors move with their handles; Direct Selection drag. curvature = the Curvature Pen's drag: every smooth knot of the touched subpaths gets its handles recomputed so the curve flows through the anchors),"stepName":"Drag Path"|"Drag Anchor Point"? (History step name; the Convert Point tool sends "Drag Path" when it drags a whole path, Direct Selection "Drag Anchor Point" when it drags one anchor; default "Drag Anchor Points"; any other value is refused)"#.into(), move_anchors), spec( "path.moveHandle", - "Drag Direction Point", - r#""subpath":i,"knot":j,"handle":"in|out","to":[x,y],"independent":bool=false (a smooth point turns its other handle to stay collinear; independent = ⌥ / Convert Point, makes a corner),"stepName":"Corner Drag"? (History step name; the Convert Point tool sends it; default "Drag Direction Point"; any other value is refused)"#.into(), + "Drag Control Point", + r#""subpath":i,"knot":j,"handle":"in|out","to":[x,y],"independent":bool=false (a smooth point turns its other handle to stay collinear; independent = ⌥ / Convert Point, makes a corner),"stepName":"Corner Drag"? (History step name; the Convert Point tool sends it; default "Drag Control Point"; any other value is refused)"#.into(), move_handle, ), spec( @@ -788,3 +803,7 @@ mod tests { #[cfg(test)] #[path = "path_delete_last_anchor_tests.rs"] mod path_delete_last_anchor_tests; + +#[cfg(test)] +#[path = "direct_select_history_names_tests.rs"] +mod direct_select_history_names_tests; diff --git a/crates/engine/src/cmd/perspective_crop_cmds.rs b/crates/engine/src/cmd/perspective_crop_cmds.rs index f1cc5f3165..161fa35e70 100644 --- a/crates/engine/src/cmd/perspective_crop_cmds.rs +++ b/crates/engine/src/cmd/perspective_crop_cmds.rs @@ -12,7 +12,7 @@ //! editable equivalent for them. Vector masks, paths, notes, slices and guides follow the affine //! map closest to the homography (exact when the quad is a parallelogram). -use photocraft_algo::transform::{Homography, Interp, convex_quad, quad_free_size, quad_size, quad_to_rect, warp_surface_clipped}; +use photocraft_algo::transform::{Homography, Interp, convex_quad_any_winding, quad_free_size, quad_size, quad_to_rect, warp_surface_clipped}; use photocraft_color::PixelFormat; use photocraft_doc::{Document, Layer, LayerContent, LayerId, Size}; use photocraft_geom::{Affine, Rect}; @@ -27,8 +27,9 @@ const CMD: &str = "image.perspectiveCrop"; const MAX_SIDE: u32 = 300_000; /// Corner coordinates beyond this are refused (far past any canvas). const MAX_COORD: f64 = 1e7; -/// The highest resolution (ppi) the crop may set, as for Image Size. -const MAX_RESOLUTION: f64 = 10_000.0; +/// The highest resolution (ppi) the crop may set: the Perspective Crop resolution field's limit +/// (#11977). +const MAX_RESOLUTION: f64 = 29_999.999; fn bad(msg: impl Into) -> EngineError { EngineError::BadParams { cmd: CMD.into(), msg: msg.into() } @@ -38,7 +39,8 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { s.active().map(|_| ()).ok_or_else(|| "no document open".into()) } -/// `corners`: four `[x, y]` points, TL, TR, BR, BL, forming a convex quad clockwise on screen. +/// `corners`: four `[x, y]` points, TL, TR, BR, BL, forming a convex quad. Wound counter-clockwise +/// on screen (a box flipped on one axis) it crops mirrored, each corner as it lies (#12489). fn corners(p: &Value) -> Result<[[f64; 2]; 4]> { let shape = || bad("`corners` must be four [x, y] points: top-left, top-right, bottom-right, bottom-left"); let list = p.get("corners").and_then(Value::as_array).filter(|a| a.len() == 4).ok_or_else(shape)?; @@ -51,9 +53,9 @@ fn corners(p: &Value) -> Result<[[f64; 2]; 4]> { } *slot = [x, y]; } - if !convex_quad(&q) { + if !convex_quad_any_winding(&q) { return Err(bad( - "the corners must form a convex quadrilateral at least 1 px in area, in order top-left, top-right, bottom-right, bottom-left (clockwise on screen)", + "the corners must form a convex quadrilateral at least 1 px in area, in order top-left, top-right, bottom-right, bottom-left (counter-clockwise on screen crops mirrored)", )); } Ok(q) @@ -386,7 +388,7 @@ mod tests { json!({"corners": [[0, 0], [10, 0], [10, 10]]}), json!({"corners": [[0, 0], [50, 0], [100, 0], [0, 50]]}), json!({"corners": [[0, 0], [50, 50], [50, 0], [0, 50]]}), - json!({"corners": [[0, 0], [0, 50], [50, 50], [50, 0]]}), + json!({"corners": [[50, 0], [0, 0], [50, 50], [0, 50]]}), json!({"corners": [[0, 0], [0.5, 0], [0.5, 0.5], [0, 0.5]]}), json!({"corners": [[0, 0], [1e300, 0], [50, 50], [0, 50]]}), json!({"corners": [[0, 0], ["a", 0], [50, 50], [0, 50]]}), diff --git a/crates/engine/src/cmd/preset_import_cmds.rs b/crates/engine/src/cmd/preset_import_cmds.rs index 4430f4d1d2..a68e297d62 100644 --- a/crates/engine/src/cmd/preset_import_cmds.rs +++ b/crates/engine/src/cmd/preset_import_cmds.rs @@ -3,7 +3,7 @@ //! - `brush.presets.importAbr` adds the presets of an `.abr` file (v1, v2, v6+) to the brush //! library as one group named after the file, with the file's own folders nested inside it //! as Photoshop does (Brushes panel › Import Brushes…, Preset Manager). Parsing lives in -//! `photocraft-psd` (`abr`), the mapping onto [`BrushSettings`] in `photocraft-io` (`abr_map`). +//! `craft-psd` (`abr`), the mapping onto [`BrushSettings`] in `photocraft-io` (`abr_map`). //! - `brush.presets.importImage` turns an image file (anything File › Open reads: PNG, JPEG, //! TIFF, PSD…) into a sampled-tip brush preset, as Edit › Define Brush Preset does with a //! selection: dark pixels paint, white and transparent ones don't (TOOL-213-12). @@ -30,7 +30,7 @@ pub const MAX_FILE_BYTES: u64 = 512 << 20; /// Largest accepted `.abr` file: brush libraries of large sampled tips outgrow [`MAX_FILE_BYTES`]. /// Tied to the decoder's sample budget (1 GiB, 512 MiB on 32-bit targets) so it never refuses /// what this accepts. -pub const MAX_ABR_FILE_BYTES: u64 = photocraft_psd::abr::MAX_TOTAL_BYTES as u64; +pub const MAX_ABR_FILE_BYTES: u64 = craft_psd::abr::MAX_TOTAL_BYTES as u64; /// File bytes from `data` (base64) or `path`, plus a default group name. pub(crate) fn file_bytes(p: &Value, cmd: &str, what: &str) -> Result<(Vec, String)> { @@ -350,9 +350,9 @@ fn lab_to_rgb([l, a, b]: [f32; 3]) -> [f32; 3] { [gamma(r), gamma(g), gamma(bb)] } -fn stop_color(c: photocraft_psd::grd::GrdColor) -> crate::presets::gradients::StopColor { +fn stop_color(c: craft_psd::grd::GrdColor) -> crate::presets::gradients::StopColor { use crate::presets::gradients::StopColor; - use photocraft_psd::grd::GrdColor; + use craft_psd::grd::GrdColor; let clamp = |c: [f32; 3]| StopColor::Rgb(c.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 })); match c { GrdColor::Foreground => StopColor::Foreground, @@ -375,7 +375,7 @@ fn import_grd(s: &mut Session, p: &Value) -> Result { None if !stem.is_empty() => stem, None => "Imported Gradients".to_string(), }; - let grads = photocraft_psd::grd::parse(&bytes).map_err(|e| bad(cmd, format!("not a readable gradient file (.grd): {e}")))?; + let grads = craft_psd::grd::parse(&bytes).map_err(|e| bad(cmd, format!("not a readable gradient file (.grd): {e}")))?; // Same default as the group insertion below and the documented contract (#10640). let replace = p.get("replace").and_then(Value::as_bool).unwrap_or(false); let mut taken = @@ -459,8 +459,8 @@ mod tests { assert!(super::file_bytes_limited(&over_limit, "test", "preset", 2).is_err()); } use super::*; - use photocraft_psd::abr::{AbrSample, LegacyBrush, LegacyTip, write_v6, write_v12}; - use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value as DV}; + use craft_psd::abr::{AbrSample, LegacyBrush, LegacyTip, write_v6, write_v12}; + use craft_psd::descriptor::{Descriptor, UnicodeString, Value as DV}; fn abr_v2() -> Vec { let tip = AbrSample { id: String::new(), width: 6, height: 4, depth: 8, data: vec![255; 24] }; @@ -484,14 +484,14 @@ mod tests { /// the value its options-bar field shows, so it paints instead of laying down nothing. #[test] fn selecting_an_imported_zero_opacity_brush_floors_it_at_one_percent() { - use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value as D}; + use craft_psd::descriptor::{Descriptor, UnicodeString, Value as D}; let preset = |opacity: i32| { Descriptor::new("brushPreset") .with("Nm ", D::Text(UnicodeString::new_nul("Faint"))) .with("toolOptions", D::Descriptor(Descriptor::new("currentToolOptions").with("Opct", D::Integer(opacity)))) }; for (opacity, expected) in [(0, 0.01), (37, 0.37)] { - let abr = photocraft_psd::abr::write_v6_folders(2, &[], &[], &[preset(opacity)], &[vec![]], true).unwrap(); + let abr = craft_psd::abr::write_v6_folders(2, &[], &[], &[preset(opacity)], &[vec![]], true).unwrap(); let mut s = Session::new(); s.execute("brush.presets.importAbr", json!({"data": photocraft_paint::tile::b64_encode(&abr), "select": true})).unwrap(); assert!((s.tools.brush.opacity - expected).abs() < 1e-6, "{opacity}: {}", s.tools.brush.opacity); @@ -588,7 +588,7 @@ mod tests { #[test] fn duplicate_gradient_names_remain_independently_selectable() { - use photocraft_psd::grd::{GrdColor, GrdGradient, GrdStop, write}; + use craft_psd::grd::{GrdColor, GrdGradient, GrdStop, write}; let gradients: Vec<_> = [0.2, 0.8] .into_iter() .map(|red| GrdGradient { @@ -627,7 +627,7 @@ mod tests { /// names distinct from the existing group's, keeping name-only selection unambiguous. #[test] fn default_gradient_reimport_keeps_names_unique_across_sibling_groups() { - use photocraft_psd::grd::{GrdColor, GrdGradient, GrdStop, write}; + use craft_psd::grd::{GrdColor, GrdGradient, GrdStop, write}; let gradients = vec![GrdGradient { name: "Sunset".into(), stops: vec![ @@ -651,7 +651,7 @@ mod tests { #[test] fn gradient_import_preserves_original_and_case_distinct_names() { - use photocraft_psd::grd::{GrdColor, GrdGradient, GrdStop, write}; + use craft_psd::grd::{GrdColor, GrdGradient, GrdStop, write}; let gradients: Vec<_> = ["Foo", "Foo", "Foo 2", "FOO"] .into_iter() .enumerate() @@ -687,7 +687,7 @@ mod tests { #[test] fn grd_import_adds_a_gradient_group() { use crate::presets::gradients::StopColor; - use photocraft_psd::grd::{GrdColor, GrdGradient, GrdStop, write}; + use craft_psd::grd::{GrdColor, GrdGradient, GrdStop, write}; let grads = vec![ GrdGradient { name: "Ember".into(), @@ -849,8 +849,8 @@ mod tests { #[test] fn abr_files_get_a_larger_size_cap() { - // 1 GiB on 64-bit; 32-bit (wasm) keeps 512 MiB so a big file fails cleanly instead of aborting. - const WANT: u64 = if cfg!(target_pointer_width = "64") { 1 << 30 } else { 512 << 20 }; + // Match craft-psd's aggregate decoded-sample budget: 2 GiB on 64-bit, 512 MiB on 32-bit. + const WANT: u64 = if cfg!(target_pointer_width = "64") { 2 << 30 } else { 512 << 20 }; const _: () = assert!(MAX_ABR_FILE_BYTES == WANT && MAX_ABR_FILE_BYTES >= MAX_FILE_BYTES); let dir = std::env::temp_dir().join(format!("pc-abr-cap-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); diff --git a/crates/engine/src/cmd/print_cmds.rs b/crates/engine/src/cmd/print_cmds.rs index ba09fdea23..d0f1fd9cd9 100644 --- a/crates/engine/src/cmd/print_cmds.rs +++ b/crates/engine/src/cmd/print_cmds.rs @@ -1525,26 +1525,32 @@ fn package(s: &mut Session, p: &Value) -> Result { // ---------- Paths to Illustrator ---------- +/// `s` with line terminators and other control characters replaced by spaces, so a name stays +/// inside its one PostScript comment line instead of ending it and adding instructions. +fn ps_comment_text(s: &str) -> String { + s.chars().map(|c| if c.is_control() { ' ' } else { c }).collect() +} + /// The document's paths as an Illustrator 3 PostScript file. `which`: "all", "work" or a path /// name. Coordinates are points (pixels at the document resolution), y up. pub fn paths_to_ai(doc: &Document, which: &str) -> Result<(String, usize)> { let dpi = f64::from(doc.resolution_dpi.max(1.0)); let k = 72.0 / dpi; let (w, h) = (f64::from(doc.size.width) * k, f64::from(doc.size.height) * k); - let mut chosen: Vec<(String, &photocraft_doc::Path)> = Vec::new(); + let mut chosen: Vec<&photocraft_doc::Path> = Vec::new(); match which { "all" => { - chosen.extend(doc.paths.iter().map(|p| (p.name.clone(), &p.path))); + chosen.extend(doc.paths.iter().map(|p| &p.path)); if let Some(wp) = &doc.work_path { - chosen.push(("Work Path".into(), wp)); + chosen.push(wp); } } - "work" => chosen.extend(doc.work_path.iter().map(|wp| ("Work Path".to_string(), wp))), - name => chosen.extend(doc.paths.iter().filter(|p| p.name == name).map(|p| (p.name.clone(), &p.path))), + "work" => chosen.extend(doc.work_path.iter()), + name => chosen.extend(doc.paths.iter().filter(|p| p.name == name).map(|p| &p.path)), } let mut s = String::new(); s.push_str("%!PS-Adobe-2.0 EPSF-1.2\n%%Creator: PhotoCraft\n"); - s.push_str(&format!("%%Title: ({})\n", doc.name.replace([')', '('], "_"))); + s.push_str(&format!("%%Title: ({})\n", ps_comment_text(&doc.name).replace([')', '('], "_"))); s.push_str(&format!( "%%BoundingBox: 0 0 {} {}\n%%HiResBoundingBox: 0 0 {w:.4} {h:.4}\n%AI3_Cropmarks: 0 0 {w:.4} {h:.4}\n", w.ceil() as i64, @@ -1553,18 +1559,28 @@ pub fn paths_to_ai(doc: &Document, which: &str) -> Result<(String, usize)> { s.push_str("%%DocumentProcessColors: Black\n%%EndComments\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n"); let pt = |x: f64, y: f64| (x * k, h - y * k); let mut n = 0; - for (name, path) in &chosen { + for path in &chosen { let subs: Vec<_> = path.subpaths.iter().filter(|sp| !sp.knots.is_empty()).collect(); if subs.is_empty() { continue; } n += 1; - s.push_str(&format!("%%Note: {name}\n")); - let compound = subs.len() > 1; - if compound { - s.push_str("*u\n"); - } + // One marked block per path, one group per subpath. A `Join` subpath belongs to the + // component before it, so it writes that component's note (union when none precedes). + s.push_str("%Adobe_Photoshop_Path_Begin:<< /defaultFill false >>\n"); + let mut component_op = photocraft_doc::PathOp::Combine; for sp in subs { + if sp.op != photocraft_doc::PathOp::Join { + component_op = sp.op; + } + s.push_str("*u\n"); + s.push_str(match component_op { + photocraft_doc::PathOp::Exclude => "%AI3_Note:<< /operation /xor /defaultFill false >>\n", + photocraft_doc::PathOp::Subtract => "%AI3_Note:<< /operation /subtract >>\n", + photocraft_doc::PathOp::Intersect => "%AI3_Note:<< /operation /intersect >>\n", + photocraft_doc::PathOp::Combine | photocraft_doc::PathOp::Join => "%AI3_Note:<< /operation /union >>\n", + }); + s.push_str("1 XR\n"); let (x, y) = pt(sp.knots[0].anchor.x, sp.knots[0].anchor.y); s.push_str(&format!("{x:.4} {y:.4} m\n")); for seg in sp.segments() { @@ -1581,10 +1597,9 @@ pub fn paths_to_ai(doc: &Document, which: &str) -> Result<(String, usize)> { } // Unpainted: `n` closes the path, `N` leaves it open. s.push_str(if sp.closed { "n\n" } else { "N\n" }); - } - if compound { s.push_str("*U\n"); } + s.push_str("%Adobe_Photoshop_Path_End\n"); } s.push_str("%%PageTrailer\n%%Trailer\n%%EOF\n"); Ok((s, n)) @@ -1685,3 +1700,7 @@ pub fn specs() -> Vec { #[cfg(test)] #[path = "print_cmds/tests.rs"] mod tests; + +#[cfg(test)] +#[path = "print_cmds/paths_export_path_blocks_tests.rs"] +mod paths_export_path_blocks_tests; diff --git a/crates/engine/src/cmd/print_cmds/paths_export_path_blocks_tests.rs b/crates/engine/src/cmd/print_cmds/paths_export_path_blocks_tests.rs new file mode 100644 index 0000000000..44d606b000 --- /dev/null +++ b/crates/engine/src/cmd/print_cmds/paths_export_path_blocks_tests.rs @@ -0,0 +1,145 @@ +//! Paths to Illustrator: each exported path is its own marked block, with one group and one +//! combine note per subpath, and no path name anywhere in the file. + +use super::*; +use photocraft_doc::{Knot, NamedPath, Path, PathOp, Subpath}; +use photocraft_geom::Point; + +const BEGIN: &str = "%Adobe_Photoshop_Path_Begin:<< /defaultFill false >>\n"; +const END: &str = "%Adobe_Photoshop_Path_End\n"; +const XOR: &str = "%AI3_Note:<< /operation /xor /defaultFill false >>\n"; + +fn with_op(mut sp: Subpath, op: PathOp) -> Subpath { + sp.op = op; + sp +} + +fn rect(x0: f64, y0: f64, x1: f64, y1: f64, op: PathOp) -> Subpath { + with_op(Subpath::polygon(&[(x0, y0), (x1, y0), (x1, y1), (x0, y1)]), op) +} + +fn circle(cx: f64, cy: f64, r: f64) -> Subpath { + let k = r * 0.552_284_749_8; + let knot = |ax: f64, ay: f64, ix: f64, iy: f64, ox: f64, oy: f64| Knot::smooth(Point::new(ax, ay), Point::new(ix, iy), Point::new(ox, oy)); + let mut sp = Subpath::polygon(&[(0.0, 0.0)]); + sp.knots = vec![ + knot(cx + r, cy, cx + r, cy - k, cx + r, cy + k), + knot(cx, cy + r, cx + k, cy + r, cx - k, cy + r), + knot(cx - r, cy, cx - r, cy + k, cx - r, cy - k), + knot(cx, cy - r, cx - k, cy - r, cx + k, cy - r), + ]; + sp.op = PathOp::Exclude; + sp +} + +fn doc_with(paths: Vec<(&str, Vec)>) -> Document { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300, "height": 200, "background": "#ffffff", "name": "Blocks.psd"})).unwrap(); + s.edit("paths", |d, _| { + d.resolution_dpi = 72.0; + for (name, subs) in paths { + d.paths.push(NamedPath { name: name.into(), path: Path::new(subs), psd_raw: None }); + } + Ok(()) + }) + .unwrap(); + (*s.active().unwrap().doc).clone() +} + +/// The text after the file's setup section: just the path blocks and the trailer. +fn body(ai: &str) -> &str { + let from = ai.find("%%EndSetup\n").map(|i| i + "%%EndSetup\n".len()).unwrap(); + &ai[from..ai.find("%%PageTrailer").unwrap()] +} + +fn rect_a() -> (&'static str, Vec) { + ("Rect A", vec![rect(20.0, 20.0, 120.0, 100.0, PathOp::Exclude)]) +} + +fn curve_b() -> (&'static str, Vec) { + ("Curve B", vec![circle(200.0, 100.0, 50.0), with_op(Subpath::polyline(&[(150.0, 170.0), (280.0, 170.0)]), PathOp::Exclude)]) +} + +#[test] +fn a_single_exclude_rectangle_is_one_exact_block_without_its_name() { + let doc = doc_with(vec![rect_a()]); + let (ai, n) = paths_to_ai(&doc, "Rect A").unwrap(); + assert_eq!(n, 1); + let want = + format!("{BEGIN}*u\n{XOR}1 XR\n20.0000 180.0000 m\n120.0000 180.0000 L\n120.0000 100.0000 L\n20.0000 100.0000 L\n20.0000 180.0000 L\nn\n*U\n{END}"); + assert_eq!(body(&ai), want); + assert!(!ai.contains("Rect A"), "{ai}"); +} + +#[test] +fn a_two_subpath_path_is_one_block_with_two_groups() { + let doc = doc_with(vec![curve_b()]); + let (ai, _) = paths_to_ai(&doc, "Curve B").unwrap(); + let b = body(&ai); + assert!(b.starts_with(BEGIN) && b.ends_with(END), "{b}"); + assert_eq!(b.matches("Path_Begin").count(), 1); + assert_eq!(b.matches("Path_End").count(), 1); + let lines: Vec<&str> = b.lines().collect(); + let first_end = lines.iter().position(|l| *l == "*U").unwrap(); + // Group one: *u, note, XR, the circle (move plus four curves), n. + assert_eq!(&lines[1..4], ["*u", XOR.trim_end(), "1 XR"]); + assert!(lines[4].ends_with(" m")); + assert!(lines[5..9].iter().all(|l| l.ends_with(" C")), "{lines:?}"); + assert_eq!(&lines[9..=first_end], ["n", "*U"]); + // Group two: the open line, ending with N. + assert_eq!(&lines[first_end + 1..], ["*u", XOR.trim_end(), "1 XR", "150.0000 30.0000 m", "280.0000 30.0000 L", "N", "*U", "%Adobe_Photoshop_Path_End"]); + assert!(!ai.contains("Curve B")); +} + +#[test] +fn each_combine_operation_writes_its_note() { + let sq = |op| rect(0.0, 0.0, 10.0, 10.0, op); + let doc = doc_with(vec![("Ops", vec![sq(PathOp::Combine), sq(PathOp::Subtract), sq(PathOp::Intersect), sq(PathOp::Exclude), sq(PathOp::Join)])]); + let (ai, _) = paths_to_ai(&doc, "Ops").unwrap(); + let notes: Vec<&str> = ai.lines().filter(|l| l.starts_with("%AI3_Note:")).collect(); + assert_eq!( + notes, + [ + "%AI3_Note:<< /operation /union >>", + "%AI3_Note:<< /operation /subtract >>", + "%AI3_Note:<< /operation /intersect >>", + "%AI3_Note:<< /operation /xor /defaultFill false >>", + // A Join subpath takes the note of the component it belongs to. + "%AI3_Note:<< /operation /xor /defaultFill false >>", + ] + ); +} + +#[test] +fn add_then_subtract_is_union_then_subtract() { + let doc = doc_with(vec![("Frame", vec![rect(0.0, 0.0, 100.0, 100.0, PathOp::Combine), rect(25.0, 25.0, 75.0, 75.0, PathOp::Subtract)])]); + let (ai, _) = paths_to_ai(&doc, "Frame").unwrap(); + let notes: Vec<&str> = ai.lines().filter(|l| l.starts_with("%AI3_Note:")).collect(); + assert_eq!(notes, ["%AI3_Note:<< /operation /union >>", "%AI3_Note:<< /operation /subtract >>"]); + assert_eq!(ai.matches("*u\n").count(), 2); + assert_eq!(ai.matches("Path_Begin").count(), 1); +} + +#[test] +fn all_paths_are_consecutive_blocks_one_per_path() { + let doc = doc_with(vec![rect_a(), curve_b()]); + let (ai, n) = paths_to_ai(&doc, "all").unwrap(); + assert_eq!(n, 2); + let b = body(&ai); + assert_eq!(b.matches(BEGIN).count(), 2); + assert!(b.contains(&format!("*U\n{END}{BEGIN}*u\n")), "{b}"); + assert!(!b.contains("%%Note:")); +} + +#[test] +fn a_path_without_knots_writes_nothing_and_empty_subpaths_are_skipped() { + let mut empty = Subpath::polygon(&[(0.0, 0.0)]); + empty.knots.clear(); + let doc = doc_with(vec![("Empty", vec![empty.clone()]), ("Mixed", vec![empty, rect(0.0, 0.0, 10.0, 10.0, PathOp::Exclude)])]); + let (ai, n) = paths_to_ai(&doc, "all").unwrap(); + assert_eq!(n, 1); + assert_eq!(body(&ai).matches(BEGIN).count(), 1); + assert_eq!(body(&ai).matches("*u\n").count(), 1); + assert_eq!(paths_to_ai(&doc, "Empty").unwrap().1, 0); + assert_eq!(paths_to_ai(&doc, "Empty").unwrap().0.matches("Path_Begin").count(), 0); +} diff --git a/crates/engine/src/cmd/print_cmds/tests.rs b/crates/engine/src/cmd/print_cmds/tests.rs index c3d6e536df..32ebd6435b 100644 --- a/crates/engine/src/cmd/print_cmds/tests.rs +++ b/crates/engine/src/cmd/print_cmds/tests.rs @@ -652,8 +652,8 @@ fn paths_export_as_illustrator_postscript() { let ai = r["ai"].as_str().unwrap(); assert!(ai.starts_with("%!PS-Adobe-2.0 EPSF-1.2")); assert!(ai.contains("%%BoundingBox: 0 0 300 150")); - assert!(ai.contains("*u\n10.0000 140.0000 m\n100.0000 140.0000 L\n"), "{ai}"); - assert!(ai.contains("\nn\n") && ai.contains("\nN\n*U\n")); + assert!(ai.contains("1 XR\n10.0000 140.0000 m\n100.0000 140.0000 L\n"), "{ai}"); + assert!(ai.contains("\nn\n*U\n") && ai.contains("\nN\n*U\n")); assert!(ai.contains(" C\n"), "curve segment"); let dir = tmp("ai"); let r = s.execute("file.export.pathsToIllustrator", json!({"path": format!("{dir}/p.ai"), "paths": "Shapes"})).unwrap(); @@ -1561,3 +1561,8 @@ fn printed_pdf_uses_winansi_for_labels_and_descriptions() { assert!(content.contains(r"(Price: \20020 \(proof\)) Tj"), "{content}"); assert!(content.is_ascii(), "encoded bytes are escaped, never UTF-8 text operands"); } + +#[test] +fn postscript_comment_text_cannot_end_its_line() { + assert_eq!(ps_comment_text("a\nshowpage\r%x"), "a showpage %x"); +} diff --git a/crates/engine/src/cmd/rasterize_style_cmds.rs b/crates/engine/src/cmd/rasterize_style_cmds.rs index 55a637d5cb..5c8210852b 100644 --- a/crates/engine/src/cmd/rasterize_style_cmds.rs +++ b/crates/engine/src/cmd/rasterize_style_cmds.rs @@ -106,17 +106,30 @@ fn bake_one(s: &mut Session, id: LayerId, key: &str) -> Result { /// one history step. fn rasterize_layer_style(s: &mut Session, p: &Value) -> Result { let ids = crate::layer_multi_cmds::targets(s, p)?; + bake_layers(s, ids, bake_one) +} + +/// Bake `ids` with `bake` as one history step; a layer that fails takes back the ones baked before +/// it (#4974). +fn bake_layers(s: &mut Session, ids: Vec, bake: impl Fn(&mut Session, LayerId, &str) -> Result) -> Result { let many = ids.len() > 1; - let key = crate::extra_cmds::step_key(s, "rasterizeLayerStyle"); - let mut done = Vec::new(); - for id in ids { - if bake_one(s, id, &key)? { - done.push(id.0); - } + let nothing = || EngineError::Other(if many { "none of the selected layers has layer effects" } else { "the layer has no layer effects" }.into()); + // Refused before a step starts: a failed `compound` still moves the revision, and a command + // that changes nothing must leave it alone. + if !ids.iter().any(|&id| s.active().and_then(|d| d.doc.layer(id)).is_some_and(can_bake)) { + return Err(nothing()); } - let Some(&first) = done.first() else { - return Err(EngineError::Other(if many { "none of the selected layers has layer effects" } else { "the layer has no layer effects" }.into())); - }; + let key = crate::extra_cmds::step_key(s, "rasterizeLayerStyle"); + let (first, done) = crate::analysis_cmds::compound(s, "Rasterize Layer Style", |s| { + let mut done = Vec::new(); + for id in ids { + if bake(s, id, &key)? { + done.push(id.0); + } + } + let Some(&first) = done.first() else { return Err(nothing()) }; + Ok((first, done)) + })?; let active = s.active().and_then(|d| d.active_layer).map(|id| id.0).filter(|id| done.contains(id)); Ok(json!({"layer": active.unwrap_or(first), "layers": done})) } diff --git a/crates/engine/src/cmd/rasterize_style_cmds/tests.rs b/crates/engine/src/cmd/rasterize_style_cmds/tests.rs index b4391cb6f2..285ef60d97 100644 --- a/crates/engine/src/cmd/rasterize_style_cmds/tests.rs +++ b/crates/engine/src/cmd/rasterize_style_cmds/tests.rs @@ -162,3 +162,58 @@ fn disabled_and_bad_params_fail_gracefully() { s.execute("layer.layerStyle.stroke", json!({"layer": g})).unwrap(); assert!(s.execute(ID, json!({"layer": g})).is_err(), "group styles are not baked"); } + +/// #4974: a layer that fails to bake takes back the ones baked before it. +#[test] +fn a_later_layer_failing_takes_back_the_baked_ones() { + let (mut s, id) = scene(8); + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let before = s.active().unwrap().doc.clone(); + let steps = s.active().unwrap().history.past_len(); + let journal = s.journal.len(); + let calls = std::cell::Cell::new(0); + let r = bake_layers(&mut s, vec![LayerId(id), LayerId(id)], |s, id, key| { + calls.set(calls.get() + 1); + if calls.get() == 1 { bake_one(s, id, key) } else { Err(EngineError::Other("second layer failed".into())) } + }); + assert!(r.is_err()); + assert_eq!(calls.get(), 2); + assert_eq!(layer(&s, id).effects.items.len(), 5); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before)); + assert_eq!(s.active().unwrap().history.past_len(), steps); + assert!(!s.active().unwrap().history.can_redo()); + assert_eq!(s.journal.len(), journal); + assert!(!s.active().unwrap().is_dirty()); +} + +/// A layer with no effects is refused before a step starts: the revision does not move. +#[test] +fn a_layer_without_effects_changes_nothing() { + let (mut s, _) = scene(8); + let plain = s.execute("layer.new.layer", json!({"name": "plain"})).unwrap()["layer"].as_u64().unwrap(); + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let (revision, steps) = (s.active().unwrap().revision, s.active().unwrap().history.past_len()); + let err = bake_layers(&mut s, vec![LayerId(plain)], bake_one).unwrap_err().to_string(); + assert!(err.contains("no layer effects"), "{err}"); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.active().unwrap().history.past_len(), steps); + assert!(!s.active().unwrap().is_dirty()); +} + +/// Through the command itself: a layer without effects is refused and nothing moves. +#[test] +fn rasterize_layer_style_on_a_layer_without_effects_changes_nothing() { + let (mut s, _) = scene(8); + s.execute("layer.new.layer", json!({"name": "plain"})).unwrap(); + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let (revision, steps, journal) = (s.active().unwrap().revision, s.active().unwrap().history.past_len(), s.journal.len()); + let err = s.execute(ID, json!({})).unwrap_err().to_string(); + assert!(err.contains("no selected layer has layer effects"), "{err}"); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.active().unwrap().history.past_len(), steps); + assert_eq!(s.journal.len(), journal); + assert!(!s.active().unwrap().is_dirty()); +} diff --git a/crates/engine/src/cmd/retouch_cmds.rs b/crates/engine/src/cmd/retouch_cmds.rs index b4fcdd9022..6c891b8449 100644 --- a/crates/engine/src/cmd/retouch_cmds.rs +++ b/crates/engine/src/cmd/retouch_cmds.rs @@ -26,10 +26,13 @@ use crate::commands::{CommandSpec, blend_from_str}; use crate::{EngineError, Result, Session}; mod art_history; +mod clone_sampling; mod content_aware_move; mod patch; mod pattern_stamp; -pub use pattern_stamp::live_impressionist as live_pattern_impressionist; +pub use pattern_stamp::{ + INDEXED_REFUSAL as PATTERN_STAMP_INDEXED_REFUSAL, live_impressionist as live_pattern_impressionist, press_refusal as pattern_stamp_press_refusal, +}; mod periodic; mod remove; pub use content_aware_move::{ContentAwarePreview, preview as content_aware_move_preview}; @@ -234,7 +237,7 @@ mod dab; mod heal; mod sampling; -pub use clone::{LiveRetouch, clone_preview, clone_preview_periodic}; +pub use clone::{LiveRetouch, clone_destination_preview, clone_preview, clone_preview_periodic, healing_preview, healing_preview_periodic}; use clone::{blend_param, clamp_samples, clone_stamp}; pub(crate) use dab::DabEffect; #[cfg(test)] @@ -256,7 +259,7 @@ pub fn specs() -> Vec { menu: &[], shortcut: None, params: brush_params!( - r#","source":[sx,sy] (sampled under the first point) | "offset":[dx,dy],"aligned":bool=true,"sampleLayer":"current|currentAndBelow|all"="current","mode":"normal|multiply|…"="normal","wrap":bool=false (repeat source and stroke at document edges for Pattern Preview) → {"damage","offset","aligned","nextSource"}"# + r#","source":[sx,sy] (sampled under the first point) | "offset":[dx,dy],"aligned":bool=true,"sampleLayer":"current|currentAndBelow|all"="current","sourceLayer":id? (Current Layer: this layer, else the picked slot's layer/document, else the paint target; explicit source/offset use this document),"mode":"normal|multiply|…"="normal","wrap":bool=false (repeat source and stroke at document edges for Pattern Preview) → {"damage","offset","aligned","nextSource"}"# ), enabled: has_pixel_layer, run: clone_stamp, @@ -420,6 +423,9 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests; +#[cfg(test)] +mod clone_source_layer_tests; + #[cfg(test)] mod patch_history_names_tests; diff --git a/crates/engine/src/cmd/retouch_cmds/art_history.rs b/crates/engine/src/cmd/retouch_cmds/art_history.rs index b95c2bceb5..cca503f536 100644 --- a/crates/engine/src/cmd/retouch_cmds/art_history.rs +++ b/crates/engine/src/cmd/retouch_cmds/art_history.rs @@ -163,6 +163,27 @@ fn stamp_region( } } +/// A source of another colour mode, then any document but an 8-bit one, refused with the reference +/// application's alert texts (#12637). The 16-bit text was seen with one layer only; two layers, +/// or a depth change after the source, showed "not directly editable", so that text covers every +/// other 16-bit case. +fn refuse_format(doc: &photocraft_doc::Document, source: &photocraft_doc::Document) -> Result<()> { + use photocraft_color::SampleType; + let why = if source.mode != doc.mode { + "the current color mode does not match that of the history state." + } else { + match doc.depth { + SampleType::U8 => return Ok(()), + SampleType::F32 => "it does not work with 32 bit per channel images (convert image to 8 or 16 bit per channel to edit).", + SampleType::U16 if source.depth == doc.depth && doc.layer_count() == 1 => { + "it does not work with 16 bit per channel images (convert image to 8 bit per channel to edit)." + } + SampleType::U16 => "the pixel data for this layer is not directly editable.", + } + }; + Err(EngineError::Other(format!("Could not use the art history brush because {why}"))) +} + /// Run `paint.artHistoryBrush`. pub fn run(s: &mut Session, p: &Value) -> Result { let _ = object(p)?; @@ -195,15 +216,11 @@ pub fn run(s: &mut Session, p: &Value) -> Result { let (stroke, id) = parse_brush(s, p, CMD)?; let _ = stroke; // The same source as the History Brush: the `state` or `snapshot` passed, else the History - // panel's source, refused after a canvas size change, then after a colour mode change, as - // Photoshop does (#12826), before a layer missing from it. Compare document modes: the pixel - // format reads Indexed and Multichannel as RGB. + // panel's source, refused after a canvas size change, then after a colour mode change (#12826) + // or at a depth other than 8 bits, as Photoshop does, before a layer missing from it. Compare + // document modes: the pixel format reads Indexed and Multichannel as RGB. let st = s.active().ok_or(EngineError::NoDocument)?; - if crate::history_source_cmds::paint_source(st, p, CMD)?.mode != st.doc.mode { - return Err(EngineError::Other( - "the current color mode does not match that of the History Brush source: set a source of this color mode in the History panel".into(), - )); - } + refuse_format(&st.doc, &*crate::history_source_cmds::paint_source(st, p, CMD)?)?; let src_surface = super::history_source(s, id, p, CMD)?; // Truncating a huge row index only changes the seed. let seed = RNG_SEED ^ p.get("state").and_then(Value::as_u64).map_or(0, |i| i as u32); @@ -302,9 +319,10 @@ mod tests { s.execute("paint.artHistoryBrush", p) } + /// 8-bit only: other depths are refused (#12637). #[test] - fn restores_open_state_at_every_depth_and_undoes() { - for (depth, mode) in [(8u64, "rgb"), (16, "rgb"), (32, "rgb"), (16, "gray")] { + fn restores_open_state_in_8_bit_modes_and_undoes() { + for (depth, mode) in [(8u64, "rgb"), (8, "gray")] { let mut s = session(48, 32, depth, mode); paint_layer(&mut s, |_, _| [0.1, 0.8, 0.2, 1.0]); s.execute("edit.fill", json!({"color": "#2030c0"})).unwrap(); @@ -449,31 +467,29 @@ mod tests { before.iter().enumerate().map(|(i, b)| (0..4).map(|c| (rgba(s, 8 + i as i32, 16)[c] - b[c]).abs()).sum::()).sum() } - /// The stroke's Opacity scales how far it restores the source, at every depth; omitted = 100. + /// The stroke's Opacity scales how far it restores the source; omitted = 100. #[test] - fn opacity_scales_the_stroke_at_every_depth() { - for depth in [8u64, 16, 32] { - let setup = || { - let mut s = session(48, 32, depth, "rgb"); - s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); - s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); - s - }; - let row = |s: &Session| (8..41).map(|x| rgba(s, x, 16)).collect::>(); - let diff = |extra: Value| { - let mut s = setup(); - let before = row(&s); - stroke(&mut s, extra).unwrap(); - row_diff(&s, &before) - }; - let none = diff(json!({"state": 1, "opacity": 0})); - let half = diff(json!({"state": 1, "opacity": 50})); - let full = diff(json!({"state": 1, "opacity": 100})); - let omitted = diff(json!({"state": 1})); - assert_eq!(none, 0.0, "opacity 0 leaves the pixels alone at depth {depth}"); - assert!(half > 0.0 && half < full, "depth {depth}: half {half} full {full}"); - assert_eq!(omitted, full, "omitted opacity is 100 at depth {depth}"); - } + fn opacity_scales_the_stroke() { + let setup = || { + let mut s = session(48, 32, 8, "rgb"); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap(); + s + }; + let row = |s: &Session| (8..41).map(|x| rgba(s, x, 16)).collect::>(); + let diff = |extra: Value| { + let mut s = setup(); + let before = row(&s); + stroke(&mut s, extra).unwrap(); + row_diff(&s, &before) + }; + let none = diff(json!({"state": 1, "opacity": 0})); + let half = diff(json!({"state": 1, "opacity": 50})); + let full = diff(json!({"state": 1, "opacity": 100})); + let omitted = diff(json!({"state": 1})); + assert_eq!(none, 0.0, "opacity 0 leaves the pixels alone"); + assert!(half > 0.0 && half < full, "half {half} full {full}"); + assert_eq!(omitted, full, "omitted opacity is 100"); } #[test] @@ -547,3 +563,7 @@ mod art_history_noop_state_tests; #[cfg(test)] #[path = "art_history_mode_mismatch_tests.rs"] mod art_history_mode_mismatch_tests; + +#[cfg(test)] +#[path = "art_history_depth_tests.rs"] +mod art_history_depth_tests; diff --git a/crates/engine/src/cmd/retouch_cmds/art_history_depth_tests.rs b/crates/engine/src/cmd/retouch_cmds/art_history_depth_tests.rs new file mode 100644 index 0000000000..d6c8b13525 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/art_history_depth_tests.rs @@ -0,0 +1,138 @@ +//! The Art History Brush works in 8-bit documents only and refuses a source of another colour +//! mode, with the reference application's alert texts: no state, no pixel change (#12637). The +//! History Brush keeps painting at every depth. + +use super::art_history_noop_state_tests::{pixels, steps, stroke}; +use super::*; + +const BITS16: &str = + "Could not use the art history brush because it does not work with 16 bit per channel images (convert image to 8 bit per channel to edit)."; +const BITS32: &str = + "Could not use the art history brush because it does not work with 32 bit per channel images (convert image to 8 or 16 bit per channel to edit)."; +const NOT_EDITABLE: &str = "Could not use the art history brush because the pixel data for this layer is not directly editable."; +const MODE: &str = "Could not use the art history brush because the current color mode does not match that of the history state."; + +/// Rows Open (white), Fill (red): row 1 is the red state. +fn filled(depth: u64, mode: &str) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 48, "height": 32, "depth": depth, "mode": mode, "background": "white"})).unwrap(); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + s +} + +/// The newest History panel row, the state that holds every layer there is now. +fn last_row(s: &Session) -> usize { + s.active().unwrap().history.entries().len() - 1 +} + +/// The stroke's error, after checking it added no state and changed no pixel. +fn refused(s: &mut Session, extra: Value, case: &str) -> String { + let (before, n) = (s.active().unwrap().doc.clone(), steps(s)); + let e = stroke(s, extra).expect_err(case).to_string(); + assert_eq!(steps(s), n, "{case}: no state"); + assert!(s.active().unwrap().doc == before, "{case}: no pixel changed"); + e +} + +/// A tolerance-0 stroke from `state` that paints and adds one state. +fn paints(s: &mut Session, state: Value, case: &str) { + let (before, n) = (pixels(s), steps(s)); + let r = stroke(s, json!({"tolerance": 0, "state": state})).unwrap_or_else(|e| panic!("{case}: {e}")); + assert!(!r["damage"].is_null(), "{case}: {r}"); + assert_eq!(steps(s), n + 1, "{case}"); + assert_ne!(pixels(s), before, "{case}: the source painted"); +} + +#[test] +fn a_single_layer_16_bit_document_is_refused() { + for mode in ["rgb", "gray"] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 48, "height": 32, "depth": 16, "mode": mode})).unwrap(); + // The source is the open state, the History panel's default. + assert_eq!(refused(&mut s, json!({"state": null, "tolerance": 0}), mode), BITS16, "{mode}"); + let mut s = filled(16, mode); + assert_eq!(refused(&mut s, json!({"tolerance": 0}), mode), BITS16, "{mode} from row 1"); + } +} + +#[test] +fn a_layered_16_bit_document_is_not_directly_editable() { + let mut s = filled(16, "rgb"); + s.execute("layer.new.layer", json!({})).unwrap(); + let row = last_row(&s); + assert_eq!(refused(&mut s, json!({"tolerance": 0, "state": row}), "two layers"), NOT_EDITABLE); +} + +#[test] +fn a_depth_change_to_16_bits_after_the_source_is_not_directly_editable() { + for layered in [false, true] { + let mut s = filled(8, "rgb"); + if layered { + s.execute("layer.new.layer", json!({})).unwrap(); + } + s.execute("image.mode.bits16", json!({})).unwrap(); + for tolerance in [0, 90] { + let case = format!("layered {layered} tolerance {tolerance}"); + let row = last_row(&s) - 1; + let e = refused(&mut s, json!({"tolerance": tolerance, "state": row}), &case); + assert_eq!(e, NOT_EDITABLE, "{case}"); + } + } +} + +#[test] +fn a_32_bit_document_is_refused() { + let mut s = filled(32, "rgb"); + assert_eq!(refused(&mut s, json!({"tolerance": 0}), "new 32-bit"), BITS32); + s.execute("layer.new.layer", json!({})).unwrap(); + let row = last_row(&s); + assert_eq!(refused(&mut s, json!({"tolerance": 0, "state": row}), "two layers"), BITS32); + let mut s = filled(8, "rgb"); + s.execute("image.mode.bits32", json!({})).unwrap(); + assert_eq!(refused(&mut s, json!({"tolerance": 0}), "8 to 32 bits after the source"), BITS32); +} + +#[test] +fn a_source_of_another_color_mode_gives_the_color_mode_text() { + let mut s = filled(8, "rgb"); + s.execute("image.mode.grayscale", json!({})).unwrap(); + for tolerance in [0, 90] { + assert_eq!(refused(&mut s, json!({"tolerance": tolerance}), "RGB to Grayscale"), MODE, "tolerance {tolerance}"); + } +} + +#[test] +fn eight_bit_documents_paint_as_before() { + for mode in ["rgb", "gray", "cmyk", "lab"] { + let mut s = filled(8, mode); + paints(&mut s, json!(0), mode); + } + // Grayscale with the source taken after the conversion. + let mut s = filled(8, "rgb"); + s.execute("image.mode.grayscale", json!({})).unwrap(); + let row = last_row(&s); + s.execute("edit.fill", json!({"color": "#ffffff"})).unwrap(); + paints(&mut s, json!(row), "Grayscale source after the conversion"); +} + +/// 16 -> 8 bits after the source wasn't measured: the deeper source is converted and paints, as +/// before. +#[test] +fn an_8_bit_document_with_a_deeper_source_still_paints() { + let mut s = filled(16, "rgb"); + s.execute("image.mode.bits8", json!({})).unwrap(); + paints(&mut s, json!(0), "16 to 8 bits after the source"); +} + +#[test] +fn the_history_brush_still_paints_at_every_depth() { + for depth in [8u64, 16, 32] { + let mut s = filled(depth, "rgb"); + let (before, n) = (pixels(&s), steps(&s)); + // Row 0, the white open state, over the red fill. + let p = json!({"points": [[8, 16], [40, 16]], "size": 12, "hardness": 100, "state": 0}); + s.execute("paint.historyBrush", p).unwrap_or_else(|e| panic!("depth {depth}: {e}")); + assert_eq!(steps(&s), n + 1, "depth {depth}"); + assert_ne!(pixels(&s), before, "depth {depth}: the source painted"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/art_history_mode_mismatch_tests.rs b/crates/engine/src/cmd/retouch_cmds/art_history_mode_mismatch_tests.rs index 87fc7e90a1..fb9565be1c 100644 --- a/crates/engine/src/cmd/retouch_cmds/art_history_mode_mismatch_tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/art_history_mode_mismatch_tests.rs @@ -33,30 +33,15 @@ fn a_source_of_another_color_mode_is_refused() { #[test] fn a_source_in_the_current_color_mode_still_paints() { - for depth in [8u64, 16] { - for mode in MODES { - let mut s = held_back_session(depth); - s.execute(mode, json!({})).unwrap(); - let row = s.active().unwrap().history.entries().len() - 1; - s.execute("edit.fill", json!({"color": "#ffffff"})).unwrap(); - let (before, n) = (pixels(&s), steps(&s)); - let r = stroke(&mut s, json!({"tolerance": 0, "state": row})).unwrap(); - assert!(!r["damage"].is_null(), "depth {depth} {mode}: {r}"); - assert_eq!(steps(&s), n + 1, "depth {depth} {mode}"); - assert_ne!(pixels(&s), before, "depth {depth} {mode}: the source state painted"); - } + for mode in MODES { + let mut s = held_back_session(8); + s.execute(mode, json!({})).unwrap(); + let row = s.active().unwrap().history.entries().len() - 1; + s.execute("edit.fill", json!({"color": "#ffffff"})).unwrap(); + let (before, n) = (pixels(&s), steps(&s)); + let r = stroke(&mut s, json!({"tolerance": 0, "state": row})).unwrap(); + assert!(!r["damage"].is_null(), "{mode}: {r}"); + assert_eq!(steps(&s), n + 1, "{mode}"); + assert_ne!(pixels(&s), before, "{mode}: the source state painted"); } } - -/// Only the colour mode is refused: a source of another bit depth converts as before (not measured -/// for this brush; today's behaviour). -#[test] -fn a_source_of_another_bit_depth_still_paints() { - let mut s = held_back_session(8); - s.execute("image.mode.bits16", json!({})).unwrap(); - let (before, n) = (pixels(&s), steps(&s)); - let r = stroke(&mut s, json!({"tolerance": 0})).unwrap(); - assert!(!r["damage"].is_null(), "{r}"); - assert_eq!(steps(&s), n + 1); - assert_ne!(pixels(&s), before); -} diff --git a/crates/engine/src/cmd/retouch_cmds/art_history_noop_state_tests.rs b/crates/engine/src/cmd/retouch_cmds/art_history_noop_state_tests.rs index 79a1a45edc..3a67d39df9 100644 --- a/crates/engine/src/cmd/retouch_cmds/art_history_noop_state_tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/art_history_noop_state_tests.rs @@ -51,21 +51,19 @@ pub(super) fn stroke(s: &mut Session, extra: Value) -> Result { #[test] fn a_click_held_back_by_the_tolerance_adds_one_unchanged_state() { - for depth in [8u64, 16, 32] { - for tolerance in [90, 95, 99, 100] { - for points in [json!([[24, 16]]), json!([[8, 16], [40, 16]])] { - let mut s = held_back_session(depth); - let (before, n) = (pixels(&s), steps(&s)); - let r = stroke(&mut s, json!({"tolerance": tolerance, "points": points})).unwrap(); - let case = format!("depth {depth} tolerance {tolerance} points {points}"); - assert!(r["damage"].is_null(), "{case}: {r}"); - assert_eq!(steps(&s), n + 1, "{case}: one state"); - assert_eq!(s.active().unwrap().history.undo_label(), Some("Art History Brush"), "{case}"); - assert_eq!(pixels(&s), before, "{case}: no pixel changed"); - assert!(s.undo(), "{case}"); - assert_eq!(steps(&s), n, "{case}: undo removes the state"); - assert_eq!(pixels(&s), before, "{case}: undo leaves the layer as it was"); - } + for tolerance in [90, 95, 99, 100] { + for points in [json!([[24, 16]]), json!([[8, 16], [40, 16]])] { + let mut s = held_back_session(8); + let (before, n) = (pixels(&s), steps(&s)); + let r = stroke(&mut s, json!({"tolerance": tolerance, "points": points})).unwrap(); + let case = format!("tolerance {tolerance} points {points}"); + assert!(r["damage"].is_null(), "{case}: {r}"); + assert_eq!(steps(&s), n + 1, "{case}: one state"); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Art History Brush"), "{case}"); + assert_eq!(pixels(&s), before, "{case}: no pixel changed"); + assert!(s.undo(), "{case}"); + assert_eq!(steps(&s), n, "{case}: undo removes the state"); + assert_eq!(pixels(&s), before, "{case}: undo leaves the layer as it was"); } } } diff --git a/crates/engine/src/cmd/retouch_cmds/blur_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/blur_refuses_indexed_tests.rs new file mode 100644 index 0000000000..16e430f650 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/blur_refuses_indexed_tests.rs @@ -0,0 +1,57 @@ +//! #12656: the Blur tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the blur tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the blur tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// The grey document with its left half black: an edge for the stroke to work on. +fn edged(mode: ColorMode, depth: SampleType) -> Session { + let mut s = session(mode, depth); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 64})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "strength": 100}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = edged(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.blur", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.blur", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = edged(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.blur", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + let before = pixels(&s); + s.execute("paint.blur", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_ne!(pixels(&s), before, "{mode:?}/{depth:?}: the stroke changed pixels"); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/burn_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/burn_refuses_indexed_tests.rs new file mode 100644 index 0000000000..d278633555 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/burn_refuses_indexed_tests.rs @@ -0,0 +1,48 @@ +//! #12673: the Burn tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the burn tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the burn tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "range": "midtones", "exposure": 100}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = session(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.burn", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.burn", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = session(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.burn", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + let before = pixels(&s); + s.execute("paint.burn", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_ne!(pixels(&s), before, "{mode:?}/{depth:?}: the stroke changed pixels"); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/clone.rs b/crates/engine/src/cmd/retouch_cmds/clone.rs index 399ccc9d07..ada043ade4 100644 --- a/crates/engine/src/cmd/retouch_cmds/clone.rs +++ b/crates/engine/src/cmd/retouch_cmds/clone.rs @@ -1,5 +1,6 @@ +use super::clone_sampling::{self, CloneFrom}; use super::heal::history_source; -use super::sampling::{SampleLayers, sample, sample_layers}; +use super::sampling::{SampleLayers, sample_layers}; use super::{ BlendMode, BrushSettings, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, SampleType, Session, Stroke, StrokePoint, Surface, Value, alpha_index, apply_coverage, bad, blend_from_str, coverage, damage_json, flag, has_pixel_layer, json, parse_brush, pattern_stamp, periodic, point, @@ -8,11 +9,14 @@ use super::{ /// Where a clone stroke samples: `offset` / `source` params, else the active Clone Source slot, /// with the slot's (or the call's) scale, rotation and flips (see `presets::clone_source`). -pub(super) fn clone_mapping(s: &mut Session, p: &Value, stroke: &Stroke, cmd: &str) -> Result { +pub(super) fn clone_mapping(s: &Session, p: &Value, stroke: &Stroke, cmd: &str) -> Result { let f = stroke.points[0]; - crate::presets::clone_source::mapping(s, p, (f.x, f.y), cmd) + crate::presets::clone_source::resolve(s, p, (f.x, f.y), cmd).map(|(map, _)| map) } +/// Most source pixels one clone sample may read (a 8192 x 8192 window); real strokes stay far below. +const MAX_CLONE_SOURCE_PIXELS: u64 = 1 << 26; + /// Source pixels for destination `rect`: a translated read, or a bilinear resample when the /// clone source is scaled, rotated or flipped. #[allow(clippy::too_many_arguments)] @@ -21,14 +25,13 @@ pub(super) fn clone_sample( id: Option, surf: &Surface, which: SampleLayers, + source: &CloneFrom, rect: Rect, map: &crate::presets::clone_source::Mapping, wrap: bool, cmd: &str, ) -> Result { - let read = |rect| { - if wrap { periodic::sample(pre, id, surf, which, rect, cmd) } else { Ok(sample(pre, id, surf, which, rect)) } - }; + let read = |rect| source.sample(pre, id, surf, which, rect, wrap, cmd); if map.is_translation() { let off = map.offset(); let src = rect.translate(off.0, off.1); @@ -41,8 +44,70 @@ pub(super) fn clone_sample( r.rect = rect; return Ok(r); } - let src = read(map.source_rect(rect))?; - Ok(crate::presets::clone_source::resample(&src, rect, map, alpha_index(&surf.format()))) + // A small W/H scale makes the source window enormous for a bounded destination: refuse it + // before the dense read allocates width x height x channels floats. + let sr = map.source_rect(rect); + if u64::from(sr.width()) * u64::from(sr.height()) > MAX_CLONE_SOURCE_PIXELS { + return Err(bad(cmd, "the scaled clone source covers too large an area; raise the clone source's W/H or use a smaller brush")); + } + let src = read(sr)?; + Ok(crate::presets::clone_source::resample(&src, rect, map, alpha_index(&source.sample_format(surf)))) +} + +/// Composite explicit source coverage onto a destination that may store no alpha channel. +/// Small working patches keep temporary allocations bounded and preserve native colours/depth. +#[allow(clippy::too_many_arguments)] +pub(super) fn apply_clone_coverage( + target: &mut Surface, + rect: Rect, + cov: &[f32], + opacity: f32, + selection: Option<&Surface>, + lock: bool, + paint: &Region, + mode: BlendMode, +) -> Rect { + let fmt = target.format(); + let n = fmt.channels(); + if fmt.alpha || paint.ch == n || rect.is_empty() { + return apply_coverage(target, rect, cov, opacity, selection, lock, paint, mode); + } + let full_width = rect.width() as usize; + let mut y = rect.y0; + while y < rect.y1 { + let y1 = y.saturating_add(64).min(rect.y1); + let mut x = rect.x0; + while x < rect.x1 { + let x1 = x.saturating_add(64).min(rect.x1); + let block = Rect::new(x, y, x1, y1); + let width = block.width() as usize; + let mut block_cov = vec![0.0; width * block.height() as usize]; + for (row, values) in block_cov.chunks_exact_mut(width).enumerate() { + let offset = (y.abs_diff(rect.y0) as usize + row).saturating_mul(full_width).saturating_add(x.abs_diff(rect.x0) as usize); + if let Some(source) = cov.get(offset..offset.saturating_add(width)) { + values.copy_from_slice(source); + } + } + // Transparent source spans cannot change an opaque target. Skip them by alpha, + // never by colour: an all-zero black source pixel is still valid opaque paint. + let covered = block_cov.iter().any(|value| *value > 0.0); + let sampled = covered && (y..y1).any(|py| (x..x1).any(|px| paint.px(px, py).get(n).is_some_and(|alpha| *alpha > 0.0))); + if !sampled { + x = x1; + continue; + } + let working = clone_sampling::opaque_alpha(Region::read(target, block), fmt); + // Quantize only when writing back to the real target, not before blending. + let mut patch = Surface::new(PixelFormat::new(fmt.mode, SampleType::F32, true)); + working.write(&mut patch); + apply_coverage(&mut patch, block, &block_cov, opacity, selection, lock, paint, mode); + let native: Vec<_> = patch.read_region(block).chunks_exact(n + 1).flat_map(|px| px.iter().take(n).copied()).collect(); + target.write_region(block, &native); + x = x1; + } + y = y1; + } + rect } /// Read-only clone overlay. Shares the stroke sampler without anchoring a source or editing history. @@ -58,6 +123,47 @@ pub fn clone_preview_periodic( map: &crate::presets::clone_source::Mapping, sample_layer: &str, wrap: bool, +) -> Result { + preview_periodic(s, rect, map, sample_layer, wrap, PreviewSource::Clone) +} + +/// Healing Brush's source overlay, including its documented cross-document Grayscale exception. +pub fn healing_preview(s: &Session, rect: Rect, map: &crate::presets::clone_source::Mapping, sample_layer: &str) -> Result { + healing_preview_periodic(s, rect, map, sample_layer, false) +} + +/// Healing Brush's source overlay with the same Pattern Preview repetition as its stroke. +pub fn healing_preview_periodic( + s: &Session, + rect: Rect, + map: &crate::presets::clone_source::Mapping, + sample_layer: &str, + wrap: bool, +) -> Result { + preview_periodic(s, rect, map, sample_layer, wrap, PreviewSource::Healing) +} + +/// The image beneath a clone overlay, always from the document being painted. +pub fn clone_destination_preview(s: &Session, rect: Rect, wrap: bool) -> Result { + let map = crate::presets::clone_source::Mapping { source: (0.0, 0.0), anchor: (0.0, 0.0), m: [1.0, 0.0, 0.0, 1.0], document: None }; + preview_periodic(s, rect, &map, "all", wrap, PreviewSource::Destination) +} + +#[derive(Clone, Copy)] +enum PreviewSource { + Clone, + Healing, + Destination, +} + +/// Sample a bounded overlay region from either the picked source or the destination composite. +fn preview_periodic( + s: &Session, + rect: Rect, + map: &crate::presets::clone_source::Mapping, + sample_layer: &str, + wrap: bool, + kind: PreviewSource, ) -> Result { if ![map.source.0, map.source.1, map.anchor.0, map.anchor.1].into_iter().chain(map.m).all(|v| v.is_finite() && v.abs() < 1_000_000.0) { return Err(bad("clone.preview", "invalid preview mapping")); @@ -78,8 +184,18 @@ pub fn clone_preview_periodic( let id = d.active_layer.ok_or_else(|| bad("clone.preview", "no active layer"))?; let surf = d.doc.layer(id).and_then(|l| l.surface()).ok_or_else(|| bad("clone.preview", "no pixel surface"))?; let which = sample_layers(&json!({"sampleLayer": sample_layer}), "clone.preview")?; - let region = clone_sample(&d.doc, Some(id), surf, which, rect, map, wrap, "clone.preview")?; - let px = region.data.chunks_exact(surf.format().channels()).map(|p| to_rgba(&surf.format(), p)).collect(); + let source = match kind { + PreviewSource::Destination => CloneFrom::default(), + PreviewSource::Clone | PreviewSource::Healing => { + let cmd = if matches!(kind, PreviewSource::Healing) { "healing.preview" } else { "clone.preview" }; + let paint_cmd = if matches!(kind, PreviewSource::Healing) { "paint.healingBrush" } else { "paint.cloneStamp" }; + let params = crate::channel_cmds::inject_target(s, paint_cmd, json!({"sampleLayer": sample_layer})); + clone_sampling::resolve_preview(s, ¶ms, map, cmd)? + } + }; + let region = clone_sample(&d.doc, Some(id), surf, which, &source, rect, map, wrap, "clone.preview")?; + let fmt = source.sample_format(surf); + let px = region.data.chunks_exact(fmt.channels()).map(|p| to_rgba(&fmt, p)).collect(); Ok(photocraft_compose::Buffer { rect, px }) } @@ -117,11 +233,13 @@ pub(super) fn clamp_samples(fmt: &PixelFormat, data: &mut [f32]) { // Clone Stamp / Healing Brush / History Brush // --------------------------------------------------------------------------------------------- +/// Paint from a frozen source and record its pairing only after the destination edit succeeds. pub(super) fn clone_stamp(s: &mut Session, p: &Value) -> Result { const CMD: &str = "paint.cloneStamp"; let (stroke, id) = parse_brush(s, p, CMD)?; reject_huge_stroke(CMD, &stroke)?; let which = sample_layers(p, CMD)?; + let source = clone_sampling::resolve(s, p, CMD)?; let mode = blend_param(p, CMD)?; let aligned = flag(p, "aligned", true); // The live stroke the canvas already drew for exactly this commit: take its pixels instead of @@ -136,13 +254,17 @@ pub(super) fn clone_stamp(s: &mut Session, p: &Value) -> Result { return Ok(l.bounds); } if flag(p, "wrap", false) { - return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, |before, r| clone_sample(pre, id, before, which, r, &map, true, CMD)); + let fmt = source.sample_format(surf); + return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, fmt, |before, r| { + clone_sample(pre, id, before, which, &source, r, &map, true, CMD) + }); } let (bounds, cov) = coverage(CMD, &stroke)?; // Samples come from the pre-stroke state, so pixels painted earlier in the stroke are never re-cloned. - let paint = clone_sample(pre, id, surf, which, bounds, &map, flag(p, "wrap", false), CMD)?; - Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) + let paint = clone_sample(pre, id, surf, which, &source, bounds, &map, flag(p, "wrap", false), CMD)?; + Ok(apply_clone_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) })?; + crate::presets::clone_source::remember_mapping(s, p, &map); let mut r = clone_result(dmg, off, aligned, p, &stroke); if from_live { r["fromLive"] = json!(true); @@ -154,7 +276,7 @@ pub(super) fn clone_stamp(s: &mut Session, p: &Value) -> Result { enum LivePaint { /// The clone source (Clone Stamp; the Healing Brush shows its texture while drawing and /// blends it on release). - Clone { which: SampleLayers, map: crate::presets::clone_source::Mapping, cmd: &'static str }, + Clone { which: SampleLayers, source: CloneFrom, map: crate::presets::clone_source::Mapping, cmd: &'static str }, /// The History Brush's history state. History(Surface), /// The Pattern Stamp's pattern, tiled from its aligned placement (Impressionist strokes are @@ -211,6 +333,7 @@ impl LiveRetouch { let f = *stroke.points.first().ok_or_else(|| bad(cmd, "`points` is empty"))?; LivePaint::Clone { which: sample_layers(p, cmd)?, + source: clone_sampling::resolve(s, &crate::channel_cmds::inject_target(s, cmd, p.clone()), cmd)?, map: crate::presets::clone_source::resolve(s, p, (f.x, f.y), cmd)?.0, cmd: if cmd == "paint.healingBrush" { "paint.healingBrush" } else { "paint.cloneStamp" }, } @@ -287,15 +410,16 @@ impl LiveRetouch { pub(crate) fn into_commit(mut self, s: &Session) -> Result { let (stroke, id) = parse_brush(s, &self.params, &self.cmd)?; let source_unchanged = match &self.paint { - LivePaint::Clone { map, .. } if self.cmd == "paint.cloneStamp" => { + LivePaint::Clone { map, source, .. } if self.cmd == "paint.cloneStamp" => { let f = stroke.points.first().ok_or_else(|| bad(&self.cmd, "`points` is empty"))?; crate::presets::clone_source::resolve(s, &self.params, (f.x, f.y), &self.cmd)?.0 == *map + && source.unchanged(&clone_sampling::resolve(s, &self.params, &self.cmd)?) } LivePaint::History(_) if self.cmd == "paint.historyBrush" => true, _ => return Err(bad(&self.cmd, "only Clone Stamp and History Brush strokes commit their live pixels")), }; if !source_unchanged || *self.brush != stroke.brush || id != self.id { - return Err(bad(&self.cmd, "the brush, layer or clone source changed during the stroke")); + return Err(bad(&self.cmd, "the brush, layer or clone source document changed during the stroke")); } let bounds = self.bounds(); let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; @@ -353,11 +477,11 @@ impl LiveRetouch { let mut tail = self.renderer.tail_preview(); self.tail = tail.as_mut().map_or(Rect::EMPTY, |t| t.take_dirty_rect()); dirty = dirty.union(&self.tail); - let LivePaint::Clone { which, map, cmd } = &self.paint else { + let LivePaint::Clone { which, source, map, cmd } = &self.paint else { return Err(bad(&self.cmd, "periodic painting requires a clone source")); }; let (pre, id, pre_surf, live_cmd) = (&self.pre, self.id, &self.pre_surf, self.cmd.as_str()); - let paint = |r| clone_sample(pre, id, pre_surf, *which, r, map, true, cmd); + let paint = |r| clone_sample(pre, id, pre_surf, *which, source, r, map, true, cmd); let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; periodic::Composite { target: surf, @@ -368,6 +492,7 @@ impl LiveRetouch { lock: self.lock, mode: self.mode, cmd: live_cmd, + paint_format: source.sample_format(pre_surf), } .draw(dirty, &self.brush, &self.points, paint) } @@ -378,16 +503,22 @@ impl LiveRetouch { return Ok(r); } let paint = match &self.paint { - LivePaint::Clone { which, map, cmd } => { - clone_sample(&self.pre, self.id, &self.pre_surf, *which, r, map, *cmd == "paint.cloneStamp" && flag(&self.params, "wrap", false), cmd)? + LivePaint::Clone { which, source, map, cmd } => { + clone_sample(&self.pre, self.id, &self.pre_surf, *which, source, r, map, *cmd == "paint.cloneStamp" && flag(&self.params, "wrap", false), cmd)? } LivePaint::History(src) => Region::read(src, r), LivePaint::Pattern { tile, place, .. } => pattern_stamp::paint_region(tile, place, &self.pre_surf.format(), r), }; // The Pattern Stamp's Behind goes beneath the pixels, as its commit lays it. let behind = matches!(self.paint, LivePaint::Pattern { behind: true, .. }); + let clone = matches!(self.paint, LivePaint::Clone { .. }); let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; surf.write_region(r, &self.pre_surf.read_region(r)); - Ok(pattern_stamp::lay_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode, behind).union(&r)) + let damage = if clone { + apply_clone_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode) + } else { + pattern_stamp::lay_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode, behind) + }; + Ok(damage.union(&r)) } } diff --git a/crates/engine/src/cmd/retouch_cmds/clone_sampling.rs b/crates/engine/src/cmd/retouch_cmds/clone_sampling.rs new file mode 100644 index 0000000000..794c8e4322 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/clone_sampling.rs @@ -0,0 +1,251 @@ +//! Resolve and freeze a clone source without changing the sampled document. +use std::sync::Arc; + +use crate::presets::clone_source::uses_slot; +use photocraft_cms::{Transform, TransformOptions}; +use photocraft_color::ColorMode; + +use super::sampling::{SampleLayers, composite_region, sample, sample_layers}; +use super::{Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, SampleType, Session, Surface, Value, bad, periodic, targets_pixels}; + +/// Frozen source-document and layer selection shared by preview and stroke sampling. +#[derive(Clone, Default)] +pub(super) struct CloneFrom { + other: Option<(Arc, u64)>, + layer: Option, + transform: Option>, + pixels: bool, +} + +impl CloneFrom { + /// Whether cached live pixels still refer to the same source snapshot and color transform. + pub(super) fn unchanged(&self, other: &Self) -> bool { + let document = match (&self.other, &other.other) { + (Some((a, ar)), Some((b, br))) => ar == br && Arc::ptr_eq(a, b), + (None, None) => true, + _ => false, + }; + let colors = match (&self.transform, &other.transform) { + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + (None, None) => true, + _ => false, + }; + document && self.layer == other.layer && colors && self.pixels == other.pixels + } + + /// Pixel cloning carries coverage independently of the destination's stored alpha flag. + /// Masks and channels retain their existing scalar sampling semantics. + pub(super) fn sample_format(&self, surf: &Surface) -> PixelFormat { + let fmt = surf.format(); + if self.pixels { alpha_format(fmt) } else { fmt } + } + + /// Read a source region into the destination's native channels, optionally wrapping its canvas. + #[allow(clippy::too_many_arguments)] + pub(super) fn sample( + &self, + pre: &Document, + target: Option, + surf: &Surface, + which: SampleLayers, + rect: Rect, + wrap: bool, + cmd: &str, + ) -> Result { + let doc = self.other.as_ref().map_or(pre, |(doc, _)| doc.as_ref()); + let fmt = self.sample_format(surf); + if self.other.is_some() && fmt.mode != pre.mode { + return Err(bad(cmd, "the destination layer color model does not match its document")); + } + let read = |rect| { + let (region, from) = if self.other.is_some() && which != SampleLayers::Current { + let from = PixelFormat::new(ColorMode::Rgb, SampleType::F32, true); + (composite_region(doc, self.layer, which, rect, from), from) + } else { + let sampled = match self.layer { + Some(id) => doc.layer(id).and_then(|l| l.surface()).ok_or_else(|| bad(cmd, "the clone source layer no longer has pixels"))?, + None => surf, + }; + if self.other.is_some() && sampled.format().mode != doc.mode { + return Err(bad(cmd, "the source layer color model does not match its document; choose All Layers")); + } + (sample(doc, target, sampled, which, rect), sampled.format()) + }; + convert_region(region, from, fmt, self.transform.as_deref(), self.pixels.then(|| doc.bounds()), cmd) + }; + if wrap { periodic::sample_with(doc.bounds(), fmt.channels(), rect, cmd, read) } else { read(rect) } + } +} + +/// Native colour/depth with an explicit coverage channel for intermediate paint pixels. +pub(super) fn alpha_format(fmt: PixelFormat) -> PixelFormat { + PixelFormat::new(fmt.mode, fmt.sample, true) +} + +/// Lift opaque native pixels into an alpha-bearing working region without a colour conversion. +pub(super) fn opaque_alpha(region: Region, fmt: PixelFormat) -> Region { + if fmt.alpha { + return region; + } + let n = fmt.channels(); + let mut out = Region::new(region.rect, n + 1); + for (src, dst) in region.data.chunks_exact(n).zip(out.data.chunks_exact_mut(n + 1)) { + if let Some(colors) = dst.get_mut(..n) { + colors.copy_from_slice(src); + } + if let Some(alpha) = dst.last_mut() { + *alpha = 1.0; + } + } + out +} + +/// Clear only sampled rows/spans outside the source canvas, without another full pixel buffer. +fn clip_canvas(region: &mut Region, bounds: Rect) { + let n = region.ch; + let row_values = region.width().saturating_mul(n); + if row_values == 0 { + return; + } + let x0 = i64::from(region.rect.x0); + let x1 = i64::from(region.rect.x1); + let left = (i64::from(bounds.x0).clamp(x0, x1) - x0) as usize; + let right = (i64::from(bounds.x1).clamp(x0, x1) - x0) as usize; + for (row_index, row) in region.data.chunks_exact_mut(row_values).enumerate() { + let y = i64::from(region.rect.y0) + row_index as i64; + if y < i64::from(bounds.y0) || y >= i64::from(bounds.y1) { + row.fill(0.0); + } else { + if let Some(span) = row.get_mut(..left.saturating_mul(n)) { + span.fill(0.0); + } + if let Some(span) = row.get_mut(right.saturating_mul(n)..) { + span.fill(0.0); + } + } + } +} + +/// Convert only the sampled region; preserve alpha and skip identical-profile HDR conversion. +fn convert_region(mut region: Region, from: PixelFormat, to: PixelFormat, transform: Option<&Transform>, canvas: Option, cmd: &str) -> Result { + // A malformed document can contain a surface whose model disagrees with its ICC profile. + // Check the native strides before the transform indexes them or its bounded scratch buffer. + if transform.is_some_and(|t| t.inputs() != from.mode.color_channels() || t.outputs() != to.mode.color_channels() || t.outputs() > 16) { + return Err(bad(cmd, "clone source color channels do not match the document profiles")); + } + let inside_canvas = canvas.is_none_or(|bounds| region.rect.intersect(&bounds) == region.rect); + if transform.is_none() && from.mode == to.mode && from.alpha == to.alpha { + if !inside_canvas && let Some(bounds) = canvas { + clip_canvas(&mut region, bounds); + } + return Ok(region); + } + let mut out = Region::new(region.rect, to.channels()); + let width = region.width(); + let canvas = canvas.filter(|_| !inside_canvas); + for (i, (src, dst)) in region.data.chunks_exact(from.channels()).zip(out.data.chunks_exact_mut(to.channels())).enumerate() { + // A surface without alpha is opaque inside its document canvas, including black + // default pixels. Outside that canvas it has no sample, regardless of stored defaults. + if let Some(bounds) = canvas { + let x = i64::from(region.rect.x0) + (i % width) as i64; + let y = i64::from(region.rect.y0) + (i / width) as i64; + if x < i64::from(bounds.x0) || y < i64::from(bounds.y0) || x >= i64::from(bounds.x1) || y >= i64::from(bounds.y1) { + continue; + } + } + if let Some(transform) = transform { + let colors = to.mode.color_channels(); + let mut converted = [0.0; 16]; + transform.eval(src, &mut converted); + dst[..colors].copy_from_slice(&converted[..colors]); + if to.alpha { + dst[colors] = if from.alpha { src.get(from.mode.color_channels()).copied().unwrap_or(1.0) } else { 1.0 }; + } + } else if from.mode == to.mode { + let colors = to.mode.color_channels(); + dst[..colors].copy_from_slice(&src[..colors]); + if to.alpha { + dst[colors] = if from.alpha { src.get(colors).copied().unwrap_or(1.0) } else { 1.0 }; + } + } else { + dst.copy_from_slice(&photocraft_raster::convert_pixel(&from, &to, src)); + } + } + Ok(out) +} + +/// Resolve a picked slot or explicit local coordinates without anchoring or modifying a document. +pub(super) fn resolve(s: &Session, p: &Value, cmd: &str) -> Result { + resolve_source(s, p, cmd, None) +} + +/// A preview mapping can explicitly name an open source independently of the selected slot. +pub(super) fn resolve_preview(s: &Session, p: &Value, map: &crate::presets::clone_source::Mapping, cmd: &str) -> Result { + resolve_source(s, p, cmd, map.document) +} + +fn resolve_source(s: &Session, p: &Value, cmd: &str, source: Option) -> Result { + let slot = s.presets.clone.active(); + let picked = uses_slot(p); + if picked && slot.document_closed && source.is_none_or(|d| Some(d.id) == slot.document) { + return Err(bad(cmd, crate::presets::clone_source::SOURCE_CLOSED)); + } + let picked_document = source.map(|d| d.id).or(slot.document); + if !targets_pixels(p) { + // A local mask/channel has no corresponding surface in another document. Refuse this + // unsupported target instead of quietly cloning the destination's own mask/channel. + if picked && picked_document.is_some_and(|id| s.active().is_none_or(|st| st.doc.id != id)) { + return Err(bad(cmd, "cross-document cloning requires a pixel-layer destination")); + } + return Ok(CloneFrom::default()); + } + let which = sample_layers(p, cmd)?; + let active = s.active().ok_or(EngineError::NoDocument)?; + // Explicit coordinates are in the destination document. A picked slot carries its document. + let doc_id = picked.then_some(picked_document).flatten().unwrap_or(active.doc.id); + let st = s.documents().iter().find(|st| st.doc.id == doc_id).ok_or_else(|| bad(cmd, "the clone source document was closed; pick a new source"))?; + let external = st.doc.id != active.doc.id; + // Adobe documents matching document modes for Clone Stamp; Healing Brush additionally + // permits Grayscale on either side. Profile conversion still applies to compatible pairs. + let healing_gray = matches!(cmd, "paint.healingBrush" | "healing.preview") && [st.doc.mode, active.doc.mode].contains(&ColorMode::Grayscale); + if external && st.doc.mode != active.doc.mode && !healing_gray { + return Err(bad(cmd, "the source and destination color modes are incompatible with this tool; convert a document before sampling")); + } + let mut layer = None; + if which == SampleLayers::Current || (external && which == SampleLayers::CurrentAndBelow) { + let id = match p.get("sourceLayer").filter(|v| !v.is_null()) { + Some(value) => Some(LayerId(value.as_u64().ok_or_else(|| bad(cmd, "sourceLayer must be a layer id"))?)), + None if picked => source.map_or(slot.layer.map(LayerId), |d| d.layer), + None => None, + } + .or(if external { st.active_layer } else { None }); + if let Some(id) = id { + let source = st.doc.layer(id).ok_or_else(|| bad(cmd, "the clone source layer no longer exists; pick a new source"))?; + if source.surface().is_some() || which != SampleLayers::Current { + layer = Some(id); + } else if external { + return Err(bad(cmd, "the clone source layer has no pixels; choose All Layers or pick a pixel layer")); + } + } else if external && which == SampleLayers::Current { + return Err(bad(cmd, "the clone source has no pixel layer")); + } + } + let transform = if external { color_transform(s, &st.doc, which, cmd)? } else { None }; + Ok(CloneFrom { other: external.then(|| (st.doc.clone(), st.revision)), layer, transform, pixels: true }) +} + +/// Choose the sampled pixel/composite profile and cache its conversion to the destination profile. +fn color_transform(s: &Session, doc: &Document, which: SampleLayers, cmd: &str) -> Result>> { + let source = if which == SampleLayers::Current { crate::color_cmds::document_profile(doc) } else { crate::color_cmds::composite_profile(doc) }; + let target = s.active().ok_or(EngineError::NoDocument)?; + let destination = crate::color_cmds::document_profile(&target.doc); + let inputs = if which == SampleLayers::Current { doc.mode.color_channels() } else { 3 }; + if source.channels() != inputs || destination.channels() != target.doc.mode.color_channels() { + return Err(bad(cmd, "cross-document cloning does not support this color model")); + } + if source.same_bytes(&destination) { + return Ok(None); + } + let opts = TransformOptions { intent: s.color.settings.intent(), bpc: s.color.settings.bpc, ..Default::default() }; + photocraft_cms::transform::cached(&source, &destination, opts).map(Some).map_err(|e| bad(cmd, format!("cannot convert clone source colors: {e}"))) +} diff --git a/crates/engine/src/cmd/retouch_cmds/clone_source_layer_tests.rs b/crates/engine/src/cmd/retouch_cmds/clone_source_layer_tests.rs new file mode 100644 index 0000000000..226a770446 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/clone_source_layer_tests.rs @@ -0,0 +1,1034 @@ +use super::*; +use crate::presets::clone_source::Mapping; + +/// Create a native colour-gradient source and an empty destination without re-picking. +fn setup(depth: u64, mode: &str) -> (Session, LayerId, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64, "depth": depth, "mode": mode})).unwrap(); + let source = s.active().unwrap().active_layer.unwrap(); + s.edit("source", |doc, _| { + let rect = doc.bounds(); + let surf = doc.layer_mut(source).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let mut data = Vec::new(); + for y in 0..64 { + for x in 0..64 { + data.extend(photocraft_raster::from_rgba(&fmt, [x as f32 / 64.0, y as f32 / 64.0, 0.25, 1.0])); + } + } + surf.write_region(rect, &data); + Ok(()) + }) + .unwrap(); + s.execute("cloneSource.set", json!({"source": [16, 16]})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let target = s.active().unwrap().active_layer.unwrap(); + (s, source, target) +} + +/// Read a layer as RGBA so assertions can compare different native depths and models. +fn pixel(s: &Session, id: LayerId, x: i32, y: i32) -> [f32; 4] { + s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().rgba(x, y) +} + +/// Use one hard dab whose opacity and flow give twenty-percent centre coverage. +fn params(wrap: bool) -> Value { + json!({"points": [[48, 48]], "size": 12, "hardness": 100, "opacity": 50, "flow": 40, "wrap": wrap}) +} + +/// Nullable client fields use the picked layer; malformed non-null overrides still fail atomically. +#[test] +fn clone_null_source_layer_matches_omission_for_clone_and_heal() { + for depth in [8, 16, 32] { + for cmd in ["paint.cloneStamp", "paint.healingBrush"] { + for external in [false, true] { + for which in ["current", "currentAndBelow"] { + if !external && which != "current" { + continue; + } + let (mut s, _, _) = setup(depth, "rgb"); + if external { + s.execute("file.new", json!({"width": 64, "height": 64, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + } + let target = s.active().unwrap().active_layer.unwrap(); + let rect = Rect::new(40, 40, 56, 56); + let mut omitted = params(false); + omitted["sampleLayer"] = json!(which); + omitted["aligned"] = json!(false); + let mut nullable = omitted.clone(); + nullable["sourceLayer"] = Value::Null; + let expected_live = LiveRetouch::begin(&s, cmd, &omitted).unwrap(); + let actual_live = LiveRetouch::begin(&s, cmd, &nullable).unwrap(); + let live_pixels = |live: &LiveRetouch| live.doc.layer(target).unwrap().surface().unwrap().read_region(rect); + assert_eq!(live_pixels(&actual_live), live_pixels(&expected_live), "{depth}/{cmd}/{external}/{which}"); + assert!(actual_live.doc.layer(target).unwrap().surface().unwrap().rgba(48, 48)[3] > 0.0, "the picked source has pixels"); + s.execute(cmd, omitted).unwrap(); + let expected = s.active().unwrap().doc.layer(target).unwrap().surface().unwrap().read_region(rect); + assert!(s.undo()); + s.execute(cmd, nullable.clone()).unwrap(); + assert_eq!(s.active().unwrap().doc.layer(target).unwrap().surface().unwrap().read_region(rect), expected); + let before = s.active().unwrap().doc.clone(); + let slots = s.presets.clone.clone(); + for invalid in [json!("bad"), json!(-1), json!(1.5), json!(true), json!([]), json!(u64::MAX)] { + nullable["sourceLayer"] = invalid; + assert!(LiveRetouch::begin(&s, cmd, &nullable).is_err()); + assert!(s.execute(cmd, nullable.clone()).is_err()); + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.presets.clone, slots); + } + } + } + } + } +} + +/// A null document preserves a slot during edits and picks the active document for a new source. +#[test] +fn clone_null_document_matches_omission_for_source_and_slot_edits() { + for depth in [8, 16, 32] { + let (mut s, _, _) = setup(depth, "rgb"); + let original = s.active().unwrap().doc.id; + s.execute("file.new", json!({"width": 64, "height": 64, "depth": depth})).unwrap(); + let active = s.active().unwrap().doc.id; + let before = s.active().unwrap().doc.clone(); + for mut p in [json!({"width": 150}), json!({"offset": [-20, -10], "anchor": [40, 30]}), json!({"source": [8, 12]})] { + let slots = s.presets.clone.clone(); + let expected = s.execute("cloneSource.set", p.clone()).unwrap(); + let expected_slots = s.presets.clone.clone(); + s.presets.clone = slots; + p["document"] = Value::Null; + assert_eq!(s.execute("cloneSource.set", p.clone()).unwrap(), expected); + assert_eq!(s.presets.clone, expected_slots); + assert_eq!(s.presets.clone.active().document, Some(if p.get("source").is_some() { active } else { original })); + assert_eq!(s.active().unwrap().doc, before, "source edits do not paint"); + } + let slots = s.presets.clone.clone(); + for invalid in [json!("bad"), json!(-1), json!(1.5), json!(true), json!([]), json!(u64::MAX)] { + assert!(s.execute("cloneSource.set", json!({"source": [20, 20], "document": invalid})).is_err()); + assert_eq!(s.presets.clone, slots); + assert_eq!(s.active().unwrap().doc, before); + } + assert!(s.execute("cloneSource.set", json!({"document": 0, "width": 200})).is_err(), "an explicit document still requires a source"); + assert_eq!(s.presets.clone, slots); + } +} + +/// A picked layer must remain the source through target switches and every rendering path. +#[test] +fn clone_current_layer_keeps_the_picked_source_for_preview_live_commit_and_undo() { + for depth in [8, 16, 32] { + for mode in ["rgb", "gray", "cmyk", "lab"] { + for wrap in [false, true] { + let (mut s, source, target) = setup(depth, mode); + let want = pixel(&s, source, 16, 16); + let map = Mapping { source: (16.0, 16.0), anchor: (48.0, 48.0), m: [1.0, 0.0, 0.0, 1.0], document: None }; + let preview = clone_preview_periodic(&s, Rect::new(48, 48, 49, 49), &map, "current", wrap).unwrap(); + assert_eq!(preview.px[0], want); + let p = params(wrap); + let live = LiveRetouch::begin(&s, "paint.cloneStamp", &p).unwrap(); + let live_pixels = live.doc.layer(target).unwrap().surface().unwrap().read_region(Rect::new(40, 40, 56, 56)); + s.offer_live_retouch(live).unwrap(); + let result = s.execute("paint.cloneStamp", p.clone()).unwrap(); + assert_eq!(result["fromLive"], true); + let got = pixel(&s, target, 48, 48); + assert!((got[3] - 0.2).abs() < 0.01, "{depth}/{mode}/{wrap}: {got:?}"); + for c in 0..3 { + assert!((got[c] - want[c]).abs() < 0.02, "{depth}/{mode}/{wrap}: {got:?} vs {want:?}"); + } + assert_eq!(pixel(&s, source, 16, 16), want, "source remains untouched"); + assert_eq!(s.active().unwrap().doc.layer(target).unwrap().surface().unwrap().read_region(Rect::new(40, 40, 56, 56)), live_pixels); + assert!(s.undo()); + assert_eq!(pixel(&s, target, 48, 48)[3], 0.0); + assert!(s.redo()); + assert_eq!(pixel(&s, target, 48, 48), got); + let (mut replay, _, replay_target) = setup(depth, mode); + replay.execute("paint.cloneStamp", p).unwrap(); + assert_eq!(pixel(&replay, replay_target, 48, 48), got, "ordinary command matches the live commit"); + } + } + } +} + +/// Missing source identities must fail atomically instead of sampling another layer. +#[test] +fn clone_deleted_source_and_invalid_source_layer_fail_without_edits() { + let (mut s, source, target) = setup(8, "rgb"); + s.execute("layer.delete", json!({"layer": source.0})).unwrap(); + let revision = s.active().unwrap().revision; + assert!(s.execute("paint.cloneStamp", params(false)).is_err()); + assert!(LiveRetouch::begin(&s, "paint.cloneStamp", ¶ms(false)).is_err()); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(pixel(&s, target, 48, 48)[3], 0.0); + for value in [json!("bad"), json!(-1), json!(999999)] { + let mut p = params(false); + p["sourceLayer"] = value; + assert!(s.execute("paint.cloneStamp", p).is_err()); + assert_eq!(s.active().unwrap().revision, revision); + } +} + +/// Transparency is valid source data, and an explicit source-layer override takes precedence. +#[test] +fn clone_transparent_source_and_explicit_source_layer_are_respected() { + let (mut s, source, target) = setup(16, "rgb"); + s.execute("cloneSource.set", json!({"source": [16, 16]})).unwrap(); + s.execute("paint.cloneStamp", params(false)).unwrap(); + assert_eq!(pixel(&s, target, 48, 48)[3], 0.0); + let mut p = params(false); + p["sourceLayer"] = json!(source.0); + s.execute("paint.cloneStamp", p).unwrap(); + assert!((pixel(&s, target, 48, 48)[3] - 0.2).abs() < 0.01); +} + +/// Retaining Current Layer sources must preserve existing same-document composite sampling. +#[test] +fn clone_source_layer_does_not_change_composite_sampling_modes() { + for which in ["currentAndBelow", "all"] { + let (mut s, source, target) = setup(8, "rgb"); + // A removed picked layer is irrelevant when sampling the visible stack. + s.execute("layer.delete", json!({"layer": source.0})).unwrap(); + let mut p = params(false); + p["sampleLayer"] = json!(which); + s.execute("paint.cloneStamp", p).unwrap(); + assert_eq!(pixel(&s, target, 48, 48)[3], 0.0); + } +} + +/// Matching coordinates alone cannot authorize cached pixels from another sampled layer. +#[test] +fn clone_live_commit_rejects_a_changed_source_layer_with_the_same_coordinates() { + let (mut s, _, target) = setup(8, "rgb"); + let live = LiveRetouch::begin(&s, "paint.cloneStamp", ¶ms(false)).unwrap(); + s.execute("cloneSource.set", json!({"source": [16, 16], "layer": target.0})).unwrap(); + assert!(s.offer_live_retouch(live).is_err()); +} + +/// Re-picking after a return to the original layer updates local and cross-layer painting. +#[test] +fn clone_repicking_on_the_original_layer_updates_both_layers() { + for depth in [8, 16, 32] { + let (mut s, source, target) = setup(depth, "rgb"); + let p = json!({"points": [[48, 48]], "size": 8, "hardness": 100}); + s.execute("paint.cloneStamp", p.clone()).unwrap(); + let first = pixel(&s, source, 16, 16); + assert_eq!(pixel(&s, target, 48, 48), first); + s.execute("layer.select", json!({"layer": source.0})).unwrap(); + s.execute("cloneSource.set", json!({"source": [8, 8]})).unwrap(); + let replacement = pixel(&s, source, 8, 8); + assert_ne!(replacement, first); + s.execute("paint.cloneStamp", p.clone()).unwrap(); + assert_eq!(pixel(&s, source, 48, 48), replacement, "same-layer painting uses the new source"); + s.execute("layer.select", json!({"layer": target.0})).unwrap(); + let map = Mapping { source: (8.0, 8.0), anchor: (48.0, 48.0), m: [1.0, 0.0, 0.0, 1.0], document: None }; + assert_eq!(clone_preview(&s, Rect::new(48, 48, 49, 49), &map, "current").unwrap().px[0], replacement); + s.execute("paint.cloneStamp", p).unwrap(); + assert_eq!(pixel(&s, target, 48, 48), replacement, "returning to the other layer uses the new source too"); + } +} + +/// Cross-document sampling must agree across previews, live pixels, replay and history. +#[test] +fn clone_sources_work_between_documents_with_preview_live_commit_and_undo() { + for depth in [8, 16, 32] { + for which in ["current", "currentAndBelow", "all"] { + for wrap in [false, true] { + let (mut s, source, _) = setup(depth, "rgb"); + let want = pixel(&s, source, 16, 16); + let source_doc = s.active().unwrap().doc.clone(); + s.execute("file.new", json!({"width": 80, "height": 80, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let target = s.active().unwrap().active_layer.unwrap(); + let mut p = params(wrap); + p["sampleLayer"] = json!(which); + let map = Mapping { source: (16.0, 16.0), anchor: (48.0, 48.0), m: [1.0, 0.0, 0.0, 1.0], document: None }; + let preview = clone_preview_periodic(&s, Rect::new(48, 48, 49, 49), &map, which, wrap).unwrap(); + for (got, expected) in preview.px[0].iter().zip(want) { + assert!((got - expected).abs() < 0.01, "{depth}/{which}/{wrap}"); + } + let live = LiveRetouch::begin(&s, "paint.cloneStamp", &p).unwrap(); + let shown = live.doc.layer(target).unwrap().surface().unwrap().rgba(48, 48); + s.offer_live_retouch(live).unwrap(); + assert_eq!(s.execute("paint.cloneStamp", p.clone()).unwrap()["fromLive"], true); + assert_eq!(pixel(&s, target, 48, 48), shown); + assert!((shown[3] - 0.2).abs() < 0.01); + assert_eq!(s.documents()[0].doc, source_doc, "the source document is read-only"); + assert!(s.undo()); + assert_eq!(pixel(&s, target, 48, 48)[3], 0.0); + s.execute("paint.cloneStamp", p).unwrap(); + assert_eq!(pixel(&s, target, 48, 48), shown, "ordinary rendering matches the live commit"); + } + } + } +} + +/// Compatible profiles convert through CMS while identical profiles preserve native ink values. +#[test] +fn clone_cross_document_matching_color_modes_and_profiles_use_cms() { + use photocraft_cms::{Builtin, TransformOptions}; + for (from, to) in [("rgb", "rgb"), ("gray", "gray"), ("cmyk", "cmyk"), ("lab", "lab")] { + let (mut s, source, _) = setup(32, from); + if from == "rgb" { + s.edit("profile", |doc, _| { + doc.icc_profile = Some(Builtin::AdobeRgbCompat.profile().to_bytes()); + Ok(()) + }) + .unwrap(); + } + let doc = s.active().unwrap().doc.clone(); + let native = doc.layer(source).unwrap().surface().unwrap().read_region(Rect::new(16, 16, 17, 17)); + s.execute("file.new", json!({"width": 64, "height": 64, "mode": to, "depth": 16})).unwrap(); + let dst = s.active().unwrap().doc.clone(); + let (from_profile, to_profile) = (crate::color_cmds::document_profile(&doc), crate::color_cmds::document_profile(&dst)); + let mut want = [0.0; 16]; + if from_profile.same_bytes(&to_profile) { + // Identical profiles preserve native ink values; a CMYK PCS round trip is lossy. + want[..native.len()].copy_from_slice(&native); + } else { + let transform = photocraft_cms::transform::cached( + &from_profile, + &to_profile, + TransformOptions { intent: s.color.settings.intent(), bpc: s.color.settings.bpc, ..Default::default() }, + ) + .unwrap(); + transform.eval(&native, &mut want); + } + s.execute("paint.cloneStamp", json!({"points": [[48,48]], "size": 8, "hardness": 100})).unwrap(); + let st = s.active().unwrap(); + let got = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().read_region(Rect::new(48, 48, 49, 49)); + for (got, want) in got.iter().zip(want).take(dst.mode.color_channels()) { + assert!((got - want).abs() < 0.005, "{from} -> {to}: {got} vs {want}"); + } + } +} + +/// Preview, live and committed painting must enforce the same documented mode compatibility. +#[test] +fn clone_and_heal_cross_document_mode_compatibility_matches_preview_live_and_commit() { + for from in ["rgb", "gray", "cmyk", "lab"] { + for to in ["rgb", "gray", "cmyk", "lab"] { + for cmd in ["paint.cloneStamp", "paint.healingBrush"] { + let (mut s, _, _) = setup(16, from); + s.execute("file.new", json!({"width": 64, "height": 64, "mode": to, "depth": 16})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let slots = s.presets.clone.clone(); + let allowed = from == to || (cmd == "paint.healingBrush" && (from == "gray" || to == "gray")); + let p = json!({"points": [[48,48]], "size": 8, "hardness": 100}); + let (map, _) = crate::presets::clone_source::resolve(&s, &p, (48.0, 48.0), cmd).unwrap(); + let rect = Rect::new(44, 44, 52, 52); + let preview = if cmd == "paint.healingBrush" { healing_preview(&s, rect, &map, "current") } else { clone_preview(&s, rect, &map, "current") }; + assert_eq!(preview.is_ok(), allowed, "preview: {from} -> {to}, {cmd}: {preview:?}"); + assert_eq!(LiveRetouch::begin(&s, cmd, &p).is_ok(), allowed, "live: {from} -> {to}, {cmd}"); + assert_eq!(s.presets.clone, slots, "preview and live construction are read-only"); + let result = s.execute(cmd, p); + assert_eq!(result.is_ok(), allowed, "commit: {from} -> {to}, {cmd}: {result:?}"); + if !allowed { + assert_eq!(s.active().unwrap().doc, before); + assert_eq!(s.presets.clone, slots); + } + } + } + } +} + +/// Frozen pixels cannot survive source edits or closure; fresh replay must sample current data. +#[test] +fn clone_closed_source_document_and_stale_live_pixels_fail_gracefully() { + let (mut s, source, _) = setup(8, "rgb"); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let target = s.active().unwrap().active_layer.unwrap(); + let p = params(false); + let live = LiveRetouch::begin(&s, "paint.cloneStamp", &p).unwrap(); + assert!(s.set_active(0)); + s.edit("source changed", |doc, _| { + doc.layer_mut(source).unwrap().surface_mut().unwrap().fill_rect(Rect::new(16, 16, 17, 17), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + assert!(s.set_active(1)); + assert!(s.offer_live_retouch(live).is_err(), "a changed source revision invalidates offered pixels"); + s.execute("paint.cloneStamp", p.clone()).unwrap(); + let updated = pixel(&s, target, 48, 48); + assert_eq!(&updated[..3], &[1.0, 0.0, 0.0], "ordinary replay reads the edited source after rejecting stale live pixels"); + assert!((updated[3] - 0.2).abs() < 0.01); + s.close(0).unwrap(); + let revision = s.active().unwrap().revision; + let anchor = s.presets.clone.active().anchor; + assert!(s.execute("paint.cloneStamp", p).is_err()); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.presets.clone.active().anchor, anchor); + for value in [json!(-1), json!("bad"), json!(999999)] { + assert!(s.execute("cloneSource.set", json!({"source": [8,8], "document": value})).is_err()); + } +} + +/// A persisted document ID must not accidentally revive an already-closed clone source. +#[test] +fn clone_closed_source_cannot_be_revived_by_reopening_a_saved_copy() { + let (mut s, source, _) = setup(8, "rgb"); + let saved_copy = (*s.active().unwrap().doc).clone(); + let expected = pixel(&s, source, 16, 16); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let target = s.active().unwrap().active_layer.unwrap(); + s.close(0).unwrap(); + let reopened = s.add_document(saved_copy.clone(), None); + assert_ne!(s.documents()[reopened].doc.id, saved_copy.id, "a new tab must not revive a closed clone source's identity"); + assert!(s.set_active(0)); + let before = s.active().unwrap().doc.clone(); + let p = params(false); + assert!(s.execute("paint.cloneStamp", p.clone()).is_err()); + assert!(LiveRetouch::begin(&s, "paint.cloneStamp", &p).is_err()); + assert_eq!(s.active().unwrap().doc, before); + s.execute("cloneSource.set", json!({"source": [16,16], "document": reopened, "layer": source.0})).unwrap(); + s.execute("paint.cloneStamp", p).unwrap(); + let got = pixel(&s, target, 48, 48); + for c in 0..3 { + assert!((got[c] - expected[c]).abs() < 0.01, "explicitly re-picking the reopened document works"); + } + assert!((got[3] - 0.2).abs() < 0.01); +} + +/// New source identities must coexist with older slots that never stored a document ID. +#[test] +fn clone_source_document_json_and_legacy_slots_are_compatible() { + let (mut s, _, _) = setup(8, "rgb"); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + let slot = s.execute("cloneSource.set", json!({"source": [8,8], "document": 0})).unwrap(); + assert_eq!(slot["document"], 0); + let mut legacy = serde_json::to_value(s.presets.clone.active()).unwrap(); + legacy.as_object_mut().unwrap().remove("document"); + let old: crate::presets::clone_source::CloneSource = serde_json::from_value(legacy).unwrap(); + assert!(old.document.is_none()); +} + +/// Every slot reply keeps stable identity while open-tab indexes may change. +#[test] +fn clone_source_replies_keep_document_identity_when_resetting_transforms() { + let (mut s, _, _) = setup(8, "rgb"); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + let document_id = s.active().unwrap().doc.id; + assert!(s.set_active(0)); + s.execute("cloneSource.set", json!({"index": 2, "source": [8,8], "document": 1, "width": 200, "rotation": 45})).unwrap(); + let replies = [ + s.execute("cloneSource.list", json!({})).unwrap()["sources"][2].clone(), + s.execute("cloneSource.select", json!({"index": 2})).unwrap(), + s.execute("cloneSource.set", json!({"index": 2, "width": 150})).unwrap(), + s.execute("cloneSource.resetTransform", json!({"index": 2})).unwrap(), + ]; + for reply in replies { + assert_eq!(reply["document"], 1, "all slot replies expose the same source-document index: {reply}"); + assert_eq!(reply["documentId"], json!(document_id)); + assert_eq!(reply["source"], json!([8.0, 8.0])); + } + assert_eq!(s.presets.clone.active().scale, [100.0, 100.0]); + assert_eq!(s.presets.clone.active().rotation, 0.0); + s.close(0).unwrap(); + let reset = s.execute("cloneSource.resetTransform", json!({"index": 2})).unwrap(); + assert_eq!(reset["document"], 0, "closing an earlier tab changes the index, not the source identity"); + assert_eq!(reset["documentId"], json!(document_id)); +} + +/// Source conversion must preserve float light above white and distinguish absent/stored alpha. +#[test] +fn clone_between_documents_preserves_float_hdr_and_source_alpha() { + for alpha in [false, true] { + let (mut s, source, _) = setup(32, "rgb"); + s.edit("source pixels", |doc, _| { + let fmt = PixelFormat::new(photocraft_color::ColorMode::Rgb, SampleType::F32, alpha); + let values = if alpha { vec![1.5, 0.25, 0.75, 0.25] } else { vec![1.5, 0.25, 0.75] }; + *doc.layer_mut(source).unwrap().surface_mut().unwrap() = Surface::with_default(fmt, &values); + Ok(()) + }) + .unwrap(); + s.execute("file.new", json!({"width": 64, "height": 64, "depth": 32})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let target = s.active().unwrap().active_layer.unwrap(); + s.execute("paint.cloneStamp", json!({"points": [[48,48]], "size": 8, "hardness": 100})).unwrap(); + assert_eq!(pixel(&s, target, 48, 48), [1.5, 0.25, 0.75, if alpha { 0.25 } else { 1.0 }]); + } +} + +/// Unsupported external mask destinations must refuse without modifying their document. +#[test] +fn clone_cross_document_mask_targets_refuse_instead_of_sampling_the_wrong_document() { + let (mut s, _, _) = setup(8, "rgb"); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let mut p = params(false); + p["target"] = json!("mask"); + assert!(s.execute("paint.cloneStamp", p.clone()).is_err()); + assert!(LiveRetouch::begin(&s, "paint.cloneStamp", &p).is_err()); + assert_eq!(s.active().unwrap().doc, before); +} + +/// Malformed document/layer colour models must produce ordinary errors before pixel edits. +#[test] +fn clone_cross_document_mismatched_surface_models_fail_without_panicking_or_editing() { + for change_source in [true, false] { + let (mut s, source, _) = setup(32, "rgb"); + s.execute("file.new", json!({"width": 64, "height": 64, "depth": 32})).unwrap(); + let target = s.active().unwrap().active_layer.unwrap(); + assert!(s.set_active(if change_source { 0 } else { 1 })); + s.edit("malformed layer", |doc, _| { + let id = if change_source { source } else { target }; + *doc.layer_mut(id).unwrap().surface_mut().unwrap() = + Surface::with_default(PixelFormat::new(photocraft_color::ColorMode::Grayscale, SampleType::F32, false), &[0.5]); + Ok(()) + }) + .unwrap(); + assert!(s.set_active(1)); + let before = s.active().unwrap().doc.clone(); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| s.execute("paint.cloneStamp", params(false)))); + assert!(result.unwrap().is_err()); + assert_eq!(s.active().unwrap().doc, before); + } +} + +/// All four finite canvas edges must agree across sampling modes, depths and rendering paths. +#[test] +fn clone_source_edges_clip_preview_live_and_committed_stamps() { + for depth in [8, 16, 32] { + for external in [false, true] { + for which in ["current", "currentAndBelow", "all"] { + for (sx, sy) in [(0, 0), (63, 0), (0, 63), (63, 63)] { + let (mut s, source, mut target) = setup(depth, "rgb"); + s.edit("finite source", |doc, _| { + let bounds = doc.bounds(); + doc.layer_mut(source).unwrap().surface_mut().unwrap().fill_rect(bounds, &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("layer.select", json!({"layer": source.0})).unwrap(); + s.execute("cloneSource.set", json!({"source": [sx, sy]})).unwrap(); + if external { + s.execute("file.new", json!({"width": 80, "height": 80, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + target = s.active().unwrap().active_layer.unwrap(); + } else { + s.execute("layer.select", json!({"layer": target.0})).unwrap(); + } + let (dx, dy) = (if sx == 0 { 1 } else { -1 }, if sy == 0 { 1 } else { -1 }); + let map = Mapping { source: (sx as f64, sy as f64), anchor: (32.0, 32.0), m: [1.0, 0.0, 0.0, 1.0], document: None }; + let preview = clone_preview(&s, Rect::new(30, 30, 35, 35), &map, which).unwrap(); + let checks = [(32, 32 + dy, 1.0), (32 + dx, 32, 1.0), (32 - dx, 32 + dy, 0.0), (32 + dx, 32 - dy, 0.0)]; + for (x, y, alpha) in checks { + let index = ((y - 30) * 5 + x - 30) as usize; + assert_eq!(preview.px[index][3], alpha, "preview {depth}/{external}/{which}/{sx},{sy} at {x},{y}"); + } + let p = json!({"points": [[32,32]], "size": 32, "hardness": 100, "sampleLayer": which}); + let live = LiveRetouch::begin(&s, "paint.cloneStamp", &p).unwrap(); + for (x, y, alpha) in checks { + assert_eq!(live.doc.layer(target).unwrap().surface().unwrap().rgba(x, y)[3], alpha); + } + s.offer_live_retouch(live).unwrap(); + assert_eq!(s.execute("paint.cloneStamp", p.clone()).unwrap()["fromLive"], true); + for (x, y, alpha) in checks { + assert_eq!(pixel(&s, target, x, y)[3], alpha, "commit {depth}/{external}/{which}/{sx},{sy} at {x},{y}"); + } + assert!(s.undo()); + s.execute("paint.cloneStamp", p).unwrap(); + for (x, y, alpha) in checks { + assert_eq!(pixel(&s, target, x, y)[3], alpha, "ordinary rendering matches the live stamp"); + } + } + } + } + } +} + +/// Missing source pixels must leave previously painted destination colours intact. +#[test] +fn clone_clipped_source_preserves_existing_destination_pixels_on_the_original_layer() { + let (mut s, source, _) = setup(16, "rgb"); + s.edit("two colors", |doc, _| { + let bounds = doc.bounds(); + let surf = doc.layer_mut(source).unwrap().surface_mut().unwrap(); + surf.fill_rect(bounds, &[0.0, 0.0, 1.0, 1.0]); + surf.fill_rect(Rect::new(0, 0, 16, 16), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("layer.select", json!({"layer": source.0})).unwrap(); + s.execute("cloneSource.set", json!({"source": [0, 0]})).unwrap(); + s.execute("paint.cloneStamp", json!({"points": [[32,32]], "size": 32, "hardness": 100})).unwrap(); + assert_eq!(pixel(&s, source, 33, 33), [1.0, 0.0, 0.0, 1.0]); + for (x, y) in [(31, 33), (33, 31), (31, 31)] { + assert_eq!(pixel(&s, source, x, y), [0.0, 0.0, 1.0, 1.0], "missing source pixels leave the blue destination intact"); + } +} + +/// Periodic sampling uses source dimensions even when the destination canvas is larger. +#[test] +fn clone_pattern_preview_wraps_at_the_source_document_edges() { + let (mut s, source, _) = setup(16, "rgb"); + let want = pixel(&s, source, 1, 16); + s.execute("cloneSource.set", json!({"source": [63,16], "layer": source.0})).unwrap(); + s.execute("file.new", json!({"width": 80, "height": 80, "depth": 16})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let target = s.active().unwrap().active_layer.unwrap(); + let map = Mapping { source: (63.0, 16.0), anchor: (48.0, 48.0), m: [1.0, 0.0, 0.0, 1.0], document: None }; + let preview = clone_preview_periodic(&s, Rect::new(50, 48, 51, 49), &map, "current", true).unwrap(); + assert_eq!(preview.px[0], want); + s.execute("paint.cloneStamp", json!({"points": [[48,48]], "size": 12, "hardness": 100, "wrap": true})).unwrap(); + assert_eq!(pixel(&s, target, 50, 48), want, "wrapping uses the 64 px source canvas, not the 80 px destination"); +} + +/// Exercise the real five-thousand-pixel limit on a twenty-four-megapixel destination. +#[test] +#[ignore = "allocates full 5,000 px clone coverage and pixel buffers; run explicitly with one test thread"] +fn clone_maximum_size_stamp_keeps_straight_source_edges() { + let (mut s, source, _) = setup(8, "rgb"); + s.edit("finite red source", |doc, _| { + let bounds = doc.bounds(); + doc.layer_mut(source).unwrap().surface_mut().unwrap().fill_rect(bounds, &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s.execute("cloneSource.set", json!({"source": [0,0], "layer": source.0})).unwrap(); + s.execute("file.new", json!({"width": 6000, "height": 4000, "background": "transparent"})).unwrap(); + let target = s.active().unwrap().active_layer.unwrap(); + let start = std::time::Instant::now(); + s.execute("paint.cloneStamp", json!({"points": [[3000,2000]], "size": 5000, "hardness": 100})).unwrap(); + eprintln!("5,000 px hard clone stamp on 24 MP: {:?}", start.elapsed()); + assert_eq!(pixel(&s, target, 3000, 2000), [1.0, 0.0, 0.0, 1.0]); + assert_eq!(pixel(&s, target, 3063, 2063), [1.0, 0.0, 0.0, 1.0]); + for (x, y) in [(2999, 2001), (3001, 1999), (3064, 2001), (3001, 2064), (4000, 2000)] { + assert_eq!(pixel(&s, target, x, y)[3], 0.0, "source clips at {x},{y} within the 5,000 px tip"); + } +} + +/// Unaligned strokes update their readout without turning that report into an aligned origin. +#[test] +fn clone_offsets_report_each_unaligned_stroke_without_persisting_its_alignment() { + for depth in [8, 16, 32] { + let (mut s, source, target) = setup(depth, "rgb"); + let want = pixel(&s, source, 16, 16); + for (x, y) in [(40, 30), (50, 40)] { + s.execute("paint.cloneStamp", json!({"points": [[x,y]], "size": 8, "hardness": 100, "aligned": false})).unwrap(); + assert_eq!(pixel(&s, target, x, y), want, "each unaligned stroke restarts at the sample"); + let listed = s.execute("cloneSource.list", json!({})).unwrap(); + assert_eq!(listed["sources"][0]["offset"], json!([16.0 - x as f64, 16.0 - y as f64])); + assert!(s.presets.clone.active().anchor.is_none(), "reporting an offset must not establish aligned sampling"); + assert_eq!(s.presets.clone.active().source, Some([16.0, 16.0])); + } + } +} + +/// Mode changes preserve aligned sampling while numeric edits use the pairing being reported. +#[test] +fn clone_offsets_follow_mode_toggles_and_manual_edits_use_the_reported_pairing() { + for depth in [8, 16, 32] { + let (mut s, source, target) = setup(depth, "rgb"); + let stamp = |s: &mut Session, x, y, aligned| { + s.execute("paint.cloneStamp", json!({"points": [[x,y]], "size": 8, "hardness": 100, "aligned": aligned})).unwrap(); + }; + stamp(&mut s, 40, 30, true); + stamp(&mut s, 50, 40, false); + assert_eq!(s.presets.clone.active().anchor, Some([40.0, 30.0])); + assert_eq!(s.execute("cloneSource.list", json!({})).unwrap()["sources"][0]["offset"], json!([-34.0, -24.0])); + stamp(&mut s, 52, 42, true); + assert_eq!(pixel(&s, target, 52, 42), pixel(&s, source, 28, 28), "switching back retains the aligned pairing"); + stamp(&mut s, 50, 40, false); + s.execute("cloneSource.set", json!({"offset": [-30,-20]})).unwrap(); + assert_eq!(s.presets.clone.active().source, Some([20.0, 20.0]), "editing the displayed offset uses its actual destination reference"); + assert_eq!(s.presets.clone.active().anchor, Some([50.0, 40.0])); + stamp(&mut s, 54, 44, false); + assert_eq!(pixel(&s, target, 54, 44), pixel(&s, source, 20, 20)); + stamp(&mut s, 54, 44, true); + assert_eq!(pixel(&s, target, 54, 44), pixel(&s, source, 24, 24), "a manual edit establishes the newly requested pairing"); + } +} + +/// An offset edit has an explicit reference and cannot partially mutate slots on invalid input. +#[test] +fn clone_offsets_accept_a_preview_reference_and_reject_invalid_points_atomically() { + let (mut s, _, _) = setup(16, "rgb"); + let reply = s.execute("cloneSource.set", json!({"offset": [-20,-10], "anchor": [40,30]})).unwrap(); + assert_eq!(reply["source"], json!([20.0, 20.0])); + assert_eq!(reply["offset"], json!([-20.0, -10.0])); + for p in [ + json!({"offset": [-20,-10], "anchor": ["bad",30]}), + json!({"offset": [-20,-10], "anchor": [1.0e300,30]}), + json!({"anchor": [40,30]}), + json!({"source": [1.0e300,0]}), + json!({"source": [20,20], "offset": ["bad",0]}), + json!({"source": [20,20], "anchor": [999999,999999], "offset": [10,20]}), + ] { + let before = s.presets.clone.clone(); + assert!(s.execute("cloneSource.set", p).is_err()); + assert_eq!(s.presets.clone, before, "a rejected edit leaves all source slots unchanged"); + } +} + +/// Only successful slot-based painting may record a source pairing. +#[test] +fn clone_offsets_do_not_record_previews_failed_strokes_or_explicit_command_sources() { + for cmd in ["paint.cloneStamp", "paint.healingBrush"] { + let (mut s, _, target) = setup(8, "rgb"); + let p = json!({"points": [[40,30]], "size": 8, "hardness": 100}); + let before = s.presets.clone.clone(); + let _live = LiveRetouch::begin(&s, cmd, &p).unwrap(); + assert_eq!(s.presets.clone, before, "a live preview is read-only"); + s.edit("lock target", |doc, _| { + doc.layer_mut(target).unwrap().locks.all = true; + Ok(()) + }) + .unwrap(); + assert!(s.execute(cmd, p.clone()).is_err()); + assert_eq!(s.presets.clone, before, "failed painting cannot anchor or report a successful pairing"); + s.edit("unlock target", |doc, _| { + doc.layer_mut(target).unwrap().locks.all = false; + Ok(()) + }) + .unwrap(); + let mut explicit = p.clone(); + explicit["offset"] = json!([-20, -10]); + s.execute(cmd, explicit).unwrap(); + assert_eq!(s.presets.clone, before, "an explicit command source does not overwrite the picked slot"); + let mut unaligned = p; + unaligned["aligned"] = json!(false); + s.execute(cmd, unaligned).unwrap(); + assert_eq!(s.execute("cloneSource.list", json!({})).unwrap()["sources"][0]["offset"], json!([-24.0, -14.0])); + assert!(s.presets.clone.active().anchor.is_none()); + } +} + +/// Old slots remain readable; re-picking clears pairings and invalid slot indexes fail safely. +#[test] +fn clone_offsets_keep_legacy_pairings_and_clear_readouts_when_a_source_is_repicked() { + let (mut s, source, _) = setup(16, "rgb"); + s.execute("paint.cloneStamp", json!({"points": [[40,30]], "size": 8, "hardness": 100})).unwrap(); + let mut old = serde_json::to_value(s.presets.clone.active()).unwrap(); + old.as_object_mut().unwrap().remove("last_anchor"); + let restored: crate::presets::clone_source::CloneSource = serde_json::from_value(old).unwrap(); + assert_eq!(restored.offset(), Some([-24.0, -14.0])); + let picked = s.execute("cloneSource.set", json!({"source": [20,20], "layer": source.0})).unwrap(); + assert!(picked["offset"].is_null()); + assert!(picked["anchor"].is_null()); + assert!(picked["lastAnchor"].is_null()); + s.execute("cloneSource.set", json!({"source": null, "offset": null, "anchor": null, "index": null, "width": 150})).unwrap(); + assert_eq!(s.presets.clone.active().source, Some([20.0, 20.0]), "null optional coordinates remain omitted for compatibility"); + for value in [json!(u64::MAX), json!(-1), json!("bad")] { + assert!(s.execute("cloneSource.set", json!({"index": value})).is_err()); + assert!(s.execute("cloneSource.select", json!({"index": value})).is_err()); + } + s.presets.clone.active = usize::MAX; + assert!( + matches!(s.execute("cloneSource.set", json!({})), Err(EngineError::BadParams { .. })), + "corrupt saved selection must be a parameter error, not an internal panic" + ); + assert!(matches!(s.execute("cloneSource.resetTransform", json!({})), Err(EngineError::BadParams { .. }))); +} + +/// A small destination dab must not request an unbounded transformed source buffer. +#[test] +fn clone_offsets_scaled_source_reads_are_bounded_before_allocation() { + for cmd in ["paint.cloneStamp", "paint.healingBrush"] { + let (mut s, _, _) = setup(8, "rgb"); + let before = s.presets.clone.clone(); + let document = s.active().unwrap().doc.clone(); + let result = s.execute(cmd, json!({"points": [[32,32]], "scale": [0.00001,0.00001], "size": 8, "hardness": 100})); + assert!(result.is_err(), "a small dab cannot allocate an unbounded transformed source"); + assert_eq!(s.active().unwrap().doc, document); + assert_eq!(s.presets.clone, before); + } +} + +/// Null optional fields must not silently change document selection or source transforms. +#[test] +fn clone_offsets_null_optional_coordinates_keep_the_picked_source_document() { + for depth in [8, 16, 32] { + let (mut s, source, _) = setup(depth, "rgb"); + let want = pixel(&s, source, 16, 16); + s.execute("file.new", json!({"width": 64, "height": 64, "depth": depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let target = s.active().unwrap().active_layer.unwrap(); + s.execute("paint.cloneStamp", json!({"points": [[40,30]], "size": 8, "hardness": 100, "source": null, "offset": null, "anchor": null})).unwrap(); + assert_eq!(pixel(&s, target, 40, 30), want, "null optional coordinates must not silently switch sampling to the destination document"); + assert_eq!(s.execute("cloneSource.list", json!({})).unwrap()["sources"][0]["offset"], json!([-24.0, -14.0])); + s.execute("cloneSource.set", json!({"width": 200, "rotation": 90})).unwrap(); + let (map, _) = + crate::presets::clone_source::resolve(&s, &json!({"scale": null, "rotation": null, "flipH": null}), (40.0, 30.0), "paint.cloneStamp").unwrap(); + assert_eq!(map.m, crate::presets::clone_source::transform_matrix([200.0, 100.0], 90.0, false, false)); + } +} + +/// Extreme affine source coordinates must resolve to missing pixels without overflow or NaN. +#[test] +fn clone_and_heal_transformed_far_sources_are_finite_and_preserve_the_destination() { + for depth in [8, 16, 32] { + for cmd in ["paint.cloneStamp", "paint.healingBrush"] { + let (mut s, _, target) = setup(depth, "rgb"); + s.edit("green destination", |doc, _| { + let bounds = doc.bounds(); + doc.layer_mut(target).unwrap().surface_mut().unwrap().fill_rect(bounds, &[0.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + for source in [[3.0e9, 0.0], [0.0, 3.0e9], [-3.0e9, 0.0], [0.0, -3.0e9], [f64::MAX, f64::MAX]] { + s.execute(cmd, json!({"points": [[32,32]], "source": source, "rotation": 45, "size": 8, "hardness": 100})).unwrap(); + let got = pixel(&s, target, 32, 32); + for (got, want) in got.into_iter().zip([0.0, 1.0, 0.0, 1.0]) { + assert!(got.is_finite() && (got - want).abs() < 1e-5, "{cmd} at {depth}-bit, source {source:?}: {got}"); + } + } + } + } +} + +/// Build equivalent opaque sources with/without stored alpha, using quantized fixture colours. +fn no_alpha_scene(depth: u64, mode: &str, source_alpha: bool, target_alpha: bool, external: bool, at: [i32; 2], color: [f32; 4]) -> (Session, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64, "depth": depth, "mode": mode})).unwrap(); + let source = s.active().unwrap().active_layer.unwrap(); + s.edit("opaque source", |doc, _| { + let bounds = doc.bounds(); + let surf = doc.layer_mut(source).unwrap().surface_mut().unwrap(); + let fmt = PixelFormat::new(surf.format().mode, surf.format().sample, source_alpha); + let mut quantized = Surface::new(fmt); + quantized.write_region(Rect::new(0, 0, 1, 1), &photocraft_raster::from_rgba(&fmt, color)); + let values = quantized.read_region(Rect::new(0, 0, 1, 1)); + *surf = if source_alpha { + let mut finite = Surface::new(fmt); + finite.fill_rect(bounds, &values); + finite + } else { + Surface::with_default(fmt, &values) + }; + Ok(()) + }) + .unwrap(); + s.execute("cloneSource.set", json!({"source": at})).unwrap(); + if external { + s.execute("file.new", json!({"width": 80, "height": 80, "depth": depth, "mode": mode})).unwrap(); + } + s.execute("layer.new.layer", json!({})).unwrap(); + let target = s.active().unwrap().active_layer.unwrap(); + s.edit("blue destination", |doc, _| { + let surf = doc.layer_mut(target).unwrap().surface_mut().unwrap(); + let fmt = PixelFormat::new(surf.format().mode, surf.format().sample, target_alpha); + let mut quantized = Surface::new(fmt); + quantized.write_region(Rect::new(0, 0, 1, 1), &photocraft_raster::from_rgba(&fmt, [0.0, 0.0, 1.0, 1.0])); + *surf = Surface::with_default(fmt, &quantized.read_region(Rect::new(0, 0, 1, 1))); + Ok(()) + }) + .unwrap(); + (s, target) +} + +/// Compare native values with an opaque alpha-bearing reference at the same colour/depth. +fn assert_opaque_reference(actual: &Surface, expected: &Surface, rect: Rect) { + let (n, en) = (actual.channels(), expected.channels()); + for (i, (a, e)) in actual.read_region(rect).chunks_exact(n).zip(expected.read_region(rect).chunks_exact(en)).enumerate() { + assert_eq!(a, &e[..n], "native pixel {i}, {:?}", actual.format()); + } +} + +/// Canvas coverage is independent of stored alpha, including opaque black and wrapped sources. +#[test] +fn clone_no_alpha_sources_clip_preview_live_and_commit_at_all_canvas_corners() { + for depth in [8, 16, 32] { + for mode in ["rgb", "gray", "cmyk", "lab"] { + for target_alpha in [false, true] { + for external in [false, true] { + for wrap in [false, true] { + for at in [[0, 0], [63, 0], [0, 63], [63, 63]] { + let color = if at[0] == at[1] { [0.0, 0.0, 0.0, 1.0] } else { [1.0, 0.0, 0.0, 1.0] }; + let (mut actual, target) = no_alpha_scene(depth, mode, false, target_alpha, external, at, color); + let (mut reference, expected) = no_alpha_scene(depth, mode, true, true, external, at, color); + let initial = actual.active().unwrap().doc.layer(target).unwrap().surface().unwrap().clone(); + let fmt = initial.format(); + let map = Mapping { source: (at[0] as f64, at[1] as f64), anchor: (32.0, 32.0), m: [1.0, 0.0, 0.0, 1.0], document: None }; + let roi = Rect::new(24, 24, 40, 40); + let shown = clone_preview_periodic(&actual, roi, &map, "current", wrap).unwrap(); + let wanted = clone_preview_periodic(&reference, roi, &map, "current", wrap).unwrap(); + for (i, (a, e)) in shown.px.iter().zip(&wanted.px).enumerate() { + assert_eq!(a, e, "preview {i}: {depth}/{mode}/{target_alpha}/{external}/{wrap}/{at:?}"); + } + let p = json!({"points": [[32,32]], "size": 12, "hardness": 100, "opacity": 50, "flow": 40, "wrap": wrap}); + reference.execute("paint.cloneStamp", p.clone()).unwrap(); + let expected_surf = reference.active().unwrap().doc.layer(expected).unwrap().surface().unwrap(); + let live = LiveRetouch::begin(&actual, "paint.cloneStamp", &p).unwrap(); + assert_opaque_reference(live.doc.layer(target).unwrap().surface().unwrap(), expected_surf, roi); + actual.offer_live_retouch(live).unwrap(); + assert_eq!(actual.execute("paint.cloneStamp", p.clone()).unwrap()["fromLive"], true); + assert_opaque_reference(actual.active().unwrap().doc.layer(target).unwrap().surface().unwrap(), expected_surf, roi); + assert!(actual.undo()); + actual.execute("paint.cloneStamp", p).unwrap(); + let surf = actual.active().unwrap().doc.layer(target).unwrap().surface().unwrap(); + assert_eq!(surf.format(), fmt, "cloning must retain the destination's native format"); + assert_opaque_reference(surf, expected_surf, roi); + if !wrap { + let x = if at[0] == 0 { 31 } else { 33 }; + let y = if at[1] == 0 { 31 } else { 33 }; + let outside = Rect::new(x, y, x + 1, y + 1); + assert_eq!(surf.read_region(outside), initial.read_region(outside), "missing source leaves destination pixels intact"); + assert_eq!(shown.px[((y - 24) * 16 + x - 24) as usize][3], 0.0); + } + let inside = Rect::new(32, 32, 33, 33); + assert_ne!(surf.read_region(inside), initial.read_region(inside), "opaque black must paint inside the source canvas"); + } + } + } + } + } + } +} + +/// Affine filtering, blend modes and source composites retain alpha-bearing source coverage. +#[test] +fn clone_no_alpha_sources_match_alpha_sources_with_transforms_and_composites() { + for mode in ["rgb", "cmyk"] { + for which in ["current", "currentAndBelow", "all"] { + for blend in ["normal", "multiply", "lighten"] { + for wrap in [false, true] { + let color = if blend == "normal" { [0.0, 0.0, 0.0, 1.0] } else { [1.0, 0.25, 0.75, 1.0] }; + let (mut actual, target) = no_alpha_scene(32, mode, false, false, true, [0, 0], color); + let (mut reference, expected) = no_alpha_scene(32, mode, true, true, true, [0, 0], color); + for session in [&mut actual, &mut reference] { + session.execute("cloneSource.set", json!({"width": 150, "height": 75, "rotation": 30, "flipH": true})).unwrap(); + } + let p = + json!({"points": [[32,32]], "size": 12, "hardness": 100, "opacity": 50, "flow": 40, "sampleLayer": which, "mode": blend, "wrap": wrap}); + let (map, _) = crate::presets::clone_source::resolve(&actual, &p, (32.0, 32.0), "paint.cloneStamp").unwrap(); + let (reference_map, _) = crate::presets::clone_source::resolve(&reference, &p, (32.0, 32.0), "paint.cloneStamp").unwrap(); + let roi = Rect::new(24, 24, 40, 40); + let preview = clone_preview_periodic(&actual, roi, &map, which, wrap).unwrap(); + let wanted = clone_preview_periodic(&reference, roi, &reference_map, which, wrap).unwrap(); + for (a, e) in preview.px.iter().zip(&wanted.px) { + assert_eq!(a, e, "{mode}/{which}/{blend}/{wrap}"); + } + reference.execute("paint.cloneStamp", p.clone()).unwrap(); + let expected_surf = reference.active().unwrap().doc.layer(expected).unwrap().surface().unwrap(); + let live = LiveRetouch::begin(&actual, "paint.cloneStamp", &p).unwrap(); + assert_opaque_reference(live.doc.layer(target).unwrap().surface().unwrap(), expected_surf, roi); + actual.offer_live_retouch(live).unwrap(); + assert_eq!(actual.execute("paint.cloneStamp", p.clone()).unwrap()["fromLive"], true); + assert!(actual.undo()); + actual.execute("paint.cloneStamp", p).unwrap(); + assert_opaque_reference(actual.active().unwrap().doc.layer(target).unwrap().surface().unwrap(), expected_surf, roi); + } + } + } + } +} + +/// The shared Healing Brush sampler keeps opaque destinations equivalent to alpha-bearing ones. +#[test] +fn clone_no_alpha_healing_sources_match_alpha_sources_in_preview_and_commit() { + for depth in [16, 32] { + for which in ["current", "currentAndBelow", "all"] { + for wrap in [false, true] { + let (mut actual, target) = no_alpha_scene(depth, "rgb", false, false, true, [0, 0], [0.5, 0.5, 0.5, 1.0]); + let (mut reference, expected) = no_alpha_scene(depth, "rgb", true, true, true, [0, 0], [0.5, 0.5, 0.5, 1.0]); + let p = json!({"points": [[32,32]], "size": 12, "hardness": 100, "sampleLayer": which, "wrap": wrap}); + let roi = Rect::new(24, 24, 40, 40); + let live = LiveRetouch::begin(&actual, "paint.healingBrush", &p).unwrap(); + let expected_live = LiveRetouch::begin(&reference, "paint.healingBrush", &p).unwrap(); + assert_opaque_reference(live.doc.layer(target).unwrap().surface().unwrap(), expected_live.doc.layer(expected).unwrap().surface().unwrap(), roi); + actual.execute("paint.healingBrush", p.clone()).unwrap(); + reference.execute("paint.healingBrush", p).unwrap(); + assert_opaque_reference( + actual.active().unwrap().doc.layer(target).unwrap().surface().unwrap(), + reference.active().unwrap().doc.layer(expected).unwrap().surface().unwrap(), + roi, + ); + } + } + } +} + +/// Hover sampling must refuse the same cross-document grayscale targets as painting. +#[test] +fn clone_cross_document_hover_rejects_targeted_masks_and_channels_like_strokes() { + use crate::channel_cmds::ChannelTarget; + for target_mask in [false, true] { + let (mut s, _, _) = setup(8, "rgb"); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + if target_mask { + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.active_mut().unwrap().channel_view.target = ChannelTarget::LayerMask; + } else { + s.execute("channel.new", json!({"fill": "white"})).unwrap(); + } + let map = Mapping { source: (16.0, 16.0), anchor: (32.0, 32.0), m: [1.0, 0.0, 0.0, 1.0], document: None }; + let rect = Rect::new(30, 30, 34, 34); + assert!(s.execute("paint.cloneStamp", json!({"points": [[32,32]], "size": 8})).is_err()); + assert!(clone_preview(&s, rect, &map, "current").is_err(), "a refused cross-document target cannot have a source overlay"); + assert!(super::clone::healing_preview(&s, rect, &map, "current").is_err()); + } +} + +/// A Poisson boundary cannot create source coverage for an absent sampled pixel. +#[test] +fn clone_healing_absent_source_preserves_nonuniform_destinations() { + for depth in [8, 16, 32] { + for mode in ["rgb", "gray", "cmyk", "lab"] { + for wrap in [false, true] { + for source_alpha in [false, true] { + for target_alpha in [false, true] { + for source_point in [[-100, -100], [0, 0]] { + for blend in ["normal", "multiply"] { + let (mut s, target) = no_alpha_scene(depth, mode, source_alpha, target_alpha, true, source_point, [0.5, 0.5, 0.5, 1.0]); + s.edit("nonuniform destination", |doc, _| { + let bounds = doc.bounds(); + let surf = doc.layer_mut(target).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + surf.fill_rect(bounds, &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + for (x, y) in [(30, 32), (34, 34)] { + surf.write_region(Rect::new(x, y, x + 1, y + 1), &photocraft_raster::from_rgba(&fmt, [0.25, 0.25, 0.25, 1.0])); + } + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.layer(target).unwrap().surface().unwrap().clone(); + let p = json!({"points": [[32,32]], "size": 14, "hardness": 100, "mode": blend, "wrap": wrap}); + let live = LiveRetouch::begin(&s, "paint.healingBrush", &p).unwrap(); + if !wrap { + assert_eq!(live.doc.layer(target).unwrap().surface().unwrap().rgba(30, 32), before.rgba(30, 32)); + } + s.execute("paint.healingBrush", p).unwrap(); + let after = s.active().unwrap().doc.layer(target).unwrap().surface().unwrap(); + assert_eq!(after.format(), before.format()); + if wrap { + assert_ne!(after.rgba(30, 32), before.rgba(30, 32), "wrapped source pixels still heal: {depth}/{mode}/{blend}"); + continue; + } + assert_eq!( + after.rgba(30, 32), + before.rgba(30, 32), + "absent source {source_point:?}, depth {depth}, alpha {source_alpha}/{target_alpha}, {blend}" + ); + if source_point[0] < 0 { + assert_eq!(after.read_region(Rect::new(0, 0, 80, 80)), before.read_region(Rect::new(0, 0, 80, 80))); + } else { + assert_ne!(after.rgba(34, 34), before.rgba(34, 34), "valid source pixels still heal"); + } + } + } + } + } + } + } + } +} + +/// Nonuniform soft-tip coverage must stay aligned across the opaque destination's working tiles. +#[test] +fn clone_no_alpha_soft_stroke_matches_reference_across_multiple_working_patches() { + for mode in ["normal", "multiply"] { + let (mut actual, target) = no_alpha_scene(16, "rgb", false, false, true, [0, 0], [1.0, 0.0, 0.0, 1.0]); + let (mut reference, expected) = no_alpha_scene(16, "rgb", true, true, true, [0, 0], [1.0, 0.0, 0.0, 1.0]); + let p = json!({"points": [[32,32],[64,48]], "size": 180, "hardness": 0, "opacity": 50, "flow": 40, "mode": mode}); + reference.execute("paint.cloneStamp", p.clone()).unwrap(); + let roi = Rect::new(-64, -64, 160, 160); + let expected_surf = reference.active().unwrap().doc.layer(expected).unwrap().surface().unwrap(); + let live = LiveRetouch::begin(&actual, "paint.cloneStamp", &p).unwrap(); + assert_opaque_reference(live.doc.layer(target).unwrap().surface().unwrap(), expected_surf, roi); + actual.execute("paint.cloneStamp", p).unwrap(); + assert_opaque_reference(actual.active().unwrap().doc.layer(target).unwrap().surface().unwrap(), expected_surf, roi); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs b/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs index dc36026ce9..8d106b7bc9 100644 --- a/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs +++ b/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs @@ -2,26 +2,28 @@ //! content-aware fill close the gaps. //! //! The selection is the content, `offset` how far the user dragged it. At the new place the content -//! is pasted, fitted to its new surroundings by `color`, and a band along its edge, inside the -//! selection, is re-synthesised from the surroundings so that it merges in. In `move` mode the place -//! the content left is then filled content-aware (`extend` keeps it). That fill never samples the -//! moved content, so the object doesn't come back as a ghost; the edge band may sample it (it is the -//! context the band blends towards), but not the content's old place. +//! is pasted and a band along its edge, inside the selection, is re-synthesised from the surroundings +//! so that it merges in. `color` decides how that pasted middle meets the new surroundings. In `move` +//! mode the place the content left is then filled content-aware (`extend` keeps it). That fill never +//! samples the moved content, so the object doesn't come back as a ghost; the edge band may sample it +//! (it is the context the band blends towards), but not the content's old place. //! //! Measured on Photoshop 25.4 (a 60 px selection holding a ring-shaped object, dragged 150 px): //! * **Structure** 3 to 7 give the same result, bit for bit: the content is copied exactly up to //! about 8 px from the selection's edge, and that band blends into the surroundings. 2 widens the //! band; 1 re-synthesises the content too, so even its middle is no longer an exact copy. -//! * **Color** 0 pastes the content as it is; higher values bring its level towards the new -//! surroundings by up to about `0.04 · color` (Patch Tool, content 42 and 102 levels brighter: -//! 3 shifts it 32 and 31 levels, 10 shifts it 35 and 95), a limited gain and bias -//! ([`photocraft_algo::content_aware::color_amount`]). +//! * **Color** 0 pastes the middle as it is. Content-Aware Move keeps that middle through Color 5. +//! Above 5, when every colour channel's mean shift agrees (a brightness change), the middle moves +//! toward the new surroundings, the whole way at Color 10. A hue change leaves the middle alone. +//! The edge band still blends at every Color. The Patch Tool keeps a limited gain and bias of +//! about `0.04 · color` ([`photocraft_algo::content_aware::color_amount`]: content 42 and 102 +//! levels brighter shifts 32 and 31 levels at 3, and 35 and 95 at 10). //! //! The selection moves with the content, as in Photoshop. A soft selection counts wherever it is //! above zero (as the Patch Tool's); the band does the blending. The fills are PatchMatch //! completions and can take seconds on large selections, so the command runs as a background job //! (#210): with progress, cancellable, and the document unchanged until it applies. The Patch -//! Tool's Content-Aware mode lands its content the same way ([`land`]). +//! Tool's Content-Aware mode lands its content through [`land`], keeping that limited fit. //! //! **Transform On Drop** (the options-bar checkbox): after the drop a transform box lets the user //! scale and rotate the content before the blend is computed. `scaleX` / `scaleY` (%) and @@ -379,12 +381,82 @@ fn outer_ring(gw: usize, gh: usize, m: &[bool], w: usize) -> Vec { erode(gw, gh, &inside, w).iter().zip(m).map(|(keep, sel)| !*keep && !*sel).collect() } +/// Mean of channel `c` over interleaved samples, or `None` when there is no finite sample. +fn channel_mean(samples: &[f32], ch: usize, c: usize) -> Option { + if ch == 0 || c >= ch { + return None; + } + let mut sum = 0.0f64; + let mut n = 0u64; + for px in samples.chunks_exact(ch) { + let v = px.get(c).copied()?; + if !v.is_finite() { + return None; + } + sum += f64::from(v); + n = n.saturating_add(1); + } + if n == 0 { None } else { Some((sum / n as f64) as f32) } +} + +/// Gain and bias for Content-Aware Move's kept middle. Colour channels copy as they are, except +/// when `color` is above 5 and the surroundings differ by a brightness change: then each channel +/// gets gain 1 and a share of that mean difference, the whole of it at Color 10. A hue change +/// (the channels disagree) stays a plain copy at every Color. Alpha is always copied. +/// +/// The means are the ring just outside the selection, the same samples the Patch fit uses. On the +/// measured patches that ring has the same mean as the content, so the middle moves by about the +/// difference between the new surroundings and the content. +fn cam_core_fit(ch: usize, from: &[f32], to: &[f32], color: u8, alpha: Option) -> Vec<(f32, f32)> { + let identity = vec![(1.0f32, 0.0f32); ch]; + if ch == 0 || color <= 5 { + return identity; + } + let mut diffs = Vec::new(); + for c in 0..ch { + if Some(c) == alpha { + continue; + } + let (Some(from_mean), Some(to_mean)) = (channel_mean(from, ch, c), channel_mean(to, ch, c)) else { + return identity; + }; + let d = to_mean - from_mean; + if !d.is_finite() { + return identity; + } + diffs.push((c, d)); + } + if diffs.is_empty() { + return identity; + } + let mut lo = f32::MAX; + let mut hi = f32::MIN; + for &(_, d) in &diffs { + lo = lo.min(d); + hi = hi.max(d); + } + // Within about 8 levels the channels agree: a brightness change. Further apart is a hue + // change, and the middle stays. Grey (one colour channel) always agrees with itself. + if hi - lo > 8.0 / 255.0 { + return identity; + } + let weight = f32::from(color.saturating_sub(5).min(5)) / 5.0; + let mut gb = identity; + for (c, d) in diffs { + if let Some(slot) = gb.get_mut(c) { + *slot = (1.0, weight * d); + } + } + gb +} + /// Content landing at `dst_area`: the pixels of the window around it, with `selected` (the /// selection's shape there) to be replaced by the content found `shift` away (`content` = that -/// window, so `content` pixel = window pixel + `shift`). The content's middle is copied, its level -/// fitted to the new surroundings by `color`; a `band_width(structure)` band inside the selection's -/// edge is re-synthesised from the surroundings and that middle, never sampling `avoid`. Writes the -/// result into the target and returns the rectangle it changed. +/// window, so `content` pixel = window pixel + `shift`). The content's middle is copied and fitted +/// with the Patch Tool's limited gain and bias; a `band_width(structure)` band inside the +/// selection's edge is re-synthesised from the surroundings and that middle, never sampling +/// `avoid`. Writes the result into the target and returns the rectangle it changed. +/// Content-Aware Move calls [`land_at`] so its middle follows that tool's Color rule. #[allow(clippy::too_many_arguments)] pub(super) fn land( doc: &mut Document, @@ -399,6 +471,27 @@ pub(super) fn land( stage: (f32, f32), ctx: &crate::jobs::JobCtx, label: &str, +) -> Result { + land_at(doc, t, p, win, selected, content, avoid, structure, color, stage, ctx, label, false) +} + +/// [`land`], with `cam` choosing the middle's colour fit: the Patch Tool's limited gain and bias, +/// or Content-Aware Move's brightness shift. +#[allow(clippy::too_many_arguments)] +fn land_at( + doc: &mut Document, + t: Target, + p: &Value, + win: Rect, + selected: &[bool], + content: &Region, + avoid: &[bool], + structure: u8, + color: u8, + stage: (f32, f32), + ctx: &crate::jobs::JobCtx, + label: &str, + cam: bool, ) -> Result { let (w, h) = (win.width() as usize, win.height() as usize); let here = read(doc, t, p, win)?; @@ -414,9 +507,11 @@ pub(super) fn land( // outside the selection's shape. let ring = outer_ring(w, h, selected, 6); let pick = |r: &Region| -> Vec { ring.iter().enumerate().filter(|(_, k)| **k).flat_map(|(i, _)| r.data[i * n..(i + 1) * n].to_vec()).collect() }; - let gb = level_transform(n, &pick(content), &pick(&here), color_amount(color)); let fmt = crate::channel_cmds::target_surface(doc, t.id, p)?.0.format(); let alpha = alpha_index(&fmt); + let from = pick(content); + let to = pick(&here); + let gb = if cam { cam_core_fit(n, &from, &to, color, alpha) } else { level_transform(n, &from, &to, color_amount(color)) }; let mut buf = here; for (i, _) in core.iter().enumerate().filter(|(_, c)| **c) { for (c, &(g, b)) in gb.iter().enumerate() { @@ -470,7 +565,7 @@ fn run_move(doc: &mut Document, sel: &Surface, plan: &Plan, p: &Value, ctx: &cra } }; let old_place = mask(sel, win); - let mut damage = land(doc, plan.target, p, win, &moved, &content, &old_place, plan.structure, plan.color, (0.0, split), ctx, label)?; + let mut damage = land_at(doc, plan.target, p, win, &moved, &content, &old_place, plan.structure, plan.color, (0.0, split), ctx, label, true)?; // 2. Move: fill the place the content left (where the content didn't land on it). if plan.mode == Mode::Move { @@ -799,3 +894,7 @@ mod tests { s.execute("paint.contentAwareMove", p).unwrap(); } } + +#[cfg(test)] +#[path = "content_aware_move_color_tests.rs"] +mod color_tests; diff --git a/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs b/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs new file mode 100644 index 0000000000..55e2d306bf --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/content_aware_move_color_tests.rs @@ -0,0 +1,194 @@ +//! Content-Aware Move's Color control (#12197). Through Color 5 the moved middle stays as it was. +//! At Color 10 a brightness change shifts that middle by the mean difference of the surroundings; +//! a hue change leaves it alone. The edge band still blends. Move and Extend share the fit. + +use super::*; + +fn session(w: u32, h: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": w, "height": h, "depth": 8, "mode": "rgb"})).unwrap(); + s +} + +fn paint(s: &mut Session, f: impl Fn(i32, i32) -> [u8; 3]) { + s.edit("setup", |doc, active| { + let b = doc.bounds(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let mut data = Vec::new(); + for y in b.y0..b.y1 { + for x in b.x0..b.x1 { + let px = f(x, y); + data.extend(photocraft_raster::from_rgba(&fmt, [px[0] as f32 / 255.0, px[1] as f32 / 255.0, px[2] as f32 / 255.0, 1.0])); + } + } + surf.write_region(b, &data); + Ok(()) + }) + .unwrap(); +} + +fn levels(s: &Session, x: i32, y: i32) -> [i32; 3] { + let d = s.active().unwrap(); + let px = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y); + [0, 1, 2].map(|c| (px[c] * 255.0).round() as i32) +} + +fn checker(x: i32, y: i32) -> Option { + if (100..180).contains(&x) && (100..180).contains(&y) { + let (cx, cy) = ((x - 100) / 10, (y - 100) / 10); + Some(if (cx + cy) % 2 == 0 { 60 } else { 200 }) + } else { + None + } +} + +/// 800×600. Left half grey, right half green, with the 80×80 checker at (100, 100). +fn green_doc() -> Session { + let mut s = session(800, 600); + paint(&mut s, |x, y| { + if let Some(v) = checker(x, y) { + [v, v, v] + } else if x < 400 { + [128, 128, 128] + } else { + [40, 160, 60] + } + }); + s +} + +/// The same checker on a horizontal grey ramp, constant across each 10 px column. +fn ramp_doc() -> Session { + let mut s = session(800, 600); + paint(&mut s, |x, y| { + if let Some(v) = checker(x, y) { + [v, v, v] + } else { + let column = x.div_euclid(10) * 10; + let v = (40.0 + 180.0 * column as f32 / 790.0).round().clamp(0.0, 255.0) as u8; + [v, v, v] + } + }); + s +} + +fn flat_doc() -> Session { + let mut s = session(800, 600); + paint(&mut s, |x, _| if x < 400 { [204, 204, 204] } else { [51, 51, 51] }); + s +} + +fn select_and_move(s: &mut Session, [x, y, w, h]: [i32; 4], offset: [i32; 2], color: u64, mode: &str) { + s.execute("select.rect", json!({"x": x, "y": y, "width": w, "height": h})).unwrap(); + s.execute("paint.contentAwareMove", json!({"offset": offset, "structure": 4, "color": color, "mode": mode})).unwrap(); +} + +fn assert_near(got: [i32; 3], want: [i32; 3], tol: i32, what: &str) { + for (c, (g, w)) in got.iter().zip(want).enumerate() { + assert!((g - w).abs() <= tol, "{what} channel {c}: {got:?} vs {want:?} (±{tol})"); + } +} + +#[test] +fn the_core_fit_shifts_brightness_and_leaves_a_hue_alone() { + let grey = vec![130.0 / 255.0; 3]; + let bright = vec![176.0 / 255.0; 3]; + assert_eq!(cam_core_fit(3, &grey, &bright, 5, None), vec![(1.0, 0.0); 3], "color 5 does not move the middle"); + let bias = (176.0 - 130.0) / 255.0; + for (g, b) in cam_core_fit(3, &grey, &bright, 10, None) { + assert!((g - 1.0).abs() < 1e-5 && (b - bias).abs() < 1e-5, "color 10 is gain 1 plus the mean difference"); + } + // Grey onto the green: the channels disagree, so the middle is copied. + let green = vec![40.0 / 255.0, 160.0 / 255.0, 60.0 / 255.0]; + assert_eq!(cam_core_fit(3, &grey, &green, 10, None), vec![(1.0, 0.0); 3]); + // One colour channel is a brightness change. Alpha is copied, not fitted. + let from = vec![200.0 / 255.0, 200.0 / 255.0, 200.0 / 255.0, 1.0]; + let to = vec![51.0 / 255.0, 51.0 / 255.0, 51.0 / 255.0, 0.25]; + let gb = cam_core_fit(4, &from, &to, 10, Some(3)); + assert_eq!(gb[3], (1.0, 0.0), "alpha is copied"); + let expect = (51.0 - 200.0) / 255.0; + assert!((gb[0].1 - expect).abs() < 1e-5 && gb[0].0 == 1.0); + assert_eq!(cam_core_fit(1, &[200.0 / 255.0], &[51.0 / 255.0], 10, None)[0].0, 1.0); +} + +#[test] +fn color_ten_on_green_leaves_the_middle_and_blends_the_edge() { + // Selection 120,120 40×40 dragged (140,140) → (600,420). Row y 420 is the middle of the landing. + let mut kept = green_doc(); + select_and_move(&mut kept, [120, 120, 40, 40], [460, 280], 0, "move"); + let mut fitted = green_doc(); + select_and_move(&mut fitted, [120, 120, 40, 40], [460, 280], 10, "move"); + + // Color 0 keeps today's copy of the checker. Color 10 stays within ±5 of that, not a green tint. + for (x, v) in [(590, 200), (595, 200), (600, 60), (605, 60), (610, 200)] { + assert_eq!(levels(&kept, x, 420), [v, v, v], "color 0 keeps the checker at x {x}"); + assert_near(levels(&fitted, x, 420), levels(&kept, x, 420), 5, "color 10 middle"); + } + // Edge band at Color 10. x 585 matches 55,86,60. x 610 is kept core (200), within ±20 of + // 188,197,189. x 615's reference is 134,181,142; the existing fill already misses it at + // Color 0 (about 178,190,180 against 143,182,149) and Color 10 lands near 101,160,111. + // The range covers that blend and the reference, and rejects the old tint 77,197,97. + assert_near(levels(&fitted, 585, 420), [55, 86, 60], 20, "x 585"); + assert_near(levels(&fitted, 610, 420), [188, 197, 189], 20, "x 610"); + let edge = levels(&fitted, 615, 420); + assert!((90..=150).contains(&edge[0]) && (150..=195).contains(&edge[1]) && (100..=155).contains(&edge[2]), "x 615 blends into the green: {edge:?}"); + + // Extend uses the same landing, so the middle stays too. + let mut extended = green_doc(); + select_and_move(&mut extended, [120, 120, 40, 40], [460, 280], 10, "extend"); + for x in [590, 600, 610] { + assert_near(levels(&extended, x, 420), levels(&fitted, x, 420), 5, "extend matches move"); + } +} + +#[test] +fn a_brightness_change_shifts_the_middle_only_past_color_five() { + let row = |color: u64| { + let mut s = ramp_doc(); + select_and_move(&mut s, [120, 120, 40, 40], [460, 280], color, "move"); + (levels(&s, 590, 420), levels(&s, 600, 420)) + }; + let (light, dark) = row(0); + assert_eq!((light, dark), ([200, 200, 200], [60, 60, 60]), "color 0 keeps the checker"); + assert_eq!(row(5), ([200, 200, 200], [60, 60, 60]), "color 5 leaves the middle"); + let (light, dark) = row(10); + // Measured about +43 (242 / 104); the ring mean predicts about +46. Either is a real shift. + assert!((230..=252).contains(&light[0]), "color 10 light cell: {light:?}"); + assert!((90..=112).contains(&dark[0]), "color 10 dark cell: {dark:?}"); + assert_eq!(light, [light[0]; 3]); + assert_eq!(dark, [dark[0]; 3]); + + // Same lighting, dropped straight down: the middle darkens (about −63; dark cells clip). + let mut s = ramp_doc(); + select_and_move(&mut s, [120, 120, 40, 40], [0, 280], 10, "move"); + let (light, dark) = (levels(&s, 130, 420), levels(&s, 140, 420)); + assert!(light[0] >= 120 && light[0] <= 155, "same lighting light cell: {light:?}"); + assert!(dark[0] <= 12, "same lighting dark cell clips near 0: {dark:?}"); + assert_eq!(light, [light[0]; 3]); + assert_eq!(dark, [dark[0]; 3]); +} + +#[test] +fn a_flat_patch_matches_the_new_surroundings_at_color_ten() { + let middle = |color: u64, mode: &str| { + let mut s = flat_doc(); + select_and_move(&mut s, [150, 250, 100, 100], [400, 0], color, mode); + levels(&s, 600, 300) + }; + for mode in ["move", "extend"] { + assert_eq!(middle(0, mode), [204, 204, 204], "{mode} color 0 keeps 204"); + assert_eq!(middle(3, mode), [204, 204, 204], "{mode} color 3 leaves the middle"); + assert_eq!(middle(10, mode), [51, 51, 51], "{mode} color 10 becomes 51"); + } + // The landing itself agrees; the old place is the part Move refills and Extend keeps. + let mut moved = flat_doc(); + select_and_move(&mut moved, [150, 250, 100, 100], [400, 0], 10, "move"); + let mut extended = flat_doc(); + select_and_move(&mut extended, [150, 250, 100, 100], [400, 0], 10, "extend"); + for y in [256, 300, 340] { + for x in [556, 600, 640] { + assert_eq!(levels(&moved, x, y), levels(&extended, x, y), "move and extend agree at {x},{y}"); + } + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/dab.rs b/crates/engine/src/cmd/retouch_cmds/dab.rs index a0fe5da71b..564df7512d 100644 --- a/crates/engine/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine/src/cmd/retouch_cmds/dab.rs @@ -16,6 +16,76 @@ fn per_dab(e: f32, spacing: f32) -> f32 { 1.0 - (1.0 - e.clamp(0.0, 1.0)).powf(spacing.clamp(0.01, 1.0)) } +/// The dab spacing, as a share of the tip's diameter, at which the reference's Sharpen drags +/// with Protect Detail were measured: each point of a drag got 4 dabs (#12938). +const PROTECT_DETAIL_SPACING: f32 = 0.25; + +/// The share of a full Protect Detail dab that a dab of `radius` at `moved` px from the previous +/// one applies: the first dab of a stroke (a click) is a full dab, and a drag adds up to the +/// reference's 4 full dabs over each point whatever the spacing, so many overlapping dabs don't +/// compound into black and white bands. It scales the strength itself rather than `1 − k` like +/// [`per_dab`], which stays 1 for a hard tip at 100 %. +#[inline] +fn protect_detail_share(moved: Option, radius: f32) -> f32 { + moved.map_or(1.0, |m| (m / (2.0 * radius.max(0.5) * PROTECT_DETAIL_SPACING)).clamp(0.0, 1.0)) +} + +/// Tracks a Protect Detail stroke's dabs for [`protect_detail_share`]. +#[derive(Default)] +pub(super) struct ProtectDetailShares { + /// The previous dab's centre and share. + prev: Option<(photocraft_geom::Point, f32)>, + /// The most coverage the dabs on the current centre have applied at each pixel of the rect. + covered: Option<(Rect, Vec)>, +} + +impl ProtectDetailShares { + /// The share of a full dab that `fp` applies, and the coverage over `fp.rect` to apply it with. + /// + /// Dabs on one centre (the stamps of Scattering's Count with Scatter 0, or airbrush build-up + /// while the pointer is held still) apply the share of their step once at each pixel: a dab + /// adds only where its coverage exceeds what the dabs before it on that centre applied, so a + /// larger jittered stamp sharpens the ring only it covers, and repeats never compound. + pub(super) fn next(&mut self, fp: &Footprint) -> (f32, Vec) { + let c = fp.dab.center; + let share = match self.prev { + Some((p, s)) if p == c => s, + Some((p, _)) => { + self.covered = None; + protect_detail_share(Some((c.x - p.x).hypot(c.y - p.y) as f32), fp.dab.radius) + } + None => protect_detail_share(None, fp.dab.radius), + }; + self.prev = Some((c, share)); + let (rect, cov) = match self.covered.take() { + Some((rect, cov)) if rect.contains_rect(&fp.rect) => (rect, cov), + Some((old, old_cov)) => { + let rect = old.union(&fp.rect); + let mut cov = vec![0.0; rect.width() as usize * rect.height() as usize]; + for y in old.y0..old.y1 { + let (from, to) = + (((y - old.y0) as usize) * old.width() as usize, ((y - rect.y0) as usize) * rect.width() as usize + (old.x0 - rect.x0) as usize); + cov[to..to + old.width() as usize].copy_from_slice(&old_cov[from..from + old.width() as usize]); + } + (rect, cov) + } + None => (fp.rect, vec![0.0; fp.cov.len()]), + }; + let mut cov = cov; + let (fw, rw) = (fp.rect.width() as usize, rect.width() as usize); + let mut fresh = vec![0.0; fp.cov.len()]; + for y in fp.rect.y0..fp.rect.y1 { + let (from, to) = (((y - fp.rect.y0) as usize) * fw, ((y - rect.y0) as usize) * rw + (fp.rect.x0 - rect.x0) as usize); + for ((f, &a), done) in fresh[from..from + fw].iter_mut().zip(&fp.cov[from..from + fw]).zip(&mut cov[to..to + fw]) { + *f = (a - *done).max(0.0); + *done = done.max(a); + } + } + self.covered = Some((rect, cov)); + (share, fresh) + } +} + /// Apply an RGB colour transform `f(rgb, strength)` to each covered pixel of a dab (through straight /// RGBA, so it works for Gray/CMYK/Lab too; untouched pixels are never round-tripped). fn color_dab(fmt: &PixelFormat, work: &mut Region, fp: &Footprint, strength: f32, spacing: f32, f: impl Fn([f32; 3], f32) -> [f32; 3]) { @@ -221,6 +291,8 @@ impl DabTool { /// How far around each dab the effect reads (Blur and Sharpen read a neighbourhood). fn neighborhood(&self) -> DabNeighborhood { match self { + // Protect Detail sharpens against its own, wider Gaussian (#12938). + Self::Focus { sharpen: true, protect: true, .. } => DabNeighborhood::Halo((photocraft_algo::retouch::PROTECT_DETAIL_SIGMA * 3.0).ceil() as i32 + 1), Self::Focus { sigma, .. } => DabNeighborhood::Halo((sigma * 3.0).ceil() as i32 + 1), Self::Smudge { max_size, .. } => DabNeighborhood::Smudge(Smudge::sampling_radius(*max_size)), _ => DabNeighborhood::Halo(0), @@ -236,11 +308,14 @@ impl DabTool { Self::Sponge { saturate, vibrance } => Box::new(move |work, fp| color_dab(&fmt, work, fp, 0.5, sp, |c, k| sponge(c, k, saturate, vibrance))), Self::Focus { sharpen, strength, protect, sigma } => { let a = alpha_index(&fmt); + let mut shares = ProtectDetailShares::default(); Box::new(move |work, fp| { let r = fp.rect.intersect(&work.rect); - if r.is_empty() { + let (share, fresh) = if sharpen && protect { shares.next(fp) } else { (1.0, Vec::new()) }; + if r.is_empty() || (sharpen && protect && (share <= 0.0 || fresh.iter().all(|&f| f <= 0.0))) { return; } + let fresh_at = |x: i32, y: i32| fresh[(y - fp.rect.y0) as usize * fp.rect.width() as usize + (x - fp.rect.x0) as usize]; let (w, h, n) = (work.width(), work.height(), work.ch); let win = ((r.x0 - work.rect.x0) as usize, (r.y0 - work.rect.y0) as usize, (r.x1 - work.rect.x0) as usize, (r.y1 - work.rect.y0) as usize); let out = if sharpen { local_sharpen(&work.data, w, h, n, a, win, 1.0, protect) } else { local_blur(&work.data, w, h, n, a, win, sigma) }; @@ -253,7 +328,11 @@ impl DabTool { return; } for x in r.x0..r.x1 { - let k = per_dab(fp.at(x, y) * strength, sp); + // Protect Detail: one click at 50 % does half of what 100 % does, and + // a drag over a point adds up to the reference's 4 dabs (#12938). + // Spread over `1/spacing` dabs (`per_dab`), a click did 7 % of it at + // the default 10 % spacing. + let k = if sharpen && protect { fresh_at(x, y) * strength * share } else { per_dab(fp.at(x, y) * strength, sp) }; if k <= 0.0 { continue; } @@ -280,13 +359,18 @@ impl DabTool { } } -/// The reference application refuses a Dodge or Sharpen stroke in Indexed Color and Bitmap -/// documents, with its alert's words (#12686, #12953); other modes (Multichannel and Duotone were -/// not measured) paint as before. The live stroke checks this too, so it previews nothing there. +/// The reference application refuses a Dodge, Burn, Sponge, Blur, Sharpen or Smudge stroke in +/// Indexed Color and Bitmap documents, with its alert's words (#12686, #12673, #13033, #12656, +/// #12953, #12967); other modes (Multichannel and Duotone were not measured) paint as before. The +/// live stroke checks this too, so it previews nothing there. fn mode_refusal(s: &Session, cmd: &str) -> Result<()> { let tool = match cmd { "paint.dodge" => "dodge tool", + "paint.burn" => "burn tool", + "paint.sponge" => "sponge tool", + "paint.blur" => "blur tool", "paint.sharpen" => "sharpen tool", + "paint.smudge" => "smudge tool", _ => return Ok(()), }; let why = match s.active().map(|st| st.doc.mode) { @@ -316,10 +400,11 @@ pub(super) fn dab_cmd(s: &mut Session, p: &Value, cmd: &str) -> Result { let fmt = surf.format(); let mut effect = tool.effect(fmt, stroke.brush.spacing); let mut sampler = all.then(|| AllLayers::new(pre, fmt)); - Ok(apply_dab_stroke(surf, &stroke, sel, lock, tool.neighborhood().halo(), |work, fp| match &mut sampler { + apply_dab_stroke(surf, &stroke, sel, lock, tool.neighborhood().halo(), |work, fp| match &mut sampler { Some(all) => all.dab(work, fp, |w, f| effect(w, f)), None => effect(work, fp), - })) + }) + .map_err(|e| bad(cmd, e.to_string())) })?; let mut r = json!({ "damage": damage_json(dmg) }); if from_live { @@ -716,6 +801,22 @@ mod dodge_refuses_indexed_tests; #[path = "sharpen_refuses_indexed_tests.rs"] mod sharpen_refuses_indexed_tests; +#[cfg(test)] +#[path = "burn_refuses_indexed_tests.rs"] +mod burn_refuses_indexed_tests; + +#[cfg(test)] +#[path = "sponge_refuses_indexed_tests.rs"] +mod sponge_refuses_indexed_tests; + +#[cfg(test)] +#[path = "blur_refuses_indexed_tests.rs"] +mod blur_refuses_indexed_tests; + +#[cfg(test)] +#[path = "smudge_refuses_indexed_tests.rs"] +mod smudge_refuses_indexed_tests; + #[cfg(test)] #[path = "smudge_mode_tests.rs"] mod smudge_mode_tests; diff --git a/crates/engine/src/cmd/retouch_cmds/heal.rs b/crates/engine/src/cmd/retouch_cmds/heal.rs index ca7a44328e..9388258ef7 100644 --- a/crates/engine/src/cmd/retouch_cmds/heal.rs +++ b/crates/engine/src/cmd/retouch_cmds/heal.rs @@ -1,4 +1,4 @@ -use super::clone::{blend_param, clamp_samples, clone_mapping, clone_result, clone_sample}; +use super::clone::{apply_clone_coverage, blend_param, clamp_samples, clone_mapping, clone_result, clone_sample}; use super::periodic; use super::sampling::{SampleLayers, composite_region, sample_all_layers, sample_layers}; use super::{ @@ -44,11 +44,19 @@ pub(super) fn heal_region(fmt: &PixelFormat, src: &Region, dst: &Region, mask: & out } +/// The reference's alert for the Healing Brush in an Indexed Color document (#12112). Bitmap, +/// Duotone and Multichannel weren't measured and heal as before. +const INDEXED_REFUSAL: &str = "Could not set the clone source because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; + pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result { const CMD: &str = "paint.healingBrush"; + if s.active().is_some_and(|st| st.doc.mode == photocraft_color::ColorMode::Indexed) { + return Err(EngineError::Other(INDEXED_REFUSAL.into())); + } let (stroke, id) = parse_brush(s, p, CMD)?; reject_huge_stroke(CMD, &stroke)?; let which = sample_layers(p, CMD)?; + let source = super::clone_sampling::resolve(s, p, CMD)?; let mode = blend_param(p, CMD)?; let aligned = flag(p, "aligned", true); let map = clone_mapping(s, p, &stroke, CMD)?; @@ -59,8 +67,8 @@ pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result { let wrap = flag(p, "wrap", false); let (bounds, cov) = coverage(CMD, &stroke)?; let (g, cov) = pad_coverage(bounds, &cov, 2); - let fmt = surf.format(); - let src = clone_sample(pre, id, surf, which, g, &map, wrap, CMD)?; + let fmt = source.sample_format(surf); + let src = clone_sample(pre, id, surf, which, &source, g, &map, wrap, CMD)?; // The destination the texture is fitted to: the layer itself, or what the user sees when // sampling several layers (so healing onto an empty layer matches the composite). let dst = if wrap { @@ -68,18 +76,29 @@ pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result { } else if which == SampleLayers::Current { Region::read(surf, g) } else { - composite_region(pre, id, which, g, fmt) + composite_region(pre, id, which, g, surf.format()) }; - let mask: Vec = cov.iter().map(|c| *c > 0.0).collect(); - let healed = heal_region(&fmt, &src, &dst, &mask); + let dst = if fmt.alpha && !surf.format().alpha { super::clone_sampling::opaque_alpha(dst, surf.format()) } else { dst }; + // The solver can reconstruct positive alpha from the destination boundary even where + // no source pixel exists. Keep source availability separate from the solved channels. + let alpha = super::alpha_index(&fmt); + let has_source = |pixel: &[f32]| alpha.is_none_or(|a| pixel.get(a).is_some_and(|value| *value > 0.0)); + let mask: Vec = cov.iter().zip(src.data.chunks_exact(fmt.channels())).map(|(c, pixel)| *c > 0.0 && has_source(pixel)).collect(); + let mut healed = heal_region(&fmt, &src, &dst, &mask); + for (pixel, sample) in healed.data.chunks_exact_mut(fmt.channels()).zip(src.data.chunks_exact(fmt.channels())) { + if !has_source(sample) { + pixel.fill(0.0); + } + } if wrap { - return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, |_, r| { + return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, fmt, |_, r| { let part = healed.crop(r); if part.rect == r { Ok(part) } else { Err(bad(CMD, "the healed patch does not cover the stroke")) } }); } - Ok(apply_coverage(surf, g, &cov, stroke.brush.opacity, sel, lock, &healed, mode)) + Ok(apply_clone_coverage(surf, g, &cov, stroke.brush.opacity, sel, lock, &healed, mode)) })?; + crate::presets::clone_source::remember_mapping(s, p, &map); Ok(clone_result(dmg, off, aligned, p, &stroke)) } @@ -291,3 +310,7 @@ pub(super) fn spot_healing(s: &mut Session, p: &Value) -> Result { let dmg = run_stroke(s, "Spot Healing Brush", id, p, |pre, surf, sel, lock| spot_heal_surface(surf, pre, &stroke, kind, all, sel, lock))?; Ok(json!({ "damage": damage_json(dmg) })) } + +#[cfg(test)] +#[path = "heal_indexed_tests.rs"] +mod heal_indexed_tests; diff --git a/crates/engine/src/cmd/retouch_cmds/heal_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/heal_indexed_tests.rs new file mode 100644 index 0000000000..48a3afb5e2 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/heal_indexed_tests.rs @@ -0,0 +1,65 @@ +//! #12112: the Healing Brush refuses an Indexed Color document with the reference application's +//! message, painting nothing and adding no history. RGB, Grayscale, CMYK and Lab at every depth +//! keep healing; Bitmap, Duotone and Multichannel (not measured) don't get the refusal. + +use photocraft_color::{Color, ColorMode, SampleType}; +use photocraft_doc::Size; + +use super::*; + +const MESSAGE: &str = "Could not set the clone source because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; + +/// A 64 × 64 `mode` document of `depth`, mid grey with its left half black: the edge is the +/// texture the stroke heals onto the flat grey. +fn edged(mode: ColorMode, depth: SampleType) -> Session { + let mut s = Session::new(); + s.add_document(Document::with_background("t", Size::new(64, 64), mode, depth, Color::rgb(0.5, 0.5, 0.5)), None); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 64})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn stroke() -> Value { + json!({"points": [[48, 32]], "source": [32, 32], "size": 20, "hardness": 100}) +} + +/// The Background's native samples and the History length. +fn state(s: &Session) -> (Vec, usize) { + let st = s.active().unwrap(); + let surf = st.doc.layers[0].surface().unwrap(); + ((0..64).flat_map(|y| (0..64).flat_map(move |x| surf.pixel(x, y))).collect(), st.history.past_len()) +} + +#[test] +fn an_indexed_document_refuses_with_the_reference_words() { + let mut s = edged(ColorMode::Indexed, SampleType::U8); + let before = state(&s); + let err = s.execute("paint.healingBrush", stroke()).unwrap_err().to_string(); + assert_eq!(err, MESSAGE); + assert!(state(&s) == before, "nothing painted, no history state"); +} + +#[test] +fn other_modes_keep_healing_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] { + for depth in depths { + let mut s = edged(mode, depth); + let (pixels, steps) = state(&s); + s.execute("paint.healingBrush", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + let after = state(&s); + assert!(after.0 != pixels, "{mode:?}/{depth:?}: healed"); + assert_eq!(after.1, steps + 1, "{mode:?}/{depth:?}: one history step"); + } + } +} + +#[test] +fn unmeasured_modes_never_get_the_indexed_refusal() { + for mode in [ColorMode::Bitmap, ColorMode::Duotone, ColorMode::Multichannel] { + let mut s = edged(mode, SampleType::U8); + let err = s.execute("paint.healingBrush", stroke()).err().map(|e| e.to_string()); + assert_ne!(err.as_deref(), Some(MESSAGE), "{mode:?}"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs index 8c05c99085..bea06153f4 100644 --- a/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs +++ b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs @@ -9,7 +9,7 @@ //! Impressionist was not measured: those strokes lay their dabs over the pixels in Normal, as //! they did before Behind existed. -use photocraft_color::{BlendMode, PixelFormat}; +use photocraft_color::{BlendMode, ColorMode, PixelFormat}; use photocraft_compose::pattern::{Placement, Tile, render}; use photocraft_doc::{LayerId, Pattern}; use photocraft_geom::Rect; @@ -19,11 +19,30 @@ use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use serde_json::{Value, json}; use super::{bad, blend_param, damage_json, flag, has_pixel_layer, parse_brush, reject_huge_stroke}; -use crate::{Result, Session}; +use crate::{EngineError, Result, Session}; const STREAM_PHASE_X: u64 = 101; const STREAM_PHASE_Y: u64 = 102; +/// The reference's alert for a Pattern Stamp stroke in an Indexed Color document (#12887). +pub const INDEXED_REFUSAL: &str = "Could not fill because the pattern and image have different color modes."; + +/// The reference refuses every pattern in an Indexed Color document before painting: RGB, +/// Grayscale, CMYK, Lab and Indexed ones from another image. It paints only a pattern with the +/// document's own colour table, which PhotoCraft can't tell apart, so that one is refused too. +/// Bitmap, Duotone and Multichannel documents weren't measured and paint as before. +fn mode_refusal(s: &Session) -> Result<()> { + if s.active().is_some_and(|st| st.doc.mode == ColorMode::Indexed) { Err(EngineError::Other(INDEXED_REFUSAL.into())) } else { Ok(()) } +} + +/// [`mode_refusal`] for a press with the stroke's `p`, so the canvas can alert before the stroke +/// starts: `None` when the pattern paints, or when `p` names no pattern (the stroke reports that). +pub fn press_refusal(s: &Session, p: &Value) -> Option { + mode_refusal(s).err()?; + crate::pattern_cmds::resolve_param(s, "paint.patternStamp", p).ok()?; + Some(INDEXED_REFUSAL.into()) +} + pub(super) fn enabled(s: &Session) -> std::result::Result<(), String> { has_pixel_layer(s)?; if crate::pattern_cmds::resolve_id(s, "").is_none() { Err("no pattern selected".into()) } else { Ok(()) } @@ -58,6 +77,7 @@ impl Setup { let aligned = flag(p, "aligned", true); let impressionist = flag(p, "impressionist", false); let pat = crate::pattern_cmds::resolve_param(s, CMD, p)?; + mode_refusal(s)?; if pat.is_empty() { return Err(bad(CMD, "the pattern is empty")); } @@ -163,7 +183,7 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result { if st.impressionist { // Halo is the dab footprint only: Impressionist jitters phase, it does not blur. let effect = st.impressionist_effect(surf.format()); - Ok(apply_dab_stroke(surf, &st.stroke, sel, lock, 0, effect)) + apply_dab_stroke(surf, &st.stroke, sel, lock, 0, effect).map_err(|e| bad(CMD, e.to_string())) } else { paint_aligned(surf, &st, sel, lock, CMD) } @@ -366,3 +386,7 @@ mod tests { assert!(reject_huge_stroke("t", &stroke(&[(0.0, 0.0), (9000.0, 9000.0)], 100.0)).is_err()); } } + +#[cfg(test)] +#[path = "pattern_stamp_indexed_tests.rs"] +mod pattern_stamp_indexed_tests; diff --git a/crates/engine/src/cmd/retouch_cmds/pattern_stamp_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/pattern_stamp_indexed_tests.rs new file mode 100644 index 0000000000..6fb7adc4c0 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/pattern_stamp_indexed_tests.rs @@ -0,0 +1,96 @@ +//! #12887: in an Indexed Color document the Pattern Stamp refuses every pattern (RGB, Grayscale, +//! CMYK, Lab, or one defined from an Indexed image) with the reference application's message, +//! painting nothing and adding no history; the live strokes are refused the same way. RGB, +//! Grayscale, CMYK and Lab documents at every depth keep painting with it. + +use super::super::LiveRetouch; +use super::*; + +/// A new `mode` document of `depth` bits, 64 × 64, white. +fn new_doc(s: &mut Session, mode: &str, depth: u64) { + s.execute("file.new", json!({"width": 64, "height": 64, "depth": depth, "mode": mode})).unwrap(); +} + +/// The reference's test pattern: 20 × 20 with red, green, blue and white quadrants, defined from a +/// `mode` document. Returns its id. +fn quadrants(s: &mut Session, mode: &str) -> String { + s.execute("file.new", json!({"width": 20, "height": 20, "depth": 8, "mode": mode})).unwrap(); + for (x, y, color) in [(0, 0, "#ff0000"), (10, 0, "#00ff00"), (0, 10, "#0000ff")] { + s.execute("select.rect", json!({"x": x, "y": y, "width": 10, "height": 10})).unwrap(); + s.execute("edit.fill", json!({"color": color})).unwrap(); + } + s.execute("select.deselect", json!({})).unwrap(); + let r = s.execute("edit.definePattern", json!({"name": format!("Quadrants {mode}")})).unwrap(); + r["pattern"].as_str().unwrap().to_string() +} + +fn to_indexed(s: &mut Session) { + s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none"})).unwrap(); +} + +fn stroke(pattern: &str, impressionist: bool) -> Value { + json!({"points": [[12, 32], [52, 32]], "size": 30, "hardness": 100, "pattern": pattern, "impressionist": impressionist}) +} + +/// The active layer's pixels and the History length. +fn state(s: &Session) -> (Vec<[f32; 4]>, usize) { + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + ((0..64).flat_map(|y| (0..64).map(move |x| surf.rgba(x, y))).collect(), st.history.past_len()) +} + +#[test] +fn an_rgb_pattern_is_refused_in_an_indexed_document_with_the_reference_words() { + let mut s = Session::new(); + let pat = quadrants(&mut s, "rgb"); + new_doc(&mut s, "rgb", 8); + to_indexed(&mut s); + let before = state(&s); + for impressionist in [false, true] { + let err = s.execute("paint.patternStamp", stroke(&pat, impressionist)).unwrap_err().to_string(); + assert_eq!(err, INDEXED_REFUSAL, "impressionist {impressionist}"); + assert_eq!(state(&s), before, "impressionist {impressionist}: nothing painted, no history"); + } + // The press check the canvas alerts with, and the live strokes, which preview nothing. + assert_eq!(press_refusal(&s, &stroke(&pat, false)).as_deref(), Some(INDEXED_REFUSAL)); + let live = LiveRetouch::begin(&s, "paint.patternStamp", &stroke(&pat, false)).err().map(|e| e.to_string()); + assert_eq!(live.as_deref(), Some(INDEXED_REFUSAL), "live"); + let dabs = live_impressionist(&s, &stroke(&pat, true)).err().map(|e| e.to_string()); + assert_eq!(dabs.as_deref(), Some(INDEXED_REFUSAL), "live Impressionist"); +} + +#[test] +fn other_documents_keep_painting_with_the_rgb_pattern() { + let mut s = Session::new(); + let pat = quadrants(&mut s, "rgb"); + for mode in ["rgb", "grayscale", "cmyk", "lab"] { + for depth in [8, 16, 32] { + new_doc(&mut s, mode, depth); + let (pixels, steps) = state(&s); + assert_eq!(press_refusal(&s, &stroke(&pat, false)), None, "{mode}/{depth}"); + s.execute("paint.patternStamp", stroke(&pat, false)).unwrap_or_else(|e| panic!("{mode}/{depth}: {e}")); + let after = state(&s); + assert_ne!(after.0, pixels, "{mode}/{depth}: painted"); + assert_eq!(after.1, steps + 1, "{mode}/{depth}: one history step"); + } + } +} + +#[test] +fn grayscale_cmyk_lab_and_indexed_patterns_are_refused_in_an_indexed_document_too() { + let mut s = Session::new(); + let mut patterns = ["grayscale", "cmyk", "lab"].map(|mode| quadrants(&mut s, mode)).to_vec(); + // A pattern defined from an Indexed Color image. + s.execute("file.new", json!({"width": 20, "height": 20, "depth": 8, "mode": "rgb"})).unwrap(); + to_indexed(&mut s); + patterns.push(s.execute("edit.definePattern", json!({"name": "Indexed"})).unwrap()["pattern"].as_str().unwrap().to_string()); + new_doc(&mut s, "rgb", 8); + to_indexed(&mut s); + let before = state(&s); + for pat in patterns { + let err = s.execute("paint.patternStamp", stroke(&pat, false)).unwrap_err().to_string(); + assert_eq!(err, INDEXED_REFUSAL, "{pat}"); + assert_eq!(press_refusal(&s, &stroke(&pat, false)).as_deref(), Some(INDEXED_REFUSAL), "{pat}"); + assert_eq!(state(&s), before, "{pat}: nothing painted, no history"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/periodic.rs b/crates/engine/src/cmd/retouch_cmds/periodic.rs index 63c3b40f07..dbd7917ecc 100644 --- a/crates/engine/src/cmd/retouch_cmds/periodic.rs +++ b/crates/engine/src/cmd/retouch_cmds/periodic.rs @@ -1,6 +1,7 @@ //! Bounded reads from the repeating document tile used by Pattern Preview. -use super::{BlendMode, BrushSettings, Document, LayerId, Rect, Region, Result, SampleLayers, Stroke, StrokePoint, Surface, alpha_index, apply_coverage, bad}; +use super::clone::apply_clone_coverage; +use super::{BlendMode, BrushSettings, Document, LayerId, PixelFormat, Rect, Region, Result, SampleLayers, Stroke, StrokePoint, Surface, alpha_index, bad}; /// At most four disjoint rectangles in the document tile. Projecting the dirty area separately /// from the stroke bounds avoids scanning the whole document when a small dab crosses a seam. @@ -35,6 +36,7 @@ pub(super) fn stroke( lock: bool, mode: BlendMode, cmd: &str, + paint_format: PixelFormat, mut paint: impl FnMut(&Surface, Rect) -> Result, ) -> Result { let mut renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0); @@ -42,7 +44,7 @@ pub(super) fn stroke( renderer.finish(); let before = target.clone(); let bounds = renderer.bounds(); - Composite { target, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection, lock, mode, cmd }.draw( + Composite { target, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection, lock, mode, cmd, paint_format }.draw( bounds, &stroke.brush, &stroke.points, @@ -63,9 +65,12 @@ pub(super) struct Composite<'a> { pub mode: BlendMode, /// The command an over-budget stroke's error names. pub cmd: &'a str, + /// The sampled native channels, including temporary coverage for opaque pixel layers. + pub paint_format: PixelFormat, } impl Composite<'_> { + /// Fold dabs into bounded destination patches before applying selection, opacity and blending. pub fn draw(&mut self, dirty: Rect, brush: &BrushSettings, points: &[StrokePoint], mut paint: impl FnMut(Rect) -> Result) -> Result { let ctx = photocraft_paint::BrushContext::new(brush); let mut generator = photocraft_paint::dynamics::DabGenerator::new(brush, 1.0); @@ -96,9 +101,9 @@ impl Composite<'_> { while x < rect.x1 { let x1 = x.saturating_add(64).min(rect.x1); let dst = Rect::new(x, y, x1, y1); - let mut stroke = PatchStroke::new(dst, self.target.channels()); + let mut stroke = PatchStroke::new(dst, self.paint_format.channels()); let mut dual_stroke = PatchStroke::new(dst, 1); - let alpha = alpha_index(&self.target.format()); + let alpha = alpha_index(&self.paint_format); for (dab, bounds) in &primary { if !project(*bounds, self.tile).iter().any(|r| !r.intersect(&dst).is_empty()) { continue; @@ -127,7 +132,7 @@ impl Composite<'_> { } } self.target.write_region(dst, &self.before.read_region(dst)); - apply_coverage(self.target, dst, &stroke.coverage, self.opacity, self.selection, self.lock, &stroke.paint, self.mode); + apply_clone_coverage(self.target, dst, &stroke.coverage, self.opacity, self.selection, self.lock, &stroke.paint, self.mode); damage = damage.union(&dst); x = x1; } @@ -138,6 +143,7 @@ impl Composite<'_> { } #[allow(clippy::too_many_arguments)] + /// Gather one dab's periodic copies using its strongest coverage at each destination pixel. fn fold_dab( &self, ctx: &photocraft_paint::BrushContext, @@ -148,7 +154,7 @@ impl Composite<'_> { paint: &mut impl FnMut(Rect) -> Result, work: &mut u64, ) -> Result { - let mut result = PatchStroke::new(dst, if dual { 1 } else { self.target.channels() }); + let mut result = PatchStroke::new(dst, if dual { 1 } else { self.paint_format.channels() }); let (w, h) = (i64::from(self.tile.width()), i64::from(self.tile.height())); let nx0 = (i64::from(bounds.x0) - i64::from(dst.x1)).div_euclid(w) + 1; let nx1 = (i64::from(bounds.x1) - 1 - i64::from(dst.x0)).div_euclid(w); @@ -217,6 +223,7 @@ impl PatchStroke { Self { coverage: vec![0.0; len], depth: vec![0.0; len], paint: Region::new(rect, channels) } } + /// Accumulate flow-weighted, premultiplied native colours and independent source alpha. fn accumulate(&mut self, dab: &photocraft_paint::Dab, footprint: &PatchStroke, alpha: Option) { let rect = self.paint.rect; for y in rect.y0..rect.y1 { @@ -245,6 +252,7 @@ impl PatchStroke { } } + /// Recover straight colours while keeping stroke coverage separate from source alpha. fn normalize(&mut self, alpha: Option) { let rect = self.paint.rect; for y in rect.y0..rect.y1 { @@ -263,14 +271,18 @@ impl PatchStroke { } pub(super) fn sample(pre: &Document, id: Option, surf: &Surface, which: SampleLayers, rect: Rect, cmd: &str) -> Result { - let tile = pre.bounds(); + sample_with(pre.bounds(), surf.channels(), rect, cmd, |r| Ok(super::sample(pre, id, surf, which, r))) +} + +/// Repeat `read` using the source document's bounds, even when the target is a different size. +pub(super) fn sample_with(tile: Rect, n: usize, rect: Rect, cmd: &str, mut read: impl FnMut(Rect) -> Result) -> Result { if tile.is_empty() { return Err(bad(cmd, "cannot repeat an empty document")); } if rect.is_empty() { - return Ok(Region::new(Rect::EMPTY, surf.channels())); + return Ok(Region::new(Rect::EMPTY, n)); } - let (w, h, n) = (rect.width() as usize, rect.height() as usize, surf.channels()); + let (w, h) = (rect.width() as usize, rect.height() as usize); let len = w .checked_mul(h) .and_then(|v| v.checked_mul(n)) @@ -287,7 +299,7 @@ pub(super) fn sample(pre: &Document, id: Option, surf: &Surface, which: while dx < w { let sx = (i64::from(rect.x0) + dx as i64 - i64::from(tile.x0)).rem_euclid(i64::from(tile.width())) as i32 + tile.x0; let cols = (w - dx).min((tile.x1 - sx) as usize); - let part = super::sample(pre, id, surf, which, Rect::new(sx, sy, sx + cols as i32, sy + rows as i32)); + let part = read(Rect::new(sx, sy, sx + cols as i32, sy + rows as i32))?; for (dst, src) in out.data.chunks_exact_mut(w * n).skip(dy).take(rows).zip(part.data.chunks_exact(cols * n)) { if let Some(dst) = dst.get_mut(dx * n..(dx + cols) * n) { dst.copy_from_slice(src); diff --git a/crates/engine/src/cmd/retouch_cmds/smudge_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/smudge_refuses_indexed_tests.rs new file mode 100644 index 0000000000..4a621b27c3 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/smudge_refuses_indexed_tests.rs @@ -0,0 +1,57 @@ +//! #12967: the Smudge tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the smudge tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the smudge tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// The grey document with its left half black: an edge for the stroke to work on. +fn edged(mode: ColorMode, depth: SampleType) -> Session { + let mut s = session(mode, depth); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 64})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "strength": 100}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = edged(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.smudge", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.smudge", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = edged(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.smudge", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + let before = pixels(&s); + s.execute("paint.smudge", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_ne!(pixels(&s), before, "{mode:?}/{depth:?}: the stroke changed pixels"); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/sponge_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/sponge_refuses_indexed_tests.rs new file mode 100644 index 0000000000..61dd03901c --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/sponge_refuses_indexed_tests.rs @@ -0,0 +1,49 @@ +//! #13033: the Sponge tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the sponge tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the sponge tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "mode": "desaturate"}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = session(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.sponge", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.sponge", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +/// +/// The grey document has no saturation to take away, so this checks that the stroke runs and +/// records its History step, not that pixels change. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = session(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.sponge", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + s.execute("paint.sponge", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index c96b153fb7..c6918ef1db 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -67,6 +67,23 @@ fn periodic_clone_projection_is_disjoint_and_matches_pixel_modulo() { } } +#[test] +fn a_hugely_scaled_clone_source_is_refused_before_the_dense_read() { + use super::clone::clone_sample; + use super::sampling::sample_layers; + use crate::presets::clone_source::Mapping; + let s = session(32, 24, 8, "rgb"); + let d = s.active().unwrap(); + let id = d.active_layer.unwrap(); + let surf = d.doc.layer(id).unwrap().surface().unwrap(); + let which = sample_layers(&json!({"sampleLayer": "current"}), "paint.cloneStamp").unwrap(); + let source = super::clone_sampling::resolve(&s, &json!({"sampleLayer": "current"}), "paint.cloneStamp").unwrap(); + // 1000x: a 100x100 destination asks for a ~100000x100000 source window. + let map = Mapping { source: (0.0, 0.0), anchor: (0.0, 0.0), m: [1000.0, 0.0, 0.0, 1000.0], document: None }; + let r = clone_sample(&d.doc, Some(id), surf, which, &source, Rect::new(0, 0, 100, 100), &map, false, "paint.cloneStamp"); + assert!(r.is_err()); +} + #[test] fn periodic_clone_preview_interpolates_across_transformed_source_seam() { use crate::presets::clone_source::Mapping; @@ -75,7 +92,7 @@ fn periodic_clone_preview_interpolates_across_transformed_source_seam() { paint_layer(&mut s, |x, _| if x == 0 { [1.0, 0.0, 0.0, 1.0] } else { [0.0, 0.0, 1.0, 1.0] }); let before = s.active().unwrap().doc.clone(); // A rotated mapping samples halfway between the last and first columns. - let map = Mapping { source: (31.5, 10.0), anchor: (0.0, 0.0), m: [0.0, 1.0, -1.0, 0.0] }; + let map = Mapping { source: (31.5, 10.0), anchor: (0.0, 0.0), m: [0.0, 1.0, -1.0, 0.0], document: None }; let r = Rect::new(0, 0, 1, 1); let wrapped = clone_preview_periodic(&s, r, &map, "current", true).unwrap(); assert_eq!(wrapped.px, [[0.5, 0.0, 0.5, 1.0]]); @@ -208,7 +225,7 @@ fn clone_preview_matches_source_without_mutating_session() { s.execute("cloneSource.set", json!({"source": [8,8]})).unwrap(); let revision = s.active().unwrap().revision; let slots = s.presets.clone.clone(); - let map = Mapping { source: (8.0, 8.0), anchor: (20.0, 20.0), m: [1.0, 0.0, 0.0, 1.0] }; + let map = Mapping { source: (8.0, 8.0), anchor: (20.0, 20.0), m: [1.0, 0.0, 0.0, 1.0], document: None }; let buf = clone_preview(&s, Rect::new(20, 20, 21, 21), &map, "current").unwrap(); let expected = rgba(&s, 8, 8); for (actual, expected) in buf.px[0].iter().zip(expected) { @@ -470,19 +487,195 @@ fn blur_reduces_local_variance_and_sharpen_increases_it() { s.execute("paint.blur", json!({"points": [[5, 15], [25, 15]], "size": 20, "hardness": 100, "strength": 100})).unwrap(); assert!(var(&s, 10) < v0 * 0.5, "depth {depth}: {v0} → {}", var(&s, 10)); assert!((var(&s, 45) - v0).abs() < 1e-3, "outside untouched"); - // Sharpen a low-contrast checkerboard: contrast grows; Protect Detail caps it at the local range. + // Sharpen a low-contrast checkerboard: contrast grows, with Protect Detail too (#12938). let mut s = session(60, 30, depth, "rgb"); paint_layer(&mut s, |x, y| if (x + y) % 2 == 0 { [0.45, 0.45, 0.45, 1.0] } else { [0.55, 0.55, 0.55, 1.0] }); let v0 = var(&s, 10); s.execute("paint.sharpen", json!({"points": [[5, 15], [25, 15]], "size": 20, "hardness": 100, "strength": 100, "protectDetail": false})).unwrap(); assert!(var(&s, 10) > v0 * 1.5, "depth {depth}: {v0} → {}", var(&s, 10)); - // Pinned at 25%: Protect Detail clamps per dab, so denser dabs creep past the range. + // Protect Detail moves a pixel by less than 6 levels per dab; at 25 % spacing four dabs + // pass over each point. s.execute("paint.sharpen", json!({"points": [[35, 15], [55, 15]], "size": 20, "hardness": 100, "strength": 100, "spacing": 25})).unwrap(); let hi = (10..20).flat_map(|y| (40..50).map(move |x| (x, y))).map(|(x, y)| rgba(&s, x, y)[0]).fold(0.0, f32::max); - assert!(hi <= 0.55 + tol(depth), "protect detail: {hi}"); + assert!(hi > 0.55 + tol(depth) && hi <= 0.55 + 4.0 * 6.0 / 255.0 + tol(depth), "protect detail: {hi}"); } } +#[test] +fn protect_detail_click_on_a_step_follows_strength() { + // #12938: one 40 px hard click on a grey 96 | 160 step, Protect Detail on (the default). The + // reference gives x 399/400 = 90/164 at 100 % and 93/162 at 50 %; Strength applies once per dab. + let level = |s: &Session, x| (rgba(s, x, 20)[0] * 255.0).round() as i32; + for (strength, dark, light, tol) in [(100, 90, 164, 3), (50, 93, 162, 2), (1, 96, 160, 0)] { + let mut s = session(80, 40, 8, "rgb"); + paint_layer(&mut s, |x, _| if x < 40 { [96.0 / 255.0, 96.0 / 255.0, 96.0 / 255.0, 1.0] } else { [160.0 / 255.0, 160.0 / 255.0, 160.0 / 255.0, 1.0] }); + s.execute("paint.sharpen", json!({"points": [[40, 20]], "size": 40, "hardness": 100, "strength": strength})).unwrap(); + let (d, l) = (level(&s, 39), level(&s, 40)); + assert!((d - dark).abs() <= tol && (l - light).abs() <= tol, "{strength} %: x 399/400 = {d}/{l}, want {dark}/{light} ± {tol}"); + } +} + +#[test] +fn protect_detail_drags_at_the_default_spacing_widen_the_halo_without_banding() { + // #12938: three 40 px hard drags down a grey 96 | 160 step with the brush's own spacing. The + // reference gives a smooth halo that deepens and widens with every pass, with no 0/255 + // pattern. Its drags put 4 dabs on each point (25 % spacing); at the default 10 % the drag + // must add up to the same, not to 10 full dabs. + let level = |s: &Session, x| (rgba(s, x, 80)[0] * 255.0).round() as i32; + let drag = |s: &mut Session, strength, spacing: Option| { + let mut p = json!({"points": [[40, 10], [40, 150]], "size": 40, "hardness": 100, "strength": strength}); + if let Some(sp) = spacing { + p["spacing"] = json!(sp); + } + s.execute("paint.sharpen", p).unwrap(); + }; + let step = |x: i32, _| if x < 40 { [96.0 / 255.0, 96.0 / 255.0, 96.0 / 255.0, 1.0] } else { [160.0 / 255.0, 160.0 / 255.0, 160.0 / 255.0, 1.0] }; + for strength in [50, 100] { + let (mut s, mut at25) = (session(80, 160, 8, "rgb"), session(80, 160, 8, "rgb")); + assert!((s.tools.brush.spacing - 0.1).abs() < 1e-6, "the default retouch spacing"); + paint_layer(&mut s, step); + paint_layer(&mut at25, step); + let (mut depth, mut width) = (0, 0); + for pass in 1..=3 { + drag(&mut s, strength, None); + drag(&mut at25, strength, Some(25)); + let row: Vec = (0..80).map(|x| level(&s, x)).collect(); + assert!(row.iter().all(|v| (1..=254).contains(v)), "{strength} % pass {pass}: black and white bands {row:?}"); + for x in [39, 40] { + let (got, want) = (level(&s, x), level(&at25, x)); + assert!((got - want).abs() <= 4, "{strength} % pass {pass}: x {x} = {got} at the default spacing, {want} at 25 %"); + } + let (d, w) = (96 - row[39], (20..40).filter(|&x| row[x] < 94).count()); + assert!(d > depth && w >= width, "{strength} % pass {pass}: halo depth {d} (was {depth}), width {w} (was {width}): {row:?}"); + (depth, width) = (d, w); + } + assert!(width >= 4, "{strength} %: the halo widens to {width} px"); + } +} + +#[test] +fn protect_detail_sharpens_with_every_stamp_of_a_count_but_not_with_airbrush_repeats() { + // Scattering's Count with Scatter 0 lays several stamps on the same centre; with size jitter + // each has its own footprint, and a larger one must sharpen the ring only it covers (the + // stamps after the first used to get no share at all). An airbrush click repeats the same + // stamp, which adds nothing, so the measured click is kept. + let click = |set: &dyn Fn(&mut photocraft_paint::BrushSettings)| { + let mut s = session(80, 40, 8, "rgb"); + paint_layer(&mut s, |x, _| if x < 40 { [96.0 / 255.0, 96.0 / 255.0, 96.0 / 255.0, 1.0] } else { [160.0 / 255.0, 160.0 / 255.0, 160.0 / 255.0, 1.0] }); + set(&mut s.tools.brush); + s.execute("paint.sharpen", json!({"points": [[40, 20]], "size": 40, "hardness": 100, "strength": 100})).unwrap(); + // The whole image, row by row: a larger stamp's ring meets the step above and below the click. + (0..40).flat_map(|y| (0..80).map(move |x| (x, y))).map(|(x, y)| (rgba(&s, x, y)[0] * 255.0).round() as i32).collect::>() + }; + let jitter = |b: &mut photocraft_paint::BrushSettings| { + b.shape_dynamics.enabled = true; + b.shape_dynamics.size.jitter = 1.0; + b.shape_dynamics.size.minimum = 0.0; + }; + let count = |b: &mut photocraft_paint::BrushSettings| { + jitter(b); + b.scattering.enabled = true; + b.scattering.count = 4; + }; + // A seed whose click lays a later stamp clearly larger than the first, as the stroke's own + // dab builder sees it (size jitter only shrinks, so a later stamp may also fall inside). + let seed = (0..256) + .find(|&seed| { + let mut b = session(8, 8, 8, "rgb").tools.brush.clone(); + b.size = 40.0; + count(&mut b); + b.seed = seed; + let mut dabs = Vec::new(); + let step = photocraft_paint::dynamics::StepInput { + point: photocraft_paint::StrokePoint::new(40.0, 20.0, 1.0), + direction: 0.0, + initial_direction: 0.0, + step: 0, + }; + photocraft_paint::dynamics::DabBuilder::new(&b).build(&step, &mut dabs); + dabs.len() == 4 && dabs[1..].iter().any(|d| d.radius > dabs[0].radius + 3.0) + }) + .expect("a seed with a larger later stamp"); + let one = click(&|b| { + jitter(b); + b.seed = seed; + }); + let four = click(&|b| { + count(b); + b.seed = seed; + }); + let moved = |img: &[i32]| img.iter().enumerate().map(|(i, v)| (v - if i % 80 < 40 { 96 } else { 160 }).abs()).sum::(); + assert!(moved(&four) > moved(&one), "seed {seed}: Count 4 sharpens the ring its larger stamp adds ({} vs {})", moved(&four), moved(&one)); + assert!(four.iter().all(|v| (1..=254).contains(v)), "no black and white bands"); + let plain = click(&|_| {}); + let airbrush = click(&|b| b.build_up = true); + assert_eq!(airbrush, plain, "an airbrush click repeats its stamp, which adds nothing"); + // With size jitter the airbrush click's two dabs differ in size; the second still doesn't + // sharpen what the first already did. + let airbrush_jitter = click(&|b| { + jitter(b); + b.seed = seed; + b.build_up = true; + }); + let centre = 20 * 80 + 39..=20 * 80 + 40; + assert_eq!(airbrush_jitter[centre.clone()], one[centre], "a jittered airbrush repeat doesn't sharpen the centre again"); +} + +#[test] +fn protect_detail_dabs_on_one_centre_apply_at_most_one_dab_at_each_pixel() { + // Airbrush build-up held still with shape jitter lays dabs of changing size on one centre. + // Together they apply each pixel's largest coverage once, so a held stroke stays bounded, + // while a larger stamp still reaches the ring the smaller ones missed. + let dab = |x: f64, radius: f32| photocraft_paint::Dab { + center: photocraft_geom::Point { x, y: 50.0 }, + radius, + alpha: 1.0, + angle: 0.0, + roundness: 1.0, + flip_x: false, + flip_y: false, + opacity: 1.0, + color: [0.0; 4], + depth: 0.0, + index: 0, + proj_angle: 0.0, + proj_scale: 1.0, + wet: 1.0, + mix: 1.0, + }; + let mut shares = super::dab::ProtectDetailShares::default(); + let (mut applied, mut largest) = (std::collections::HashMap::new(), std::collections::HashMap::new()); + for (i, radius) in [10.0, 20.0, 15.0, 20.0, 5.0].into_iter().enumerate() { + let fp = photocraft_paint::retouch::footprint(&dab(50.0, radius), i, 1.0); + let (share, fresh) = shares.next(&fp); + assert_eq!(share, 1.0, "dab {i}: the click's share"); + let w = fp.rect.width() as usize; + let at = |v: &[f32], x: i32, y: i32| v[(y - fp.rect.y0) as usize * w + (x - fp.rect.x0) as usize]; + if i == 1 { + assert!(at(&fresh, 65, 50) > 0.9, "the larger stamp sharpens the ring the first missed"); + assert_eq!(at(&fresh, 50, 50), 0.0, "but not the centre again"); + } + if i >= 2 { + assert!(fresh.iter().all(|&f| f == 0.0), "dab {i} (radius {radius}) adds nothing the run hasn't applied"); + } + for y in fp.rect.y0..fp.rect.y1 { + for x in fp.rect.x0..fp.rect.x1 { + *applied.entry((x, y)).or_insert(0.0) += at(&fresh, x, y); + let l = largest.entry((x, y)).or_insert(0.0f32); + *l = l.max(at(&fp.cov, x, y)); + } + } + } + for (p, a) in &applied { + assert!((a - largest[p]).abs() < 1e-6 && *a <= 1.0, "pixel {p:?}: applied {a}, largest coverage {}", largest[p]); + } + // A dab on a new centre starts a new run: its full coverage at the share for 5 px moved. + let fp = photocraft_paint::retouch::footprint(&dab(55.0, 20.0), 5, 1.0); + let (share, fresh) = shares.next(&fp); + assert!((share - 0.5).abs() < 1e-6, "5 px over a quarter of 40 px: {share}"); + assert_eq!(fresh, fp.cov); +} + #[test] fn smudge_moves_colour_along_the_stroke() { for depth in DEPTHS { @@ -1605,9 +1798,10 @@ fn content_aware_move_structure_and_color_shape_the_result() { }; let (kept, some, fitted) = (mean(0), mean(3), mean(10)); assert!((kept - 0.8).abs() < 1e-3, "color 0 keeps the colour: {kept}"); - // Photoshop shifts by up to about 0.04 per step of Color. - assert!((some - 0.68).abs() < 0.03, "color 3 adapts part of the way: {some}"); - assert!((fitted - 0.4).abs() < 0.03, "color 10 adapts most of the way: {fitted}"); + // A brightness-only patch stays through Color 5 and matches the new surroundings at Color 10 + // (0.8 onto 0.2). https://github.com/storytold/photocraft/issues/12197#issuecomment-6716231485 + assert!((some - 0.8).abs() < 0.03, "color 3 leaves the middle: {some}"); + assert!((fitted - 0.2).abs() < 0.03, "color 10 matches the new surroundings: {fitted}"); } #[test] @@ -2774,6 +2968,257 @@ fn periodic_clone_interior_matches_ordinary_brush_masks_and_transparency() { } } +// --------------------------------------------------------------------------------------------- +// Clone source in another document +// --------------------------------------------------------------------------------------------- + +/// Two open documents: 0 holds `source`, 1 (active) holds `dest`; the clone source is set at +/// `at` in document 0. +fn two_documents(depth: u64, source: impl Fn(i32, i32) -> [f32; 4], dest: impl Fn(i32, i32) -> [f32; 4], at: [i32; 2]) -> Session { + let mut s = session(48, 40, depth, "rgb"); + paint_layer(&mut s, source); + s.execute("cloneSource.set", json!({"source": at})).unwrap(); + s.execute("file.new", json!({"width": 64, "height": 48, "depth": depth, "mode": "rgb"})).unwrap(); + paint_layer(&mut s, dest); + s +} + +/// Straight RGBA of document `i`'s active layer at a pixel. +fn doc_rgba(s: &Session, i: usize, x: i32, y: i32) -> [f32; 4] { + let d = &s.documents()[i]; + d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y) +} + +fn ramp(x: i32, y: i32) -> [f32; 4] { + [x as f32 / 48.0, y as f32 / 40.0, ((x * 7 + y * 3) % 11) as f32 / 11.0, 1.0] +} + +#[test] +fn clone_stamp_paints_from_the_document_the_source_was_set_in() { + for depth in DEPTHS { + for wrap in [false, true] { + let mut s = two_documents(depth, ramp, |_, _| [0.0, 0.0, 1.0, 1.0], [10, 12]); + let source_before = s.documents()[0].doc.clone(); + assert_eq!(s.active_index(), Some(1)); + let r = s.execute("paint.cloneStamp", json!({"points": [[30, 20], [40, 20]], "size": 8, "hardness": 100, "wrap": wrap})).unwrap(); + assert_eq!(r["offset"], json!([-20, -8])); + for x in [30, 35, 40] { + let (got, want) = (doc_rgba(&s, 1, x, 20), doc_rgba(&s, 0, x - 20, 12)); + for c in 0..4 { + assert!((got[c] - want[c]).abs() <= tol(depth), "depth {depth} wrap {wrap} x {x}: {got:?} vs {want:?}"); + } + } + assert_eq!(s.documents()[0].doc, source_before, "the source document is only read"); + // Aligned: the next stroke keeps the pairing, still in the other document. + s.execute("paint.cloneStamp", json!({"points": [[50, 30]], "size": 4, "hardness": 100, "wrap": wrap})).unwrap(); + let (got, want) = (doc_rgba(&s, 1, 50, 30), doc_rgba(&s, 0, 30, 22)); + assert!((got[0] - want[0]).abs() <= tol(depth) && (got[1] - want[1]).abs() <= tol(depth), "{got:?} vs {want:?}"); + assert!(s.undo() && s.undo()); + assert_eq!(doc_rgba(&s, 1, 35, 20), [0.0, 0.0, 1.0, 1.0], "undo restores the painted document"); + } + } +} + +#[test] +fn clone_source_in_the_painted_document_still_samples_it() { + let mut s = two_documents(8, ramp, |x, _| [0.0, x as f32 / 64.0, 1.0, 1.0], [10, 12]); + // ⌥-click in the document being painted: it is its own source again. + s.execute("cloneSource.set", json!({"source": [10, 12]})).unwrap(); + s.execute("paint.cloneStamp", json!({"points": [[30, 20]], "size": 4, "hardness": 100})).unwrap(); + let (got, want) = (doc_rgba(&s, 1, 30, 20), doc_rgba(&s, 1, 10, 12)); + assert!((got[1] - want[1]).abs() <= tol(8), "{got:?} vs {want:?}"); + assert_eq!(s.execute("cloneSource.list", json!({})).unwrap()["sources"][0]["document"], json!(1)); +} + +#[test] +fn clone_from_another_document_converts_depth_but_requires_matching_colour_modes() { + // A grayscale 8-bit source cloned into a 16-bit grayscale document. + let mut s = session(24, 24, 8, "gray"); + paint_layer(&mut s, |x, _| [x as f32 / 24.0, x as f32 / 24.0, x as f32 / 24.0, 1.0]); + s.execute("cloneSource.set", json!({"source": [12, 12]})).unwrap(); + s.execute("file.new", json!({"width": 40, "height": 40, "depth": 16, "mode": "gray"})).unwrap(); + paint_layer(&mut s, |_, _| [1.0, 0.0, 0.0, 1.0]); + s.execute("paint.cloneStamp", json!({"points": [[30, 30]], "size": 4, "hardness": 100})).unwrap(); + let got = doc_rgba(&s, 1, 30, 30); + let want = doc_rgba(&s, 0, 12, 12); + for c in 0..3 { + assert!((got[c] - want[0]).abs() <= tol(8), "gray copied into every channel: {got:?} vs {want:?}"); + } + // Aligned, (38, 2) maps to source (20, -16): past the smaller source document's edge there is + // nothing to clone, so the destination keeps its pixels. + let before = doc_rgba(&s, 1, 38, 2); + s.execute("paint.cloneStamp", json!({"points": [[38, 2]], "size": 2, "hardness": 100})).unwrap(); + assert_eq!(doc_rgba(&s, 1, 38, 2), before, "no source pixels: the destination is unchanged"); + + let mut s = two_documents(8, |_, _| [0.0, 1.0, 1.0, 1.0], |_, _| [1.0, 1.0, 1.0, 1.0], [5, 5]); + s.execute("file.new", json!({"width": 16, "height": 16, "depth": 8, "mode": "cmyk"})).unwrap(); + paint_layer(&mut s, |_, _| [1.0, 1.0, 1.0, 1.0]); + // Adobe documents matching color modes for Clone Stamp. Reject RGB into CMYK atomically. + let before = s.active().unwrap().doc.clone(); + let err = s.execute("paint.cloneStamp", json!({"points": [[8, 8]], "size": 4, "hardness": 100})).unwrap_err(); + assert!(err.to_string().contains("color modes"), "{err}"); + assert_eq!(s.active().unwrap().doc, before); +} + +#[test] +fn clone_from_another_document_samples_the_layer_it_was_set_on() { + // Document 0: red background, and an empty layer above it, active when the source is set. + let mut s = session(32, 32, 8, "rgb"); + paint_layer(&mut s, |_, _| [1.0, 0.0, 0.0, 1.0]); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("cloneSource.set", json!({"source": [10, 10]})).unwrap(); + s.execute("file.new", json!({"width": 32, "height": 32, "depth": 8, "mode": "rgb"})).unwrap(); + paint_layer(&mut s, |_, _| [0.0, 0.0, 1.0, 1.0]); + // Current Layer reads the empty layer: nothing to paint. Non-aligned: every stroke starts at + // the source point. + s.execute("paint.cloneStamp", json!({"points": [[20, 20]], "size": 4, "hardness": 100, "sampleLayer": "current", "aligned": false})).unwrap(); + assert_eq!(doc_rgba(&s, 1, 20, 20), [0.0, 0.0, 1.0, 1.0]); + // Current & Below and All Layers read the source document's composite down from that layer. + for (sample, at) in [("currentAndBelow", 10), ("all", 24)] { + s.execute("paint.cloneStamp", json!({"points": [[at, 6]], "size": 4, "hardness": 100, "sampleLayer": sample, "aligned": false})).unwrap(); + let px = doc_rgba(&s, 1, at, 6); + assert!(px[0] > 0.99 && px[2] < 0.01, "{sample}: {px:?}"); + } + // Removing the picked layer refuses the stroke until the user picks a new source. + s.set_active(0); + s.execute("layer.delete", json!({})).unwrap(); + s.set_active(1); + let params = json!({"points": [[6, 26]], "size": 4, "hardness": 100, "sampleLayer": "current", "aligned": false}); + let before = s.active().unwrap().doc.clone(); + let err = s.execute("paint.cloneStamp", params.clone()).unwrap_err(); + assert!(err.to_string().contains("no longer exists"), "{err}"); + assert_eq!(s.active().unwrap().doc, before); + s.execute("cloneSource.set", json!({"source": [10, 10], "document": 0})).unwrap(); + s.execute("paint.cloneStamp", params).unwrap(); + assert!(doc_rgba(&s, 1, 6, 26)[0] > 0.99); +} + +#[test] +fn healing_brush_heals_from_another_document() { + let mut s = two_documents(16, texture, |_, _| [0.4, 0.6, 0.5, 1.0], [20, 20]); + let before = s.active().unwrap().doc.clone(); + s.execute("paint.healingBrush", json!({"points": [[30, 24]], "size": 12, "hardness": 100})).unwrap(); + let after = s.active().unwrap().doc.clone(); + let id = s.active().unwrap().active_layer.unwrap(); + let r = Rect::new(26, 20, 34, 28); + let (a, b) = (before.layer(id).unwrap().surface().unwrap().read_region(r), after.layer(id).unwrap().surface().unwrap().read_region(r)); + assert_ne!(a, b, "the source document's texture is healed in"); +} + +#[test] +fn live_clone_from_another_document_matches_the_commit() { + for depth in DEPTHS { + let mut s = two_documents(depth, texture, |_, _| [0.1, 0.2, 0.3, 1.0], [12, 12]); + let params = json!({"points": [[30, 22], [38, 26]], "size": 10, "hardness": 60, "opacity": 80}); + let live = LiveRetouch::begin(&s, "paint.cloneStamp", ¶ms).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let bounds = s.active().unwrap().doc.bounds(); + let shown = live.doc.layer(id).unwrap().surface().unwrap().read_region(bounds); + s.execute("paint.cloneStamp", params).unwrap(); + let committed = s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().read_region(bounds); + assert_eq!(shown, committed, "depth {depth}"); + } +} + +#[test] +fn live_clone_rejects_a_source_document_changed_during_the_stroke() { + let mut s = two_documents(8, texture, |_, _| [0.1, 0.2, 0.3, 1.0], [12, 12]); + let params = json!({"points": [[30, 22], [38, 26]], "size": 10, "hardness": 60, "opacity": 80}); + let live = LiveRetouch::begin(&s, "paint.cloneStamp", ¶ms).unwrap(); + + assert!(s.set_active(0)); + s.execute("paint.pencil", json!({"points": [[12, 12]], "size": 4, "color": "#ff0000"})).unwrap(); + assert!(s.set_active(1)); + + let error = s.offer_live_retouch(live).unwrap_err(); + assert!(error.to_string().contains("source document changed"), "{error}"); + let result = s.execute("paint.cloneStamp", params).unwrap(); + assert!(result.get("fromLive").is_none(), "the stale live pixels must not be committed"); +} + +#[test] +fn clone_preview_reads_another_document() { + use crate::presets::clone_source::{Mapping, SourceDoc}; + let mut s = two_documents(8, ramp, |_, _| [0.0, 0.0, 1.0, 1.0], [10, 12]); + let source = SourceDoc { id: s.documents()[0].doc.id, layer: s.documents()[0].active_layer }; + let map = Mapping { source: (10.0, 12.0), anchor: (30.0, 30.0), m: [1.0, 0.0, 0.0, 1.0], document: Some(source) }; + // The public preview API's explicit mapping remains independent of the selected slot. + s.execute("cloneSource.select", json!({"index": 1})).unwrap(); + let slots = s.presets.clone.clone(); + let buf = clone_preview(&s, Rect::new(30, 30, 31, 31), &map, "current").unwrap(); + assert_eq!(s.presets.clone, slots, "preview never changes the selected slot"); + let want = doc_rgba(&s, 0, 10, 12); + for (a, b) in buf.px[0].iter().zip(want) { + assert!((a - b).abs() < 0.01, "{:?} vs {want:?}", buf.px[0]); + } +} + +#[test] +fn clone_source_document_closed_or_invalid_is_an_error() { + let mut s = two_documents(8, ramp, |_, _| [0.0, 0.0, 1.0, 1.0], [10, 12]); + s.execute("file.close", json!({"document": 0})).unwrap(); + let before = s.active().unwrap().doc.clone(); + for cmd in ["paint.cloneStamp", "paint.healingBrush"] { + let e = s.execute(cmd, json!({"points": [[20, 20]], "size": 4})).unwrap_err(); + assert!(e.to_string().contains("closed"), "{cmd}: {e}"); + assert!(LiveRetouch::begin(&s, cmd, &json!({"points": [[20, 20]], "size": 4})).is_err()); + } + assert_eq!(s.active().unwrap().doc, before, "nothing painted"); + assert_eq!(s.presets.clone.active().anchor, None, "a refused stroke pairs nothing"); + assert_eq!(s.execute("cloneSource.list", json!({})).unwrap()["sources"][0]["document"], Value::Null); + // Explicit `source`/`offset` params sample the painted document, whatever the slot says. + s.execute("paint.cloneStamp", json!({"points": [[20, 20]], "offset": [4, 0], "size": 4})).unwrap(); + // Setting a source in the painted document recovers. + s.execute("cloneSource.set", json!({"source": [5, 5]})).unwrap(); + s.execute("paint.cloneStamp", json!({"points": [[20, 20]], "size": 4})).unwrap(); +} + +#[test] +fn a_copy_opened_after_the_clone_source_document_closed_is_not_the_source() { + // A native copy keeps its document's ID. Opening one after the source document was closed + // must not make the slot read the copy. + let mut s = two_documents(8, ramp, |_, _| [0.0, 0.0, 1.0, 1.0], [10, 12]); + let source = s.documents()[0].doc.id; + let copy = (*s.close(0).unwrap().doc).clone(); + let i = s.add_document(copy, None); + assert_ne!(s.documents()[i].doc.id, source, "a picked source reserves its document ID"); + assert_eq!(s.execute("cloneSource.list", json!({})).unwrap()["sources"][0]["document"], Value::Null); + // Neither in the other document nor in the copy itself does the stroke read the copy. + for painted in [0, i] { + assert!(s.set_active(painted)); + let before = s.active().unwrap().doc.clone(); + let e = s.execute("paint.cloneStamp", json!({"points": [[20, 20]], "size": 4})).unwrap_err(); + assert!(e.to_string().contains("closed"), "document {painted}: {e}"); + assert!(LiveRetouch::begin(&s, "paint.cloneStamp", &json!({"points": [[20, 20]], "size": 4})).is_err()); + assert_eq!(s.active().unwrap().doc, before, "document {painted}: nothing painted"); + } + // Setting a source in the copy makes it the source again. + s.execute("cloneSource.set", json!({"source": [10, 12]})).unwrap(); + assert_eq!(s.execute("cloneSource.list", json!({})).unwrap()["sources"][0]["document"], json!(i)); + s.execute("paint.cloneStamp", json!({"points": [[20, 20]], "size": 4})).unwrap(); +} + +#[test] +fn clone_source_set_names_the_source_document() { + let mut s = two_documents(8, ramp, |_, _| [0.0, 0.0, 1.0, 1.0], [0, 0]); + // From document 1, set a source in document 0 by index. + let r = s.execute("cloneSource.set", json!({"source": [10, 12], "document": 0})).unwrap(); + assert_eq!(r["document"], json!(0)); + assert_eq!(r["layer"], json!(s.documents()[0].active_layer.unwrap().0)); + s.execute("paint.cloneStamp", json!({"points": [[30, 20]], "size": 4, "hardness": 100})).unwrap(); + let (got, want) = (doc_rgba(&s, 1, 30, 20), doc_rgba(&s, 0, 10, 12)); + assert!((got[0] - want[0]).abs() <= tol(8), "{got:?} vs {want:?}"); + for bad in [ + json!({"source": [1, 1], "document": 2}), + json!({"source": [1, 1], "document": -1}), + json!({"source": [1, 1], "document": "0"}), + json!({"document": 0}), + ] { + assert!(s.execute("cloneSource.set", bad.clone()).is_err(), "{bad}"); + } + assert_eq!(s.presets.clone.active().source, Some([10.0, 12.0]), "a refused call changes nothing"); +} + // --------------------------------------------------------------------------------------------- // View › Pattern Preview: Clone Stamp and Healing Brush wrap across the canvas edges (#8883) // --------------------------------------------------------------------------------------------- diff --git a/crates/engine/src/cmd/smart_cmds/contents.rs b/crates/engine/src/cmd/smart_cmds/contents.rs index cce8b7002a..8f28fe2a26 100644 --- a/crates/engine/src/cmd/smart_cmds/contents.rs +++ b/crates/engine/src/cmd/smart_cmds/contents.rs @@ -99,7 +99,8 @@ pub(super) fn export_contents(s: &mut Session, p: &Value) -> Result { return Ok(json!({"path": path, "fileName": name, "bytes": bytes.len(), "converted": false})); } let contents = decode_source(&name, &bytes)?; - let r = photocraft_io::export(&contents, path, &Default::default()).map_err(|e| other(format!("can't export the contents as {}: {e}", base_name(path))))?; + let r = photocraft_io::export(&contents, path, &photocraft_io::ExportOptions { read_linked_files: s.authorize.is_none(), ..Default::default() }) + .map_err(|e| other(format!("can't export the contents as {}: {e}", base_name(path))))?; crate::file_cmds::write_file(path, &r.bytes)?; Ok(json!({"path": path, "fileName": name, "bytes": r.bytes.len(), "converted": true, "warnings": r.warnings})) } diff --git a/crates/engine/src/cmd/smart_cmds/rendering.rs b/crates/engine/src/cmd/smart_cmds/rendering.rs index e922e125ef..5102e728f8 100644 --- a/crates/engine/src/cmd/smart_cmds/rendering.rs +++ b/crates/engine/src/cmd/smart_cmds/rendering.rs @@ -156,8 +156,16 @@ fn renders_in_object(f: &SmartFilter) -> bool { /// requesting session's authority denies the filter's params: callers surface the error instead of /// rendering (and caching) unfiltered pixels. fn apply_smart_filter(f: &SmartFilter, sm: &SmartObject, cur: &Surface, canvas: Rect, extent: Rect, ctx: &JobCtx) -> Result { + // Equalize bypasses `apply_filter_to_surface_in` (the gate there), so check the command first. + crate::jobs::authorize_render_command(&f.command, &f.params)?; let params = crate::distort_cmds::placed_puppet_params(&f.command, &f.params, sm); - let out = match crate::filters::apply_filter_to_surface_in(&f.command, ¶ms, cur, canvas, None, extent, ctx)? { + let rendered = if f.command == "image.adjustments.equalize" { + ctx.check()?; + crate::adjust_cmds::adjust_as_filter("equalize", ¶ms, cur, sm.filter_mask.as_ref())? + } else { + crate::filters::apply_filter_to_surface_in(&f.command, ¶ms, cur, canvas, None, extent, ctx)? + }; + let out = match rendered { // Unknown ids (e.g. Photoshop filters we don't implement) leave the pixels alone. Some(out) => out, None => cur.clone(), @@ -347,7 +355,7 @@ pub(super) fn render_in(doc: &Document, sm: &SmartObject, ctx: &JobCtx) -> Resul let keys: Vec = filters .iter() .scan(placed_key, |key, f| { - *key = stack_cache::filter_key(key, f); + *key = stack_cache::filter_key(key, f, sm.filter_mask.as_ref()); Some(*key) }) .collect(); diff --git a/crates/engine/src/cmd/smart_cmds/stack_cache.rs b/crates/engine/src/cmd/smart_cmds/stack_cache.rs index 372d30eaab..69ee6515f0 100644 --- a/crates/engine/src/cmd/smart_cmds/stack_cache.rs +++ b/crates/engine/src/cmd/smart_cmds/stack_cache.rs @@ -48,11 +48,24 @@ pub(super) fn placed_key(bytes: &[u8], fmt: PixelFormat, sm: &SmartObject, canva } /// The stage after applying `f` to stage `below`. -pub(super) fn filter_key(below: &StageKey, f: &SmartFilter) -> StageKey { +pub(super) fn filter_key(below: &StageKey, f: &SmartFilter, mask: Option<&photocraft_doc::LayerMask>) -> StageKey { let mut h = blake3::Hasher::new(); h.update(below); h.update(format!("{}\0{}\0{:?}\0", f.command, f.params, f.blend).as_bytes()); h.update(&f.opacity.to_bits().to_le_bytes()); + // Equalize's histogram depends on coverage; downstream stages inherit this key. + if f.command == "image.adjustments.equalize" + && let Some(mask) = mask.filter(|m| m.enabled) + { + h.update(format!("{:?}|{}", mask.surface.format(), mask.density).as_bytes()); + h.update(mask.surface.default_bytes()); + let mut tiles: Vec<_> = mask.surface.tiles().collect(); + tiles.sort_by_key(|(coord, _)| **coord); + for (coord, tile) in tiles { + h.update(format!("{coord:?}").as_bytes()); + h.update(&tile.bytes()); + } + } *h.finalize().as_bytes() } diff --git a/crates/engine/src/cmd/smartselect_cmds.rs b/crates/engine/src/cmd/smartselect_cmds.rs index 3d1088528f..941540e6f9 100644 --- a/crates/engine/src/cmd/smartselect_cmds.rs +++ b/crates/engine/src/cmd/smartselect_cmds.rs @@ -69,6 +69,26 @@ pub(crate) fn with_doc_sampler(doc: &Document, layer: Option, all_la } } +/// A flat, opaque image: what Quick Selection reads with a group active and Sample All Layers off. +struct FlatSampler; + +impl Sampler for FlatSampler { + fn rgba(&self, r: Rect) -> Vec<[f32; 4]> { + vec![[0.0, 0.0, 0.0, 1.0]; r.width() as usize * r.height() as usize] + } +} + +/// Runs `f` with Quick Selection's sampler: [`with_sampler`]'s, except that with a group active +/// and Sample All Layers off it reads a flat area, so a click selects only the brush disc instead +/// of the composite's shapes, as the reference application does (#12933). Artboards and frames, +/// groups too but not measured, keep reading the composite. +fn with_quick_sampler(s: &Session, all_layers: bool, f: impl FnOnce(&dyn Sampler, &Document) -> R) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let plain_group = |l: &Layer| l.frame.is_none() && matches!(&l.content, LayerContent::Group(g) if g.artboard.is_none()); + let group = d.active_layer.and_then(|id| d.doc.layer(id)).is_some_and(plain_group); + if group && !all_layers { Ok(f(&FlatSampler, &d.doc)) } else { with_sampler(s, all_layers, f) } +} + /// Stores `region` combined with the current selection by `m` as one history step. /// Finding nothing never destroys work: the selection (and history) is left alone and the /// caller gets `changed: false`, whatever the mode. (Select Subject and Object Selection run @@ -112,7 +132,7 @@ fn quick_selection(s: &mut Session, p: &Value) -> Result { _ => SelectionMode::Add, }; let enhance = b(p, "enhanceEdge", false); - let region = with_sampler(s, b(p, "sampleAllLayers", false), |smp, doc| { + let region = with_quick_sampler(s, b(p, "sampleAllLayers", false), |smp, doc| { let canvas = doc.bounds(); let Some(r) = quick::quick_select(smp, canvas, &pts, size) else { return Ok(None) }; let surface = matting::region_surface(&r); @@ -598,3 +618,5 @@ mod tests; #[cfg(test)] mod object_mode_refusal_tests; +#[cfg(test)] +mod quick_group_target_tests; diff --git a/crates/engine/src/cmd/smartselect_cmds/quick_group_target_tests.rs b/crates/engine/src/cmd/smartselect_cmds/quick_group_target_tests.rs new file mode 100644 index 0000000000..94edd217b3 --- /dev/null +++ b/crates/engine/src/cmd/smartselect_cmds/quick_group_target_tests.rs @@ -0,0 +1,121 @@ +//! Quick Selection with a group active (#12933): with Sample All Layers off it reads a flat area, +//! so a click selects only the brush disc; with it on, or with an adjustment layer active, it +//! reads the composite as before. +//! +//! The document is the one the issue measured against the reference application. + +use super::*; + +const W: i32 = 800; +const H: i32 = 600; +/// The centre of "red 2", the click the issue measured. +const RED2_CLICK: [f32; 2] = [550.0, 150.0]; + +/// The issue's document: white Background; pixel layer Shapes with red (220,30,30) rectangles +/// 100,100-300,250 ("red 1") and 500,100-600,200 ("red 2"); an empty pixel layer Blue on top; then +/// a new, empty group, which is left active. +fn issue_document() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": W, "height": H, "depth": 8})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Shapes"})).unwrap(); + for [x, y, w, h] in [[100, 100, 200, 150], [500, 100, 100, 100]] { + s.execute("select.rect", json!({"x": x, "y": y, "width": w, "height": h})).unwrap(); + s.execute("edit.fill", json!({"color": "#dc1e1e"})).unwrap(); + } + s.execute("select.deselect", json!({})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Blue"})).unwrap(); + s.execute("layer.new.group", json!({})).unwrap(); + s +} + +/// A Quick Selection click at `at` with the default 30 px brush. +fn click(s: &mut Session, at: [f32; 2], sample_all: bool) -> Value { + s.execute("select.quick", json!({"points": [at], "size": 30, "mode": "new", "sampleAllLayers": sample_all})).unwrap() +} + +/// The kind of the active layer ("Group", "Adjustment", "Pixel", ...). +fn active_kind(s: &Session) -> &'static str { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().content.kind_name() +} + +/// The selection's coverage at every document pixel, row-major. +fn coverage(s: &Session) -> Vec { + let sel = s.active().unwrap().doc.selection.clone(); + (0..H).flat_map(|y| (0..W).map(move |x| (x, y))).map(|(x, y)| sel.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0))).collect() +} + +/// `[left, top, right, bottom]` of the selection, as the issue writes bounds. +fn bounds(s: &Session) -> [i32; 4] { + let b = s.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(); + [b.x0, b.y0, b.x1, b.y1] +} + +/// Asserts the selection covers the whole rectangle `[x0, y0, x1, y1)` and reaches at most +/// `slack` pixels beyond it: the composite's shape, not a brush disc. +fn assert_selects_rect(s: &Session, [x0, y0, x1, y1]: [i32; 4], slack: i32) { + let cov = coverage(s); + for y in y0..y1 { + for x in x0..x1 { + assert!(cov[(y * W + x) as usize] >= 0.5, "({x},{y}) inside the shape is not selected"); + } + } + let [l, t, r, b] = bounds(s); + assert!(l >= x0 - slack && t >= y0 - slack && r <= x1 + slack && b <= y1 + slack, "bounds {:?} reach past the shape", [l, t, r, b]); +} + +#[test] +fn a_group_without_sample_all_layers_selects_only_the_brush_disc() { + // The disc a click on a flat area gives: Background active, which is white everywhere. + let mut flat = issue_document(); + let d = flat.active_mut().unwrap(); + d.active_layer = Some(d.doc.layers[0].id); + assert_eq!(active_kind(&flat), "Pixel"); + click(&mut flat, RED2_CLICK, false); + let disc = coverage(&flat); + + let mut s = issue_document(); + let before = s.active().unwrap().history.past_len(); + let out = click(&mut s, RED2_CLICK, false); + assert_eq!(out["changed"], json!(true)); + assert_eq!(s.active().unwrap().history.past_len(), before + 1); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Quick Selection")); + assert_eq!(active_kind(&s), "Group"); + // Pixel for pixel the flat-area disc, not red 2 (100 x 100) from the composite. + assert!(coverage(&s) == disc, "a group click differs from the brush disc on a flat area"); + let [l, t, r, b] = bounds(&s); + assert!((30..=40).contains(&(r - l)) && (30..=40).contains(&(b - t)), "bounds {:?} are not a 30 px brush disc", [l, t, r, b]); + assert!(l < 550 && r > 550 && t < 150 && b > 150, "bounds {:?} miss the click", [l, t, r, b]); +} + +#[test] +fn a_group_with_sample_all_layers_reads_the_composite() { + let mut s = issue_document(); + assert_eq!(active_kind(&s), "Group"); + click(&mut s, [200.0, 175.0], true); + // Measured: 99,99,301,251, all of red 1. + assert_selects_rect(&s, [100, 100, 300, 250], 3); +} + +#[test] +fn an_adjustment_layer_reads_the_composite() { + let mut s = issue_document(); + s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + assert_eq!(active_kind(&s), "Adjustment"); + click(&mut s, RED2_CLICK, false); + assert_selects_rect(&s, [500, 100, 600, 200], 3); +} + +#[test] +fn an_artboard_or_a_frame_still_reads_the_composite() { + // Not measured for these groups, so they keep reading the composite. + for (cmd, params) in + [("layer.new.artboard", json!({"rect": [700, 500, 50, 50]})), ("layer.new.frame", json!({"x": 700, "y": 500, "width": 50, "height": 50}))] + { + let mut s = issue_document(); + s.execute(cmd, params).unwrap(); + assert_eq!(active_kind(&s), "Group", "{cmd}"); + click(&mut s, RED2_CLICK, false); + assert_selects_rect(&s, [500, 100, 600, 200], 3); + } +} diff --git a/crates/engine/src/cmd/style_asl_cmds.rs b/crates/engine/src/cmd/style_asl_cmds.rs index 840459bf6d..1a7eaf4fe1 100644 --- a/crates/engine/src/cmd/style_asl_cmds.rs +++ b/crates/engine/src/cmd/style_asl_cmds.rs @@ -7,7 +7,7 @@ //! - `style.presets.exportAsl` writes styles (all, one group or named ones) as an `.asl`, with the //! patterns their effects use. //! -//! The container lives in `photocraft-psd` (`asl`), the mapping onto effects in `photocraft-io` +//! The container lives in `craft-psd` (`asl`), the mapping onto effects in `photocraft-io` //! (`asl_map`). use serde_json::{Value, json}; diff --git a/crates/engine/src/cmd/swatch_cmds.rs b/crates/engine/src/cmd/swatch_cmds.rs index fc9a4c36b1..1a65981567 100644 --- a/crates/engine/src/cmd/swatch_cmds.rs +++ b/crates/engine/src/cmd/swatch_cmds.rs @@ -3,14 +3,14 @@ //! Photoshop `.aco` and Adobe Swatch Exchange `.ase` files. //! //! The library is [`PresetState::swatches`](crate::presets::PresetState) (model and colour -//! conversions in [`crate::presets::swatches`]); file parsing is `photocraft_psd::{aco, ase}`. +//! conversions in [`crate::presets::swatches`]); file parsing is `craft_psd::{aco, ase}`. //! Swatches are addressed by name (names are kept unique across the library, as for the other //! presets), optionally narrowed by `group`, or by `index` (position across all groups, in //! panel order). Like the other preset commands they change the preferences document, not a //! document's history. -use photocraft_psd::aco::{AcoColor, AcoSwatch}; -use photocraft_psd::ase::{AseColor, AseEntry, AseFile, AseKind, AseSwatch}; +use craft_psd::aco::{AcoColor, AcoSwatch}; +use craft_psd::ase::{AseColor, AseEntry, AseFile, AseKind, AseSwatch}; use serde_json::{Value, json}; use crate::commands::CommandSpec; @@ -473,18 +473,18 @@ fn kind_to_ase(k: SwatchKind) -> AseKind { } /// Colors in an `.act` color table (what the format holds). -pub const ACT_COLORS: usize = photocraft_psd::act::COLOR_COUNT; +pub const ACT_COLORS: usize = craft_psd::act::COLOR_COUNT; /// `.act` bytes as `#rrggbb` colors plus the transparent index, for the Color Table dialog. pub fn act_table(bytes: &[u8]) -> std::result::Result<(Vec, Option), String> { - let f = photocraft_psd::act::parse(bytes).map_err(|e| e.to_string())?; + let f = craft_psd::act::parse(bytes).map_err(|e| e.to_string())?; let hex = |c: &[u8; 3]| format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]); Ok((f.used().iter().map(hex).collect(), f.transparent_index().map(|i| i as u64))) } /// Encode colors as `.act` bytes (at most [`ACT_COLORS`]); the transparent index is kept. pub fn act_bytes(colors: &[[u8; 3]], transparent: Option) -> std::result::Result, String> { - photocraft_psd::act::write(colors, Some(colors.len().min(ACT_COLORS) as u16), transparent).map_err(|e| e.to_string()) + craft_psd::act::write(colors, Some(colors.len().min(ACT_COLORS) as u16), transparent).map_err(|e| e.to_string()) } /// Parse a swatch file into groups (`group` names the group for ungrouped colours). @@ -494,7 +494,7 @@ pub fn read_file(bytes: &[u8], format: Format, group: &str) -> std::result::Resu let fallback = |i: usize, name: &str| if name.trim().is_empty() { format!("Swatch {}", i + 1) } else { clip(name.trim()) }; match format { Format::Aco => { - let f = photocraft_psd::aco::parse(bytes).map_err(|e| format!("not a readable .aco swatch file: {e}"))?; + let f = craft_psd::aco::parse(bytes).map_err(|e| format!("not a readable .aco swatch file: {e}"))?; let books = f.swatches.iter().filter(|s| matches!(s.color, AcoColor::Other { .. })).count(); if books > 0 { warnings.push(format!( @@ -510,7 +510,7 @@ pub fn read_file(bytes: &[u8], format: Format, group: &str) -> std::result::Resu out.push(Group::new(group, items)); } Format::Act => { - let f = photocraft_psd::act::parse(bytes).map_err(|e| format!("not a readable .act color table: {e}"))?; + let f = craft_psd::act::parse(bytes).map_err(|e| format!("not a readable .act color table: {e}"))?; if let Some(t) = f.transparent_index() { warnings.push(format!("color {} is the table's transparent color; swatches have no transparency so it was kept opaque", t + 1)); } @@ -523,7 +523,7 @@ pub fn read_file(bytes: &[u8], format: Format, group: &str) -> std::result::Resu out.push(Group::new(group, items)); } Format::Ase => { - let f = photocraft_psd::ase::parse(bytes).map_err(|e| format!("not a readable .ase swatch file: {e}"))?; + let f = craft_psd::ase::parse(bytes).map_err(|e| format!("not a readable .ase swatch file: {e}"))?; let mut skipped = 0; let mut n = 0usize; let mut conv = |s: &AseSwatch| -> Option { @@ -542,13 +542,13 @@ pub fn read_file(bytes: &[u8], format: Format, group: &str) -> std::result::Resu AseEntry::Swatch(s) => loose.extend(conv(s)), AseEntry::Group { name, swatches } => { let items: Vec = swatches.iter().filter_map(&mut conv).collect(); - let name = if name.trim().is_empty() { group.to_string() } else { clip(name.trim()) }; + let name = if name.trim().is_empty() { clip(group) } else { clip(name.trim()) }; out.push(Group::new(&name, items)); } } } if !loose.is_empty() || out.is_empty() { - out.insert(0, Group::new(group, loose)); + out.insert(0, Group::new(&clip(group), loose)); } if skipped > 0 { warnings.push(format!("{skipped} swatches in an unknown colour model were skipped")); @@ -576,7 +576,7 @@ pub fn write_file(groups: &[Group], format: Format) -> std::result::Resu warnings.push(".aco files don't mark spot or global colours; save as .ase to keep them".into()); } let n = swatches.len(); - let bytes = photocraft_psd::aco::write(&swatches).map_err(|e| e.to_string())?; + let bytes = craft_psd::aco::write(&swatches).map_err(|e| e.to_string())?; Ok((bytes, n, warnings)) } Format::Act => { @@ -597,12 +597,12 @@ pub fn write_file(groups: &[Group], format: Format) -> std::result::Resu if skipped > 0 { warnings.push(format!("{skipped} non-RGB swatches can't be stored in an .act file and were left out (save as .aco to keep them)")); } - if triplets.len() > photocraft_psd::act::COLOR_COUNT { - warnings.push(format!("only the first {} swatches fit in an .act file", photocraft_psd::act::COLOR_COUNT)); - triplets.truncate(photocraft_psd::act::COLOR_COUNT); + if triplets.len() > craft_psd::act::COLOR_COUNT { + warnings.push(format!("only the first {} swatches fit in an .act file", craft_psd::act::COLOR_COUNT)); + triplets.truncate(craft_psd::act::COLOR_COUNT); } let n = triplets.len(); - let bytes = photocraft_psd::act::write(&triplets, Some(n as u16), None).map_err(|e| e.to_string())?; + let bytes = craft_psd::act::write(&triplets, Some(n as u16), None).map_err(|e| e.to_string())?; Ok((bytes, n, warnings)) } Format::Ase => { @@ -627,7 +627,7 @@ pub fn write_file(groups: &[Group], format: Format) -> std::result::Resu if books > 0 { warnings.push(format!("{books} colour-book swatches can't be stored in an .ase file and were left out (save as .aco to keep them)")); } - let bytes = photocraft_psd::ase::write(&AseFile { entries }).map_err(|e| e.to_string())?; + let bytes = craft_psd::ase::write(&AseFile { entries }).map_err(|e| e.to_string())?; Ok((bytes, n, warnings)) } } @@ -639,12 +639,12 @@ fn import(s: &mut Session, p: &Value) -> Result { // `.act` has no magic: exactly 768/772 bytes. An `.act` whose first colour is `0, 1, x` or // `0, 2, x` starts like an `.aco`, and the .aco reader ignores trailing bytes, so at those // lengths an .aco header only counts when its sections fill the file exactly. - let act_len = bytes.len() == photocraft_psd::act::PALETTE_LEN || bytes.len() == photocraft_psd::act::PALETTE_LEN + photocraft_psd::act::TRAILER_LEN; + let act_len = bytes.len() == craft_psd::act::PALETTE_LEN || bytes.len() == craft_psd::act::PALETTE_LEN + craft_psd::act::TRAILER_LEN; let format = match str_param(p, "format") { Some(f) => Format::parse(f).ok_or_else(|| bad(CMD, format!("unknown format `{f}` (aco|act|ase)")))?, None if ext_format(str_param(p, "path")) == Some(Format::Act) => Format::Act, - None if bytes.starts_with(photocraft_psd::ase::SIGNATURE) => Format::Ase, - None if matches!(bytes.get(..2), Some([0, 1] | [0, 2])) && (!act_len || photocraft_psd::aco::sections_len(&bytes) == Some(bytes.len())) => Format::Aco, + None if bytes.starts_with(craft_psd::ase::SIGNATURE) => Format::Ase, + None if matches!(bytes.get(..2), Some([0, 1] | [0, 2])) && (!act_len || craft_psd::aco::sections_len(&bytes) == Some(bytes.len())) => Format::Aco, None if act_len => Format::Act, None => ext_format(str_param(p, "path")).ok_or_else(|| bad(CMD, "not an .aco, .act or .ase swatch file"))?, }; diff --git a/crates/engine/src/cmd/swatch_cmds/tests.rs b/crates/engine/src/cmd/swatch_cmds/tests.rs index 54fadda05c..0a7529de7a 100644 --- a/crates/engine/src/cmd/swatch_cmds/tests.rs +++ b/crates/engine/src/cmd/swatch_cmds/tests.rs @@ -141,7 +141,7 @@ fn aco_round_trip_keeps_16_bit_values_and_books() { AcoSwatch { name: "G".into(), color: AcoColor::Gray(1234) }, AcoSwatch { name: "Book".into(), color: AcoColor::Other { space: 3, values: [9, 8, 7, 6] } }, ]; - let file = photocraft_psd::aco::write(&swatches).unwrap(); + let file = craft_psd::aco::write(&swatches).unwrap(); let mut s = Session::new(); let r = s.execute("swatches.import", json!({"data": b64_encode(&file), "group": "Pro", "mode": "replace"})).unwrap(); assert_eq!((r["format"].as_str(), r["count"].as_u64()), (Some("aco"), Some(6))); @@ -174,7 +174,7 @@ fn act_round_trip_loads_a_photoshop_color_table() { let v = i as u8; *c = [v, 255 - v, 128]; } - let file = photocraft_psd::act::write(&colors, Some(256), Some(255)).unwrap(); + let file = craft_psd::act::write(&colors, Some(256), Some(255)).unwrap(); assert_eq!(file.len(), 772); let mut s = Session::new(); let r = s.execute("swatches.import", json!({"data": b64_encode(&file), "group": "Table", "mode": "replace"})).unwrap(); @@ -187,7 +187,7 @@ fn act_round_trip_loads_a_photoshop_color_table() { assert_eq!(r["format"].as_str(), Some("act")); // Export keeps the 256 RGB colors; the trailer comes back in canonical form // (swatches have no transparency to preserve). - let canon = photocraft_psd::act::write(&colors, Some(256), None).unwrap(); + let canon = craft_psd::act::write(&colors, Some(256), None).unwrap(); assert_eq!(export_bytes(&mut s, json!({"format": "act"})), canon); // A bigger library is capped at 256 with a warning; groups collapse to one list. for i in 0..300 { @@ -207,7 +207,7 @@ fn act_that_starts_like_an_aco_is_still_an_act() { for (i, c) in colors.iter_mut().enumerate().skip(1) { *c = [(i as u8).wrapping_add(4), 7, 9]; } - for file in [photocraft_psd::act::write(&colors, None, None).unwrap(), photocraft_psd::act::write(&colors, Some(256), None).unwrap()] { + for file in [craft_psd::act::write(&colors, None, None).unwrap(), craft_psd::act::write(&colors, Some(256), None).unwrap()] { assert_eq!(&file[..4], &[0, 1, 0, 5]); let mut s = Session::new(); let r = s.execute("swatches.import", json!({"data": b64_encode(&file), "mode": "replace"})).unwrap(); @@ -215,8 +215,8 @@ fn act_that_starts_like_an_aco_is_still_an_act() { } // A real .aco of exactly 768 bytes (ten swatches with 25-character names) stays an .aco. let swatches: Vec = (0..10u16).map(|i| AcoSwatch { name: format!("{i:0>25}"), color: AcoColor::Rgb([i * 1000, 0, 65535]) }).collect(); - let file = photocraft_psd::aco::write(&swatches).unwrap(); - assert_eq!(file.len(), photocraft_psd::act::PALETTE_LEN); + let file = craft_psd::aco::write(&swatches).unwrap(); + assert_eq!(file.len(), craft_psd::act::PALETTE_LEN); let mut s = Session::new(); let r = s.execute("swatches.import", json!({"data": b64_encode(&file), "mode": "replace"})).unwrap(); assert_eq!((r["format"].as_str(), r["count"].as_u64()), (Some("aco"), Some(10))); @@ -239,7 +239,7 @@ fn ase_round_trip_keeps_groups_floats_and_kinds() { }, ], }; - let bytes = photocraft_psd::ase::write(&src).unwrap(); + let bytes = craft_psd::ase::write(&src).unwrap(); let mut s = Session::new(); let r = s.execute("swatches.import", json!({"data": b64_encode(&bytes), "group": "Exchange"})).unwrap(); assert_eq!(r["groups"], json!(["Exchange", "Brand"])); @@ -251,7 +251,7 @@ fn ase_round_trip_keeps_groups_floats_and_kinds() { assert_eq!(brand.items[2].color, SwatchColor::Gray(0.75)); // Export both groups and read them back. let out = export_bytes(&mut s, json!({"format": "ase", "swatches": ["Loose", "Spot ink", "Global lab", "Gray"]})); - let back = photocraft_psd::ase::parse(&out).unwrap(); + let back = craft_psd::ase::parse(&out).unwrap(); let flat: Vec<&AseSwatch> = back .entries .iter() @@ -271,7 +271,7 @@ fn ase_round_trip_keeps_groups_floats_and_kinds() { // HSB swatches become RGB in .ase. s.execute("swatches.add", json!({"name": "Hue", "color": {"model": "hsb", "values": [120, 100, 100]}})).unwrap(); let out = export_bytes(&mut s, json!({"format": "ase", "swatches": ["Hue"]})); - let back = photocraft_psd::ase::parse(&out).unwrap(); + let back = craft_psd::ase::parse(&out).unwrap(); assert_eq!( back.entries, vec![AseEntry::Group { @@ -357,7 +357,7 @@ fn bad_params_fail_gracefully() { fn library_limits() { let mut s = Session::new(); let one = vec![AcoSwatch { name: "x".into(), color: AcoColor::Gray(0) }; 60_000]; - let file = b64_encode(&photocraft_psd::aco::write(&one).unwrap()); + let file = b64_encode(&craft_psd::aco::write(&one).unwrap()); s.execute("swatches.import", json!({"data": file, "mode": "replace"})).unwrap(); assert!(s.execute("swatches.import", json!({"data": file})).is_err(), "over the library limit"); assert_eq!(names(&s).len(), 60_000); @@ -381,7 +381,7 @@ fn unnamed_groups_are_numbered_in_linear_time() { let paper = AseSwatch { name: "Paper".into(), color: AseColor::Gray(1.0), kind: AseKind::Process }; let mut entries = vec![AseEntry::Group { name: String::new(), swatches: Vec::new() }; n]; entries[0] = AseEntry::Group { name: String::new(), swatches: vec![paper] }; - let file = b64_encode(&photocraft_psd::ase::write(&AseFile { entries }).unwrap()); + let file = b64_encode(&craft_psd::ase::write(&AseFile { entries }).unwrap()); let r = s.execute("swatches.import", json!({"data": file, "group": "Ink"})).unwrap(); assert_eq!(s.presets.swatches.len(), MAX_GROUPS); let names: Vec = r["groups"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect(); @@ -406,7 +406,7 @@ fn repeated_group_names_take_the_first_free_number() { } let paper = AseSwatch { name: "Paper".into(), color: AseColor::Gray(1.0), kind: AseKind::Process }; let entries = ["Brand", "Brand", "Brand", "Brand 1"].into_iter().map(|name| AseEntry::Group { name: name.into(), swatches: vec![paper.clone()] }).collect(); - let file = b64_encode(&photocraft_psd::ase::write(&AseFile { entries }).unwrap()); + let file = b64_encode(&craft_psd::ase::write(&AseFile { entries }).unwrap()); let r = s.execute("swatches.import", json!({"data": file})).unwrap(); // The file's "Brand 1" comes after the first "Brand" took that name. assert_eq!(r["groups"], json!(["Brand 1", "Brand 3", "Brand 4", "Brand 1 1"])); diff --git a/crates/engine/src/cmd/variables_cmds.rs b/crates/engine/src/cmd/variables_cmds.rs index c56ee0f6c0..d109959bdd 100644 --- a/crates/engine/src/cmd/variables_cmds.rs +++ b/crates/engine/src/cmd/variables_cmds.rs @@ -27,6 +27,16 @@ fn has_data_sets(s: &Session) -> std::result::Result<(), String> { Ok(()) } +/// File > Import > Variable Data Sets needs variables to fill: without any, every header column +/// is an unknown name and the import makes empty data sets (#13920). +fn has_variables(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or_else(|| "no document".to_string())?; + if st.doc.variables.defs.is_empty() { + return Err("no variables in document".into()); + } + Ok(()) +} + fn bad(cmd: &str, msg: impl Into) -> EngineError { EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } } @@ -530,6 +540,7 @@ pub fn specs() -> Vec { "Variable Data Sets…", &["File", "Import"], "{path, delimiter?} → {imported}: CSV header = variable names, each row a data set (first column may be the data-set name)", + has_variables, |s, p| import_data_sets(s, p) ), spec!( @@ -555,3 +566,6 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests; + +#[cfg(test)] +mod import_enabled_tests; diff --git a/crates/engine/src/cmd/variables_cmds/import_enabled_tests.rs b/crates/engine/src/cmd/variables_cmds/import_enabled_tests.rs new file mode 100644 index 0000000000..823a226a72 --- /dev/null +++ b/crates/engine/src/cmd/variables_cmds/import_enabled_tests.rs @@ -0,0 +1,87 @@ +//! #13920: File > Import > Variable Data Sets is greyed until the active document has a variable. + +use super::*; + +const IMPORT: &str = "file.import.variableDataSets"; + +fn new_doc(s: &mut Session) { + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); +} + +fn define_variable(s: &mut Session) { + let layer = s.active().unwrap().doc.layers[0].id; + s.execute("image.variables.define", json!({"defs": [{"name": "show", "layer": layer.0, "type": "visibility"}]})).unwrap(); +} + +fn refusal(s: &mut Session) -> String { + let path = std::env::temp_dir().join(format!("pc-vars-{}-import-enabled.csv", std::process::id())); + match s.execute(IMPORT, json!({"path": path.to_string_lossy()})) { + Err(EngineError::Disabled(id, why)) => { + assert_eq!(id, IMPORT); + why + } + other => panic!("expected a refusal, got {other:?}"), + } +} + +/// The other File > Import entries, with whether each is enabled now. +fn other_imports(s: &Session) -> Vec<(&'static str, bool)> { + crate::cmd::command_specs().iter().filter(|c| c.menu == ["File", "Import"] && c.id != IMPORT).map(|c| (c.id, s.is_enabled(c.id))).collect() +} + +#[test] +fn import_is_disabled_without_a_document() { + let mut s = Session::new(); + assert!(!s.is_enabled(IMPORT)); + assert_eq!(refusal(&mut s), "no document"); +} + +#[test] +fn import_is_disabled_without_variables_and_leaves_the_document_alone() { + let mut s = Session::new(); + new_doc(&mut s); + assert!(!s.is_enabled(IMPORT)); + assert_eq!(refusal(&mut s), "no variables in document"); + assert!(s.active().unwrap().doc.variables.data_sets.is_empty()); +} + +#[test] +fn import_is_enabled_with_a_variable_and_no_data_sets() { + let mut s = Session::new(); + new_doc(&mut s); + define_variable(&mut s); + assert!(s.active().unwrap().doc.variables.data_sets.is_empty()); + assert!(s.is_enabled(IMPORT)); + + let path = std::env::temp_dir().join(format!("pc-vars-{}-import-enabled-ok.csv", std::process::id())); + std::fs::write(&path, "show\ntrue\nfalse\n").unwrap(); + let r = s.execute(IMPORT, json!({"path": path.to_string_lossy()})).unwrap(); + let _ = std::fs::remove_file(&path); + assert_eq!(r["imported"], 2); +} + +#[test] +fn import_follows_the_active_document() { + let mut s = Session::new(); + new_doc(&mut s); + define_variable(&mut s); + new_doc(&mut s); + // The new, active document has no variables; the one behind it does. + assert!(!s.is_enabled(IMPORT)); + assert_eq!(refusal(&mut s), "no variables in document"); + + assert!(s.set_active(0)); + assert!(s.is_enabled(IMPORT)); + assert!(s.set_active(1)); + assert!(!s.is_enabled(IMPORT)); +} + +#[test] +fn other_import_entries_do_not_depend_on_variables() { + let mut s = Session::new(); + new_doc(&mut s); + let without = other_imports(&s); + assert!(!without.is_empty(), "File > Import has other entries"); + define_variable(&mut s); + assert_eq!(other_imports(&s), without); +} diff --git a/crates/engine/src/cmd/vector_cmds.rs b/crates/engine/src/cmd/vector_cmds.rs index 4539b22c4f..71f8ab9d26 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),"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}"## + r##"{{"kind":"rect|roundedRect|ellipse|triangle|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/triangle/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (triangle and polygon: rounds every vertex, star: its outer points; a triangle fills its rect, apex at the top centre),"from":[x,y],"to":[x,y],"weight":px=1 (line),"arrowStart":bool=false,"arrowEnd":bool=false,"arrowWidth":px=52,"arrowLength":px=50,"arrowConcavity":-50..50=0 (line; rounded to a whole percent),"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),"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"## + 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":-50..50? (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 @@ -372,3 +372,9 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests; + +#[cfg(test)] +mod line_tool_history_name_tests; + +#[cfg(test)] +mod line_arrowhead_history_names_tests; diff --git a/crates/engine/src/cmd/vector_cmds/line_arrowhead_history_names_tests.rs b/crates/engine/src/cmd/vector_cmds/line_arrowhead_history_names_tests.rs new file mode 100644 index 0000000000..a88d6c04d5 --- /dev/null +++ b/crates/engine/src/cmd/vector_cmds/line_arrowhead_history_names_tests.rs @@ -0,0 +1,118 @@ +//! #13267: an edit of one arrowhead setting in the Properties panel is named after it in History +//! ("Change Arrowhead End", "Change Arrowhead Width", ...); other `shape.edit`s keep "Edit Shape". + +use serde_json::{Value, json}; + +use super::*; + +/// A document whose active layer is a line with arrowhead settings (a live `ArrowLine`). +fn arrow_line() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600})).unwrap(); + s.execute( + "shape.create", + json!({"kind": "line", "from": [100, 300], "to": [600, 300], "weight": 4, "arrowStart": false, "arrowEnd": false, "arrowWidth": 5, "arrowLength": 10, "arrowConcavity": 0}), + ) + .unwrap(); + s +} + +fn steps(s: &Session) -> usize { + s.active().unwrap().history.past_len() +} + +fn last_step(s: &Session) -> Option<&str> { + s.active().unwrap().history.undo_label() +} + +fn edit(s: &mut Session, p: Value) { + s.execute("shape.edit", p).unwrap(); +} + +#[test] +fn each_arrowhead_setting_names_its_step() { + let cases = [ + (json!({"arrowStart": true}), "Change Arrowhead Start"), + (json!({"arrowEnd": true}), "Change Arrowhead End"), + (json!({"arrowWidth": 15}), "Change Arrowhead Width"), + (json!({"arrowLength": 20}), "Change Arrowhead Length"), + (json!({"arrowConcavity": 30}), "Change Arrowhead Concavity"), + ]; + for (p, name) in cases { + let mut s = arrow_line(); + let n = steps(&s); + edit(&mut s, p); + assert_eq!(steps(&s), n + 1, "{name}"); + assert_eq!(last_step(&s), Some(name)); + } +} + +#[test] +fn turning_end_off_is_also_change_arrowhead_end() { + let mut s = arrow_line(); + edit(&mut s, json!({"arrowEnd": true})); + edit(&mut s, json!({"arrowEnd": false})); + assert_eq!(last_step(&s), Some("Change Arrowhead End")); +} + +#[test] +fn the_panel_keys_layer_and_coalesce_do_not_change_the_name() { + let mut s = arrow_line(); + let id = s.active().unwrap().active_layer.unwrap().0; + edit(&mut s, json!({"arrowWidth": 15, "layer": id, "coalesce": "w"})); + assert_eq!(last_step(&s), Some("Change Arrowhead Width")); +} + +#[test] +fn one_drag_of_a_field_is_still_one_step() { + let mut s = arrow_line(); + let n = steps(&s); + for w in [6, 9, 12, 15] { + edit(&mut s, json!({"arrowWidth": w, "coalesce": "arrow-width:drag-1"})); + } + assert_eq!(steps(&s), n + 1); + assert_eq!(last_step(&s), Some("Change Arrowhead Width")); +} + +#[test] +fn other_edits_keep_edit_shape() { + for p in [ + json!({"weight": 8}), + json!({"from": [50, 300]}), + json!({"fill": "#ff0000"}), + json!({"name": "Arrow"}), + json!({"arrowWidth": 15, "arrowLength": 20}), + json!({"arrowEnd": true, "weight": 8}), + ] { + let mut s = arrow_line(); + edit(&mut s, p.clone()); + assert_eq!(last_step(&s), Some("Edit Shape"), "{p}"); + } +} + +#[test] +fn a_refused_arrowhead_edit_adds_no_step() { + let mut s = arrow_line(); + let n = steps(&s); + assert!(s.execute("shape.edit", json!({"arrowWidth": "wide"})).is_err()); + assert!(s.execute("shape.edit", json!({"arrowEnd": 1})).is_err()); + assert_eq!(steps(&s), n); +} + +#[test] +fn a_plain_line_turning_an_arrowhead_on_is_change_arrowhead_end() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600})).unwrap(); + s.execute("shape.create", json!({"kind": "line", "from": [100, 300], "to": [600, 300], "weight": 4})).unwrap(); + edit(&mut s, json!({"arrowEnd": true})); + assert_eq!(last_step(&s), Some("Change Arrowhead End")); +} + +#[test] +fn arrowhead_keys_on_a_shape_that_is_not_a_line_stay_edit_shape() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600})).unwrap(); + s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 100, 80]})).unwrap(); + edit(&mut s, json!({"arrowWidth": 15})); + assert_eq!(last_step(&s), Some("Edit Shape")); +} diff --git a/crates/engine/src/cmd/vector_cmds/line_tool_history_name_tests.rs b/crates/engine/src/cmd/vector_cmds/line_tool_history_name_tests.rs new file mode 100644 index 0000000000..2cf94ff571 --- /dev/null +++ b/crates/engine/src/cmd/vector_cmds/line_tool_history_name_tests.rs @@ -0,0 +1,67 @@ +//! #13244: a Line tool drag is one History step named "Line Tool" in Shape and Path mode; the +//! commands without the tool keep "New Shape Layer" and "Work Path". + +use serde_json::{Value, json}; + +use super::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn steps(s: &Session) -> usize { + s.active().unwrap().history.past_len() +} + +fn last_step(s: &Session) -> Option<&str> { + s.active().unwrap().history.undo_label() +} + +fn line(history_name: Option<&str>) -> Value { + json!({"kind": "line", "from": [400, 300], "to": [600, 400], "weight": 6, "historyName": history_name}) +} + +/// The closed outline a Path-mode Line drag adds to the Work Path. +fn outline(x: f64) -> Value { + json!({"subpaths": [{"knots": [[x, 300.0], [x + 200.0, 300.0], [x + 200.0, 306.0], [x, 306.0]]}]}) +} + +#[test] +fn a_shape_mode_line_is_one_step_named_line_tool() { + let mut s = session(); + let n = steps(&s); + s.execute("shape.create", line(Some("Line Tool"))).unwrap(); + assert_eq!(steps(&s), n + 1); + assert_eq!(last_step(&s), Some("Line Tool")); +} + +#[test] +fn each_path_mode_line_is_one_step_named_line_tool() { + let mut s = session(); + for x in [100.0, 400.0] { + let n = steps(&s); + s.execute("path.set", json!({"name": "work", "path": outline(x), "historyName": "Line Tool"})).unwrap(); + assert_eq!(steps(&s), n + 1); + assert_eq!(last_step(&s), Some("Line Tool")); + } +} + +#[test] +fn without_the_tool_the_commands_keep_their_own_names() { + let mut s = session(); + s.execute("shape.create", line(None)).unwrap(); + assert_eq!(last_step(&s), Some("New Shape Layer")); + s.execute("path.set", json!({"name": "work", "path": outline(100.0)})).unwrap(); + assert_eq!(last_step(&s), Some("Work Path")); +} + +#[test] +fn an_unknown_history_name_is_refused_without_a_step() { + let mut s = session(); + let n = steps(&s); + assert!(s.execute("shape.create", line(Some("Ellipse Tool"))).is_err()); + assert!(s.execute("path.set", json!({"name": "work", "path": outline(100.0), "historyName": 7})).is_err()); + assert_eq!(steps(&s), n); +} diff --git a/crates/engine/src/cmd/vector_cmds/params.rs b/crates/engine/src/cmd/vector_cmds/params.rs index bab083c162..ea52a43bc9 100644 --- a/crates/engine/src/cmd/vector_cmds/params.rs +++ b/crates/engine/src/cmd/vector_cmds/params.rs @@ -320,7 +320,7 @@ pub(super) fn live_json(l: &LiveShape) -> Value { /// Builds a live shape from `kind` + geometry params. pub(super) fn live_from_params(cmd: &str, kind: &str, p: &Value, prev: Option<&LiveShape>) -> Result { let prev_rect = match prev { - Some(LiveShape::Rect { rect, .. } | LiveShape::Ellipse { rect } | LiveShape::Polygon { rect, .. }) => Some(*rect), + Some(LiveShape::Rect { rect, .. } | LiveShape::Ellipse { rect } | LiveShape::Polygon { rect, .. } | LiveShape::Triangle { rect, .. }) => Some(*rect), _ => None, }; let rect = || nums::<4>(p, "rect").or(prev_rect).ok_or_else(|| bad(cmd, "`rect`: [x, y, w, h] is required")); @@ -340,6 +340,14 @@ pub(super) fn live_from_params(cmd: &str, kind: &str, p: &Value, prev: Option<&L LiveShape::Rect { rect: rect()?, radii: radii(p).unwrap_or(r) } } "ellipse" => LiveShape::Ellipse { rect: rect()? }, + "triangle" => { + let pc = match prev { + Some(LiveShape::Triangle { corner_radius, .. }) => *corner_radius, + _ => 0.0, + }; + let corner_radius = f64p(p, "cornerRadius").map_or(pc, |v| if v.is_finite() { v.clamp(0.0, 1.0e6) } else { pc }); + LiveShape::Triangle { rect: rect()?, corner_radius } + } "polygon" | "star" => { let (ps, pr, pc) = match prev { Some(LiveShape::Polygon { sides, star_ratio, corner_radius, .. }) => (*sides, *star_ratio, *corner_radius), @@ -398,7 +406,9 @@ pub(super) fn live_from_params(cmd: &str, kind: &str, p: &Value, prev: Option<&L 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)?, + // A whole -50..50 % as in Photoshop (#13258); a shape saved with the old 0..100 + // range keeps working when another property is edited. + concavity: dim("arrowConcavity", if pc.is_finite() { pc.clamp(-50.0, 50.0) } else { 0.0 }, -50.0, 50.0)?.round(), } } else { LiveShape::Line { from, to, weight } diff --git a/crates/engine/src/cmd/vector_cmds/paths.rs b/crates/engine/src/cmd/vector_cmds/paths.rs index 37ab7a3b27..b2e687f174 100644 --- a/crates/engine/src/cmd/vector_cmds/paths.rs +++ b/crates/engine/src/cmd/vector_cmds/paths.rs @@ -73,18 +73,23 @@ pub(super) fn paths_list(s: &Session) -> Result { })) } -/// Only Freeform Pen overrides these shared commands' normal History labels (#12829). +/// The tools that override these shared commands' normal History labels with their own name: +/// Freeform Pen (#12829) and the Line tool (#13244). +const TOOL_HISTORY_NAMES: [&str; 2] = ["Freeform Pen", "Line Tool"]; + /// Validate before editing so malformed automation input cannot change the document. pub(super) fn pen_history_name<'a>(p: &Value, cmd: &str, default: &'a str) -> Result<&'a str> { match p.get("historyName") { None | Some(Value::Null) => Ok(default), - Some(Value::String(n)) if n == "Freeform Pen" => Ok("Freeform Pen"), - Some(_) => Err(bad(cmd, "`historyName` must be \"Freeform Pen\"")), + Some(v) => { + TOOL_HISTORY_NAMES.into_iter().find(|&n| v.as_str() == Some(n)).ok_or_else(|| bad(cmd, "`historyName` must be \"Freeform Pen\" or \"Line Tool\"")) + } } } /// Replaces the Work Path or a saved path, or appends subpaths with the requested operation. -/// The optional Freeform Pen history label overrides the normal Work Path or Save Path label. +/// The optional Freeform Pen or Line Tool history label overrides the normal Work Path or Save +/// Path label. pub(super) fn path_set(s: &mut Session, p: &Value) -> Result { const CMD: &str = "path.set"; let path = parse_path(p.get("path").ok_or_else(|| bad(CMD, "missing `path`"))?).map_err(|e| bad(CMD, e))?; diff --git a/crates/engine/src/cmd/vector_cmds/shape.rs b/crates/engine/src/cmd/vector_cmds/shape.rs index 547ad47eca..800499af30 100644 --- a/crates/engine/src/cmd/vector_cmds/shape.rs +++ b/crates/engine/src/cmd/vector_cmds/shape.rs @@ -80,6 +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::Triangle { .. } => "triangle", LiveShape::Line { .. } | LiveShape::ArrowLine { .. } => "line", } } @@ -234,6 +235,7 @@ 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::Triangle { rect, corner_radius } => LiveShape::Triangle { rect: r(rect), 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); @@ -426,6 +428,7 @@ fn default_name(kind: &str) -> &'static str { "roundedRect" | "roundRect" => "Rounded Rectangle", "ellipse" => "Ellipse", "polygon" => "Polygon", + "triangle" => "Triangle", "star" => "Star", "line" => "Line", _ => "Shape", @@ -433,7 +436,8 @@ fn default_name(kind: &str) -> &'static str { } /// Creates a shape layer, or adds path components to the shape identified by `addTo`. -/// The Freeform Pen history override labels new layers; additions retain the Add Shape label. +/// The Freeform Pen or Line Tool history override labels new layers; additions retain the Add +/// Shape label. pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result { const CMD: &str = "shape.create"; let label = super::paths::pen_history_name(p, CMD, "New Shape Layer")?; @@ -453,7 +457,10 @@ pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result { let id = LayerId(target); with_shape(s, id, "Add Shape", |sh, _| { for mut sp in path.subpaths { - sp.op = op; + // A joined subpath (a hole) belongs to the component before it, which takes `op`. + if sp.op != PathOp::Join { + sp.op = op; + } sh.path.subpaths.push(sp); } sh.live = None; @@ -541,13 +548,36 @@ pub(super) fn path_to_shape(s: &mut Session, p: &Value) -> Result { shape_info(s, id) } +/// The History name of a `shape.edit` of layer `id`: an edit of one arrowhead setting of a line +/// is named after it, "Change Arrowhead End" (#13267). The reference application was measured for +/// End and Width; Start, Length and Concavity follow the same pattern. Any other edit, several +/// keys at once, or arrowhead keys sent to a shape that isn't a line stay "Edit Shape". +fn edit_history_name(s: &Session, id: LayerId, p: &Value) -> &'static str { + const EDIT: &str = "Edit Shape"; + let is_line = s + .active() + .and_then(|st| st.doc.layer(id)) + .is_some_and(|l| matches!(&l.content, LayerContent::Shape(sh) if matches!(sh.live, Some(LiveShape::Line { .. } | LiveShape::ArrowLine { .. })))); + let Some(o) = p.as_object().filter(|_| is_line) else { return EDIT }; + let mut changed = o.keys().map(String::as_str).filter(|k| !matches!(*k, "layer" | "coalesce") && !k.starts_with("__")); + match (changed.next(), changed.next()) { + (Some("arrowStart"), None) => "Change Arrowhead Start", + (Some("arrowEnd"), None) => "Change Arrowhead End", + (Some("arrowWidth"), None) => "Change Arrowhead Width", + (Some("arrowLength"), None) => "Change Arrowhead Length", + (Some("arrowConcavity"), None) => "Change Arrowhead Concavity", + _ => EDIT, + } +} + pub(super) fn shape_edit(s: &mut Session, p: &Value) -> Result { const CMD: &str = "shape.edit"; let id = layer_id(s, p)?; let fg = s.tools.foreground; let fgc = Color::rgba(fg[0], fg[1], fg[2], fg[3]); let name = p.get("name").and_then(Value::as_str).map(str::to_string); - with_shape(s, id, "Edit Shape", |sh, layer| { + let label = edit_history_name(s, id, p); + with_shape(s, id, label, |sh, layer| { if let Some(v) = p.get("path") { sh.path = parse_path(v).map_err(|e| bad(CMD, e))?; sh.live = None; @@ -782,6 +812,14 @@ pub(super) fn selection_to_shape(s: &mut Session, p: &Value) -> Result { shape_create(s, &q) } +#[cfg(test)] +#[path = "triangle_layer_name_tests.rs"] +mod triangle_layer_name_tests; + +#[cfg(test)] +#[path = "triangle_box_geometry_tests.rs"] +mod triangle_box_geometry_tests; + #[cfg(test)] mod arrow_affine_regression_tests { use super::*; diff --git a/crates/engine/src/cmd/vector_cmds/tests.rs b/crates/engine/src/cmd/vector_cmds/tests.rs index 93d220a1de..707d6c1a49 100644 --- a/crates/engine/src/cmd/vector_cmds/tests.rs +++ b/crates/engine/src/cmd/vector_cmds/tests.rs @@ -312,6 +312,23 @@ fn reapplying_unchanged_live_rectangle_keeps_nonuniformly_scaled_corners() { } } +/// #13442 review: a component added with `addTo` takes `op` on its first subpath; its joined +/// subpaths (holes) stay joined instead of turning into components of their own. +#[test] +fn shape_add_to_keeps_joined_subpaths() { + use photocraft_doc::vector::{Path, PathOp, Subpath}; + let mut s = session(100, 100, 8); + let id = s.execute("shape.create", json!({"kind": "rect", "rect": [0, 0, 40, 40]})).unwrap()["layer"].as_u64().unwrap(); + let ring = Path::new(vec![ + Subpath::polygon(&[(50.0, 50.0), (90.0, 50.0), (90.0, 90.0), (50.0, 90.0)]), + Subpath::polygon(&[(60.0, 60.0), (60.0, 80.0), (80.0, 80.0), (80.0, 60.0)]).with_op(PathOp::Join), + ]); + let path = crate::vector_cmds::path_json(&ring); + s.execute("shape.create", json!({"kind": "path", "path": path, "addTo": id, "op": "subtract"})).unwrap(); + let ops: Vec = shape(&s, id).path.subpaths.iter().map(|sp| sp.op).collect(); + assert_eq!(ops, [PathOp::Combine, PathOp::Subtract, PathOp::Join]); +} + #[test] fn shape_add_to_with_path_ops() { let mut s = session(100, 100, 8); @@ -1447,7 +1464,7 @@ fn arrowhead_dimensions_reject_invalid_values_without_mutation() { 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)]), + ("arrowConcavity", [json!("0"), json!(null), json!([]), json!(-51), json!(51)]), ] { for invalid in invalids { let mut create = json!({ @@ -1469,6 +1486,35 @@ fn arrowhead_dimensions_reject_invalid_values_without_mutation() { } } +/// Concavity takes -50..50 % (#13258); a shape saved with the old 0..100 range still edits. +#[test] +fn arrow_concavity_takes_minus_fifty_to_fifty() { + let mut s = session(160, 120, 8); + let concavity = |s: &Session, id: u64| match s.active().unwrap().doc.layer(LayerId(id)).map(|l| &l.content) { + Some(LayerContent::Shape(sh)) => match sh.live { + Some(LiveShape::ArrowLine { concavity, .. }) => concavity, + _ => panic!("expected a live arrow"), + }, + _ => panic!("expected a shape layer"), + }; + let created = s.execute("shape.create", json!({"kind": "line", "from": [10, 20], "to": [120, 20], "arrowEnd": true, "arrowConcavity": -50})).unwrap(); + let id = created["layer"].as_u64().unwrap(); + assert_eq!(concavity(&s, id), -50.0); + s.execute("shape.edit", json!({"layer": id, "arrowConcavity": 50})).unwrap(); + assert_eq!(concavity(&s, id), 50.0); + // Whole percents only, as the fields take them. + s.execute("shape.edit", json!({"layer": id, "arrowConcavity": -20.6})).unwrap(); + assert_eq!(concavity(&s, id), -21.0); + + if let Some(LayerContent::Shape(sh)) = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).layer_mut(LayerId(id)).map(|l| &mut l.content) + && let Some(LiveShape::ArrowLine { concavity, .. }) = &mut sh.live + { + *concavity = 80.0; + } + s.execute("shape.edit", json!({"layer": id, "arrowWidth": 12})).unwrap(); + assert_eq!(concavity(&s, id), 50.0, "an old 0..100 value is clamped, not refused"); +} + #[test] fn headless_diagonal_arrow_preserves_geometry_after_nonuniform_scale() { let mut s = session(400, 400, 8); diff --git a/crates/engine/src/cmd/vector_cmds/triangle_box_geometry_tests.rs b/crates/engine/src/cmd/vector_cmds/triangle_box_geometry_tests.rs new file mode 100644 index 0000000000..7dcc5de64f --- /dev/null +++ b/crates/engine/src/cmd/vector_cmds/triangle_box_geometry_tests.rs @@ -0,0 +1,171 @@ +//! The Triangle tool and Create Triangle draw a triangle that fills the dragged box, apex at the +//! top centre, as its own live kind (#13350). A 3-sided polygon stays inscribed in its ellipse. + +use serde_json::{Value, json}; + +use super::super::{LayerContent, LayerId}; +use super::shape_path; +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + s +} + +fn create(s: &mut Session, p: Value) -> u64 { + s.execute("shape.create", p).unwrap()["layer"].as_u64().unwrap() +} + +fn info(s: &mut Session, id: u64) -> Value { + s.execute("shape.info", json!({"layer": id})).unwrap() +} + +fn anchors(v: &Value) -> Vec<(f64, f64)> { + let knots = v["path"]["subpaths"][0]["knots"].as_array().unwrap(); + knots.iter().map(|k| (k["anchor"][0].as_f64().unwrap(), k["anchor"][1].as_f64().unwrap())).collect() +} + +fn path_anchors(p: &Value) -> Vec<(f64, f64)> { + shape_path(p).unwrap().subpaths[0].knots.iter().map(|k| (k.anchor.x, k.anchor.y)).collect() +} + +fn close(got: &[(f64, f64)], want: &[(f64, f64)], tol: f64) { + assert_eq!(got.len(), want.len(), "{got:?}"); + for (g, w) in got.iter().zip(want) { + assert!((g.0 - w.0).abs() <= tol && (g.1 - w.1).abs() <= tol, "{got:?} vs {want:?}"); + } +} + +type Tri = [(f64, f64); 3]; + +const BIG: [(f64, f64); 3] = [(500.0, 300.0), (600.0, 400.0), (400.0, 400.0)]; +const ROUND: [(f64, f64); 6] = [(485.858, 314.142), (514.142, 314.142), (565.858, 365.858), (551.716, 400.0), (448.284, 400.0), (434.142, 365.858)]; + +#[test] +fn a_triangle_fills_its_box() { + let mut s = session(); + let id = create(&mut s, json!({"kind": "triangle", "rect": [400, 300, 200, 100], "fill": "#000000"})); + let v = info(&mut s, id); + assert_eq!(anchors(&v), BIG); + assert_eq!(v["kind"], "triangle"); + assert_eq!(v["live"], json!({"kind": "triangle", "rect": [400.0, 300.0, 200.0, 100.0], "corner_radius": 0.0})); + let LayerContent::Shape(sh) = &s.active().unwrap().doc.layer(LayerId(id)).unwrap().content else { panic!("not a shape layer") }; + let c = sh.cache.as_ref().unwrap(); + assert!(c.rgba(598, 399)[3] > 0.9 && c.rgba(402, 399)[3] > 0.9, "the base corners are filled"); + assert!(c.rgba(410, 310)[3] < 0.01, "above the left edge is empty"); +} + +#[test] +fn the_preview_and_the_measured_boxes_agree() { + let mut s = session(); + let cases: [([f64; 4], Tri); 3] = [ + ([400.0, 300.0, 200.0, 100.0], BIG), + ([400.0, 300.0, 100.0, 100.0], [(450.0, 300.0), (500.0, 400.0), (400.0, 400.0)]), + ([300.0, 250.0, 200.0, 100.0], [(400.0, 250.0), (500.0, 350.0), (300.0, 350.0)]), + ]; + for (rect, want) in cases { + let p = json!({"kind": "triangle", "rect": rect}); + assert_eq!(path_anchors(&p), want); + let id = create(&mut s, p.clone()); + assert_eq!( + shape_path(&p).unwrap(), + match &s.active().unwrap().doc.layer(LayerId(id)).unwrap().content { + LayerContent::Shape(sh) => sh.path.clone(), + _ => panic!("not a shape layer"), + } + ); + } +} + +#[test] +fn a_negative_rect_gives_the_same_triangle_apex_up() { + let mut s = session(); + let id = create(&mut s, json!({"kind": "triangle", "rect": [600, 400, -200, -100]})); + assert_eq!(anchors(&info(&mut s, id)), BIG); +} + +#[test] +fn editing_the_radius_or_the_box_keeps_the_triangle() { + let mut s = session(); + let id = create(&mut s, json!({"kind": "triangle", "rect": [400, 300, 200, 100]})); + s.execute("shape.edit", json!({"layer": id, "cornerRadius": 20})).unwrap(); + let v = info(&mut s, id); + close(&anchors(&v), &ROUND, 1e-3); + assert_eq!(v["live"]["rect"], json!([400.0, 300.0, 200.0, 100.0])); + assert_eq!(v["live"]["corner_radius"], json!(20.0)); + s.execute("shape.edit", json!({"layer": id, "rect": [10, 10, 50, 80]})).unwrap(); + let v = info(&mut s, id); + assert_eq!((v["live"]["kind"].as_str(), v["live"]["corner_radius"].as_f64()), (Some("triangle"), Some(20.0))); + let before = v["live"].clone(); + s.execute("shape.edit", json!({"layer": id, "sides": 7, "starRatio": 0.3})).unwrap(); + assert_eq!(info(&mut s, id)["live"], before); +} + +/// `Session::execute` turns a command's panic into an `Err`, so a hostile-input test has to tell +/// that error from a graceful one. +fn graceful(r: &crate::Result) -> bool { + !matches!(r, Err(e) if e.to_string().contains("internal error")) +} + +#[test] +fn hostile_radii_never_panic() { + let mut s = session(); + let id = create(&mut s, json!({"kind": "triangle", "rect": [400, 300, 200, 100]})); + for r in [json!(-5), json!(1e300), json!("x")] { + let result = s.execute("shape.edit", json!({"layer": id, "cornerRadius": r})); + assert!(graceful(&result), "{result:?}"); + let r = info(&mut s, id)["live"]["corner_radius"].as_f64().unwrap(); + assert!(r.is_finite() && r >= 0.0, "{r}"); + } +} + +#[test] +fn hostile_boxes_never_panic() { + let mut s = session(); + let layers = s.active().unwrap().doc.layer_count(); + // Out of range, or not a box: refused, and no layer is added. + for rect in [json!([0, 0, 1e300, 1e300]), json!([1e300, 1e300, 10, 10]), json!([0, 0, 10]), json!([0, 0, "w", 10]), json!(null)] { + let result = s.execute("shape.create", json!({"kind": "triangle", "rect": rect, "cornerRadius": 20})); + assert!(result.is_err() && graceful(&result), "{result:?}"); + } + assert_eq!(s.active().unwrap().doc.layer_count(), layers); + // A box with no width or no height has no corner to round. + for rect in [[5, 5, 0, 0], [5, 5, 0, 50], [5, 5, 50, 0]] { + let result = s.execute("shape.create", json!({"kind": "triangle", "rect": rect, "cornerRadius": 20})); + assert!(graceful(&result), "{rect:?}: {result:?}"); + } +} + +#[test] +fn a_scale_keeps_the_triangle_live_and_a_flip_makes_it_a_path() { + let mut s = session(); + let id = create(&mut s, json!({"kind": "triangle", "rect": [400, 300, 200, 100], "cornerRadius": 10})); + s.execute("shape.edit", json!({"layer": id, "transform": [0.5, 0, 0, 0.5, 0, 0]})).unwrap(); + let v = info(&mut s, id); + assert_eq!(v["live"]["rect"], json!([200.0, 150.0, 100.0, 50.0])); + assert_eq!(v["live"]["corner_radius"], json!(5.0)); + let id = create(&mut s, json!({"kind": "triangle", "rect": [400, 300, 200, 100]})); + s.execute("shape.edit", json!({"layer": id, "transform": [1, 0, 0, -1, 0, 700]})).unwrap(); + let v = info(&mut s, id); + assert!(v["live"].is_null()); + assert_eq!(v["kind"], "path"); + assert_eq!(anchors(&v), [(500.0, 400.0), (600.0, 300.0), (400.0, 300.0)]); +} + +#[test] +fn a_three_sided_polygon_and_undo_are_unchanged() { + let mut s = session(); + let id = create(&mut s, json!({"kind": "polygon", "rect": [400, 300, 200, 100], "sides": 3})); + let v = info(&mut s, id); + close(&anchors(&v), &[(500.0, 300.0), (586.603, 375.0), (413.397, 375.0)], 1e-3); + assert_eq!(v["kind"], "polygon"); + + let id = create(&mut s, json!({"kind": "triangle", "rect": [400, 300, 200, 100]})); + s.execute("shape.edit", json!({"layer": id, "cornerRadius": 20})).unwrap(); + let before = info(&mut s, id); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("edit.redo", json!({})).unwrap(); + let after = info(&mut s, id); + assert_eq!((&after["live"], &after["path"]), (&before["live"], &before["path"])); +} diff --git a/crates/engine/src/cmd/vector_cmds/triangle_layer_name_tests.rs b/crates/engine/src/cmd/vector_cmds/triangle_layer_name_tests.rs new file mode 100644 index 0000000000..7c4376e64c --- /dev/null +++ b/crates/engine/src/cmd/vector_cmds/triangle_layer_name_tests.rs @@ -0,0 +1,70 @@ +//! The Triangle tool and Create Triangle name their shape layers Triangle N, not Polygon N (#13353). + +use serde_json::{Value, json}; + +use super::super::{LayerContent, LayerId, LiveShape, shape_path}; +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 160, "background": "white"})).unwrap(); + s +} + +/// The params the Triangle tool's drag and Create Triangle's OK send. +fn triangle(rect: [f64; 4]) -> Value { + json!({"kind": "triangle", "rect": rect}) +} + +fn name(info: &Value) -> &str { + info["name"].as_str().unwrap() +} + +#[test] +fn triangles_are_named_triangle_n() { + let mut s = session(); + let first = s.execute("shape.create", triangle([20.0, 20.0, 60.0, 40.0])).unwrap(); + let second = s.execute("shape.create", triangle([90.0, 30.0, 50.0, 50.0])).unwrap(); + assert_eq!((name(&first), name(&second)), ("Triangle 1", "Triangle 2")); +} + +#[test] +fn a_triangle_is_a_live_triangle_that_ignores_sides_and_star_ratio() { + let mut s = session(); + // Any `sides` or `starRatio` sent along is ignored: a triangle has 3 sides and no star. + let p = json!({"kind": "triangle", "rect": [20, 20, 60, 40], "sides": 7, "starRatio": 0.3, "cornerRadius": 4}); + let id = s.execute("shape.create", p.clone()).unwrap()["layer"].as_u64().unwrap(); + let LayerContent::Shape(sh) = &s.active().unwrap().doc.layer(LayerId(id)).unwrap().content else { panic!("not a shape layer") }; + assert_eq!(sh.live, Some(LiveShape::Triangle { rect: [20.0, 20.0, 60.0, 40.0], corner_radius: 4.0 })); + // The drag's preview and Path mode draw the same outline, which is not the inscribed 3-sided polygon. + assert_eq!(sh.path, shape_path(&p).unwrap()); + let polygon = json!({"kind": "polygon", "rect": [20, 20, 60, 40], "sides": 3, "cornerRadius": 4}); + assert_ne!(sh.path, shape_path(&polygon).unwrap()); +} + +#[test] +fn polygons_and_triangles_count_on_their_own() { + let mut s = session(); + let tri = s.execute("shape.create", triangle([20.0, 20.0, 60.0, 40.0])).unwrap(); + let poly = s.execute("shape.create", json!({"kind": "polygon", "rect": [90, 30, 50, 50], "sides": 5})).unwrap(); + let three = s.execute("shape.create", json!({"kind": "polygon", "rect": [90, 90, 50, 50], "sides": 3})).unwrap(); + assert_eq!((name(&tri), name(&poly), name(&three)), ("Triangle 1", "Polygon 1", "Polygon 2")); +} + +#[test] +fn an_explicit_name_wins() { + let mut s = session(); + let info = s.execute("shape.create", json!({"kind": "triangle", "rect": [20, 20, 60, 40], "name": "Roof"})).unwrap(); + assert_eq!(name(&info), "Roof"); +} + +#[test] +fn a_triangle_without_a_rect_is_refused() { + let mut s = session(); + let history = s.active().unwrap().history.past_len(); + for p in [json!({"kind": "triangle"}), json!({"kind": "triangle", "rect": "x"})] { + assert!(s.execute("shape.create", p.clone()).is_err(), "{p}"); + } + assert!(shape_path(&json!({"kind": "triangle"})).is_err()); + assert_eq!(s.active().unwrap().history.past_len(), history); +} diff --git a/crates/engine/src/cmd/video_cmds.rs b/crates/engine/src/cmd/video_cmds.rs index 9e49c108df..7bf065a037 100644 --- a/crates/engine/src/cmd/video_cmds.rs +++ b/crates/engine/src/cmd/video_cmds.rs @@ -433,7 +433,7 @@ fn load_frames(path: &str, fmt: photocraft_color::PixelFormat, opts: &photocraft Ok(()) }; for f in &files { - let bytes = std::fs::read(f).map_err(|e| EngineError::Other(format!("read `{}`: {e}", f.display())))?; + let bytes = crate::allocation::read_file_within(f, max_footage_bytes).map_err(|e| EngineError::Other(format!("read `{}`: {e}", f.display())))?; let name = f.to_string_lossy(); // A GIF (a still one is its only frame) or an animated WebP brings every frame. let animation = match photocraft_codecs::detect(&bytes) { diff --git a/crates/engine/src/cmd/warp_cmds.rs b/crates/engine/src/cmd/warp_cmds.rs index ae887cb7af..040468c819 100644 --- a/crates/engine/src/cmd/warp_cmds.rs +++ b/crates/engine/src/cmd/warp_cmds.rs @@ -560,9 +560,42 @@ pub fn split_warp(w: &Warp, at: Option<[f64; 2]>, how: Split) -> Option { } } }; + if ok && matches!(how, Split::Remove) { + restore_default_grid(&mut mesh); + } ok.then(|| Warp::custom(mesh, w.bounds)) } +/// After a split is removed: when what is left is the Default grid's thirds that a one-way split +/// made real (`commit_default_sections`) and nothing else, merge them back into the Default grid's +/// one patch, which draws them as guides again (#12912). Only when that loses nothing: splitting +/// the merged patch at the thirds must give back the same points, so thirds whose anchors or +/// handles were moved, or any other grid, stay as they are. The mesh doesn't record where its +/// sections came from, so a straight 3 x 1 (or 1 x 3) grid at exactly the thirds made another way +/// merges too; nothing is lost, as the Default grid draws the same lines as guides. +fn restore_default_grid(mesh: &mut BezierMesh) { + const THIRDS: [f64; 4] = [0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0]; + let is = |k: &[f64], want: &[f64]| k.len() == want.len() && k.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-9); + let columns = is(&mesh.us, &THIRDS) && is(&mesh.vs, &[0.0, 1.0]); + let rows = is(&mesh.vs, &THIRDS) && is(&mesh.us, &[0.0, 1.0]); + if !(columns || rows) { + return; + } + let mut merged = mesh.clone(); + let removed = if columns { merged.remove_split_u(2) && merged.remove_split_u(1) } else { merged.remove_split_v(2) && merged.remove_split_v(1) }; + if !removed { + return; + } + let mut again = merged.clone(); + let split = if columns { again.split_u(1.0 / 3.0) && again.split_u(2.0 / 3.0) } else { again.split_v(1.0 / 3.0) && again.split_v(2.0 / 3.0) }; + let same = split + && again.points.len() == mesh.points.len() + && again.points.iter().zip(&mesh.points).all(|(a, b)| (a[0] - b[0]).abs() < 1e-6 && (a[1] - b[1]).abs() < 1e-6); + if same { + *mesh = merged; + } +} + fn param_rect(p: &Value) -> [f64; 4] { let Some(r) = p.get("rect").and_then(Value::as_array) else { return [0.0, 0.0, 1.0, 1.0]; @@ -761,3 +794,7 @@ mod tests; #[cfg(test)] #[path = "warp_split_default_grid_tests.rs"] mod warp_split_default_grid_tests; + +#[cfg(test)] +#[path = "warp_remove_split_default_grid_tests.rs"] +mod warp_remove_split_default_grid_tests; diff --git a/crates/engine/src/cmd/warp_remove_split_default_grid_tests.rs b/crates/engine/src/cmd/warp_remove_split_default_grid_tests.rs new file mode 100644 index 0000000000..c7cdda0bce --- /dev/null +++ b/crates/engine/src/cmd/warp_remove_split_default_grid_tests.rs @@ -0,0 +1,95 @@ +//! #12912: removing the only split of a one-way split of the Default warp grid gives back the +//! Default grid (one patch, its thirds drawn as guides), for a horizontal and a vertical split. +//! Other grids, and thirds that were edited after the split, keep today's behaviour. + +use super::*; + +/// The 400 x 300 layer box of the issue, at (200, 150). +const BOX: [f64; 4] = [200.0, 150.0, 600.0, 450.0]; +const THIRDS: [f64; 4] = [0.0, 1.0 / 3.0, 2.0 / 3.0, 1.0]; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s +} + +/// Runs a split command on `mesh`, as the Free Transform warp session does. +fn split_cmd(s: &mut Session, cmd: &str, mesh: BezierMesh, at: [f64; 2]) -> BezierMesh { + let warp = serde_json::to_value(Warp::custom(mesh, BOX)).unwrap(); + let r = s.execute(cmd, json!({"warp": warp, "at": at})).unwrap(); + let out: Warp = serde_json::from_value(r["warp"].clone()).unwrap(); + out.mesh.unwrap() +} + +fn default_grid() -> BezierMesh { + BezierMesh::identity(BOX, 1, 1) +} + +fn assert_mesh_near(got: &BezierMesh, want: &BezierMesh) { + assert_eq!((got.us.len(), got.vs.len()), (want.us.len(), want.vs.len()), "{got:?}"); + assert_eq!(got.points.len(), want.points.len()); + for (g, w) in got.points.iter().zip(&want.points) { + assert!((g[0] - w[0]).abs() < 1e-6 && (g[1] - w[1]).abs() < 1e-6, "{g:?} != {w:?}"); + } +} + +#[test] +fn removing_the_only_horizontal_split_gives_back_the_default_grid() { + let mut s = session(); + let split = split_cmd(&mut s, "edit.transform.splitWarpHorizontally", default_grid(), [400.0, 320.0]); + assert_eq!((split.us.len(), split.vs.len()), (4, 3), "3 columns x 2 rows"); + let m = split_cmd(&mut s, "edit.transform.removeWarpSplit", split, [400.0, 320.0]); + assert_eq!((m.us.as_slice(), m.vs.as_slice()), ([0.0, 1.0].as_slice(), [0.0, 1.0].as_slice())); + assert_mesh_near(&m, &default_grid()); +} + +#[test] +fn removing_the_only_vertical_split_gives_back_the_default_grid() { + let mut s = session(); + let split = split_cmd(&mut s, "edit.transform.splitWarpVertically", default_grid(), [300.0, 200.0]); + assert_eq!((split.us.len(), split.vs.len()), (3, 4), "2 columns x 3 rows"); + let m = split_cmd(&mut s, "edit.transform.removeWarpSplit", split, [300.0, 200.0]); + assert_eq!((m.us.as_slice(), m.vs.as_slice()), ([0.0, 1.0].as_slice(), [0.0, 1.0].as_slice())); + assert_mesh_near(&m, &default_grid()); +} + +#[test] +fn a_bent_default_grid_comes_back_bent() { + // The whole Default patch warped before the split: the merge is exact, so it comes back as is. + let mut bent = default_grid(); + let nx = bent.nx(); + bent.points[1] = [bent.points[1][0], bent.points[1][1] - 40.0]; + bent.points[nx + 2] = [bent.points[nx + 2][0] + 25.0, bent.points[nx + 2][1]]; + let mut s = session(); + let split = split_cmd(&mut s, "edit.transform.splitWarpHorizontally", bent.clone(), [400.0, 320.0]); + // On the row line, halfway across: well clear of the column thirds. + let at = split.eval(0.5, split.vs[1]); + let m = split_cmd(&mut s, "edit.transform.removeWarpSplit", split, at); + assert_mesh_near(&m, &bent); +} + +#[test] +fn edited_thirds_are_kept() { + // An anchor on a third moved after the split: merging would lose it, so the columns stay. + let mut s = session(); + let mut split = split_cmd(&mut s, "edit.transform.splitWarpHorizontally", default_grid(), [400.0, 320.0]); + let nx = split.nx(); + split.points[3][0] += 20.0; + split.points[nx * 3 + 3][0] += 20.0; + let m = split_cmd(&mut s, "edit.transform.removeWarpSplit", split, [400.0, 320.0]); + assert_eq!(m.us, THIRDS.to_vec(), "the three columns stay"); + assert_eq!(m.vs, vec![0.0, 1.0], "the row line is removed"); +} + +#[test] +fn other_grids_keep_todays_behaviour() { + let mut s = session(); + // A 3 x 3 grid: removing one row line leaves 3 x 2. + let m = split_cmd(&mut s, "edit.transform.removeWarpSplit", BezierMesh::identity(BOX, 3, 3), [400.0, 250.0]); + assert_eq!((m.us.len(), m.vs.len()), (4, 3)); + // A 2 x 2 grid: removing its row line leaves 2 columns, not the Default grid. + let m = split_cmd(&mut s, "edit.transform.removeWarpSplit", BezierMesh::identity(BOX, 2, 2), [250.0, 300.0]); + assert_eq!((m.us.as_slice(), m.vs.as_slice()), ([0.0, 0.5, 1.0].as_slice(), [0.0, 1.0].as_slice())); +} diff --git a/crates/engine/src/cmd/web_cmds/optimizer.rs b/crates/engine/src/cmd/web_cmds/optimizer.rs index 2186f3b70a..73ac0325f8 100644 --- a/crates/engine/src/cmd/web_cmds/optimizer.rs +++ b/crates/engine/src/cmd/web_cmds/optimizer.rs @@ -155,6 +155,9 @@ pub fn optimize( if preview { look = rgba(&data, layout); } + // The profile only with Embed Color Profile on, as the WebP and JPEG branches do: Quick + // Export, which never sets it, writes no iCCP chunk (#13798). + let icc = icc.filter(|_| st.embed_icc); let img = photocraft_codecs::Image::from_u8(ww, hh, layout, data).map_err(e)?.with_icc(icc.map(<[u8]>::to_vec)).with_meta(meta()); let opts = photocraft_codecs::EncodeOptions { png_interlaced: st.interlaced, @@ -428,3 +431,7 @@ fn quantize_rows(px: &mut [[f32; 4]], w: usize, pal: &[[u8; 3]], dither: Dither, #[cfg(target_arch = "wasm32")] quantize_band(px, w, 0, pal, dither, amount, t) } + +#[cfg(test)] +#[path = "png_embed_icc_tests.rs"] +mod png_embed_icc_tests; diff --git a/crates/engine/src/cmd/web_cmds/png_embed_icc_tests.rs b/crates/engine/src/cmd/web_cmds/png_embed_icc_tests.rs new file mode 100644 index 0000000000..f295d8409a --- /dev/null +++ b/crates/engine/src/cmd/web_cmds/png_embed_icc_tests.rs @@ -0,0 +1,67 @@ +//! #13798: a Quick Export PNG carries no ICC profile, with Convert to sRGB on or off, and Save for +//! Web's PNG-24 embeds one only with Embed Color Profile on. The pixels are as before. + +use serde_json::json; + +use crate::Session; + +fn tmp(name: &str) -> String { + let d = std::env::temp_dir().join(format!("photocraft-png-icc-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d.to_string_lossy().into_owned() +} + +/// A red document with a wide-gamut profile (Adobe RGB) assigned. +fn tagged() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10, "background": "#c81e1e"})).unwrap(); + s.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); + assert!(s.active().unwrap().doc.icc_profile.is_some(), "the document has a profile"); + s +} + +/// The PNG's chunk types, in order. +fn chunks(bytes: &[u8]) -> Vec { + assert_eq!(bytes.get(..8), Some(b"\x89PNG\r\n\x1a\n".as_slice()), "a PNG"); + let mut out = Vec::new(); + let mut at = 8; + while let Some(head) = bytes.get(at..at + 8) { + let len = u32::from_be_bytes([head[0], head[1], head[2], head[3]]) as usize; + out.push(String::from_utf8_lossy(&head[4..8]).into_owned()); + at += 12 + len; + } + out +} + +fn pixels(path: &str) -> Vec { + let img = photocraft_codecs::decode(&std::fs::read(path).unwrap()).unwrap(); + img.convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8).data().to_vec() +} + +#[test] +fn a_quick_export_png_embeds_no_profile_with_convert_to_srgb_on_or_off() { + let dir = tmp("quick"); + let mut s = tagged(); + for convert in [true, false] { + s.execute("file.export.exportPreferences", json!({"quickExportFormat": "png", "metadata": "none", "convertToSrgb": convert})).unwrap(); + let path = format!("{dir}/convert-{convert}.png"); + s.execute("file.export.quickExport", json!({"path": path})).unwrap(); + let found = chunks(&std::fs::read(&path).unwrap()); + assert!(!found.iter().any(|c| c == "iCCP"), "convert {convert}: {found:?}"); + assert!(photocraft_codecs::decode(&std::fs::read(&path).unwrap()).unwrap().icc.is_none(), "convert {convert}"); + } + s.execute("prefs.reset", json!({"path": "export"})).unwrap(); +} + +#[test] +fn save_for_web_png24_embeds_the_profile_only_when_asked_and_keeps_its_pixels() { + let dir = tmp("sfw"); + let mut s = tagged(); + let (on, off) = (format!("{dir}/on.png"), format!("{dir}/off.png")); + s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "embedIcc": true, "path": on})).unwrap(); + s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "embedIcc": false, "path": off})).unwrap(); + assert!(chunks(&std::fs::read(&on).unwrap()).iter().any(|c| c == "iCCP"), "Embed Color Profile on"); + assert!(!chunks(&std::fs::read(&off).unwrap()).iter().any(|c| c == "iCCP"), "Embed Color Profile off"); + assert_eq!(pixels(&on), pixels(&off), "only the profile differs"); +} diff --git a/crates/engine/src/cmd/web_cmds/quick.rs b/crates/engine/src/cmd/web_cmds/quick.rs index 916a06f8d2..4341a7ed97 100644 --- a/crates/engine/src/cmd/web_cmds/quick.rs +++ b/crates/engine/src/cmd/web_cmds/quick.rs @@ -106,6 +106,9 @@ pub(super) fn quick_export(s: &mut Session, p: &Value) -> Result { "jpg" => { o.insert("format".into(), json!("jpeg")); o.insert("quality".into(), json!(prefs.jpeg_quality.min(100))); + // Quick Export JPGs are progressive (SOF2) at every quality, as the reference + // application writes them; Save for Web keeps its own checkbox (#13787). + o.insert("progressive".into(), json!(true)); } "gif" => { o.insert("format".into(), json!("gif")); @@ -114,7 +117,12 @@ pub(super) fn quick_export(s: &mut Session, p: &Value) -> Result { // WebP uses the regular exporter. Its optional quality is in the Photoshop-style // 0–12 save scale: invert that mapping so the codec receives the chosen 1–100. // Keeping quality absent preserves the historical lossless Quick Export behavior. - let (wdoc, _, _) = web_document(&doc, &json!({}), &WebSettings { convert_to_srgb: prefs.convert_to_srgb, ..Default::default() })?; + let st = WebSettings::from_params(&Value::Object(o.clone()), cmd)?; + let (mut wdoc, _, _) = web_document(&doc, &json!({}), &st)?; + // The regular exporter embeds the document's XMP and EXIF as they are: give it only + // what the metadata choice keeps, as the Save for Web formats get. + wdoc.metadata.xmp = web_xmp(&doc, st.metadata).map(std::sync::Arc::from); + wdoc.metadata.exif = web_exif(&doc, st.metadata).map(|e| std::sync::Arc::new(e.to_vec())); let quality = if prefs.webp_lossless { None } else { Some((f64::from(prefs.webp_quality.clamp(1, 100)) - 1.0) * 12.0 / 99.0) }; let warnings = crate::file_cmds::save_doc(&wdoc, &path, quality)?; crate::automate_cmds::fire_event(s, "export"); @@ -145,3 +153,7 @@ pub(super) fn quick_export(s: &mut Session, p: &Value) -> Result { crate::automate_cmds::fire_event(s, "export"); Ok(json!({"path": path, "format": fmt, "bytes": opt.bytes.len(), "warnings": web_warnings(&st, exif, wdoc.resolution_dpi)})) } + +#[cfg(test)] +#[path = "quick_jpg_progressive_tests.rs"] +mod quick_jpg_progressive_tests; diff --git a/crates/engine/src/cmd/web_cmds/quick_jpg_progressive_tests.rs b/crates/engine/src/cmd/web_cmds/quick_jpg_progressive_tests.rs new file mode 100644 index 0000000000..e394d3483c --- /dev/null +++ b/crates/engine/src/cmd/web_cmds/quick_jpg_progressive_tests.rs @@ -0,0 +1,108 @@ +//! Quick Export writes progressive JPGs (SOF2) at every quality, as the reference application +//! does, while Save for Web keeps its own Progressive checkbox, off by default (#13787). + +use super::*; + +fn tmp(name: &str) -> String { + let d = std::env::temp_dir().join(format!("photocraft-quick-jpg-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d.to_string_lossy().into_owned() +} + +/// A 64×48 8-bit document: a white background with a flat blue block over its left half. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "depth": 8, "name": "quick.psd", "background": "white"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 48})).unwrap(); + s.execute("edit.fill", json!({"color": "#3366cc"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +/// The marker of the file's frame header (0xC0 baseline, 0xC2 progressive), found by walking the +/// marker segments in front of the first scan. +fn sof_marker(bytes: &[u8]) -> Option { + let mut i = 2; + while i + 4 <= bytes.len() { + if bytes[i] != 0xFF { + return None; + } + let m = bytes[i + 1]; + if (0xC0..=0xCF).contains(&m) && !matches!(m, 0xC4 | 0xC8 | 0xCC) { + return Some(m); + } + if m == 0xDA { + return None; + } + let len = usize::from(u16::from_be_bytes([bytes[i + 2], bytes[i + 3]])); + i += 2 + len; + } + None +} + +fn rgba8(bytes: &[u8]) -> Vec { + let img = photocraft_codecs::decode(bytes).unwrap(); + assert_eq!(img.dimensions(), (64, 48)); + img.convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8).data().to_vec() +} + +fn max_channel_diff(a: &[u8], b: &[u8]) -> u8 { + assert_eq!(a.len(), b.len()); + a.iter().zip(b).map(|(x, y)| x.abs_diff(*y)).max().unwrap_or(0) +} + +#[test] +fn quick_export_jpg_is_progressive_at_every_quality() { + let dir = tmp("every_quality"); + let mut s = session(); + s.execute("file.export.exportPreferences", json!({"quickExportFormat": "jpg"})).unwrap(); + let convert = s.prefs().export.convert_to_srgb; + for q in [1, 14, 29, 43, 57, 71, 85, 100] { + s.execute("file.export.exportPreferences", json!({"jpegQuality": q})).unwrap(); + let quick = format!("{dir}/quick-{q}.jpg"); + s.execute("file.export.quickExport", json!({"path": quick})).unwrap(); + let quick = std::fs::read(&quick).unwrap(); + assert_eq!(sof_marker(&quick), Some(0xC2), "Quick Export at quality {q} is progressive"); + + // Only the scan layout changed: Save for Web's progressive output at the same settings + // decodes to the same pixels. + let settings = json!({"format": "jpeg", "quality": q, "metadata": "copyright", "convertToSrgb": convert, "matte": "#ffffff"}); + let web = format!("{dir}/web-{q}.jpg"); + let mut p = settings.clone(); + p["progressive"] = json!(true); + p["path"] = json!(web); + s.execute("file.export.saveForWebLegacy", p).unwrap(); + let diff = max_channel_diff(&rgba8(&quick), &rgba8(&std::fs::read(&web).unwrap())); + assert!(diff <= 2, "quality {q}: Quick Export and Save for Web pixels differ by {diff}"); + + // Save for Web keeps its own checkbox, off by default: baseline. + let baseline = format!("{dir}/baseline-{q}.jpg"); + let mut p = settings; + p["path"] = json!(baseline); + s.execute("file.export.saveForWebLegacy", p).unwrap(); + assert_eq!(sof_marker(&std::fs::read(&baseline).unwrap()), Some(0xC0), "Save for Web at quality {q} stays baseline by default"); + } +} + +#[test] +fn quick_export_jpg_opens_again_with_the_same_pixels() { + let dir = tmp("round_trip"); + let mut s = session(); + s.execute("file.export.exportPreferences", json!({"quickExportFormat": "jpg"})).unwrap(); + // The default quality, then the highest. + for q in [None, Some(100)] { + if let Some(q) = q { + s.execute("file.export.exportPreferences", json!({"jpegQuality": q})).unwrap(); + } + let path = format!("{dir}/round-{}.jpg", q.map_or_else(|| "default".to_string(), |q| q.to_string())); + s.execute("file.export.quickExport", json!({"path": path})).unwrap(); + let bytes = std::fs::read(&path).unwrap(); + assert_eq!(sof_marker(&bytes), Some(0xC2)); + // The blue half ends on a block edge, so every pixel is flat colour. + for (i, got) in rgba8(&bytes).as_chunks::<4>().0.iter().enumerate() { + let want = if i % 64 < 32 { [0x33, 0x66, 0xcc, 255] } else { [255, 255, 255, 255] }; + assert!(max_channel_diff(got, &want) <= 2, "quality {q:?}, pixel ({}, {}): {got:?}, want {want:?}", i % 64, i / 64); + } + } +} diff --git a/crates/engine/src/cmd/web_cmds/tests.rs b/crates/engine/src/cmd/web_cmds/tests.rs index 82c2a6c5a9..ef7e3c3ea6 100644 --- a/crates/engine/src/cmd/web_cmds/tests.rs +++ b/crates/engine/src/cmd/web_cmds/tests.rs @@ -1396,6 +1396,25 @@ fn embed_color_profile_tags_an_untagged_document_srgb() { } } +/// Quick Export as WebP goes through the regular exporter, which embeds a document's XMP and +/// EXIF whole: the export preferences' metadata choice must still apply to it. +#[test] +fn quick_export_webp_keeps_only_the_chosen_metadata() { + let dir = tmp("quick_webp_metadata"); + let mut s = session(8); + s.execute("file.fileInfo", json!({"copyright": "© Example", "description": "secret notes"})).unwrap(); + let has = |b: &[u8], needle: &[u8]| b.windows(needle.len()).any(|w| w == needle); + for (choice, lossless) in [("none", true), ("copyright", false)] { + s.execute("file.export.exportPreferences", json!({"quickExportFormat": "png", "metadata": choice, "webpLossless": lossless})).unwrap(); + let path = format!("{dir}/{choice}.webp"); + s.execute("file.export.quickExport", json!({"path": path})).unwrap(); + let bytes = std::fs::read(&path).unwrap(); + assert!(!has(&bytes, b"secret notes"), "{choice}: the description is not {choice}"); + assert_eq!(has(&bytes, b"Example"), choice == "copyright", "{choice}"); + } + s.execute("prefs.reset", json!({"path": "export"})).unwrap(); +} + /// #5305: `folder` writes the whole image there under the document's own name, so an action /// recorded with the suggested name saves each document it is played on under that name; it is /// a destination, never a remembered setting. diff --git a/crates/engine/src/dense_budget_tests.rs b/crates/engine/src/dense_budget_tests.rs new file mode 100644 index 0000000000..6103dfc818 --- /dev/null +++ b/crates/engine/src/dense_budget_tests.rs @@ -0,0 +1,91 @@ +//! Commands that expand a layer into dense buffers over its content bounds (or the canvas) refuse, +//! before allocating, when those buffers would pass the working budget: a few distant tiles in a +//! small document, or a huge empty canvas, would otherwise ask for terabytes. + +use std::sync::Arc; + +use photocraft_doc::{LayerId, LayerMask}; +use photocraft_geom::Rect; +use photocraft_raster::Surface; +use serde_json::json; + +use crate::Session; + +/// Two 10 px blocks two billion pixels apart: two stored tiles, trillions of pixels of bounds. +fn distant_blocks(s: &Surface) -> Surface { + let fmt = s.format(); + let mut out = Surface::with_default(fmt, &s.default_pixel()); + out.fill_rect(Rect::new(0, 0, 10, 10), &vec![1.0; fmt.channels()]); + out.fill_rect(Rect::new(2_000_000_000, 2_000_000_000, 2_000_000_010, 2_000_000_010), &vec![1.0; fmt.channels()]); + out +} + +/// A small document whose active layer holds [`distant_blocks`]. +fn sparse_session() -> (Session, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + let doc = Arc::make_mut(&mut s.active_mut().unwrap().doc); + let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + *surf = distant_blocks(surf); + (s, id) +} + +fn refused(s: &mut Session, cmd: &str, p: serde_json::Value) { + let before = s.active().unwrap().doc.clone(); + let e = s.execute(cmd, p).unwrap_err().to_string(); + assert!(e.contains("working memory"), "{cmd}: {e}"); + assert!(Arc::ptr_eq(&before, &s.active().unwrap().doc), "{cmd} left the document as it was"); +} + +#[test] +fn apply_layer_mask_over_distant_tiles_is_refused() { + let (mut s, id) = sparse_session(); + Arc::make_mut(&mut s.active_mut().unwrap().doc).layer_mut(id).unwrap().mask = Some(LayerMask::reveal_all()); + refused(&mut s, "layer.layerMask.apply", json!({"layer": id.0})); +} + +#[test] +fn shadows_highlights_over_distant_tiles_is_refused() { + let (mut s, id) = sparse_session(); + refused(&mut s, "image.adjustments.shadowsHighlights", json!({"layer": id.0})); +} + +#[test] +fn image_size_without_distant_tiles_still_resamples() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap(); + s.execute("image.imageSize", json!({"width": 128, "height": 128})).unwrap(); + assert_eq!(s.active().unwrap().doc.size.width, 128); +} + +#[test] +fn face_detection_on_a_huge_empty_canvas_is_refused() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300_000, "height": 300_000, "background": "transparent"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let e = s.execute("image.detectFaces", json!({"sampleAllLayers": false})).unwrap_err().to_string(); + assert!(e.contains("working memory"), "{e}"); +} + +#[test] +fn multichannel_on_a_huge_empty_canvas_is_refused() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 300_000, "height": 300_000, "background": "transparent"})).unwrap(); + refused(&mut s, "image.mode.multichannel", json!({})); +} + +/// A quadtone keeps an f32 density and a stored plane for each of its four inks beside the +/// flattened image: 52 B per pixel, past the budget at 15,000 × 15,000 px where one colour +/// channel's 28 B would have passed. +#[test] +fn multichannel_counts_every_duotone_ink() { + use photocraft_color::ColorMode; + use photocraft_doc::{Duotone, DuotoneInk}; + let mut s = Session::new(); + s.execute("file.new", json!({"width": 15_000, "height": 15_000, "background": "transparent"})).unwrap(); + let doc = Arc::make_mut(&mut s.active_mut().unwrap().doc); + doc.mode = ColorMode::Duotone; + doc.duotone = Some(Duotone { inks: (0..4).map(|i| DuotoneInk::new(format!("ink {i}"), [0.0; 3])).collect(), psd_raw: None }); + refused(&mut s, "image.mode.multichannel", json!({})); +} diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index 4f464b79d7..4d98747394 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -37,6 +37,10 @@ pub enum EngineError { SourceChanged { name: String }, #[error("{0}")] Other(String), + /// A batch or droplet stopped at its nesting or shared playback-step limit. A batch whose + /// step hits one fails that input instead of saving it unprocessed. + #[error("{0}")] + BatchLimit(String), /// A background job was cancelled (see [`jobs`]); nothing changed. #[error("cancelled")] Cancelled, diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs index 26fae8eeca..dd263e335a 100644 --- a/crates/engine/src/filters.rs +++ b/crates/engine/src/filters.rs @@ -213,7 +213,7 @@ pub(crate) fn apply_filter_to_surface_in( } // Image › Adjustments recorded as smart filters (Levels, Curves, Shadows/Highlights… from PSD). if let Some(kind) = id.strip_prefix("image.adjustments.") { - return Ok(crate::adjust_cmds::adjust_as_filter(kind, params, surf)); + return crate::adjust_cmds::adjust_as_filter(kind, params, surf, None); } // WebAssembly plug-in smart filters (plugin_cmds). if id == crate::plugin_cmds::RUN { diff --git a/crates/engine/src/filters_ext.rs b/crates/engine/src/filters_ext.rs index 467b3a8dc1..ebe352a05b 100644 --- a/crates/engine/src/filters_ext.rs +++ b/crates/engine/src/filters_ext.rs @@ -567,9 +567,13 @@ pub(crate) fn map_document(p: &Value) -> Option<&Value> { p.get("mapDocument").filter(|d| !d.is_null() && d.as_i64().is_none_or(|i| i >= 0)) } +/// Largest displacement-map file read (the same cap as imported presets). +const MAX_MAP_FILE_BYTES: u64 = 512 << 20; + /// Displace's map read from a file (flattened, or its `mapLayer`). fn map_from_path(path: &str, layer: Option) -> Result> { - let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("cannot read displacement map `{path}`: {e}")))?; + let bytes = + crate::allocation::read_file_within(path, MAX_MAP_FILE_BYTES).map_err(|e| EngineError::Other(format!("cannot read displacement map `{path}`: {e}")))?; let imported = crate::file_cmds::import(path, &bytes).map_err(|e| EngineError::Other(format!("cannot open displacement map `{path}`: {e}")))?; Ok(map_from_document(&imported, layer)) } diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index 31e29abe23..a20f0164e9 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -962,6 +962,7 @@ pub fn import_options(prefs: &crate::prefs::Preferences) -> photocraft_io::Impor photocraft_io::ImportOptions { max_group_depth: prefs.file_handling.rasterize_svg_groups_deeper_than as usize, demosaic: prefs.raw_defaults.demosaic.method(), + keep_raw: false, pdf_dpi: prefs.file_handling.pdf_dpi, pdf_pages: match (prefs.file_handling.pdf_first_page, prefs.file_handling.pdf_last_page) { (0, 0) => None, @@ -1260,6 +1261,8 @@ impl Session { let name_w = name.to_string(); let name_a = name.to_string(); let mut opts = import_options(self.prefs()); + // An interactive raw open keeps its sensor data for the Camera Raw dialog it may show. + opts.keep_raw = confirm_damage && self.prefs().raw_defaults.open_in_camera_raw; opts.psd_high_memory_approved = approve_high_memory; opts.psd_approved_estimate = approved_estimate; let test_memory_scope = photocraft_io::memory::TestMemoryScope::capture(); diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs index f89779954b..9f7c2c7873 100644 --- a/crates/engine/src/layer_style.rs +++ b/crates/engine/src/layer_style.rs @@ -512,7 +512,7 @@ pub fn contour_from_param(v: &Value) -> Option { /// The contours of an `.shc` contour preset file (Contour Editor › Load…), as `contour` params. /// Points are rescaled from the file's `0..=255` levels; unusable curves are skipped. pub fn contours_from_shc(bytes: &[u8]) -> Result> { - let file = photocraft_psd::shc::parse(bytes).map_err(|e| EngineError::Other(format!("not a contour file: {e}")))?; + let file = craft_psd::shc::parse(bytes).map_err(|e| EngineError::Other(format!("not a contour file: {e}")))?; Ok(file .into_iter() .filter_map(|c| { @@ -533,7 +533,7 @@ pub fn contour_to_shc(contour: &Contour) -> Result> { /// An `.shc` file holding every contour of `list` (Save Contours…). pub fn contour_to_shc_all(list: &[&Contour]) -> Result> { - let file: Vec = list + let file: Vec = list .iter() .map(|contour| { let (name, points) = match contour { @@ -543,12 +543,12 @@ pub fn contour_to_shc_all(list: &[&Contour]) -> Result> { let points = points .iter() .enumerate() - .map(|(i, p)| photocraft_psd::shc::ShcPoint { input: p.input * 255.0, output: p.output * 255.0, continuous: !contour.is_corner(i) }) + .map(|(i, p)| craft_psd::shc::ShcPoint { input: p.input * 255.0, output: p.output * 255.0, continuous: !contour.is_corner(i) }) .collect(); - photocraft_psd::shc::ShcContour { name, points } + craft_psd::shc::ShcContour { name, points } }) .collect(); - photocraft_psd::shc::write(&file).map_err(|e| EngineError::Other(format!("can't write the contour: {e}"))) + craft_psd::shc::write(&file).map_err(|e| EngineError::Other(format!("can't write the contour: {e}"))) } /// An effect of `kind` with its factory settings (before params are applied). diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 153009df3d..ef4eae9be2 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -372,6 +372,9 @@ mod tests; #[cfg(test)] mod fx_mode_tests; +#[cfg(test)] +mod dense_budget_tests; + #[cfg(test)] mod brush_clear_background_tests; pub mod command_hints; diff --git a/crates/engine/src/pixels.rs b/crates/engine/src/pixels.rs index a66a67b927..bb5f6924a5 100644 --- a/crates/engine/src/pixels.rs +++ b/crates/engine/src/pixels.rs @@ -537,12 +537,16 @@ pub fn remap_surface(s: &Surface, map: impl Fn(i32, i32) -> (i32, i32)) -> Surfa let r = s.content_bounds(); let mut out = Surface::with_default(s.format(), &s.default_pixel()); let n = s.channels(); - let raw = s.read_region(r); - let w = r.width() as usize; - for (i, px) in raw.chunks_exact(n).enumerate() { - let (x, y) = (r.x0 + (i % w) as i32, r.y0 + (i / w) as i32); - let (nx, ny) = map(x, y); - out.write_pixel(nx, ny, px); + // Tile by tile: unstored pixels read as the default `out` already has, and the content + // bounds of a sparse surface can span a grid of mostly nothing. + for tr in s.tiles().map(|(c, _)| c.rect().intersect(&r)).filter(|t| !t.is_empty()) { + let raw = s.read_region(tr); + let w = tr.width() as usize; + for (i, px) in raw.chunks_exact(n).enumerate() { + let (x, y) = (tr.x0 + (i % w) as i32, tr.y0 + (i / w) as i32); + let (nx, ny) = map(x, y); + out.write_pixel(nx, ny, px); + } } out } diff --git a/crates/engine/src/pixels/tests.rs b/crates/engine/src/pixels/tests.rs index f5330dfaa4..03efb8cb2c 100644 --- a/crates/engine/src/pixels/tests.rs +++ b/crates/engine/src/pixels/tests.rs @@ -468,3 +468,17 @@ fn full_coverage_keeps_the_edit_over_huge_hdr_values() { assert_eq!(out[..3], [a, a, a], "{a} over {o}"); } } + +/// Remapping walks the stored tiles, not the dense rectangle around them: two pixels a million +/// pixels apart (a ~4 TB rectangle) flip to their mirrored places. +#[test] +fn remap_surface_of_distant_tiles_does_not_densify_the_gap() { + let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true); + let mut s = Surface::new(fmt); + let (a, b) = ([1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0]); + s.write_pixel(-500_000, 3, &from_rgba(&fmt, a)); + s.write_pixel(500_000, 9, &from_rgba(&fmt, b)); + let out = remap_surface(&s, |x, y| (-x - 1, y)); + assert_eq!(out.pixel(499_999, 3), from_rgba(&fmt, a)); + assert_eq!(out.pixel(-500_001, 9), from_rgba(&fmt, b)); +} diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 0c717621f5..af7875acad 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -120,6 +120,11 @@ choice!( /// fastest and softest. Photoshop's Camera Raw has no such choice. RawDemosaic { Ahd = "ahd", Mhc = "mhc", Bilinear = "bilinear" } default Ahd ); +choice!( + /// MCP › When PhotoCraft Is Closed: what `photocraft-cli mcp` does when an + /// agent calls a tool and the app isn't running. + WhenAppClosed { Launch = "launch", Headless = "headless", Error = "error" } default Launch +); impl Unit { /// Document pixels → this unit. `dpi` is the document resolution, `extent` the 100% length @@ -1169,18 +1174,62 @@ impl Default for RawDefaults { } } +/// Before the agents switch, a Control Port other than 0 started the control server by itself. +/// A saved `integrations` section like that keeps its connection: the port now means "on, at this +/// port". Every reader of the saved section applies this (the app, its launch read, and +/// `photocraft-cli mcp`), so they agree. +pub fn migrate_integrations(section: &mut Value) { + if let Some(integrations) = section.as_object_mut() + && !integrations.contains_key("connectAgents") + && integrations.get("controlPort").and_then(Value::as_u64).is_some_and(|p| (1..=65535).contains(&p)) + { + integrations.insert("connectAgents".into(), json!(true)); + } +} + +/// A saved `integrations` section read as the app's preference load reads it: migrated, and +/// leniently (a value of the wrong type keeps its default, the rest still loads). The desktop +/// app's launch read and `photocraft-cli mcp` use it, so a bad value can't reset, say, When +/// PhotoCraft Is Closed for them alone. +pub fn read_integrations_section(mut section: Value) -> Integrations { + migrate_integrations(&mut section); + read_section(section) +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct Integrations { /// Allow agents to drive the app over the loopback control channel / MCP bridge. pub allow_agent_control: bool, - /// Default control port (0 = only when `--control` is given). + /// Port agents connect to (0 = any free port, published in the connection file). pub control_port: u32, + /// The folder automation may read from when no `--automation-read-root` is given (empty = + /// none). Applied at once while agents are connected. + pub read_root: String, + /// The folder automation may write to when no `--automation-write-root` is given (empty = + /// none). Applied at once while agents are connected. + pub write_root: String, + /// Without the suite's `AI-MCP` flag, agents may connect: the desktop app serves the control + /// protocol on loopback for `photocraft-cli mcp` without `--control`, and starts or stops it at + /// once when this changes (off by default; launch flags still win). Set from a saved Control + /// Port ([`migrate_integrations`]); not in the dialog. With the flag the ArtCraft Launcher's + /// switch decides instead. After the older fields, so a + /// section saved as a list still reads them where they were. + pub connect_agents: bool, + /// What `photocraft-cli mcp` does while agents may use the app but it is closed. + pub when_app_closed: WhenAppClosed, } impl Default for Integrations { fn default() -> Self { - Self { allow_agent_control: true, control_port: 0 } + Self { + allow_agent_control: true, + control_port: 0, + read_root: String::new(), + write_root: String::new(), + connect_agents: false, + when_app_closed: WhenAppClosed::Launch, + } } } @@ -1423,6 +1472,11 @@ impl Preferences { /// Set a value by dotted path, validating it. Unknown paths and wrong types are errors. pub fn set(&mut self, path: &str, value: Value) -> std::result::Result<(), String> { + // `set_path` skips empty segments, so `.alternateShortcuts.x` would reach the typed state + // below the per-path validators above; refuse such paths instead. + if path.split('.').any(str::is_empty) { + return Err(format!("invalid preference path `{path}`")); + } if path == "alternateShortcuts" { let obj = value.as_object().ok_or("`alternateShortcuts` maps command ids to lists of shortcuts")?; let mut map = BTreeMap::new(); @@ -1517,7 +1571,8 @@ impl Preferences { pub fn alternates(&self, id: &str, primary: Option<&str>) -> Vec { let main = primary.and_then(normalize_shortcut); let keys: Vec = match self.alternate_shortcuts.get(id) { - Some(list) => list.iter().filter_map(|s| normalize_shortcut(s)).collect(), + // A hand-edited settings file can hold more than `alternate_keys` admits. + Some(list) => list.iter().take(MAX_ALTERNATES).filter_map(|s| normalize_shortcut(s)).collect(), None => default_alternates(id).filter_map(normalize_shortcut).collect(), }; let mut out: Vec = Vec::with_capacity(keys.len()); @@ -1647,6 +1702,9 @@ impl Session { { *language = json!("sr-latn"); } + if let Some(integrations) = v.get_mut("integrations") { + migrate_integrations(integrations); + } let color = v.as_object_mut().and_then(|m| m.remove("colorSettings")); let presets = v.as_object_mut().and_then(|m| m.remove("presets")); let mut invalid = Vec::new(); diff --git a/crates/engine/src/prefs/tests.rs b/crates/engine/src/prefs/tests.rs index fd7e278370..aec791d96f 100644 --- a/crates/engine/src/prefs/tests.rs +++ b/crates/engine/src/prefs/tests.rs @@ -1134,6 +1134,19 @@ fn the_web_build_caps_memory_usage() { } } +#[test] +fn paths_with_empty_segments_cannot_skip_the_alternate_shortcut_limit() { + let mut prefs = Preferences::default(); + let many: Vec = (1..=100).map(|n| format!("F{n}")).collect(); + for path in [".alternateShortcuts", "alternateShortcuts..", ".alternateShortcuts.file.save", "interface..systemTitleBar"] { + assert!(prefs.set(path, json!({"file.save": many})).is_err(), "{path}"); + } + assert!(prefs.set("alternateShortcuts.file.save", json!(many)).is_err()); + assert!(prefs.alternate_shortcuts.is_empty()); + prefs.alternate_shortcuts.insert("file.save".into(), (1..=100).map(|n| format!("F{n}")).collect()); + assert!(prefs.alternates("file.save", None).len() <= MAX_ALTERNATES); +} + /// The effect cache budget is the stored MB in bytes, at least 16 MB (a hand-edited 0 included), /// at most 1536 MB on a 32-bit address space (the web, 32-bit Windows) and 65536 MB elsewhere, /// and never wraps: on wasm32 an uncapped 4096 MB shifted into `usize` was 0. Both kinds of @@ -1204,3 +1217,21 @@ fn an_effect_cache_above_the_cap_loads_clamped_and_does_not_block_apply() { assert_eq!(s.execute("prefs.get", json!({"path": "fileHandling.recentFileCount"})).unwrap(), json!(7), "{saved} MB"); } } + +/// A file from before the agents switch whose Control Port started the control server keeps +/// it on; one without a port, or that already says, is left as it is. +#[test] +fn a_saved_control_port_turns_the_agent_connection_on() { + let load = |text: &str| { + let mut session = Session::new(); + session.load_prefs_json(text).unwrap(); + session.prefs().integrations.clone() + }; + let legacy = load(r#"{"integrations":{"allowAgentControl":true,"controlPort":7878}}"#); + assert!(legacy.connect_agents); + assert_eq!(legacy.control_port, 7878); + assert!(!load(r#"{"integrations":{"controlPort":0}}"#).connect_agents); + assert!(!load(r#"{"integrations":{"controlPort":70000}}"#).connect_agents, "not a usable port"); + assert!(!load(r#"{"integrations":{"controlPort":7878,"connectAgents":false}}"#).connect_agents, "an explicit choice wins"); + assert!(!load("{}").connect_agents, "off by default"); +} diff --git a/crates/engine/src/prefs/validate.rs b/crates/engine/src/prefs/validate.rs index 57b89ff73f..771382084c 100644 --- a/crates/engine/src/prefs/validate.rs +++ b/crates/engine/src/prefs/validate.rs @@ -3,7 +3,7 @@ use super::{ AppearanceMode, Ask, CanvasBorder, CanvasColor, CheckerColors, CheckerSize, ColorPicker, DarkTheme, ExportLocation, ExportMetadata, FontPreview, GpuBackend, Interpolation, LightTheme, LineStyle, LinuxDisplayServer, LogDestination, LogDetail, OtherCursor, PaintingCursor, PlaybackPerformance, PointSize, PressureCurve, QuickExportFormat, RawColorSpace, RawDemosaic, RawDepth, RawSharpen, RenderingMode, RightClickPaint, TabletInput, TextEngine, - Theme, TypeUnit, UiFontSize, UiScale, Unit, Value, + Theme, TypeUnit, UiFontSize, UiScale, Unit, Value, WhenAppClosed, }; /// Preferences dialog sections in Photoshop's order: (id, title). @@ -102,6 +102,7 @@ pub fn choices(path: &str) -> Option<&'static [&'static str]> { "performance.gpuBackend" => GpuBackend::NAMES, "performance.linuxDisplayServer" => LinuxDisplayServer::NAMES, "performance.renderingMode" => RenderingMode::NAMES, + "integrations.whenAppClosed" => WhenAppClosed::NAMES, "actions.performance" => PlaybackPerformance::NAMES, _ => return None, }) diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rs index cc93556412..e8944984fd 100644 --- a/crates/engine/src/preset_store.rs +++ b/crates/engine/src/preset_store.rs @@ -222,7 +222,14 @@ impl PresetBackend for DirBackend { let path = self.path(name)?; let dir = path.parent().ok_or_else(|| format!("{name}: no parent directory"))?; std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; - photocraft_format::atomic_write(&path, bytes).map_err(|e| format!("{name}: {e}")) + // The document writer follows a symlink to the file it points at on purpose; a preset + // entry is managed by this store, and a link someone put there would carry the write + // outside the directory the store confines itself to. + if std::fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink()) { + return Err(format!("{name}: a symbolic link is not a preset file")); + } + // No-follow: a link swapped in after the check above is replaced, never written through. + photocraft_format::atomic_write_no_follow(&path, bytes).map_err(|e| format!("{name}: {e}")) } fn remove(&self, name: &str) -> Result<(), String> { match std::fs::remove_file(self.path(name)?) { diff --git a/crates/engine/src/preset_store/tests.rs b/crates/engine/src/preset_store/tests.rs index 7f0ead6c6b..f1b925a550 100644 --- a/crates/engine/src/preset_store/tests.rs +++ b/crates/engine/src/preset_store/tests.rs @@ -1,5 +1,5 @@ use super::*; -use photocraft_psd::abr::{AbrSample, LegacyBrush, LegacyTip, write_v12}; +use craft_psd::abr::{AbrSample, LegacyBrush, LegacyTip, write_v12}; use serde_json::json; use std::path::PathBuf; @@ -598,10 +598,10 @@ fn a_store_without_previews_makes_them_once_and_then_loads_lazily() { /// A v6 `.abr` whose presets sit in Photoshop folders (`phry`). fn abr_with_folders(presets: &[(&str, &[&str])]) -> Vec { - use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value}; + use craft_psd::descriptor::{Descriptor, UnicodeString, Value}; let descs: Vec = presets.iter().map(|(n, _)| Descriptor::new("brushPreset").with("Nm ", Value::Text(UnicodeString::new_nul(n)))).collect(); let folders: Vec> = presets.iter().map(|(_, f)| f.iter().map(|x| x.to_string()).collect()).collect(); - photocraft_psd::abr::write_v6_folders(2, &[], &[], &descs, &folders, true).unwrap() + craft_psd::abr::write_v6_folders(2, &[], &[], &descs, &folders, true).unwrap() } #[test] @@ -1136,3 +1136,21 @@ fn migration_preserves_duplicate_names_but_refuses_duplicate_ids() { assert!(mem.read(PATTERNS_FILE, 1 << 20).is_err()); assert_eq!(mem.read(LEGACY_PATTERNS_FILE, MAX_PATTERNS_BYTES).unwrap(), old); } + +/// A symlink planted among the presets must not carry a managed write to its target: the +/// document writer follows links on purpose, the store confines itself to its directory. +#[cfg(unix)] +#[test] +fn a_symlinked_preset_entry_is_refused_not_written_through() { + let dir = TempDir::new("symlink"); + std::fs::create_dir_all(&dir.0).unwrap(); + let outside = dir.0.join("outside.txt"); + std::fs::write(&outside, b"victim").unwrap(); + std::os::unix::fs::symlink(&outside, dir.0.join("planted.json")).unwrap(); + let be = DirBackend::new(&dir.0); + let e = be.write("planted.json", b"{}").unwrap_err(); + assert!(e.contains("symbolic link"), "{e}"); + assert_eq!(std::fs::read(&outside).unwrap(), b"victim"); + be.write("fresh.json", b"{}").unwrap(); + assert_eq!(be.read("fresh.json", 1024).unwrap(), b"{}"); +} diff --git a/crates/engine/src/presets.rs b/crates/engine/src/presets.rs index 1845daa6d0..aeb3bae90e 100644 --- a/crates/engine/src/presets.rs +++ b/crates/engine/src/presets.rs @@ -435,5 +435,9 @@ pub fn specs() -> Vec { pub(crate) fn call(s: &mut Session, id: &str, p: Value) -> Result { let spec = crate::commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; (spec.enabled)(s).map_err(|why| EngineError::Disabled(id.to_string(), why))?; + // A nested command answers to the session's authorization hook like a direct call. + if let Some(gate) = s.authorize { + gate(id, &p)?; + } (spec.run)(s, &p) } diff --git a/crates/engine/src/presets/clone_source.rs b/crates/engine/src/presets/clone_source.rs index 1ee1341330..13a94f721f 100644 --- a/crates/engine/src/presets/clone_source.rs +++ b/crates/engine/src/presets/clone_source.rs @@ -7,7 +7,11 @@ //! anchor (where the stroke started after the source was set) onto the source around the //! sample point: a 200 % width paints the source twice as wide, a 30° rotation paints it turned //! 30° counter-clockwise on screen (Photoshop's sense). +//! +//! A slot remembers the document its source was set in, so ⌥-clicking in one open document and +//! painting in another clones across them, as in Photoshop. +use photocraft_doc::{DocId, LayerId}; use photocraft_geom::Rect; use photocraft_paint::retouch::Region; use serde::{Deserialize, Serialize}; @@ -19,14 +23,28 @@ use crate::{Result, Session}; pub const SLOTS: usize = 5; +/// A stroke from a slot whose source document was closed. +pub(crate) const SOURCE_CLOSED: &str = "the clone source's document was closed: set a new source (Alt-click, or cloneSource.set)"; + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloneSource { /// Sample point (document px) set by ⌥-click. pub source: Option<[f64; 2]>, /// Destination point paired with `source` (first aligned stroke after setting it). pub anchor: Option<[f64; 2]>, - /// Layer the source was set on (informational, like the panel's document/layer line). + /// Mapping origin used by the last successful stroke or an explicit offset edit. + /// Kept separate so reporting an unaligned stroke does not change aligned sampling. + #[serde(default)] + pub last_anchor: Option<[f64; 2]>, + /// Layer picked with the source; Current Layer sampling reads this layer after switching targets. pub layer: Option, + /// Identity of the document picked with the source; absent in older saved slots. + #[serde(default)] + pub document: Option, + /// `document` was closed. Kept apart from the ID, because a document opened later can carry + /// the same one (a native copy keeps its original's), and it must not become the source. + #[serde(default)] + pub document_closed: bool, /// W and H in percent. pub scale: [f64; 2], /// Degrees, counter-clockwise. @@ -41,7 +59,19 @@ pub struct CloneSource { impl Default for CloneSource { fn default() -> Self { - CloneSource { source: None, anchor: None, layer: None, scale: [100.0, 100.0], rotation: 0.0, flip_h: false, flip_v: false, linked: false } + CloneSource { + source: None, + anchor: None, + last_anchor: None, + layer: None, + document: None, + document_closed: false, + scale: [100.0, 100.0], + rotation: 0.0, + flip_h: false, + flip_v: false, + linked: false, + } } } @@ -53,13 +83,27 @@ impl CloneSource { && !self.flip_h && !self.flip_v } - /// The panel's Offset X/Y: source − anchor (once a stroke paired them). + /// Offset X/Y of the most recently used pairing, in source-minus-destination document pixels. pub fn offset(&self) -> Option<[f64; 2]> { - Some([self.source?[0] - self.anchor?[0], self.source?[1] - self.anchor?[1]]) + let anchor = self.last_anchor.or(self.anchor)?; + Some([self.source?[0] - anchor[0], self.source?[1] - anchor[1]]) } - fn to_json(&self, i: usize) -> Value { + /// The other document a stroke in document `painting` samples: `None` when the source was + /// set in `painting` itself (or before slots remembered their document). + pub fn source_doc(&self, painting: Option) -> Option { + let id = self.document.filter(|d| Some(*d) != painting)?; + Some(SourceDoc { id, layer: self.layer.map(LayerId) }) + } + /// The source document's ID while it is still open: `None` once it was closed, even when a + /// document with the same ID was opened since. + pub fn open_document(&self) -> Option { + self.document.filter(|_| !self.document_closed) + } + /// `document` is the source document's index among the open documents (`null` when it was + /// closed or never recorded). + fn to_json(&self, i: usize, document: Option) -> Value { json!({ - "index": i, "source": self.source, "anchor": self.anchor, "offset": self.offset(), "layer": self.layer, + "index": i, "source": self.source, "anchor": self.anchor, "lastAnchor": self.last_anchor, "offset": self.offset(), "layer": self.layer, "document": document, "documentId": self.document, "width": self.scale[0], "height": self.scale[1], "linked": self.linked, "rotation": self.rotation, "flipH": self.flip_h, "flipV": self.flip_v, }) } @@ -95,18 +139,34 @@ impl CloneSources { pub fn active(&self) -> &CloneSource { &self.slots[self.active.min(SLOTS - 1)] } + /// Document `id` is closing: the slots set in it keep their point, but no longer read it or + /// a document opened later with the same ID ([`Session::close`]). + pub fn forget_doc(&mut self, id: DocId) { + for slot in self.slots.iter_mut().filter(|s| s.document == Some(id)) { + slot.document_closed = true; + } + } pub fn active_mut(&mut self) -> &mut CloneSource { &mut self.slots[self.active.min(SLOTS - 1)] } } +/// Another open document a clone source was set in, and the layer it was set on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SourceDoc { + pub id: DocId, + pub layer: Option, +} + /// How a clone stroke samples: destination `d` reads the source at -/// `source + m · (d − anchor)` (`m` row-major 2 × 2). +/// `source + m · (d − anchor)` (`m` row-major 2 × 2), in `document` when the source is in +/// another open document (`None`: the document being painted). #[derive(Clone, Copy, Debug, PartialEq)] pub struct Mapping { pub source: (f64, f64), pub anchor: (f64, f64), pub m: [f64; 4], + pub document: Option, } impl Mapping { @@ -151,28 +211,46 @@ pub fn transform_matrix(scale: [f64; 2], rotation_deg: f64, flip_h: bool, flip_v [f[3] / det, -f[1] / det, -f[2] / det, f[0] / det] } -fn pt(p: &Value, k: &str) -> Option<(f64, f64)> { - let a = p.get(k)?.as_array()?; - Some((a.first()?.as_f64()?, a.get(1)?.as_f64()?)) +/// Null optional coordinates are omitted. Geometry, sampling and commit metadata must agree +/// on this decision so an empty optional field cannot switch the source document. +pub(crate) fn uses_slot(p: &Value) -> bool { + ["source", "offset"].into_iter().all(|key| p.get(key).is_none_or(Value::is_null)) } /// Resolve a clone stroke's mapping from its params and the active slot. `first` is the /// stroke's first point. With `"aligned"` strokes the slot remembers the anchor so later /// strokes keep sampling relative to the original pairing. pub fn mapping(s: &mut Session, p: &Value, first: (f64, f64), cmd: &str) -> Result { - let (m, anchor) = resolve(s, p, first, cmd)?; - if let Some(a) = anchor { - s.presets.clone.active_mut().anchor = Some(a); - } + let (m, _) = resolve(s, p, first, cmd)?; + remember_mapping(s, p, &m); Ok(m) } +/// Record a successful slot-based stroke after its pixel edit succeeds. Explicit command sources +/// never overwrite a picked slot, and unaligned reporting never changes its aligned anchor. +pub fn remember_mapping(s: &mut Session, p: &Value, map: &Mapping) { + if !uses_slot(p) { + return; + } + let slot = s.presets.clone.active_mut(); + let anchor = [map.anchor.0, map.anchor.1]; + slot.last_anchor = Some(anchor); + if p.get("aligned").and_then(Value::as_bool).unwrap_or(true) { + slot.anchor = Some(anchor); + } +} + /// [`mapping`] without remembering anything: the mapping, and the anchor an aligned stroke from /// the slot stores (a live preview resolves the same mapping the commit will). pub fn resolve(s: &Session, p: &Value, first: (f64, f64), cmd: &str) -> Result<(Mapping, Option<[f64; 2]>)> { + // Explicit paint coordinates retain their existing wide range: an in-range far source + // clones transparency. Interactive slot edits use the smaller preview range below. + let source = input_point(p, "source", cmd)?; + let offset = input_point(p, "offset", cmd)?; + let anchor_param = input_point(p, "anchor", cmd)?.map(|a| (a[0], a[1])); let aligned = p.get("aligned").and_then(Value::as_bool).unwrap_or(true); let slot = s.presets.clone.active().clone(); - let explicit_tf = ["scale", "rotation", "flipH", "flipV"].iter().any(|k| p.get(*k).is_some()); + let explicit_tf = ["scale", "rotation", "flipH", "flipV"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); let m = if explicit_tf { let sc = p .get("scale") @@ -183,13 +261,12 @@ pub fn resolve(s: &Session, p: &Value, first: (f64, f64), cmd: &str) -> Result<( } else { transform_matrix(slot.scale, slot.rotation, slot.flip_h, slot.flip_v) }; - let anchor_param = pt(p, "anchor"); - if let Some(off) = pt(p, "offset") { + if let Some([dx, dy]) = offset { let a = anchor_param.unwrap_or(first); - return Ok((Mapping { source: (a.0 + off.0, a.1 + off.1), anchor: a, m }, None)); + return Ok((Mapping { source: (a.0 + dx, a.1 + dy), anchor: a, m, document: None }, None)); } - if let Some(src) = pt(p, "source") { - return Ok((Mapping { source: src, anchor: anchor_param.unwrap_or(first), m }, None)); + if let Some([sx, sy]) = source { + return Ok((Mapping { source: (sx, sy), anchor: anchor_param.unwrap_or(first), m, document: None }, None)); } let Some(src) = slot.source else { return Err(bad(cmd, "missing `source` ([x,y]) or `offset` ([dx,dy]); or set one with cloneSource.set")) }; let src = (src[0], src[1]); @@ -197,7 +274,11 @@ pub fn resolve(s: &Session, p: &Value, first: (f64, f64), cmd: &str) -> Result<( (true, Some(a)) => (a[0], a[1]), _ => first, }; - Ok((Mapping { source: src, anchor, m }, aligned.then_some([anchor.0, anchor.1]))) + if slot.document_closed { + return Err(bad(cmd, SOURCE_CLOSED)); + } + let document = slot.source_doc(s.active().map(|d| d.doc.id)); + Ok((Mapping { source: src, anchor, m, document }, aligned.then_some([anchor.0, anchor.1]))) } /// The Clone Source overlay's blend mode applied to one pixel: the source `src` over the image @@ -225,12 +306,12 @@ pub fn resample(src: &Region, dst: Rect, map: &Mapping, alpha: Option) -> let n = src.ch; let mut out = Region::new(dst, n); let w = dst.width() as usize; - let fetch = |x: i32, y: i32, buf: &mut [f32]| { - if x < src.rect.x0 || y < src.rect.y0 || x >= src.rect.x1 || y >= src.rect.y1 { + let fetch = |x: f64, y: f64, buf: &mut [f32]| { + if x < f64::from(src.rect.x0) || y < f64::from(src.rect.y0) || x >= f64::from(src.rect.x1) || y >= f64::from(src.rect.y1) { buf.fill(0.0); return; } - buf.copy_from_slice(src.px(x, y)); + buf.copy_from_slice(src.px(x as i32, y as i32)); if let Some(a) = alpha { let av = buf[a]; for (c, v) in buf.iter_mut().enumerate() { @@ -244,13 +325,20 @@ pub fn resample(src: &Region, dst: Rect, map: &Mapping, alpha: Option) -> for (i, px) in out.data.chunks_exact_mut(n).enumerate() { let (x, y) = (dst.x0 + (i % w) as i32, dst.y0 + (i / w) as i32); let (sx, sy) = map.map(x as f64 + 0.5, y as f64 + 0.5); + // Keep the bilinear neighbours in floating point until the source bounds check: + // saturating an off-canvas sample to i32::MAX then adding one used to overflow. + // Non-finite mappings have no source pixel and must not introduce NaN alpha. + if !sx.is_finite() || !sy.is_finite() { + px.fill(0.0); + continue; + } let (fx, fy) = (sx - 0.5, sy - 0.5); - let (x0, y0) = (fx.floor() as i32, fy.floor() as i32); - let (tx, ty) = ((fx - x0 as f64) as f32, (fy - y0 as f64) as f32); + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = ((fx - x0) as f32, (fy - y0) as f32); fetch(x0, y0, &mut q[0]); - fetch(x0 + 1, y0, &mut q[1]); - fetch(x0, y0 + 1, &mut q[2]); - fetch(x0 + 1, y0 + 1, &mut q[3]); + fetch(x0 + 1.0, y0, &mut q[1]); + fetch(x0, y0 + 1.0, &mut q[2]); + fetch(x0 + 1.0, y0 + 1.0, &mut q[3]); for c in 0..n { let top = q[0][c] + (q[1][c] - q[0][c]) * tx; let bot = q[2][c] + (q[3][c] - q[2][c]) * tx; @@ -271,45 +359,101 @@ pub fn resample(src: &Region, dst: Rect, map: &Mapping, alpha: Option) -> // ------------------------------------------------------------------ commands fn index(s: &Session, p: &Value, cmd: &str) -> Result { - match p.get("index").and_then(Value::as_u64) { - Some(i) if (i as usize) < SLOTS => Ok(i as usize), - Some(i) => Err(bad(cmd, format!("index {i} out of range (0..{SLOTS})"))), - None => Ok(s.presets.clone.active), + let i = match p.get("index") { + Some(v) if !v.is_null() => v.as_u64().and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad(cmd, "index must be a source-slot number"))?, + _ => s.presets.clone.active, + }; + if i < SLOTS { Ok(i) } else { Err(bad(cmd, format!("index {i} out of range (0..{SLOTS})"))) } +} + +/// Parse finite coordinate pairs without narrowing the legacy range of explicit paint commands. +fn input_point(p: &Value, key: &str, cmd: &str) -> Result> { + let Some(value) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) }; + let values = value.as_array().filter(|v| v.len() == 2).ok_or_else(|| bad(cmd, format!("{key} must be [x,y]")))?; + let point = values.first().and_then(Value::as_f64).zip(values.get(1).and_then(Value::as_f64)); + match point { + Some((x, y)) if x.is_finite() && y.is_finite() => Ok(Some([x, y])), + _ => Err(bad(cmd, format!("{key} coordinates must be finite"))), } } +/// Validate editable pixel coordinates before any slot is changed or an offset is added. +fn edit_point(p: &Value, key: &str, cmd: &str) -> Result> { + let point = input_point(p, key, cmd)?; + if point.is_some_and(|p| !valid_point(p)) { + return Err(bad(cmd, format!("{key} coordinates exceed the clone preview range"))); + } + Ok(point) +} + +/// Match the preview's coordinate range and reject sums that overflow or leave that range. +fn valid_point(point: [f64; 2]) -> bool { + point.into_iter().all(|v| v.is_finite() && v.abs() < 1_000_000.0) +} + +/// Describe a slot with both its stable document identity and its current open-tab index. +fn slot_json(s: &Session, i: usize) -> Value { + let slot = &s.presets.clone.slots[i.min(SLOTS - 1)]; + let document = slot.open_document().and_then(|id| s.documents().iter().position(|st| st.doc.id == id)); + slot.to_json(i, document) +} + +/// Report all slot geometry and stable identities with their current open-document indexes. fn list(s: &mut Session, _: &Value) -> Result { let c = &s.presets.clone; Ok( - json!({"active": c.active, "sources": c.slots.iter().enumerate().map(|(i, x)| x.to_json(i)).collect::>(), "overlay": serde_json::to_value(&c.overlay).unwrap_or(Value::Null)}), + json!({"active": c.active, "sources": (0..SLOTS).map(|i| slot_json(s, i)).collect::>(), "overlay": serde_json::to_value(&c.overlay).unwrap_or(Value::Null)}), ) } +/// Select a validated slot without changing its source, pairing or transform. fn select(s: &mut Session, p: &Value) -> Result { const CMD: &str = "cloneSource.select"; - let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad(CMD, "missing `index`"))? as usize; - if i >= SLOTS { - return Err(bad(CMD, format!("index {i} out of range (0..{SLOTS})"))); - } + p.get("index").filter(|v| !v.is_null()).ok_or_else(|| bad(CMD, "missing `index`"))?; + let i = index(s, p, CMD)?; s.presets.clone.active = i; - Ok(s.presets.clone.active().to_json(i)) + Ok(slot_json(s, i)) } +/// Validate a source/transform edit atomically, using the displayed reference for numeric offsets. fn set(s: &mut Session, p: &Value) -> Result { const CMD: &str = "cloneSource.set"; let i = index(s, p, CMD)?; - let active_layer = s.active().and_then(|d| d.active_layer).map(|l| l.0); - let slot = &mut s.presets.clone.slots[i]; - if let Some((x, y)) = pt(p, "source") { + let source = edit_point(p, "source", CMD)?; + let offset = edit_point(p, "offset", CMD)?; + let anchor = edit_point(p, "anchor", CMD)?; + if anchor.is_some() && offset.is_none() { + return Err(bad(CMD, "anchor requires an offset edit")); + } + let doc = match p.get("document").filter(|v| !v.is_null()) { + None => s.active(), + Some(value) => { + if source.is_none() { + return Err(bad(CMD, "document requires a source point")); + } + let index = value.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad(CMD, "document must be an open document index"))?; + Some(s.documents().get(index).ok_or_else(|| bad(CMD, "the source document is not open"))?) + } + }; + let (document, active_layer) = (doc.map(|st| st.doc.id), doc.and_then(|st| st.active_layer).map(|id| id.0)); + // Build the edited slot off to the side so a rejected coordinate or sum is atomic. + let mut slot = s.presets.clone.slots[i].clone(); + if let Some([x, y]) = source { // A new sample point re-pairs with the next stroke. slot.source = Some([x, y]); slot.anchor = None; + slot.last_anchor = None; slot.layer = p.get("layer").and_then(Value::as_u64).or(active_layer); + slot.document = document; + slot.document_closed = false; } - if let Some((dx, dy)) = pt(p, "offset") { - // Offset X/Y fields: keep the anchor (or the source as anchor) and move the source. - let a = slot.anchor.or(slot.source).ok_or_else(|| bad(CMD, "set a `source` before an offset"))?; + if let Some([dx, dy]) = offset { + // Edit the pairing shown in the panel, including an unaligned stroke or a live preview. + // Supplying its anchor does not paint; it makes the requested displacement explicit. + slot.source.ok_or_else(|| bad(CMD, "set a `source` before an offset"))?; + let a = anchor.or(slot.last_anchor).or(slot.anchor).or(slot.source).ok_or_else(|| bad(CMD, "set a `source` before an offset"))?; slot.anchor = Some(a); + slot.last_anchor = Some(a); slot.source = Some([a[0] + dx, a[1] + dy]); } if let Some(a) = p.get("scale").and_then(Value::as_array) { @@ -348,21 +492,27 @@ fn set(s: &mut Session, p: &Value) -> Result { slot.flip_v = b; } if p.get("clear").and_then(Value::as_bool) == Some(true) { - *slot = CloneSource::default(); + slot = CloneSource::default(); } + if [slot.source, slot.anchor, slot.last_anchor].into_iter().flatten().any(|p| !valid_point(p)) { + return Err(bad(CMD, "the edited clone coordinates exceed their range")); + } + s.presets.clone.slots[i] = slot; if p.get("select").and_then(Value::as_bool).unwrap_or(true) { s.presets.clone.active = i; } - Ok(s.presets.clone.slots[i].to_json(i)) + Ok(slot_json(s, i)) } +/// Reset scale/rotation/flips while retaining source identity and established pairings. fn reset_transform(s: &mut Session, p: &Value) -> Result { let i = index(s, p, "cloneSource.resetTransform")?; let slot = &mut s.presets.clone.slots[i]; (slot.scale, slot.rotation, slot.flip_h, slot.flip_v) = ([100.0, 100.0], 0.0, false, false); - Ok(slot.to_json(i)) + Ok(slot_json(s, i)) } +/// Update transient overlay appearance without editing image pixels or source geometry. fn overlay(s: &mut Session, p: &Value) -> Result { let o = &mut s.presets.clone.overlay; let flag = |k: &str| p.get(k).and_then(Value::as_bool); @@ -397,7 +547,7 @@ pub fn specs() -> Vec { label: "Clone Sources", menu: &[], shortcut: None, - params: "{} → {active,sources:[{index,source,anchor,offset,layer,width,height,linked,rotation,flipH,flipV}],overlay}", + params: "{} → {active,sources:[{index,source,anchor,lastAnchor,offset,layer,document,documentId,width,height,linked,rotation,flipH,flipV}],overlay}; offset is source minus the last used destination reference in document pixels", enabled: always, run: list, journal: false, @@ -417,7 +567,7 @@ pub fn specs() -> Vec { label: "Set Clone Source", menu: &[], shortcut: None, - params: r##"{"index":0..4?=active,"source":[x,y]? (⌥-click; re-pairs with the next stroke),"offset":[dx,dy]?,"width":%?,"height":%?|"scale":[w%,h%]?,"linked":bool? (W/H link: a lone width or height scales the other by the same factor),"rotation":deg?,"flipH":bool?,"flipV":bool?,"layer":id?,"clear":bool?,"select":bool=true}"##, + params: r##"{"index":0..4?=active,"source":[x,y]? (⌥-click; re-pairs with the next stroke),"offset":[dx,dy]? (source minus destination in document pixels),"anchor":[x,y]? (with offset: the preview/destination reference being edited; otherwise the last used reference),"width":%?,"height":%?|"scale":[w%,h%]?,"linked":bool? (W/H link: a lone width or height scales the other by the same factor),"rotation":deg?,"flipH":bool?,"flipV":bool?,"layer":id?,"document":open document index?=active (with source),"clear":bool?,"select":bool=true}"##, enabled: always, run: set, journal: true, @@ -453,11 +603,11 @@ mod tests { // Issue repro: a 3e9 source with a rotation makes the mapping a resample, // so source_rect sees mapped coordinates far outside i32. Must clamp, not // overflow (debug panic) or wrap (release, inverted rect). - let m = Mapping { source: (3_000_000_000.0, 0.0), anchor: (10.0, 10.0), m: transform_matrix([100.0, 100.0], 45.0, false, false) }; + let m = Mapping { source: (3_000_000_000.0, 0.0), anchor: (10.0, 10.0), m: transform_matrix([100.0, 100.0], 45.0, false, false), document: None }; let r = m.source_rect(Rect::new(0, 0, 24, 16)); assert!(r.x0 <= r.x1 && r.y0 <= r.y1, "rect must stay ordered: {r:?}"); // A negative source must clamp the same way. - let m = Mapping { source: (-3_000_000_000.0, 0.0), anchor: (10.0, 10.0), m: transform_matrix([100.0, 100.0], 45.0, false, false) }; + let m = Mapping { source: (-3_000_000_000.0, 0.0), anchor: (10.0, 10.0), m: transform_matrix([100.0, 100.0], 45.0, false, false), document: None }; let r = m.source_rect(Rect::new(0, 0, 24, 16)); assert!(r.x0 <= r.x1 && r.y0 <= r.y1, "rect must stay ordered: {r:?}"); } @@ -487,7 +637,24 @@ mod tests { #[test] fn source_rect_normal_case_unchanged() { - let m = Mapping { source: (200.0, 0.0), anchor: (10.0, 10.0), m: [1.0, 0.0, 0.0, 1.0] }; + let m = Mapping { source: (200.0, 0.0), anchor: (10.0, 10.0), m: [1.0, 0.0, 0.0, 1.0], document: None }; assert_eq!(m.source_rect(Rect::new(0, 0, 24, 16)), Rect::new(188, -12, 216, 8)); } + + #[test] + fn resample_extreme_sources_are_transparent_without_overflow_or_nan() { + let mut source = Region::new(Rect::new(0, 0, 2, 2), 4); + for px in source.data.as_chunks_mut::<4>().0.iter_mut() { + px.copy_from_slice(&[1.0, 0.0, 0.0, 1.0]); + } + for at in [(3.0e9, 0.0), (0.0, 3.0e9), (-3.0e9, 0.0), (f64::MAX, f64::MAX), (f64::INFINITY, 0.0), (f64::NAN, 0.0)] { + let map = Mapping { source: at, anchor: (0.0, 0.0), m: [1.0, 0.0, 0.0, 1.0], document: None }; + assert_eq!(resample(&source, Rect::new(0, 0, 1, 1), &map, Some(3)).data, vec![0.0; 4]); + } + // The unrepresentable left neighbour is transparent, while the neighbour at MIN + // remains valid. Do not saturate both neighbours onto the same edge pixel. + source.rect = Rect::new(i32::MIN, 0, i32::MIN + 2, 2); + let map = Mapping { source: (f64::from(i32::MIN) - 0.25, 0.0), anchor: (0.0, 0.0), m: [1.0, 0.0, 0.0, 1.0], document: None }; + assert_eq!(resample(&source, Rect::new(0, 0, 1, 1), &map, Some(3)).data, vec![1.0, 0.0, 0.0, 0.75]); + } } diff --git a/crates/engine/src/presets/gradients.rs b/crates/engine/src/presets/gradients.rs index 20cb95d95b..d9f5c6bf25 100644 --- a/crates/engine/src/presets/gradients.rs +++ b/crates/engine/src/presets/gradients.rs @@ -401,19 +401,28 @@ pub const STOP: &str = "gradient.presets.stop"; /// own. `None` when the caller gave `colors` (the legacy evenly spaced form `paint.gradient` /// handles itself). pub fn tool_stops(s: &Session, p: &Value) -> Result> { + Ok(tool_preset(s, p)?.map(|g| g.resolve(s.tools.foreground, s.tools.background))) +} + +/// The same gradient as [`tool_stops`] with its colour and opacity stops kept apart, for the +/// interpolation `method`, which treats the two differently. +pub fn tool_fill_stops(s: &Session, p: &Value) -> Result> { + Ok(tool_preset(s, p)?.map(|g| g.fill_stops(s.tools.foreground, s.tools.background))) +} + +fn tool_preset(s: &Session, p: &Value) -> Result> { const CMD: &str = "paint.gradient"; if p.get("colors").and_then(Value::as_array).is_some_and(|a| !a.is_empty()) { return Ok(None); } - let g = if let Some(name) = str_param(p, "gradient") { + Ok(Some(if let Some(name) = str_param(p, "gradient") { let (gi, ii) = find(&s.presets.gradients, name, None).ok_or_else(|| bad(CMD, format!("no gradient preset \"{name}\"")))?; s.presets.gradients[gi].items[ii].clone().with_transparency(p, CMD)? } else if p.get("stops").is_some() { GradientPreset::from_params("Custom", p, CMD)? } else { s.presets.gradient.clone().with_transparency(p, CMD)? - }; - Ok(Some(g.resolve(s.tools.foreground, s.tools.background))) + })) } /// The preset named by `"preset"` (else the current gradient), or explicit `"stops"`. diff --git a/crates/engine/src/presets/shapes/csh.rs b/crates/engine/src/presets/shapes/csh.rs index d9c83bca5a..290d1f0367 100644 --- a/crates/engine/src/presets/shapes/csh.rs +++ b/crates/engine/src/presets/shapes/csh.rs @@ -38,8 +38,8 @@ fn import(s: &mut Session, p: &Value) -> Result { false, move |ctx| { ctx.check()?; - let (bytes, stem) = crate::preset_import_cmds::file_bytes_limited(¶ms, CMD, ".csh file", photocraft_psd::csh::MAX_FILE_BYTES as u64)?; - let shapes = photocraft_psd::csh::parse(&bytes).map_err(|e| bad(CMD, e.to_string()))?; + let (bytes, stem) = crate::preset_import_cmds::file_bytes_limited(¶ms, CMD, ".csh file", craft_psd::csh::MAX_FILE_BYTES as u64)?; + let shapes = craft_psd::csh::parse(&bytes).map_err(|e| bad(CMD, e.to_string()))?; if shapes.is_empty() { return Err(bad(CMD, "the CSH set contains no shapes")); } diff --git a/crates/engine/src/presets/swatches.rs b/crates/engine/src/presets/swatches.rs index eb666e1ec5..d8fe6c194a 100644 --- a/crates/engine/src/presets/swatches.rs +++ b/crates/engine/src/presets/swatches.rs @@ -11,7 +11,7 @@ //! The library persists with the preferences document (`presets.swatches`, see //! [`super::PresetState::to_json`]). The default set is our own (clean-room): grays, pastels, //! pure and dark hues. The commands live in `crate::swatch_cmds`; file formats in -//! `photocraft_psd::{aco, ase}`. +//! `craft_psd::{aco, ase}`. use std::sync::Arc; diff --git a/crates/engine/src/presets/tests.rs b/crates/engine/src/presets/tests.rs index 88647ef23e..1774753c4e 100644 --- a/crates/engine/src/presets/tests.rs +++ b/crates/engine/src/presets/tests.rs @@ -817,9 +817,8 @@ fn clone_source_flip_scale_rotation() { let px = layer_px(&s, 42, 24); assert!((px[0] - 18.0 / 63.0).abs() < 0.02, "{px:?}"); s.execute("cloneSource.resetTransform", json!({})).unwrap(); - s.execute("cloneSource.set", json!({"source": [20, 20], "width": 200, "height": 200})).unwrap(); let mut s2 = clone_doc(16); - s2.presets.clone = s.presets.clone.clone(); + s2.execute("cloneSource.set", json!({"source": [20, 20], "width": 200, "height": 200})).unwrap(); s2.execute("paint.cloneStamp", json!({"points": [[40, 24]], "size": 21, "hardness": 100})).unwrap(); // 200 %: 4 px right of the anchor samples 2 px right of the source. let px = layer_px(&s2, 44, 24); @@ -995,3 +994,20 @@ fn export_presets_survive_a_presets_json_round_trip() { assert_eq!(restored.presets.export_presets[0].name, "Web"); assert_eq!(restored.presets.export_presets[0].settings.format, "jpg"); } + +/// A nested command a preset command runs answers to the session's authorization hook: a denied one +/// does not run, an ungated call still succeeds. +#[test] +fn nested_preset_commands_answer_to_the_authorization_gate() { + fn deny_select_all(id: &str, _: &Value) -> crate::Result<()> { + if id == "select.all" { Err(crate::EngineError::Other(format!("automation command `{id}` is disabled"))) } else { Ok(()) } + } + let mut s = session(8); + s.authorize = Some(deny_select_all); + let e = super::call(&mut s, "select.all", json!({})).unwrap_err().to_string(); + assert!(e.contains("is disabled"), "{e}"); + assert!(s.active().unwrap().doc.selection.is_none(), "the denied command did not run"); + s.authorize = None; + super::call(&mut s, "select.all", json!({})).unwrap(); + assert!(s.active().unwrap().doc.selection.is_some()); +} diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index b5b82a4753..fc3b1708aa 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -162,11 +162,13 @@ impl Session { } /// Add a document (from File → New, an import, etc.) and make it active. - /// Preserve its identity unless another open document already owns it. + /// Preserve its identity unless an open document or a picked clone source reserves it. /// Identity-dependent callers must read the admitted document at the returned index. pub fn add_document(&mut self, mut doc: Document, path: Option) -> usize { + // A saved copy can reuse a closed source's persisted ID. Give the new tab another ID so + // a closed clone source stays invalid until the user explicitly picks a new source. // Persisted IDs can overlap the allocator, so check every replacement too. - while self.docs.iter().any(|st| st.doc.id == doc.id) { + while self.docs.iter().any(|st| st.doc.id == doc.id) || self.presets.clone.slots.iter().any(|slot| slot.document == Some(doc.id)) { doc.id = photocraft_doc::DocId::fresh(); } self.open_document_order.push(doc.id); @@ -215,6 +217,7 @@ impl Session { self.cancel_jobs_on(id); self.subject_cache.forget_doc(id); self.object_finder.forget_doc(id); + self.presets.clone.forget_doc(id); self.link_missing.retain(|(d, _)| *d != id.0); self.link_scan = None; } diff --git a/crates/engine/tests/atn_mapped_identifiers.rs b/crates/engine/tests/atn_mapped_identifiers.rs index df643b2608..f2a2ed0f6e 100644 --- a/crates/engine/tests/atn_mapped_identifiers.rs +++ b/crates/engine/tests/atn_mapped_identifiers.rs @@ -1,10 +1,10 @@ //! Recorded identifiers must match Photoshop, even when a local round trip would accept a typo. -use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; -use photocraft_psd::{ +use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}, }; +use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; use serde_json::json; /// A small marked document makes canvas translation and image resampling distinguishable. diff --git a/crates/psd/tests/common/csh_fixture.rs b/crates/engine/tests/common/csh_fixture.rs similarity index 100% rename from crates/psd/tests/common/csh_fixture.rs rename to crates/engine/tests/common/csh_fixture.rs diff --git a/crates/engine/tests/content_aware_fill_atn.rs b/crates/engine/tests/content_aware_fill_atn.rs index 796982207f..fe15599c21 100644 --- a/crates/engine/tests/content_aware_fill_atn.rs +++ b/crates/engine/tests/content_aware_fill_atn.rs @@ -1,11 +1,11 @@ //! #10694: Content-Aware Fill options survive ATN load, save and playback. -use photocraft_doc::{LayerId, Rect}; -use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; -use photocraft_psd::{ +use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Descriptor, Id, UnicodeString, Value as D}, }; +use photocraft_doc::{LayerId, Rect}; +use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; use serde_json::{Value, json}; const FLAGS: [(&str, &str); 4] = [ diff --git a/crates/engine/tests/convert_profile_atn.rs b/crates/engine/tests/convert_profile_atn.rs index cf1f91b6de..a635979f1c 100644 --- a/crates/engine/tests/convert_profile_atn.rs +++ b/crates/engine/tests/convert_profile_atn.rs @@ -2,15 +2,15 @@ use std::sync::Arc; +use craft_psd::{ + atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, + descriptor::{Descriptor, Id, UnicodeString, Value as D}, +}; use photocraft_cms::Builtin; use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_doc::{Document, Layer, LayerContent, SmartObject, SmartSource}; use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; use photocraft_geom::{Affine, Size}; -use photocraft_psd::{ - atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, - descriptor::{Descriptor, Id, UnicodeString, Value as D}, -}; use photocraft_raster::Surface; use serde_json::{Value, json}; @@ -259,8 +259,8 @@ fn reference_recorded_convert_to_profile_maps() { let d = Descriptor::new("null") .with( "null", - D::Reference(vec![photocraft_psd::descriptor::ReferenceItem::Enumerated { - class: photocraft_psd::descriptor::Class { name: UnicodeString::new_nul(""), class_id: Id::new("Dcmn") }, + D::Reference(vec![craft_psd::descriptor::ReferenceItem::Enumerated { + class: craft_psd::descriptor::Class { name: UnicodeString::new_nul(""), class_id: Id::new("Dcmn") }, type_id: Id::new("Ordn"), value: Id::new("Trgt"), }]), diff --git a/crates/engine/tests/csh_import.rs b/crates/engine/tests/csh_import.rs index 3c6e8779dd..7c48d6a3a9 100644 --- a/crates/engine/tests/csh_import.rs +++ b/crates/engine/tests/csh_import.rs @@ -4,7 +4,7 @@ use photocraft_engine::Session; use serde_json::json; -#[path = "../../psd/tests/common/csh_fixture.rs"] +#[path = "common/csh_fixture.rs"] mod fixture; use fixture::{polygon_csh, triangle_csh}; diff --git a/crates/psd/tests/fixtures/atn/v12-commands.atn b/crates/engine/tests/fixtures/atn/v12-commands.atn similarity index 100% rename from crates/psd/tests/fixtures/atn/v12-commands.atn rename to crates/engine/tests/fixtures/atn/v12-commands.atn diff --git a/crates/engine/tests/image_size_scale_styles_atn.rs b/crates/engine/tests/image_size_scale_styles_atn.rs index 72b91241a4..633057d752 100644 --- a/crates/engine/tests/image_size_scale_styles_atn.rs +++ b/crates/engine/tests/image_size_scale_styles_atn.rs @@ -1,12 +1,12 @@ //! #10694: Image Size style scaling survives ATN import, playback and saving. -use photocraft_color::{BlendMode, Color}; -use photocraft_doc::{Effect, Effects, FxCommon, FxPaint, LayerId, StrokeFx, StrokePosition}; -use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; -use photocraft_psd::{ +use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Descriptor, Id, UnicodeString, Value as D}, }; +use photocraft_color::{BlendMode, Color}; +use photocraft_doc::{Effect, Effects, FxCommon, FxPaint, LayerId, StrokeFx, StrokePosition}; +use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; use serde_json::{Value, json}; fn recorded(event: &str, descriptor: Option) -> Vec { diff --git a/crates/engine/tests/it/actions_panel_menu.rs b/crates/engine/tests/it/actions_panel_menu.rs index 6b65f2f08d..02719d56af 100644 --- a/crates/engine/tests/it/actions_panel_menu.rs +++ b/crates/engine/tests/it/actions_panel_menu.rs @@ -143,7 +143,7 @@ fn inserted_menu_events_roundtrip_absent_settings_and_stateless_items_execute() let mut s = session(); s.execute("actions.insertMenuItem", json!({"action":"A","id":id,"eventKind":kind})).unwrap(); let bytes = atn_cmds::export("S", &[&s.actions.list[0]], &[], false).unwrap().0; - let raw = photocraft_psd::atn::parse(&bytes).unwrap(); + let raw = craft_psd::atn::parse(&bytes).unwrap(); assert!(raw.actions[0].items[0].descriptor.is_none()); let imported = atn_cmds::import(&bytes).unwrap(); let (step, params) = &imported.actions[0].steps[0]; @@ -152,7 +152,7 @@ fn inserted_menu_events_roundtrip_absent_settings_and_stateless_items_execute() assert_eq!(params["eventKind"], kind); let (saved, skipped) = atn_cmds::export("S", &[&imported.actions[0]], &[], false).unwrap(); assert!(skipped.is_empty()); - let saved = photocraft_psd::atn::parse(&saved).unwrap(); + let saved = craft_psd::atn::parse(&saved).unwrap(); assert_eq!(saved.actions[0].items[0], raw.actions[0].items[0]); let played = s.execute("actions.play", json!({"action":"A"})).unwrap(); assert_eq!(played.get("failed").is_none(), !atn_cmds::menu_item_needs_settings(id), "{id}: {played}"); @@ -166,16 +166,16 @@ fn inserted_menu_events_roundtrip_absent_settings_and_stateless_items_execute() assert!(s.execute("actions.insertMenuItem", params).is_err()); assert_eq!(s.actions, original); } - let mut raw = photocraft_psd::atn::AtnFile::default(); - raw.actions.push(photocraft_psd::atn::AtnAction { - items: vec![photocraft_psd::atn::AtnItem { - event: photocraft_psd::atn::AtnEvent::name("gaussianBlur"), - descriptor: Some(photocraft_psd::descriptor::Descriptor::new("null")), + let mut raw = craft_psd::atn::AtnFile::default(); + raw.actions.push(craft_psd::atn::AtnAction { + items: vec![craft_psd::atn::AtnItem { + event: craft_psd::atn::AtnEvent::name("gaussianBlur"), + descriptor: Some(craft_psd::descriptor::Descriptor::new("null")), ..Default::default() }], ..Default::default() }); - let loaded = atn_cmds::import(&photocraft_psd::atn::write(&raw).unwrap()).unwrap(); + let loaded = atn_cmds::import(&craft_psd::atn::write(&raw).unwrap()).unwrap(); assert_eq!(loaded.actions[0].steps[0].0, "filter.blur.gaussianBlur"); } diff --git a/crates/engine/tests/it/atn_adjustment_make_props.rs b/crates/engine/tests/it/atn_adjustment_make_props.rs index 3cd7475428..7048432330 100644 --- a/crates/engine/tests/it/atn_adjustment_make_props.rs +++ b/crates/engine/tests/it/atn_adjustment_make_props.rs @@ -1,9 +1,9 @@ //! #8384: an adjustment layer's Make step keeps the new layer's name (`Nm `), blend mode //! (`Md `) and clipping (`Grup`) on load, playback and save. +use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; +use craft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; use photocraft_doc::{BlendMode, LayerContent}; use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; -use photocraft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; -use photocraft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; use serde_json::{Value, json}; const NAME: &str = "Independent named adjustment"; diff --git a/crates/engine/tests/it/atn_calculations.rs b/crates/engine/tests/it/atn_calculations.rs index 7b9f16984e..063f69faa8 100644 --- a/crates/engine/tests/it/atn_calculations.rs +++ b/crates/engine/tests/it/atn_calculations.rs @@ -1,8 +1,8 @@ //! Recorded Calculations Make forms, using the measured reference and ScriptListener types. +use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; +use craft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; use photocraft_engine::actions_cmds::Action; use photocraft_engine::{Session, atn_cmds}; -use photocraft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; -use photocraft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; use serde_json::{Value, json}; fn class(id: &str) -> Class { diff --git a/crates/engine/tests/it/atn_classic_gradient.rs b/crates/engine/tests/it/atn_classic_gradient.rs index 709b7a7d90..88ae76f3c2 100644 --- a/crates/engine/tests/it/atn_classic_gradient.rs +++ b/crates/engine/tests/it/atn_classic_gradient.rs @@ -1,9 +1,9 @@ //! Synthetic measured-layout recordings through public ATN load/save and playback. -use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; -use photocraft_psd::{ +use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Descriptor, Id, UnicodeString, Value as D}, }; +use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; use serde_json::json; fn enm(ty: &str, value: &str) -> D { diff --git a/crates/engine/tests/it/atn_color_lookup.rs b/crates/engine/tests/it/atn_color_lookup.rs index edc58a2122..9d86a27cc9 100644 --- a/crates/engine/tests/it/atn_color_lookup.rs +++ b/crates/engine/tests/it/atn_color_lookup.rs @@ -1,7 +1,7 @@ +use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; +use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use photocraft_doc::{Adjustment, LayerContent}; use photocraft_engine::{Session, atn_cmds}; -use photocraft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; -use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use serde_json::json; const CUBE: &[u8] = b"LUT_3D_SIZE 2\n1 1 1\n0 1 1\n1 0 1\n0 0 1\n1 1 0\n0 1 0\n1 0 0\n0 0 0\n"; diff --git a/crates/engine/tests/it/atn_content_aware_fill.rs b/crates/engine/tests/it/atn_content_aware_fill.rs index bb175549b4..c5d6aaa46b 100644 --- a/crates/engine/tests/it/atn_content_aware_fill.rs +++ b/crates/engine/tests/it/atn_content_aware_fill.rs @@ -1,11 +1,11 @@ //! Recorded CAF settings use the native operation; unsupported descriptors stay whole. +use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; +use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use photocraft_engine::{ Session, actions_cmds::Action, atn_cmds::{export, import}, }; -use photocraft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; -use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use photocraft_raster::Surface; use serde_json::{Value, json}; diff --git a/crates/engine/tests/it/atn_crystallize_cell_size.rs b/crates/engine/tests/it/atn_crystallize_cell_size.rs index 8a015f1497..85bedf1ee6 100644 --- a/crates/engine/tests/it/atn_crystallize_cell_size.rs +++ b/crates/engine/tests/it/atn_crystallize_cell_size.rs @@ -1,7 +1,7 @@ //! #7669: strict ATN export must not replace a native fractional Crystallize cell size. +use craft_psd::{atn, descriptor::Value as D}; use photocraft_engine::actions_cmds::Action; use photocraft_engine::{Session, atn_cmds}; -use photocraft_psd::{atn, descriptor::Value as D}; use serde_json::{Value, json}; const CRYSTALLIZE: &str = "filter.pixelate.crystallize"; diff --git a/crates/engine/tests/it/atn_dialog_filters.rs b/crates/engine/tests/it/atn_dialog_filters.rs index 0e1b925820..a419188fe6 100644 --- a/crates/engine/tests/it/atn_dialog_filters.rs +++ b/crates/engine/tests/it/atn_dialog_filters.rs @@ -1,6 +1,6 @@ +use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; +use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use photocraft_engine::{Session, atn_cmds}; -use photocraft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; -use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use serde_json::{Value, json}; fn encoded(code: &[u8; 4], d: Descriptor) -> Vec { diff --git a/crates/engine/tests/it/atn_direct_adjustments.rs b/crates/engine/tests/it/atn_direct_adjustments.rs index 8f59433b9e..66fce5090f 100644 --- a/crates/engine/tests/it/atn_direct_adjustments.rs +++ b/crates/engine/tests/it/atn_direct_adjustments.rs @@ -1,9 +1,9 @@ //! Recorded direct Gradient Map and Replace Color forms from #10603 / #10607. -use photocraft_engine::{Session, atn_cmds}; -use photocraft_psd::{ +use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Descriptor, Id, UnicodeString, Value as D}, }; +use photocraft_engine::{Session, atn_cmds}; use serde_json::json; fn enumeration(kind: &str, value: &str) -> D { diff --git a/crates/engine/tests/it/atn_layer_style.rs b/crates/engine/tests/it/atn_layer_style.rs index 59b484022a..3cc35bfc73 100644 --- a/crates/engine/tests/it/atn_layer_style.rs +++ b/crates/engine/tests/it/atn_layer_style.rs @@ -1,14 +1,14 @@ //! Measured layer-style action steps retain their settings and use the existing native commands. +use craft_psd::{ + atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, + descriptor::{Class, Descriptor, Id, MAX_DEPTH, ObjectArray, ReferenceItem, UnicodeString, Value as D}, +}; use photocraft_doc::{Document, Effect, LayerId}; use photocraft_engine::{ Session, actions_cmds::Action, atn_cmds::{export, import}, }; -use photocraft_psd::{ - atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, - descriptor::{Class, Descriptor, Id, MAX_DEPTH, ObjectArray, ReferenceItem, UnicodeString, Value as D}, -}; use serde_json::{Value, json}; const SCALE: &str = "layer.layerStyle.scaleEffects"; diff --git a/crates/engine/tests/it/atn_newer_events.rs b/crates/engine/tests/it/atn_newer_events.rs index 302a0545c1..bb5adf300f 100644 --- a/crates/engine/tests/it/atn_newer_events.rs +++ b/crates/engine/tests/it/atn_newer_events.rs @@ -1,10 +1,10 @@ //! #10700: recorded Link and Unlink must not replay as a state-dependent toggle. -use photocraft_doc::{Layer, LayerContent, LayerId, SmartObject, SmartSource}; -use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; -use photocraft_psd::{ +use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}, }; +use photocraft_doc::{Layer, LayerContent, LayerId, SmartObject, SmartSource}; +use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; use serde_json::json; use std::sync::Arc; diff --git a/crates/engine/tests/it/atn_perspective_warp.rs b/crates/engine/tests/it/atn_perspective_warp.rs index 2967285842..0597150593 100644 --- a/crates/engine/tests/it/atn_perspective_warp.rs +++ b/crates/engine/tests/it/atn_perspective_warp.rs @@ -1,12 +1,12 @@ //! The measured Perspective Warp descriptor shape through ATN conversion and action playback. -use photocraft_doc::{LayerContent, LayerId}; -use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; -use photocraft_geom::Rect; -use photocraft_psd::{ +use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}, }; +use photocraft_doc::{LayerContent, LayerId}; +use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; +use photocraft_geom::Rect; use serde_json::{Value, json}; const EVENT: &str = "perspectiveWarpTransform"; diff --git a/crates/engine/tests/it/atn_reference_forms.rs b/crates/engine/tests/it/atn_reference_forms.rs index 0e35280eb7..3b2032b244 100644 --- a/crates/engine/tests/it/atn_reference_forms.rs +++ b/crates/engine/tests/it/atn_reference_forms.rs @@ -1,6 +1,6 @@ +use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; +use craft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; -use photocraft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; -use photocraft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; use serde_json::{Value, json}; fn class(name: &str) -> Class { diff --git a/crates/engine/tests/it/atn_review_regressions.rs b/crates/engine/tests/it/atn_review_regressions.rs index aabe913b22..3e3abdcc40 100644 --- a/crates/engine/tests/it/atn_review_regressions.rs +++ b/crates/engine/tests/it/atn_review_regressions.rs @@ -1,8 +1,8 @@ //! Public-API regressions for the dialog-event and Batch review findings. +use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; +use craft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; use photocraft_doc::LayerContent; use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; -use photocraft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; -use photocraft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}; use serde_json::{Value, json}; /// A bounded synthetic document for command and channel comparisons. diff --git a/crates/engine/tests/it/atn_ripple_amount.rs b/crates/engine/tests/it/atn_ripple_amount.rs index 0ff38f2036..eec6a46a69 100644 --- a/crates/engine/tests/it/atn_ripple_amount.rs +++ b/crates/engine/tests/it/atn_ripple_amount.rs @@ -1,7 +1,7 @@ //! #7670: integer ATN Ripple amounts must never silently replace native fractions. +use craft_psd::{atn, descriptor::Value as D}; use photocraft_engine::actions_cmds::Action; use photocraft_engine::{Session, atn_cmds}; -use photocraft_psd::{atn, descriptor::Value as D}; use serde_json::{Value, json}; const RIPPLE: &str = "filter.distort.ripple"; diff --git a/crates/engine/tests/it/atn_shape_blur.rs b/crates/engine/tests/it/atn_shape_blur.rs index df9a5b43eb..1dc3f05a5d 100644 --- a/crates/engine/tests/it/atn_shape_blur.rs +++ b/crates/engine/tests/it/atn_shape_blur.rs @@ -1,10 +1,10 @@ +use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; +use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use photocraft_doc::LayerContent; use photocraft_engine::{Session, atn_cmds}; -use photocraft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; -use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use serde_json::json; -#[path = "../../../psd/tests/common/csh_fixture.rs"] +#[path = "../common/csh_fixture.rs"] mod csh_fixture; const SHAPE_ID: &str = "original-fixture-square"; @@ -253,7 +253,7 @@ fn custom_shape_smart_filter_keeps_geometry_across_save_without_preset_library() fn imported_csh_id_resolves_in_an_action_after_reimport_and_preference_reload() { let mut s = fixture(16); let bytes = csh_fixture::triangle_csh(); - let id = photocraft_psd::csh::parse(&bytes).unwrap()[0].id.clone(); + let id = craft_psd::csh::parse(&bytes).unwrap()[0].id.clone(); let p = json!({"data":photocraft_paint::tile::b64_encode(&bytes)}); s.execute("shape.presets.importCsh", p.clone()).unwrap(); s.execute("shape.presets.importCsh", p).unwrap(); @@ -285,7 +285,7 @@ fn imported_csh_id_resolves_in_an_action_after_reimport_and_preference_reload() // This original fixture has the same ID but a different path. Keep both presets // available by their unique names, while refusing ambiguous action playback. let other = csh_fixture::polygon_csh(&[&[(0.25, 0.25), (0.75, 0.25), (0.75, 0.75), (0.25, 0.75)]]); - assert_eq!(photocraft_psd::csh::parse(&other).unwrap()[0].id, id); + assert_eq!(craft_psd::csh::parse(&other).unwrap()[0].id, id); s.execute("shape.presets.importCsh", json!({"data":photocraft_paint::tile::b64_encode(&other)})).unwrap(); let result = s.execute("actions.play", json!({"action":"Shape"})).unwrap(); assert_eq!(result["ran"], 0); diff --git a/crates/engine/tests/it/atn_shear.rs b/crates/engine/tests/it/atn_shear.rs index fb6e605d4d..30a0f9630a 100644 --- a/crates/engine/tests/it/atn_shear.rs +++ b/crates/engine/tests/it/atn_shear.rs @@ -1,11 +1,11 @@ //! Public load/save/playback witnesses for the measured Shear action mapping. +use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; +use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use photocraft_engine::{ Session, actions_cmds::Action, atn_cmds::{Imported, export, import}, }; -use photocraft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; -use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use serde_json::{Value, json}; fn desc(class: &str) -> Descriptor { diff --git a/crates/engine/tests/it/atn_stack_modes.rs b/crates/engine/tests/it/atn_stack_modes.rs index 2de2d887df..677cd07515 100644 --- a/crates/engine/tests/it/atn_stack_modes.rs +++ b/crates/engine/tests/it/atn_stack_modes.rs @@ -1,12 +1,12 @@ //! The measured Smart Object Stack Mode events retain their descriptor and native behavior. -use photocraft_doc::{Group, Layer, LayerContent, StackMode}; -use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; -use photocraft_geom::Rect; -use photocraft_psd::{ +use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Class, Descriptor, Id, UnicodeString, Value as D}, }; +use photocraft_doc::{Group, Layer, LayerContent, StackMode}; +use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; +use photocraft_geom::Rect; use serde_json::json; const APPLY: &str = "applyImageStackPluginRenderer"; diff --git a/crates/engine/tests/it/atn_stroke_width.rs b/crates/engine/tests/it/atn_stroke_width.rs index 3034fb2f0a..6d4a058f8f 100644 --- a/crates/engine/tests/it/atn_stroke_width.rs +++ b/crates/engine/tests/it/atn_stroke_width.rs @@ -1,7 +1,7 @@ //! #7671: exported Stroke widths must have the same effect as command execution. +use craft_psd::{atn, descriptor::Value as D}; use photocraft_engine::actions_cmds::Action; use photocraft_engine::{Session, atn_cmds}; -use photocraft_psd::{atn, descriptor::Value as D}; use serde_json::{Value, json}; /// Synthetic colours and partial transparency make lost edge pixels observable at every depth. diff --git a/crates/engine/tests/it/atn_type_path.rs b/crates/engine/tests/it/atn_type_path.rs index f5b565b849..3b37deece0 100644 --- a/crates/engine/tests/it/atn_type_path.rs +++ b/crates/engine/tests/it/atn_type_path.rs @@ -1,14 +1,14 @@ //! Recorded Type > Create Work Path preserves its descriptor and uses native glyph outlines. +use craft_psd::{ + atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, + descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}, +}; use photocraft_doc::{LayerContent, LayerId}; use photocraft_engine::{ Session, actions_cmds::Action, atn_cmds::{export, import}, }; -use photocraft_psd::{ - atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, - descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}, -}; use serde_json::{Value, json}; const COMMAND: &str = "type.createWorkPath"; diff --git a/crates/engine/tests/it/atn_v12.rs b/crates/engine/tests/it/atn_v12.rs index d5bc6d8263..353201c343 100644 --- a/crates/engine/tests/it/atn_v12.rs +++ b/crates/engine/tests/it/atn_v12.rs @@ -1,11 +1,11 @@ +use craft_psd::atn; use photocraft_engine::{Session, paint::tile::b64_encode}; -use photocraft_psd::atn; use serde_json::json; /// Legacy descriptor syntax must reach the same commands and parameters as version 16. #[test] fn legacy_v12_commands_import_like_v16() { - let bytes = include_bytes!("../../../psd/tests/fixtures/atn/v12-commands.atn"); + let bytes = include_bytes!("../fixtures/atn/v12-commands.atn"); let modern = atn::write(&atn::parse(bytes).unwrap()).unwrap(); let expected = vec![ ("filter.blur.gaussianBlur".into(), json!({"radius": 2.5})), diff --git a/crates/engine/tests/it/atn_video_frames.rs b/crates/engine/tests/it/atn_video_frames.rs index 43c9261ae1..64073763c9 100644 --- a/crates/engine/tests/it/atn_video_frames.rs +++ b/crates/engine/tests/it/atn_video_frames.rs @@ -1,10 +1,10 @@ //! #10723: recorded frame edits use the active video layer and the current playhead. -use photocraft_doc::{LayerContent, LayerId}; -use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; -use photocraft_psd::{ +use craft_psd::{ atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, descriptor::{Descriptor, UnicodeString, Value as D}, }; +use photocraft_doc::{LayerContent, LayerId}; +use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; use serde_json::json; use std::sync::Arc; diff --git a/crates/engine/tests/it/crop_delete_off_background.rs b/crates/engine/tests/it/crop_delete_off_background.rs index 96350d4a1c..5a0c4340ad 100644 --- a/crates/engine/tests/it/crop_delete_off_background.rs +++ b/crates/engine/tests/it/crop_delete_off_background.rs @@ -2,10 +2,10 @@ //! Photoshop does: it keeps the pixels past the canvas, and an extension is transparent on every //! layer. Delete on keeps the Background, and Image › Reveal All is unchanged (#10867). +use craft_psd::{atn, descriptor::Value as D}; use photocraft_engine::actions_cmds::Action; use photocraft_engine::{EngineError, Session, atn_cmds}; use photocraft_geom::Rect; -use photocraft_psd::{atn, descriptor::Value as D}; use serde_json::{Value, json}; const MAGENTA: [f32; 4] = [1.0, 0.0, 1.0, 1.0]; diff --git a/crates/engine/tests/it/photoshop_oracles.rs b/crates/engine/tests/it/photoshop_oracles.rs index 435bab8cc1..61b82d9cab 100644 --- a/crates/engine/tests/it/photoshop_oracles.rs +++ b/crates/engine/tests/it/photoshop_oracles.rs @@ -15,8 +15,8 @@ use std::path::{Path, PathBuf}; +use craft_psd::PsdFile; use photocraft_doc::{Document, LayerContent}; -use photocraft_psd::PsdFile; /// Within two 8-bit steps of Photoshop (same tolerance as the io corpus). const PASS_TOL: f32 = 2.0 / 255.0; diff --git a/crates/engine/tests/it/rasterize_psd_reopen.rs b/crates/engine/tests/it/rasterize_psd_reopen.rs index a39005ac14..981fd5895c 100644 --- a/crates/engine/tests/it/rasterize_psd_reopen.rs +++ b/crates/engine/tests/it/rasterize_psd_reopen.rs @@ -33,7 +33,7 @@ fn reopen(doc: &Document) -> Document { /// Whether the PSD written for `doc` gives the layer `name` any of `keys`. fn has_block(doc: &Document, name: &str, keys: &[&[u8; 4]]) -> bool { let out = photocraft_io::export(doc, "psd", &Default::default()).unwrap(); - let f = photocraft_psd::PsdFile::from_bytes(&out.bytes).unwrap(); + let f = craft_psd::PsdFile::from_bytes(&out.bytes).unwrap(); let rec = f.layers().iter().find(|r| r.name() == name).unwrap(); keys.iter().any(|k| rec.block(k).is_some()) } diff --git a/crates/engine/tests/it/rasterize_selected_layers.rs b/crates/engine/tests/it/rasterize_selected_layers.rs index a738b51681..265af58894 100644 --- a/crates/engine/tests/it/rasterize_selected_layers.rs +++ b/crates/engine/tests/it/rasterize_selected_layers.rs @@ -3,7 +3,7 @@ //! only on the one that was clicked. An explicit `layer` param still targets exactly that layer. use photocraft_doc::{LayerContent, LayerId}; -use photocraft_engine::Session; +use photocraft_engine::{EngineError, Session}; use serde_json::{Value, json}; fn kind(s: &Session, id: LayerId) -> &'static str { @@ -143,3 +143,141 @@ fn bad_targets_fail_gracefully() { assert!(sc.s.execute(id, json!({"layer": u64::MAX})).is_err(), "{id}: no such layer"); } } + +fn deny(denied: &'static str, id: &str) -> photocraft_engine::Result<()> { + if id == denied { Err(EngineError::Other("denied".into())) } else { Ok(()) } +} + +fn deny_shape_rasterize(id: &str, _: &Value) -> photocraft_engine::Result<()> { + deny("layer.rasterize.shape", id) +} + +fn deny_vector_mask_rasterize(id: &str, _: &Value) -> photocraft_engine::Result<()> { + deny("layer.rasterize.vectorMask", id) +} + +fn deny_type_rasterize(id: &str, _: &Value) -> photocraft_engine::Result<()> { + deny("type.rasterize", id) +} + +/// Everything a refused Rasterize has to leave as it was (#4974). +struct Snapshot { + doc: std::sync::Arc, + steps: usize, + journal: usize, + selection: Vec, +} + +impl Snapshot { + fn of(s: &mut Session) -> Snapshot { + // A clean document, and a redo entry that a step recorded by mistake would drop. + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let st = s.active().unwrap(); + assert!(st.history.can_redo(), "the test needs a redo entry"); + Snapshot { doc: st.doc.clone(), steps: st.history.past_len(), journal: s.journal.len(), selection: st.selected_layers() } + } + + fn assert_restored(&self, s: &Session) { + let st = s.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&st.doc, &self.doc), "the document is the one from before"); + assert_eq!(st.history.past_len(), self.steps); + assert!(st.history.can_redo(), "the redo entry survives"); + assert_eq!(s.journal.len(), self.journal); + assert!(!st.is_dirty()); + assert_eq!(st.selected_layers(), self.selection); + } +} + +impl Scene { + /// Leave a redo entry behind: a layer that was made, then undone. + fn make_redo_entry(&mut self) { + self.s.execute("layer.new.layer", json!({})).unwrap(); + assert!(self.s.undo()); + assert!(self.s.active().unwrap().history.can_redo()); + } +} + +#[test] +fn rasterize_layer_takes_back_a_converted_layer_when_a_later_one_is_refused() { + let mut sc = scene(); + // The type layer is lower, so it is converted first; the shape layer's step is then denied. + sc.select(&[sc.text, sc.shape]); + sc.make_redo_entry(); + let before = Snapshot::of(&mut sc.s); + sc.s.authorize = Some(deny_shape_rasterize); + assert!(sc.s.execute("layer.rasterize.layer", json!({})).is_err()); + assert_eq!(kinds(&sc.s, &[sc.text, sc.shape]), ["type", "shape"]); + before.assert_restored(&sc.s); + // Allowed again, the same command converts both in one step. + sc.s.authorize = None; + sc.s.execute("layer.rasterize.layer", json!({})).unwrap(); + assert_eq!(kinds(&sc.s, &[sc.text, sc.shape]), ["raster", "raster"]); + assert_eq!(sc.s.active().unwrap().history.past_len(), before.steps + 1); +} + +#[test] +fn rasterize_layer_takes_back_the_content_when_its_vector_mask_step_is_refused() { + let mut sc = scene(); + let square = json!({"subpaths": [{"closed": true, "knots": [[4, 4], [40, 4], [40, 30], [4, 30]]}]}); + sc.s.execute("layer.vectorMask.add", json!({"layer": sc.text.0, "path": square})).unwrap(); + sc.select(&[sc.text]); + sc.make_redo_entry(); + let before = Snapshot::of(&mut sc.s); + // The type content converts, then the mask step is denied. + sc.s.authorize = Some(deny_vector_mask_rasterize); + assert!(sc.s.execute("layer.rasterize.layer", json!({})).is_err()); + assert_eq!(kind(&sc.s, sc.text), "type"); + assert!(sc.s.active().unwrap().doc.layer(sc.text).unwrap().vector_mask.is_some()); + before.assert_restored(&sc.s); +} + +#[test] +fn rasterize_layer_style_takes_back_a_baked_layer_when_a_later_one_is_refused() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + let pixels = id_of(s.execute("layer.new.layer", json!({"name": "Pixels"})).unwrap()); + s.execute("paint.stroke", json!({"points": [[20, 20]], "size": 12})).unwrap(); + let shadow = json!({"blend": "normal", "distance": 4, "size": 2, "color": "#102040"}); + s.execute("layer.layerStyle.dropShadow", shadow.clone()).unwrap(); + let text = id_of(s.execute("type.create", json!({"text": "Hi", "size": 24, "x": 4, "y": 30})).unwrap()); + s.execute("layer.layerStyle.dropShadow", shadow).unwrap(); + let mut sc = Scene { s, text, shape: pixels, smart: pixels, fill: pixels, bystander: pixels }; + // The pixel layer is lower, so it is baked first; the type layer's content step is then denied. + sc.select(&[pixels, text]); + sc.make_redo_entry(); + let before = Snapshot::of(&mut sc.s); + sc.s.authorize = Some(deny_type_rasterize); + assert!(sc.s.execute("layer.rasterize.layerStyle", json!({})).is_err()); + let st = sc.s.active().unwrap(); + assert!(!st.doc.layer(pixels).unwrap().effects.items.is_empty(), "the baked layer has its effects back"); + assert_eq!(kind(&sc.s, text), "type"); + before.assert_restored(&sc.s); + sc.s.authorize = None; + sc.s.execute("layer.rasterize.layerStyle", json!({})).unwrap(); + assert!(sc.s.active().unwrap().doc.layer(pixels).unwrap().effects.items.is_empty()); + assert_eq!(kind(&sc.s, text), "raster"); +} + +#[test] +fn each_rasterize_command_names_its_history_step() { + let cases = [ + ("layer.rasterize.layer", "text", "Rasterize"), + ("layer.rasterize.type", "text", "Rasterize Type"), + ("layer.rasterize.shape", "shape", "Rasterize Shape"), + ("layer.rasterize.fillContent", "fill", "Rasterize Fill Content"), + ("layer.rasterize.smartObject", "smart", "Rasterize Smart Object"), + ]; + for (cmd, which, label) in cases { + let mut sc = scene(); + let id = match which { + "text" => sc.text, + "shape" => sc.shape, + "fill" => sc.fill, + _ => sc.smart, + }; + sc.select(&[id]); + sc.s.execute(cmd, json!({})).unwrap(); + assert_eq!(sc.s.active().unwrap().history.undo_label(), Some(label), "{cmd}"); + } +} diff --git a/crates/engine/tests/it/smart_duplicates.rs b/crates/engine/tests/it/smart_duplicates.rs index 554fd23f0f..acbf6c8979 100644 --- a/crates/engine/tests/it/smart_duplicates.rs +++ b/crates/engine/tests/it/smart_duplicates.rs @@ -261,7 +261,7 @@ fn inspect_and_replace_contents_report_shared_instances() { fn photoshop_placed_copies_import_as_shared_instances() { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/photoshop/smart-filters/sf-none-plain.psd"); let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e} (run `cargo xtask corpus --all`)", path.display())); - let mut file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let mut file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); let placed = file.layers().iter().find(|r| r.block(b"SoLd").is_some()).expect("a placed layer").clone(); file.layers_mut().push(placed); let mut s = Session::new(); diff --git a/crates/engine/tests/it/smart_psd.rs b/crates/engine/tests/it/smart_psd.rs index 542220f34b..429a487505 100644 --- a/crates/engine/tests/it/smart_psd.rs +++ b/crates/engine/tests/it/smart_psd.rs @@ -52,7 +52,7 @@ fn max_diff(a: &[[f32; 4]], b: &[[f32; 4]]) -> f32 { /// Every block with inner structure re-parses strictly (`TaggedBlock::check_structure`). fn structure_errors(bytes: &[u8]) -> Vec { - let f = photocraft_psd::PsdFile::from_bytes(bytes).unwrap(); + let f = craft_psd::PsdFile::from_bytes(bytes).unwrap(); let mut errs = Vec::new(); for b in &f.global_blocks { if let Err(e) = b.check_structure() { @@ -229,9 +229,9 @@ fn camera_raw_psd_fixture() { .smart_filters .iter() .position(|f| { - photocraft_io::smart_map::item_for_filter(f).ok().is_some_and( - |item| matches!(item.get("Fltr"), Some(photocraft_psd::descriptor::Value::Descriptor(d)) if d.class_id.is("Adobe Camera Raw Filter")), - ) + photocraft_io::smart_map::item_for_filter(f) + .ok() + .is_some_and(|item| matches!(item.get("Fltr"), Some(craft_psd::descriptor::Value::Descriptor(d)) if d.class_id.is("Adobe Camera Raw Filter"))) }) .expect("a Camera Raw filter"); let original_item = photocraft_io::smart_map::item_for_filter(&sm.smart_filters[index]).unwrap(); @@ -261,11 +261,11 @@ fn camera_raw_psd_fixture() { assert_eq!(after.params["exposure"], 0.5); let mut expected = original_item; let mut fltr = match expected.get("Fltr").unwrap() { - photocraft_psd::descriptor::Value::Descriptor(d) => d.clone(), + craft_psd::descriptor::Value::Descriptor(d) => d.clone(), _ => panic!("Fltr must be a descriptor"), }; - fltr.items.iter_mut().find(|(key, _)| key.is("Ex12")).unwrap().1 = photocraft_psd::descriptor::Value::Double(0.5); - expected.items.iter_mut().find(|(key, _)| key.is("Fltr")).unwrap().1 = photocraft_psd::descriptor::Value::Descriptor(fltr); + fltr.items.iter_mut().find(|(key, _)| key.is("Ex12")).unwrap().1 = craft_psd::descriptor::Value::Double(0.5); + expected.items.iter_mut().find(|(key, _)| key.is("Fltr")).unwrap().1 = craft_psd::descriptor::Value::Descriptor(fltr); assert_eq!(photocraft_io::smart_map::item_for_filter(after).unwrap(), expected, "only Exposure changes"); } @@ -291,8 +291,8 @@ fn smart_filters_survive_psd_in_every_colour_model() { assert_eq!(b.smart_filters.len(), 1, "{mode} {depth}"); assert_eq!(b.smart_filters[0].command, a.smart_filters[0].command); // The cache's unfiltered planes decode back to the unfiltered rendering. - let f = photocraft_psd::PsdFile::from_bytes(&out.bytes).unwrap(); - let fx = f.global_blocks.iter().find(|g| &g.key == b"FEid").map(|g| photocraft_psd::filter_effects::FilterEffects::parse(&g.data).unwrap()).unwrap(); + let f = craft_psd::PsdFile::from_bytes(&out.bytes).unwrap(); + let fx = f.global_blocks.iter().find(|g| &g.key == b"FEid").map(|g| craft_psd::filter_effects::FilterEffects::parse(&g.data).unwrap()).unwrap(); let item = &fx.items[0]; let (w, h) = item.rect.size().unwrap(); let bits = u16::try_from(item.depth).unwrap(); @@ -396,7 +396,7 @@ fn edited_psd_smart_objects_drop_their_old_file() { let parent = s2.documents().iter().position(|d| d.doc.layer(photocraft_doc::LayerId(id)).is_some()).unwrap(); let doc2 = s2.documents()[parent].doc.clone(); let second = photocraft_io::export(&doc2, "psd", &Default::default()).unwrap().bytes; - let f = photocraft_psd::PsdFile::from_bytes(&second).unwrap(); + let f = craft_psd::PsdFile::from_bytes(&second).unwrap(); let uuids: Vec = f.global_blocks.iter().filter(|b| &b.key == b"lnk2").flat_map(|b| photocraft_io::linked::block_uuids(&b.data)).collect(); let back = photocraft_io::import("b.psd", &second).unwrap().document; let (_, sm) = smart(&back); @@ -409,7 +409,7 @@ fn edited_psd_smart_objects_drop_their_old_file() { /// through, and keeps that map through PSD export, `.pcraft` and a PSD re-import. #[test] fn displace_psd_filter_renders_with_its_embedded_map() { - use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value}; + use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value}; for depth in [8, 16, 32] { let mut s = session(depth); s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); @@ -474,7 +474,7 @@ fn displace_psd_filter_renders_with_its_embedded_map() { /// that file and the replaced contents come out displaced. #[test] fn displace_psd_filter_with_only_a_map_path_renders_after_replace_contents() { - use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value}; + use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value}; let dir = std::env::temp_dir().join(format!("pcraft-9162-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let png = |name: &str, size: (u32, u32), c: [f32; 4]| { @@ -543,7 +543,7 @@ fn displace_psd_filter_with_only_a_map_path_renders_after_replace_contents() { /// its planes through PSD export, `.pcraft` and a PSD re-import. #[test] fn perspective_warp_psd_filter_renders_warped() { - use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value}; + use craft_psd::descriptor::{Descriptor, UnicodeString, Value}; let pnts = |p: &[[f64; 2]]| { let px = |v: f64| Value::UnitFloat { unit: *b"#Pxl", value: v }; Value::List(p.iter().map(|q| Value::Descriptor(Descriptor::new("Pnt ").with("Hrzn", px(q[0])).with("Vrtc", px(q[1])))).collect()) @@ -623,7 +623,7 @@ fn lifd_v2(f: &photocraft_io::linked::LinkedFile) -> Vec { /// version-2 items. fn cs2_layout(doc: &Document) -> Vec { let out = photocraft_io::export(doc, "psd", &Default::default()).unwrap(); - let mut file = photocraft_psd::PsdFile::from_bytes(&out.bytes).unwrap(); + let mut file = craft_psd::PsdFile::from_bytes(&out.bytes).unwrap(); for rec in file.layers_mut() { rec.blocks.retain(|b| !matches!(&b.key, b"SoLd" | b"SoLE")); } @@ -717,7 +717,7 @@ fn cs2_plld_only_smart_object_saves_its_new_transform() { s.execute("edit.transform", json!({"layer": id, "matrix": [0.75, 0, 0, 0.75, 10, 4]})).unwrap(); let cs2 = cs2_layout(&s.active().unwrap().doc); let plld = |bytes: &[u8]| { - let f = photocraft_psd::PsdFile::from_bytes(bytes).unwrap(); + let f = craft_psd::PsdFile::from_bytes(bytes).unwrap(); let rec = f.layers().iter().find(|l| l.block(b"PlLd").is_some()).cloned().expect("a placed layer"); (rec.block(b"PlLd").unwrap().data.clone(), rec.block(b"SoLd").is_some()) }; @@ -779,7 +779,7 @@ fn a_soft_filter_mask_is_stored_the_way_photoshop_stores_it() { let filtered = photocraft_engine::smart_cmds::render(&doc, &unmasked).unwrap().unwrap(); let out = photocraft_io::export(&doc, "psd", &Default::default()).unwrap(); - let file = photocraft_psd::PsdFile::from_bytes(&out.bytes).unwrap(); + let file = craft_psd::PsdFile::from_bytes(&out.bytes).unwrap(); let name = doc.layer(id).unwrap().name.clone(); let record = (0..file.layers().len()).filter_map(|i| file.layer(i)).find(|l| l.name() == name).unwrap(); let img = record.rgba8().unwrap(); diff --git a/crates/engine/tests/live_dab_matches_replay.rs b/crates/engine/tests/live_dab_matches_replay.rs index aae7e32b53..a7fca39818 100644 --- a/crates/engine/tests/live_dab_matches_replay.rs +++ b/crates/engine/tests/live_dab_matches_replay.rs @@ -157,7 +157,7 @@ fn smudge_pickup_matches_full_neighborhood_when_pressure_expands() { points: points.iter().map(|q| StrokePoint::new(q[0], q[1], q[2] as f32)).collect(), }; let mut effect = Smudge::new(0.8, None, 40.0).with_alpha(Some(3)); - apply_dab_stroke(&mut expected, &stroke, None, lock, 40, |work, fp| effect.dab(work, fp)); + apply_dab_stroke(&mut expected, &stroke, None, lock, 40, |work, fp| effect.dab(work, fp)).unwrap(); let bounds = s.active().unwrap().doc.bounds(); let want = expected.read_region(bounds); s.execute("paint.smudge", params.clone()).unwrap(); diff --git a/crates/engine/tests/memory_gate.rs b/crates/engine/tests/memory_gate.rs index a740012c76..9f6228e4f7 100644 --- a/crates/engine/tests/memory_gate.rs +++ b/crates/engine/tests/memory_gate.rs @@ -116,7 +116,7 @@ fn smart_object_render_that_does_not_fit_is_refused_by_name() { #[test] fn layered_psd_is_refused_before_decode_without_changing_the_document() { - use photocraft_psd::{Compression, LayerSpec, PixelData, PsdBuilder}; + use craft_psd::{Compression, LayerSpec, PixelData, PsdBuilder}; let room = Room::new(None); const SIDE: u32 = 256; @@ -182,7 +182,7 @@ fn small_flat_psd_still_places_and_renders() { /// memory is there. #[test] fn a_psd_with_image_resources_places_and_renders_when_it_fits() { - use photocraft_psd::{LayerSpec, PixelData, PsdBuilder}; + use craft_psd::{LayerSpec, PixelData, PsdBuilder}; let room = Room::new(Some(headroom::RESERVE + 256 * MIB)); const SIDE: u32 = 64; diff --git a/crates/engine/tests/multi_channel_editing.rs b/crates/engine/tests/multi_channel_editing.rs index 694151cbe3..fbb3de72a6 100644 --- a/crates/engine/tests/multi_channel_editing.rs +++ b/crates/engine/tests/multi_channel_editing.rs @@ -99,8 +99,9 @@ fn adjustments_filters_and_drawing_preserve_other_encoded_components() { let mut s = setup(mode, depth); subset(&mut s); let before = surface(&s); - // Color Replacement refuses 32-bit RGB, as the reference application does (#11923). - if *cmd == "paint.colorReplacement" && mode == "rgb" && depth == 32 { + // Color Replacement refuses 32-bit RGB (#11923), the Art History Brush every depth + // but 8 bits (#12637), as the reference application does. + if (*cmd == "paint.colorReplacement" && mode == "rgb" && depth == 32) || (*cmd == "paint.artHistoryBrush" && depth != 8) { assert!(s.execute(cmd, p.clone()).is_err(), "{mode} {depth} {cmd} is refused"); assert_eq!(surface(&s), before, "{mode} {depth} {cmd}: nothing changed"); continue; diff --git a/crates/engine/tests/paste_style_options.rs b/crates/engine/tests/paste_style_options.rs index af0f131dd8..fe2f599ca9 100644 --- a/crates/engine/tests/paste_style_options.rs +++ b/crates/engine/tests/paste_style_options.rs @@ -1,13 +1,13 @@ //! Paste Layer Style applies group eligibility consistently and preserves the ATN flag. +use craft_psd::{ + atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, + descriptor::{Class, Descriptor, Id, UnicodeString, Value as D}, +}; use photocraft_color::{BlendMode, Color, ColorMode, SampleType}; use photocraft_doc::{BlendRange, Document, Effect, Layer, LayerId}; use photocraft_engine::{Session, actions_cmds::Action, atn_cmds, layer_multi_cmds}; use photocraft_geom::Size; -use photocraft_psd::{ - atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, - descriptor::{Class, Descriptor, Id, UnicodeString, Value as D}, -}; use serde_json::{Value, json}; const CMD: &str = "layer.layerStyle.pasteLayerStyle"; diff --git a/crates/engine/tests/vector_paste_options.rs b/crates/engine/tests/vector_paste_options.rs index 0482a5ab99..3a77938342 100644 --- a/crates/engine/tests/vector_paste_options.rs +++ b/crates/engine/tests/vector_paste_options.rs @@ -18,14 +18,14 @@ fn raster_clip_cannot_silently_paste_as_path() { use std::sync::Arc; +use craft_psd::{ + atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, + descriptor::{Class, Descriptor, Id, UnicodeString, Value as D}, +}; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::{Fill, Layer, LayerContent, Path, Subpath}; use photocraft_engine::{actions_cmds::Action, atn_cmds, edit_cmds::Clip}; use photocraft_geom::{Point, Size}; -use photocraft_psd::{ - atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, - descriptor::{Class, Descriptor, Id, UnicodeString, Value as D}, -}; use serde_json::Value; const SVG: &[u8] = br##""##; diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index 5a77e24c34..801dcf8472 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -236,7 +236,14 @@ pub fn atomic_write_with(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, byt /// [`atomic_write_with`] reporting write progress (see [`atomic_write_progress`]). pub fn atomic_write_with_progress(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, bytes: &[u8], progress: &dyn Fn(f32)) -> io::Result<()> { - replace_with(fs, retry, path, &mut |tmp| fs.write_new_progress(tmp, bytes, progress)) + replace_with(fs, retry, path, true, &mut |tmp| fs.write_new_progress(tmp, bytes, progress)) +} + +/// [`atomic_write`] that never follows a symlink at `path`: a link there is replaced by the new +/// file (the rename swaps the directory entry), so a link planted between a caller's own check +/// and this write cannot carry it outside the folder (a store managing its own entries). +pub fn atomic_write_no_follow(path: &Path, bytes: &[u8]) -> io::Result<()> { + replace_with(&RealFs, RenameRetry::platform(), path, false, &mut |tmp| RealFs.write_new_progress(tmp, bytes, &|_| {})) } /// [`atomic_write`] for a file serialized as it is written (#6607): `write` fills the temporary @@ -261,7 +268,7 @@ pub fn atomic_write_stream_progress(path: &Path, expected_len: u64, progress: &d /// [`atomic_write_stream`] through an explicit file system and retry policy. pub fn atomic_write_stream_with(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, write: &mut StreamWriter<'_>) -> io::Result<()> { - replace_with(fs, retry, path, &mut |tmp| fs.write_new_stream(tmp, write)) + replace_with(fs, retry, path, true, &mut |tmp| fs.write_new_stream(tmp, write)) } /// A stream reporting how far it has got (see [`atomic_write_stream_progress`]), every @@ -304,8 +311,8 @@ impl Seek for Progress<'_, '_> { /// The steps every atomic write shares: `write_tmp` fills a fresh temporary file beside the /// target, which is then renamed over it. -fn replace_with(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, write_tmp: &mut dyn FnMut(&Path) -> io::Result<()>) -> io::Result<()> { - let target = resolve_symlink(path).map_err(|e| context(e, format!("cannot save {}", path.display())))?; +fn replace_with(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, follow: bool, write_tmp: &mut dyn FnMut(&Path) -> io::Result<()>) -> io::Result<()> { + let target = if follow { resolve_symlink(path).map_err(|e| context(e, format!("cannot save {}", path.display())))? } else { path.to_path_buf() }; let name = target.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", path.display())))?; let dir = match target.parent() { Some(d) if !d.as_os_str().is_empty() => d.to_path_buf(), @@ -340,7 +347,10 @@ fn replace_with(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, write_tmp: & // default, its extended attributes, and its ACL. Best effort, and before the swap, so the // file the user ends up with never passes through a more permissive state. let replacing = target.exists(); - if replacing { + // A link that is replaced rather than followed has nothing to carry over: reading the target's + // attributes would open whatever it points at (a FIFO with no writer blocks there). + let replaced_link = !follow && std::fs::symlink_metadata(&target).is_ok_and(|m| m.file_type().is_symlink()); + if replacing && !replaced_link { let _ = fs.copy_metadata(&target, &tmp); } diff --git a/crates/format/src/atomic/meta.rs b/crates/format/src/atomic/meta.rs index 1a7c5493b5..65870d55aa 100644 --- a/crates/format/src/atomic/meta.rs +++ b/crates/format/src/atomic/meta.rs @@ -51,6 +51,16 @@ const XATTR_CHUNK: usize = 4 << 10; /// Errors are the caller's to ignore: each piece is attempted on its own, and the first failure /// is returned only so a caller that wants to log one can. pub fn copy_metadata(from: &Path, to: &Path) -> io::Result<()> { + // The group first: on Linux `chown` drops `security.capability`, so it must not follow the + // extended-attribute copy. + #[cfg(unix)] + let metadata = std::fs::metadata(from); + #[cfg(unix)] + let group = match &metadata { + Ok(m) => restore_group(m, to), + Err(_) => Ok(true), + }; + // The permission bits go on last. Writing an attribute needs the destination open for // writing, and replacing a read-only (0444) file would copy that mode onto the temporary // file and then be unable to touch it again. @@ -72,9 +82,41 @@ pub fn copy_metadata(from: &Path, to: &Path) -> io::Result<()> { let acl = Ok(()); // A save over a 0600 file must not widen it to whatever the process default is. + // A failed group lookup counts as "group not kept": the mode is still copied, minus the group bits. + #[cfg(unix)] + let permissions = metadata.and_then(|m| set_permissions_keeping_group(&m, to, group.as_ref().copied().unwrap_or(false))); + #[cfg(not(unix))] let permissions = std::fs::metadata(from).and_then(|m| std::fs::set_permissions(to, m.permissions())); + #[cfg(unix)] + let group = group.map(drop); + #[cfg(not(unix))] + let group = Ok(()); - attributes.and(acl).and(created).and(permissions) + attributes.and(acl).and(created).and(group).and(permissions) +} + +/// Give `to` the group of the replaced file (`from`) when it has another: group bits are access +/// for *that* group, so on a replacement owned by a different one (a setgid folder, say) they +/// would hand the file to people the original never named. `false` when the group cannot be +/// restored (the owner is not a member): [`set_permissions_keeping_group`] then leaves the group +/// bits off. +#[cfg(unix)] +fn restore_group(from: &std::fs::Metadata, to: &Path) -> io::Result { + use std::os::unix::fs::MetadataExt; + Ok(std::fs::metadata(to)?.gid() == from.gid() || std::os::unix::fs::chown(to, None, Some(from.gid())).is_ok()) +} + +/// Give `to` the permission bits of the replaced file (`from`), without the group bits when +/// [`restore_group`] could not give it the original's group. +#[cfg(unix)] +fn set_permissions_keeping_group(from: &std::fs::Metadata, to: &Path, group_kept: bool) -> io::Result<()> { + use std::os::unix::fs::PermissionsExt; + let mut permissions = from.permissions(); + if !group_kept { + permissions.set_mode(permissions.mode() & !0o070); + } + // After the chown, which clears setuid/setgid. + std::fs::set_permissions(to, permissions) } /// The creation time ("Created" in Finder) of the file being replaced, onto the file replacing diff --git a/crates/format/src/atomic/meta/tests.rs b/crates/format/src/atomic/meta/tests.rs index b9571ee93b..5c460fa5d5 100644 --- a/crates/format/src/atomic/meta/tests.rs +++ b/crates/format/src/atomic/meta/tests.rs @@ -311,6 +311,34 @@ mod windows { } } +/// A replacement owned by another group does not give that group the file: the original's group +/// is restored, or its group bits are dropped when it cannot be. +#[cfg(unix)] +#[test] +fn a_replacement_in_another_group_does_not_widen_group_access() { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let d = TempDir::new("group"); + let original = d.join("a"); + let replacement = d.join("b"); + std::fs::write(&original, b"old").unwrap(); + std::fs::write(&replacement, b"new").unwrap(); + std::fs::set_permissions(&original, std::fs::Permissions::from_mode(0o660)).unwrap(); + // Another group this process belongs to; without one there is nothing to test. + let status = std::fs::read_to_string("/proc/self/status").unwrap_or_default(); + let own = std::fs::metadata(&original).unwrap().gid(); + let groups: Vec = + status.lines().find_map(|l| l.strip_prefix("Groups:")).unwrap_or_default().split_whitespace().filter_map(|g| g.parse().ok()).collect(); + // The original's group must be one this process can assign; a setgid parent can give it another. + let Some(other) = groups.iter().copied().find(|g| *g != own).filter(|_| groups.contains(&own)) else { + return; + }; + std::os::unix::fs::chown(&replacement, None, Some(other)).unwrap(); + super::copy_metadata(&original, &replacement).unwrap(); + let after = std::fs::metadata(&replacement).unwrap(); + assert_eq!(after.gid(), own, "the original's group is restored"); + assert_eq!(after.permissions().mode() & 0o777, 0o660); +} + // ---------------------------------------------------------------- MOVE_REPLACEMENT_2 ladder (#11178) // // The Windows `ReplaceFileW` cannot be made to return `ERROR_UNABLE_TO_MOVE_REPLACEMENT_2` on diff --git a/crates/format/src/atomic/tests.rs b/crates/format/src/atomic/tests.rs index aa95cca9f3..3b6b0bd2a8 100644 --- a/crates/format/src/atomic/tests.rs +++ b/crates/format/src/atomic/tests.rs @@ -496,6 +496,43 @@ fn writes_through_a_symlink() { assert_eq!(std::fs::read(&real).unwrap(), b"new"); } +#[cfg(unix)] +#[test] +fn no_follow_replaces_a_symlink_and_leaves_its_target() { + let d = TempDir::new("nofollow"); + let real = d.0.join("real.psd"); + let link = d.0.join("link.psd"); + std::fs::write(&real, ORIGINAL).unwrap(); + std::os::unix::fs::symlink(&real, &link).unwrap(); + crate::atomic::atomic_write_no_follow(&link, b"new").unwrap(); + assert!(!std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink()); + assert_eq!(std::fs::read(&link).unwrap(), b"new"); + assert_eq!(std::fs::read(&real).unwrap(), ORIGINAL); +} + +/// Replacing a link that points at a FIFO with no writer must not open the FIFO to copy its attributes. +#[cfg(unix)] +#[test] +fn no_follow_never_opens_the_target_of_a_replaced_link() { + let d = TempDir::new("nofollow-fifo"); + let fifo = d.0.join("pipe"); + let link = d.0.join("link.psd"); + let Ok(made) = std::process::Command::new("mkfifo").arg(&fifo).status() else { return }; + if !made.success() { + return; + } + std::os::unix::fs::symlink(&fifo, &link).unwrap(); + // Run apart, so a regression fails the test instead of hanging it. + let (tx, rx) = std::sync::mpsc::channel(); + let path = link.clone(); + std::thread::spawn(move || { + let _ = tx.send(crate::atomic::atomic_write_no_follow(&path, b"new")); + }); + let r = rx.recv_timeout(std::time::Duration::from_secs(20)).expect("the write does not block on the FIFO"); + r.unwrap(); + assert_eq!(std::fs::read(&link).unwrap(), b"new"); +} + /// #6605: saving onto a dangling symlink writes through to its target instead of replacing the /// link with a regular file, even when a folder on the way to the target doesn't exist yet. #[cfg(unix)] diff --git a/crates/format/src/autosave.rs b/crates/format/src/autosave.rs index 85798bea7d..2b2a7b0a2d 100644 --- a/crates/format/src/autosave.rs +++ b/crates/format/src/autosave.rs @@ -189,6 +189,18 @@ fn worker(rx: Receiver, bundle: PathBuf, sidecar: PathBuf, last: Arc Result<()> { + // The atomic writer follows a symlink at its destination; a link planted at the sidecar's + // name in the recovery folder must not redirect the write, so it is replaced, not followed. + if let Ok(meta) = std::fs::symlink_metadata(path) + && meta.file_type().is_symlink() + { + // Windows removes a directory symlink with `remove_dir`, not `remove_file`. + #[cfg(windows)] + let dir_link = std::os::windows::fs::FileTypeExt::is_symlink_dir(&meta.file_type()); + #[cfg(not(windows))] + let dir_link = false; + if dir_link { std::fs::remove_dir(path)? } else { std::fs::remove_file(path)? } + } struct SidecarFs; impl crate::atomic::AtomicFs for SidecarFs { // As before: Windows refuses a read-only sidecar up front, Unix replaces it. @@ -451,7 +463,13 @@ 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(craft_pcraft_format::TILES_DIR), path.join(craft_pcraft_format::BLOBS_DIR)]; + // A linked `tiles/` or `blobs/` is left alone: sweeping it would delete files elsewhere. + let real_dir = |p: PathBuf| std::fs::symlink_metadata(&p).is_ok_and(|m| m.is_dir()).then_some(p); + let parts: Vec = + [Some(path.clone()), real_dir(path.join(craft_pcraft_format::TILES_DIR)), real_dir(path.join(craft_pcraft_format::BLOBS_DIR))] + .into_iter() + .flatten() + .collect(); // 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); @@ -631,4 +649,34 @@ mod tests { assert!(dir.join("first.pcraft").is_dir()); let _ = std::fs::remove_dir_all(&dir); } + + #[cfg(unix)] + #[test] + fn symlinks_in_the_recovery_folder_are_replaced_or_skipped_never_followed() { + let dir = std::env::temp_dir().join(format!( + "pcraft-links-{}-{}", + std::process::id(), + SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0) + )); + let outside = dir.join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + // A sidecar name that links to a file elsewhere: the write replaces the link. + let victim = outside.join("victim.txt"); + std::fs::write(&victim, b"keep").unwrap(); + let sidecar = dir.join("k.json"); + std::os::unix::fs::symlink(&victim, &sidecar).unwrap(); + write_sidecar(&sidecar, b"{}").unwrap(); + assert_eq!(std::fs::read(&victim).unwrap(), b"keep"); + assert_eq!(std::fs::read(&sidecar).unwrap(), b"{}"); + // A bundle whose `tiles` links elsewhere: the sweep leaves the linked folder's files. + let stale = outside.join(".x.4294967294-0.pcsave.tmp"); + std::fs::write(&stale, b"tmp").unwrap(); + let bundle = dir.join("doc-1.pcraft"); + std::fs::create_dir_all(&bundle).unwrap(); + std::os::unix::fs::symlink(&outside, bundle.join(craft_pcraft_format::TILES_DIR)).unwrap(); + std::fs::write(dir.join("doc-1.json"), b"{}").unwrap(); + sweep_orphans(&dir, std::time::Duration::ZERO); + assert!(stale.is_file(), "files behind a linked tiles folder are not swept"); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs index 9fc41cb6a4..5e82af0d81 100644 --- a/crates/format/src/convert.rs +++ b/crates/format/src/convert.rs @@ -160,13 +160,18 @@ fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM { // 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, + Some(photocraft_doc::LiveShape::ArrowLine { .. } | photocraft_doc::LiveShape::Triangle { .. }) => None, other => other.clone(), }, arrow_live: match &s.live { Some(arrow @ photocraft_doc::LiveShape::ArrowLine { .. }) => Some(arrow.clone()), _ => None, }, + // Likewise for a triangle: older builds cannot read the kind, so they open its path. + triangle_live: match &s.live { + Some(triangle @ photocraft_doc::LiveShape::Triangle { .. }) => Some(triangle.clone()), + _ => None, + }, density: s.density, feather: s.feather, }, @@ -495,11 +500,16 @@ impl Loader<'_> { warp: warp.clone(), }) } - ContentM::Shape { fill, cache, psd_raw, path, stroke, live, arrow_live, density, feather } => LayerContent::Shape(ShapeLayer { + ContentM::Shape { fill, cache, psd_raw, path, stroke, live, arrow_live, triangle_live, density, feather } => LayerContent::Shape(ShapeLayer { path: path.clone(), fill: fill.clone(), stroke: stroke.clone(), - live: arrow_live.as_ref().filter(|shape| matches!(shape, photocraft_doc::LiveShape::ArrowLine { .. })).cloned().or_else(|| live.clone()), + live: arrow_live + .as_ref() + .filter(|shape| matches!(shape, photocraft_doc::LiveShape::ArrowLine { .. })) + .or_else(|| triangle_live.as_ref().filter(|shape| matches!(shape, photocraft_doc::LiveShape::Triangle { .. }))) + .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/lib.rs b/crates/format/src/lib.rs index d1e701d0ff..c046804332 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -33,6 +33,7 @@ mod finite; mod import_conversion; pub mod manifest; mod migrate; +mod noreplace; pub mod read; mod store; pub mod zip; @@ -42,12 +43,13 @@ use std::path::Path; use photocraft_doc::Document; use photocraft_raster::Rgba8Image; -pub use atomic::{atomic_write, atomic_write_progress, atomic_write_stream, atomic_write_stream_progress}; +pub use atomic::{atomic_write, atomic_write_no_follow, atomic_write_progress, atomic_write_stream, atomic_write_stream_progress}; #[cfg(not(target_arch = "wasm32"))] pub use autosave::RecoveryStore; pub use autosave::{Autosaver, RecoveryEntry, discard_recovery, list_recovery, recover}; pub use convert::MAX_GROUP_DEPTH; pub use manifest::{FORMAT_VERSION, Manifest}; +pub use noreplace::{PublishNewError, rename_noreplace, write_noreplace}; pub use read::{read_file, read_file_limited}; pub use store::{ByteSource, DEFAULT_REVERIFY_BUDGET, PcraftWriter, SaveStats, read_entry}; diff --git a/crates/format/src/manifest.rs b/crates/format/src/manifest.rs index d57bc4e31e..7a7002f958 100644 --- a/crates/format/src/manifest.rs +++ b/crates/format/src/manifest.rs @@ -288,6 +288,10 @@ pub enum ContentM { /// Older PhotoCraft versions ignore this optional field. #[serde(default, skip_serializing_if = "Option::is_none")] arrow_live: Option, + /// A live triangle, stored apart from `live` because builds from before the kind cannot + /// read it there; they ignore this field and open the shape as its saved path. + #[serde(default, skip_serializing_if = "Option::is_none")] + triangle_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/src/noreplace.rs b/crates/format/src/noreplace.rs new file mode 100644 index 0000000000..60d74d29c8 --- /dev/null +++ b/crates/format/src/noreplace.rs @@ -0,0 +1,375 @@ +//! Exclusive publication and rename for files in one directory. +//! +//! Prefer a native exclusive rename, with atomic hard-link publication when that operation is +//! unavailable. The caller handles failures between separate file operations. Never replace +//! an exclusive operation with an existence check followed by an overwriting rename. + +use std::{ + ffi::OsStr, + fs::{File, OpenOptions}, + io::{self, Write}, + path::{Path, PathBuf}, + sync::atomic::{AtomicU64, Ordering}, +}; + +/// Publication failure distinguishes an unchanged destination from a published file whose cleanup or directory flush failed. +/// +/// With `published: false` the destination is unchanged (for example `AlreadyExists` when another +/// file got there first), so the caller may pick another name or retry. With `published: true` the +/// destination already holds the complete, flushed bytes; only cleanup or the directory flush +/// failed. Don't retry that as unpublished: a retry would fail with `AlreadyExists` against the +/// caller's own file. Report the write as done but not confirmed durable instead. +#[derive(Debug)] +pub struct PublishNewError { + /// Whether the destination name now exists with the complete bytes despite the error. + pub published: bool, + /// The failed operation: staging, writing or the rename when `published` is false; source + /// cleanup or the directory flush when it is true. + pub error: io::Error, +} + +impl std::fmt::Display for PublishNewError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if self.published { write!(f, "file published; completion unconfirmed: {}", self.error) } else { std::fmt::Display::fmt(&self.error, f) } + } +} +impl std::error::Error for PublishNewError {} + +/// Publish a complete, flushed file only if its destination is still absent. +/// Uses an exclusive staging file beside the destination. The caller must use a stable parent +/// directory where untrusted writers cannot replace the staging entry. +/// On Windows, non-Unicode paths require a filesystem that supports hard links. +pub fn write_noreplace(path: &Path, bytes: &[u8]) -> Result<(), PublishNewError> { + use crate::atomic::{AtomicFs, RealFs}; + static NEXT: AtomicU64 = AtomicU64::new(0); + let before = |error| PublishNewError { published: false, error }; + let dir = path.parent().ok_or_else(|| before(io::Error::new(io::ErrorKind::InvalidInput, "missing publication directory")))?; + // A bare filename still needs a real directory path for the final flush. + let dir = if dir.as_os_str().is_empty() { Path::new(".") } else { dir }; + let name = path.file_name().ok_or_else(|| before(io::Error::new(io::ErrorKind::InvalidInput, "missing publication filename")))?; + let (temp, mut file) = create_stage(dir, name, &NEXT).map_err(before)?; + let written = file.write_all(bytes).and_then(|_| crate::atomic::sync_file(&file)); + drop(file); + let published = written + .map_err(before) + .and_then(|()| move_noreplace(&temp, path, platform, |from, to| std::fs::hard_link(from, to), |path| std::fs::remove_file(path))); + let published = published.map_err(|failure| retry_stage_cleanup(failure, &temp, |path| std::fs::remove_file(path))); + finish_publication(published, || RealFs.sync_dir(dir)) +} + +/// Retry removing the staging name after a failure; if that fails too, name the leftover +/// staging file in the error so the caller can report or remove it. +fn retry_stage_cleanup(failure: PublishNewError, temp: &Path, remove: impl FnOnce(&Path) -> io::Result<()>) -> PublishNewError { + match remove(temp) { + Err(cleanup) if cleanup.kind() != io::ErrorKind::NotFound => PublishNewError { + published: failure.published, + error: io::Error::new(failure.error.kind(), format!("{}; staging file {} remains", failure.error, temp.display())), + }, + _ => failure, + } +} + +/// Create a staging entry whose name cannot be the destination's native filename. +fn create_stage(dir: &Path, destination: &OsStr, next: &AtomicU64) -> io::Result<(PathBuf, File)> { + // Ignore a Windows stream suffix. A different last ASCII digit stays distinct across + // case folding and trailing-dot/space normalization. An uppercase 8.3 staging name + // already satisfies DOS short-name rules, so it needs no second name. + let name = destination.as_encoded_bytes().split(|&byte| byte == b':').next().unwrap_or_default(); + let extension = if name.iter().rev().find(|byte| byte.is_ascii_digit()) == Some(&b'1') { "TM2" } else { "TM1" }; + for _ in 0..32 { + let sequence = next.fetch_add(1, Ordering::Relaxed); + let nonce = (u64::from(std::process::id()) << 8).wrapping_add(sequence) & 0xff_ffff; + let temp = dir.join(format!("PC{nonce:06X}.{extension}")); + match OpenOptions::new().write(true).create_new(true).open(&temp) { + Ok(file) => return Ok((temp, file)), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + } + } + // Not `AlreadyExists`: that means the destination is taken, and callers may pick another name. + Err(io::Error::other("no unused publication temp name")) +} + +/// Rename a file within one stable directory, refusing an existing destination atomically. +/// Directories are not supported: the hard-link fallback cannot link them. +/// The caller must ensure untrusted writers cannot replace the source entry. +/// Unsupported rename primitives use a hard link followed by unlink, never an overwriting +/// rename or cross-volume copy. If unlink fails, both names retain the same bytes and this +/// returns an error, so the caller reports retirement as incomplete. +/// The caller must flush the directory before reporting crash-durable migration completion; +/// the existing `atomic::AtomicFs::sync_dir` provides that separately fallible operation. +pub fn rename_noreplace(from: &Path, to: &Path) -> io::Result<()> { + if from == to || from.parent().is_none() || from.parent() != to.parent() { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "no-replace retirement requires distinct names in one directory")); + } + move_noreplace(from, to, platform, |from, to| std::fs::hard_link(from, to), |path| std::fs::remove_file(path)).map_err(|failure| failure.error) +} + +/// Use fallback only when the exclusive rename primitive itself is unsupported. +fn unsupported_rename(error: &io::Error) -> bool { + #[cfg(unix)] + if matches!(error.raw_os_error(), Some(code) if code == rustix::io::Errno::INVAL.raw_os_error() || code == rustix::io::Errno::NOSYS.raw_os_error()) { + return true; + } + error.kind() == io::ErrorKind::Unsupported +} + +/// Linking claims an absent destination atomically; a later unlink failure is already published. +fn move_noreplace( + from: &Path, + to: &Path, + rename: impl FnOnce(&Path, &Path) -> io::Result<()>, + link: impl FnOnce(&Path, &Path) -> io::Result<()>, + remove: impl FnOnce(&Path) -> io::Result<()>, +) -> Result<(), PublishNewError> { + match rename(from, to) { + Ok(()) => Ok(()), + Err(error) if unsupported_rename(&error) => { + link(from, to).map_err(|error| PublishNewError { published: false, error })?; + remove(from).map_err(|error| PublishNewError { published: true, error }) + } + Err(error) => Err(PublishNewError { published: false, error }), + } +} + +/// A successful name change is durable only after the separately fallible directory flush. +fn finish_publication(result: Result<(), PublishNewError>, sync: impl FnOnce() -> io::Result<()>) -> Result<(), PublishNewError> { + match result { + Ok(()) => sync().map_err(|error| PublishNewError { published: true, error }), + Err(failure) => { + if failure.published { + let _ = sync(); + } + Err(failure) + } + } +} + +/// Prefer the native exclusive rename when the Windows wrapper can represent both paths. +#[cfg(windows)] +fn platform(from: &Path, to: &Path) -> io::Result<()> { + let (Some(from), Some(to)) = (from.to_str(), to.to_str()) else { + // The existing hard-link fallback takes native paths, including unpaired surrogates. + return Err(io::ErrorKind::Unsupported.into()); + }; + if from.contains('\0') || to.contains('\0') { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "file path contains a NUL character")); + } + // MoveFile (unlike MoveFileEx with REPLACE_EXISTING) fails if the destination exists. + // The same-directory restriction above also excludes its cross-volume copy behavior. + winsafe::MoveFile(from, to).map_err(|error| io::Error::from_raw_os_error(error.raw() as i32)) +} + +#[cfg(all(unix, any(target_os = "linux", target_os = "android", target_os = "redox", target_vendor = "apple")))] +fn platform(from: &Path, to: &Path) -> io::Result<()> { + // rustix maps NOREPLACE to Linux renameat2 or Apple's RENAME_EXCL, without unsafe FFI here. + rustix::fs::renameat_with(rustix::fs::CWD, from, rustix::fs::CWD, to, rustix::fs::RenameFlags::NOREPLACE).map_err(io::Error::from) +} + +#[cfg(not(any(windows, all(unix, any(target_os = "linux", target_os = "android", target_os = "redox", target_vendor = "apple")))))] +fn platform(_from: &Path, _to: &Path) -> io::Result<()> { + Err(io::Error::new(io::ErrorKind::Unsupported, "this platform has no supported no-replace retirement primitive")) +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + struct Dir(PathBuf); + impl Dir { + fn new() -> io::Result { + static NEXT: AtomicU64 = AtomicU64::new(0); + let path = std::env::temp_dir().join(format!("pc-noreplace-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + // Never clean a preexisting directory to make the fixture pass. + std::fs::create_dir(&path)?; + Ok(Self(path)) + } + } + impl Drop for Dir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn retirement_moves_the_original_bytes_without_overwriting_a_backup() { + let dir = Dir::new().unwrap(); + let from = dir.0.join("legacy"); + let to = dir.0.join("retained"); + std::fs::write(&from, b"exact original bytes").unwrap(); + std::fs::write(&to, b"existing backup").unwrap(); + assert_eq!(rename_noreplace(&from, &to).unwrap_err().kind(), io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read(&from).unwrap(), b"exact original bytes"); + assert_eq!(std::fs::read(&to).unwrap(), b"existing backup"); + std::fs::remove_file(&to).unwrap(); + rename_noreplace(&from, &to).unwrap(); + assert!(!from.exists()); + assert_eq!(std::fs::read(&to).unwrap(), b"exact original bytes"); + } + + #[test] + fn retirement_refuses_same_name_and_missing_source_without_changing_existing_data() { + let dir = Dir::new().unwrap(); + let from = dir.0.join("legacy"); + let to = dir.0.join("retained"); + std::fs::write(&to, b"existing backup").unwrap(); + assert!(rename_noreplace(&from, &to).is_err()); + assert_eq!(std::fs::read(&to).unwrap(), b"existing backup"); + assert_eq!(rename_noreplace(&to, &to).unwrap_err().kind(), io::ErrorKind::InvalidInput); + assert_eq!(std::fs::read(&to).unwrap(), b"existing backup"); + } + + #[test] + fn publication_keeps_an_existing_destination_and_leaves_no_owned_temp() { + let dir = Dir::new().unwrap(); + let path = dir.0.join("actions.atn"); + std::fs::write(&path, b"existing ATN").unwrap(); + let error = write_noreplace(&path, b"replacement").unwrap_err(); + assert!(!error.published); + assert_eq!(std::fs::read(&path).unwrap(), b"existing ATN"); + assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 1); + } + + #[test] + fn publication_creates_complete_bytes_then_removes_its_temp_name() { + let dir = Dir::new().unwrap(); + let path = dir.0.join("actions.atn"); + write_noreplace(&path, b"complete ATN").unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"complete ATN"); + assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 1); + } + + /// Even the first generated candidate cannot create the destination before publication. + #[test] + fn staging_does_not_create_a_destination_alias() { + let dir = Dir::new().unwrap(); + let (first, file) = create_stage(&dir.0, OsStr::new("actions.atn"), &AtomicU64::new(0)).unwrap(); + drop(file); + std::fs::remove_file(&first).unwrap(); + let name = first.file_name().unwrap().to_str().unwrap(); + for alias in [name.to_owned(), name.to_ascii_lowercase(), format!("{name}. "), format!("{name}::$DATA")] { + let (temp, file) = create_stage(&dir.0, OsStr::new(&alias), &AtomicU64::new(0)).unwrap(); + assert_eq!(temp.extension(), Some(OsStr::new("TM2")), "{alias}"); + assert!(!first.try_exists().unwrap()); + drop(file); + std::fs::remove_file(temp).unwrap(); + } + } + + /// The native-path fallback preserves both byte content and no-clobber behavior. + #[cfg(windows)] + #[test] + fn publication_and_retirement_accept_native_windows_paths() { + use std::{ffi::OsString, os::windows::ffi::OsStringExt}; + + let dir = Dir::new().unwrap(); + let path = |suffix: &str| { + let mut name = OsString::from_wide(&[0xd800]); + name.push(suffix); + assert!(name.to_str().is_none()); + dir.0.join(name) + }; + let from = path("-legacy"); + let to = path("-retained"); + write_noreplace(&from, b"original").unwrap(); + let error = write_noreplace(&from, b"other").unwrap_err(); + assert!(!error.published); + assert_eq!(error.error.kind(), io::ErrorKind::AlreadyExists); + std::fs::write(&to, b"existing").unwrap(); + assert_eq!(rename_noreplace(&from, &to).unwrap_err().kind(), io::ErrorKind::AlreadyExists); + assert_eq!(std::fs::read(&from).unwrap(), b"original"); + assert_eq!(std::fs::read(&to).unwrap(), b"existing"); + std::fs::remove_file(&to).unwrap(); + rename_noreplace(&from, &to).unwrap(); + assert!(!from.try_exists().unwrap()); + assert_eq!(std::fs::read(&to).unwrap(), b"original"); + assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 1); + } + + /// An existing destination survives both the fallback and the native primitive unchanged. + #[test] + fn fallback_is_exclusive_and_moves_complete_bytes() { + let dir = Dir::new().unwrap(); + let (from, to) = (dir.0.join("legacy"), dir.0.join("backup")); + std::fs::write(&from, b"original").unwrap(); + std::fs::write(&to, b"existing").unwrap(); + let unsupported = |_: &Path, _: &Path| Err(io::Error::from(io::ErrorKind::Unsupported)); + let failed = move_noreplace(&from, &to, unsupported, |from, to| std::fs::hard_link(from, to), |path| std::fs::remove_file(path)).unwrap_err(); + assert!(!failed.published); + assert_eq!(std::fs::read(&to).unwrap(), b"existing"); + assert_eq!(std::fs::read(&from).unwrap(), b"original"); + std::fs::remove_file(&to).unwrap(); + move_noreplace(&from, &to, unsupported, |from, to| std::fs::hard_link(from, to), |path| std::fs::remove_file(path)).unwrap(); + assert!(!from.exists()); + assert_eq!(std::fs::read(&to).unwrap(), b"original"); + } + + /// A published destination cannot be called unchanged when source cleanup or fsync fails. + #[test] + fn fallback_unlink_and_directory_flush_failures_report_publication() { + let dir = Dir::new().unwrap(); + let (from, to) = (dir.0.join("legacy"), dir.0.join("backup")); + std::fs::write(&from, b"original").unwrap(); + let error = move_noreplace( + &from, + &to, + |_, _| Err(io::ErrorKind::Unsupported.into()), + |from, to| std::fs::hard_link(from, to), + |_| Err(io::ErrorKind::PermissionDenied.into()), + ) + .unwrap_err(); + assert!(error.published); + assert_eq!(std::fs::read(&from).unwrap(), b"original"); + assert_eq!(std::fs::read(&to).unwrap(), b"original"); + let error = finish_publication(Err(error), || Ok(())).unwrap_err(); + assert!(error.published); + assert_eq!(error.error.kind(), io::ErrorKind::PermissionDenied); + let error = finish_publication(Ok(()), || Err(io::ErrorKind::Other.into())).unwrap_err(); + assert!(error.published); + assert_eq!(std::fs::read(&to).unwrap(), b"original"); + } + + /// Running out of staging names must not look like a taken destination. + #[test] + fn staging_exhaustion_is_not_reported_as_an_existing_destination() { + let dir = Dir::new().unwrap(); + let next = AtomicU64::new(0); + for _ in 0..32 { + drop(create_stage(&dir.0, OsStr::new("actions.atn"), &next).unwrap().1); + } + let error = create_stage(&dir.0, OsStr::new("actions.atn"), &AtomicU64::new(0)).unwrap_err(); + assert_ne!(error.kind(), io::ErrorKind::AlreadyExists); + } + + /// A staging name that cannot be removed is named in the error, keeping its kind and state. + #[test] + fn failed_staging_cleanup_names_the_leftover_file() { + let temp = Path::new("PC000001.TM1"); + let failure = || PublishNewError { published: true, error: io::ErrorKind::PermissionDenied.into() }; + let error = retry_stage_cleanup(failure(), temp, |_| Err(io::ErrorKind::PermissionDenied.into())); + assert!(error.published); + assert_eq!(error.error.kind(), io::ErrorKind::PermissionDenied); + assert!(error.error.to_string().contains("PC000001.TM1"), "{}", error.error); + let error = retry_stage_cleanup(failure(), temp, |_| Ok(())); + assert!(!error.error.to_string().contains("PC000001.TM1")); + let error = retry_stage_cleanup(failure(), temp, |_| Err(io::ErrorKind::NotFound.into())); + assert!(!error.error.to_string().contains("PC000001.TM1")); + } + + /// Ordinary rename failures must not trigger a second filesystem mutation route. + #[test] + fn ordinary_rename_errors_do_not_attempt_fallback() { + for kind in [io::ErrorKind::AlreadyExists, io::ErrorKind::PermissionDenied, io::ErrorKind::NotFound] { + let result = move_noreplace( + Path::new("from"), + Path::new("to"), + |_, _| Err(kind.into()), + |_, _| panic!("ordinary failure must not link"), + |_| panic!("ordinary failure must not unlink"), + ); + let error = result.unwrap_err(); + assert!(!error.published); + assert_eq!(error.error.kind(), kind); + } + } +} diff --git a/crates/format/src/read.rs b/crates/format/src/read.rs index 5d8856b58d..e089af6ea3 100644 --- a/crates/format/src/read.rs +++ b/crates/format/src/read.rs @@ -7,7 +7,7 @@ //! that large with `ERROR_INVALID_PARAMETER` ("The parameter is incorrect", #375). //! - **A clear out-of-memory error.** The buffer is reserved up front with `try_reserve_exact`, //! and a file larger than the memory available says how much it needed. A file that grows past -//! its stat length while being read grows the buffer with `try_reserve` too. +//! its stat length while being read grows the buffer with fallible, bounded reservations too. //! - **A total limit.** No read returns more than [`MAX_OPEN_BYTES`], so a file that keeps growing //! while it is read cannot keep an open or a save from finishing. //! @@ -107,7 +107,10 @@ fn read_all_with(reader: &mut impl Read, size_hint: u64, chunk: usize, max: u64) return Err(too_large(max)); } let room = usize::try_from(max - buf.len() as u64).unwrap_or(usize::MAX); - buf.try_reserve(n.max(chunk).min(room)).map_err(|_| out_of_memory(needed))?; + // Keep geometric growth for expanding files, capped at the caller's remaining budget. + // try_reserve can double capacity even when the requested increment fits. + let growth = n.max(chunk).max(buf.capacity()).min(room); + buf.try_reserve_exact(growth).map_err(|_| out_of_memory(needed))?; buf.extend_from_slice(&probe[..n]); } let room = u64::try_from((buf.capacity() - buf.len()).min(chunk)).unwrap_or(u64::MAX); @@ -218,9 +221,12 @@ mod tests { #[test] fn growing_past_the_hint_stays_within_the_limit() { let data = vec![3u8; 4_000]; - let buf = read_all_with(&mut std::io::Cursor::new(&data), 0, 1 << 20, 5_000).unwrap(); - assert_eq!(buf, data); - assert!(buf.capacity() <= 5_000, "reserved {}", buf.capacity()); + // A 3,000-byte initial capacity would double past the limit with try_reserve. + for hint in [0, 3_000] { + let buf = read_all_with(&mut std::io::Cursor::new(&data), hint, 1 << 20, 5_000).unwrap(); + assert_eq!(buf, data); + assert!(buf.capacity() <= 5_000, "hint {hint}, reserved {}", buf.capacity()); + } let e = read_all_with(&mut std::io::Cursor::new(vec![3u8; 9_000]), 0, 1 << 20, 5_000).unwrap_err(); assert_eq!(e.kind(), io::ErrorKind::FileTooLarge); } diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index c41a9ecdee..bc61ef438a 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -119,11 +119,25 @@ impl Compressor { } } +/// Smallest zstd window [`decompress_bounded`] accepts, whatever the object's size. +const MAX_ZSTD_WINDOW_FLOOR: u64 = 8 << 20; + /// Decodes a zstd frame of at most `max` bytes (`LimitExceeded` beyond). With `exact`, the /// decoded length must be exactly that (`Corrupt` otherwise). fn decompress_bounded(data: &[u8], max: usize, exact: Option, what: &str) -> Result> { let zstd = |e: &dyn std::fmt::Display| FormatError::corrupt(format!("{what}: zstd: {e}")); - let mut dec = ruzstd::decoding::StreamingDecoder::new(data).map_err(|e| zstd(&e))?; + // The decoder allocates its window up front, before any output reaches the length check: + // hold it to what this object may decode to (our frames use a 128 KiB window; libzstd's + // defaults stay under 8 MiB), not ruzstd's 128 MiB default. + let window = u64::try_from(exact.unwrap_or(max)).unwrap_or(u64::MAX).max(MAX_ZSTD_WINDOW_FLOOR); + let mut dec = match ruzstd::decoding::StreamingDecoder::new_with_max_window_size(data, window) { + Ok(dec) => dec, + // A well-formed frame asking for more window than this object may decode to is over its limit. + Err(ruzstd::decoding::errors::FrameDecoderError::WindowSizeTooBig { requested, .. }) => { + return Err(FormatError::LimitExceeded(format!("{what}: zstd window of {requested} bytes exceeds {window}"))); + } + Err(e) => return Err(zstd(&e)), + }; let mut out = Vec::with_capacity(exact.unwrap_or(0).min(max).min(64 << 20)); // `max` may be `usize::MAX`: one byte past it must not overflow. let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1); @@ -879,11 +893,12 @@ fn write_bundle_file(root: &Path, path: &Path, data: &[u8], fs: &dyn crate::atom validate_bundle_file(root, path)?; file.write_all(data)?; file.sync_all()?; - drop(file); - // Preserve the existing mode where possible, as the generic atomic writer does. + // Preserve the existing mode where possible, as the generic atomic writer does: through + // the open handle, so a staging entry swapped meanwhile is not what gets the mode. if let Ok(permissions) = std::fs::metadata(path).map(|m| m.permissions()) { - let _ = std::fs::set_permissions(&tmp, permissions); + let _ = file.set_permissions(permissions); } + drop(file); // Recheck the parent and target just before publishing. rename replaces a symlink // itself, never its referent, even if one appears after this check. validate_bundle_file(root, path)?; @@ -1798,3 +1813,14 @@ fn an_incompressible_blob_at_its_limit_still_loads() { let e = spent(9 * data.len() as u64 + 1).blob_bounded(&hash, usize::MAX).unwrap_err(); assert!(matches!(e, FormatError::LimitExceeded(ref m) if m.contains(&format!("exceeds {} bytes", data.len() - 1))), "{e}"); } + +/// A well-formed zstd frame that asks for a larger window than the object may decode to is over +/// its limit, not damaged; one within the window decodes. +#[test] +fn a_zstd_window_past_the_limit_is_a_limit_not_corruption() { + // Magic, a header with a window descriptor only (exponent 15: a 32 MiB window), then one empty last raw block. + let frame = |window_descriptor: u8| [0x28, 0xB5, 0x2F, 0xFD, 0x00, window_descriptor, 0x01, 0x00, 0x00]; + let e = decompress_bounded(&frame(15 << 3), 100, None, "tile").unwrap_err(); + assert!(matches!(e, FormatError::LimitExceeded(_)), "{e}"); + assert_eq!(decompress_bounded(&frame(0), 100, None, "tile").unwrap(), Vec::::new()); +} diff --git a/crates/format/tests/it/main.rs b/crates/format/tests/it/main.rs index 71eae66ddd..ae17798530 100644 --- a/crates/format/tests/it/main.rs +++ b/crates/format/tests/it/main.rs @@ -10,3 +10,4 @@ mod frame_stroke; mod layer_labels; mod roundtrip; mod smart_contents; +mod triangle_live; diff --git a/crates/format/tests/it/triangle_live.rs b/crates/format/tests/it/triangle_live.rs new file mode 100644 index 0000000000..8fb22020c8 --- /dev/null +++ b/crates/format/tests/it/triangle_live.rs @@ -0,0 +1,130 @@ +//! A live triangle (#13350) is saved in `triangle_live`, beside `live`, so builds from before the +//! kind still open the file and show the saved path. + +use photocraft_color::{ColorMode, SampleType}; +use photocraft_doc::{Document, Fill, Layer, LayerContent, LiveShape, Path, ShapeLayer, Subpath}; +use photocraft_format::*; +use serde_json::{Value, json}; + +fn triangle_json() -> Value { + json!({"kind": "triangle", "rect": [400.0, 300.0, 200.0, 100.0], "corner_radius": 20.0}) +} + +fn path() -> Path { + Path::new(vec![Subpath::polygon(&[(500.0, 300.0), (600.0, 400.0), (400.0, 400.0)])]) +} + +fn document(live: LiveShape) -> Document { + let mut doc = Document::new("Triangle", photocraft_doc::Size::new(800, 600), ColorMode::Rgb, SampleType::U8); + doc.layers.push(Layer::new( + "Triangle 1", + LayerContent::Shape(ShapeLayer { path: path(), fill: Some(Fill::Solid(photocraft_doc::Color::BLACK)), live: Some(live), ..Default::default() }), + )); + doc +} + +fn live(v: Value) -> LiveShape { + serde_json::from_value(v).unwrap() +} + +fn content(doc: &Document) -> Value { + let bytes = save_to_bytes(doc, &SaveOptions::default()).unwrap(); + let json = serde_json::to_value(read_manifest(&bytes).unwrap()).unwrap(); + json["document"]["layers"][0]["content"].clone() +} + +#[test] +fn a_live_triangle_round_trips_through_pcraft() { + let doc = document(live(triangle_json())); + let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap(); + assert_eq!(load_from_bytes(&bytes).unwrap(), doc); +} + +#[test] +fn a_live_triangle_is_written_beside_live_so_older_builds_open_the_file() { + let saved = content(&document(live(triangle_json()))); + assert!(saved["live"].is_null()); + assert_eq!(saved["triangle_live"], triangle_json()); + assert_eq!(saved["path"], serde_json::to_value(path()).unwrap()); + + // An old reader that knows only the earlier kinds. + #[derive(serde::Deserialize, Debug, PartialEq)] + struct LegacyShape { + live: Option, + path: Path, + } + let legacy: LegacyShape = serde_json::from_value(saved).unwrap(); + assert_eq!(legacy, LegacyShape { live: None, path: path() }); +} + +#[test] +fn a_three_sided_polygon_from_an_older_file_stays_a_polygon() { + let doc = document(LiveShape::Polygon { rect: [400.0, 300.0, 200.0, 100.0], sides: 3, star_ratio: 1.0, corner_radius: 0.0 }); + let saved = content(&doc); + assert_eq!(saved["live"]["kind"], "polygon"); + assert!(saved.get("triangle_live").is_none()); + let bytes = save_to_bytes(&doc, &SaveOptions::default()).unwrap(); + assert_eq!(load_from_bytes(&bytes).unwrap(), doc); +} + +#[test] +fn the_triangle_kind_uses_these_json_names() { + assert_eq!(serde_json::to_value(live(triangle_json())).unwrap(), triangle_json()); + let bare = live(json!({"kind": "triangle", "rect": [0.0, 0.0, 10.0, 10.0]})); + assert_eq!(serde_json::to_value(bare).unwrap()["corner_radius"], json!(0.0)); +} + +/// `doc` saved, with `members` set on its first layer's content: what no save writes. +fn saved_with(doc: &Document, members: &Value) -> Vec { + let bytes = save_to_bytes(doc, &SaveOptions::default()).unwrap(); + let bundle = zip::ZipReader::new(&bytes).unwrap(); + let mut out = zip::ZipWriter::new(); + for entry in &bundle.entries { + let mut data = bundle.read(entry, usize::MAX).unwrap(); + if entry.name == "manifest.json" { + let mut manifest: Value = serde_json::from_slice(&data).unwrap(); + for (key, value) in members.as_object().unwrap() { + manifest["document"]["layers"][0]["content"][key] = value.clone(); + } + data = serde_json::to_vec(&manifest).unwrap(); + } + out.add(&entry.name, &data).unwrap(); + } + out.finish().unwrap() +} + +fn loaded_live(bytes: &[u8]) -> Option { + match &load_from_bytes(bytes).unwrap().layers[0].content { + LayerContent::Shape(shape) => shape.live.clone(), + _ => panic!("a shape layer"), + } +} + +/// No save writes these, but a hand-made or damaged file can hold them: the arrow field wins over +/// the triangle field, which wins over `live`; a field holding another kind is ignored; and a +/// value that is no live shape fails the load with an error. +#[test] +fn both_fields_a_wrong_kind_and_junk_never_panic() { + let doc = document(live(triangle_json())); + let arrow = json!({"kind": "arrowLine", "from": [0.0, 0.0], "to": [9.0, 0.0], "weight": 1.0, "start": false, "end": true, "width": 5.0, "length": 5.0, "concavity": 0.0}); + let rect = json!({"kind": "rect", "rect": [1.0, 2.0, 3.0, 4.0], "radii": [0.0, 0.0, 0.0, 0.0]}); + // Both new fields: the arrow wins. The triangle field wins over `live`. + assert_eq!(loaded_live(&saved_with(&doc, &json!({"arrow_live": arrow}))), Some(live(arrow.clone()))); + assert_eq!(loaded_live(&saved_with(&doc, &json!({"live": rect}))), Some(live(triangle_json()))); + // A field holding another kind is ignored, and `live` is read instead. + assert_eq!(loaded_live(&saved_with(&doc, &json!({"triangle_live": rect}))), None); + assert_eq!(loaded_live(&saved_with(&doc, &json!({"triangle_live": arrow, "live": rect}))), Some(live(rect.clone()))); + assert_eq!(loaded_live(&saved_with(&doc, &json!({"arrow_live": triangle_json(), "triangle_live": null}))), None); + // A value that is no live shape fails the load with an error. + for junk in [ + json!(7), + json!("x"), + json!({}), + json!({"kind": "hexagon"}), + json!({"kind": "triangle"}), + json!({"kind": "triangle", "rect": [1, 2, 3]}), + json!({"kind": "triangle", "rect": [0, 0, "w", 10]}), + ] { + assert!(load_from_bytes(&saved_with(&doc, &json!({"triangle_live": junk}))).is_err(), "{junk}"); + } +} diff --git a/crates/gpu/src/fx_passes.rs b/crates/gpu/src/fx_passes.rs index db952febfd..dbc61d0853 100644 --- a/crates/gpu/src/fx_passes.rs +++ b/crates/gpu/src/fx_passes.rs @@ -158,7 +158,7 @@ impl Compositor { } if let Some(t) = t_trace.filter(|_| !damage.is_empty()) { - eprintln!("effect maps of `{}`: shape + distance fields over {damage:?} in {:.2} ms (CPU)", layer.name, t.elapsed().as_secs_f64() * 1000.0); + eprintln!("effect maps of {:?}: shape + distance fields over {damage:?} in {:.2} ms (CPU)", layer.name, t.elapsed().as_secs_f64() * 1000.0); } e.progs.truncate(progs.len()); while e.progs.len() < progs.len() { diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rs index 166e977800..e5418aab4d 100644 --- a/crates/gpu/src/plan.rs +++ b/crates/gpu/src/plan.rs @@ -64,7 +64,13 @@ pub fn plan(doc: &Document) -> Result, Unsupported> { // layers below can't change the result, so they cost no passes or uploads. let start = doc.layers.iter().rposition(|l| photocraft_compose::occludes_below(l, doc.mode)).unwrap_or(0); let root = p.stack_inner(doc.layers.get(start..).unwrap_or(&doc.layers), root, Some(start))?; - Ok(p.finish(root)) + let plan = p.finish(root); + // Every slot becomes a chunk-sized texture before the first pass runs: a compact document + // of deeply nested isolated groups must not ask for hundreds of them. + if plan.slots > planner::MAX_PLAN_SLOTS { + return Err(Unsupported(format!("{} accumulator slots, more than the {} the GPU keeps (composited on the CPU)", plan.slots, planner::MAX_PLAN_SLOTS))); + } + Ok(plan) } #[cfg(test)] diff --git a/crates/gpu/src/plan/planner.rs b/crates/gpu/src/plan/planner.rs index 02d25954b6..3fe3cee6c9 100644 --- a/crates/gpu/src/plan/planner.rs +++ b/crates/gpu/src/plan/planner.rs @@ -14,8 +14,18 @@ pub(super) struct Planner<'a> { /// Layers planned so far, counting a layer each time it is planned (a clipped pass-through /// group is planned twice). visits: usize, + /// Gradient lookup tables built so far (64 KiB of host memory each, kept in the plan). + luts: std::cell::Cell, } +/// Most gradient lookup tables one plan keeps (64 MiB): a nested clipped pass-through group +/// plans its gradient fills again at every level, each with its own table. +const MAX_PLAN_LUTS: usize = 1024; + +/// Most accumulator slots one plan may hold live at once: every slot is a chunk-sized texture +/// (`cells.rs`), and nested isolated groups keep their ancestors' slots live. +pub(super) const MAX_PLAN_SLOTS: u32 = 32; + /// Most layer plannings one document may take: a pass-through group with clipped layers is /// planned twice, so groups nested in one another double the work at every level. const MAX_PLAN_VISITS: usize = 100_000; @@ -182,7 +192,16 @@ fn check_effect_gradients(items: &[&Effect]) -> Result<(), Unsupported> { impl<'a> Planner<'a> { pub(super) fn new(cx: DocCtx<'a>) -> Self { - Planner { passes: Vec::new(), free: Vec::new(), refs: Vec::new(), cx, fx: Vec::new(), checkpoints: Vec::new(), visits: 0 } + Planner { + passes: Vec::new(), + free: Vec::new(), + refs: Vec::new(), + cx, + fx: Vec::new(), + checkpoints: Vec::new(), + visits: 0, + luts: std::cell::Cell::new(0), + } } pub(super) fn finish(self, root: Slot) -> Plan<'a> { @@ -711,6 +730,10 @@ impl<'a> Planner<'a> { // position hash, see the shader). let quantum = photocraft_compose::adjustment_quantum(self.cx.depth).unwrap_or(0.0); p.params[2] = [offset.0, offset.1, quantum, if *dither { 1.0 } else { 0.0 }]; + self.luts.set(self.luts.get() + 1); + if self.luts.get() > MAX_PLAN_LUTS { + return Err(Unsupported("too many gradient fills to plan for the GPU (composited on the CPU)".into())); + } let ramp = photocraft_compose::gradient_fill::Ramp::new(f); let mut rows = vec![[0.0f32; 4096]; 4]; for k in 0..4096 { diff --git a/crates/gpu/src/plan/tests.rs b/crates/gpu/src/plan/tests.rs index 781d35d039..c563fb289f 100644 --- a/crates/gpu/src/plan/tests.rs +++ b/crates/gpu/src/plan/tests.rs @@ -377,6 +377,50 @@ fn advanced_blending_falls_back_to_the_cpu() { assert!(plan(&d).is_err(), "knockout inside a group"); } +/// A chunk-sized texture per live slot: nesting isolated groups keeps every ancestor's slot +/// live, so past a depth the plan is refused and the CPU composites instead. +#[test] +fn deeply_nested_isolated_groups_are_refused_before_their_slots_are_allocated() { + let nested = |depth: usize| { + let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let mut inner = Layer::raster("leaf", d.pixel_format()); + inner.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 4, 4), &[0.0, 0.0, 1.0, 1.0]); + let mut layers = vec![inner]; + for _ in 0..depth { + let mut sibling = Layer::raster("s", d.pixel_format()); + sibling.surface_mut().unwrap().fill_rect(Rect::new(2, 2, 6, 6), &[1.0, 0.0, 0.0, 0.5]); + let mut group = Layer::group("g", vec![sibling, layers.pop().unwrap()]); + group.blend = BlendMode::Multiply; + group.opacity = 0.5; + layers = vec![group]; + } + d.layers.extend(layers); + d + }; + assert!(plan(&nested(4)).unwrap().slots <= planner::MAX_PLAN_SLOTS); + let e = plan(&nested(200)).unwrap_err().to_string(); + assert!(e.contains("accumulator slots"), "{e}"); +} + +/// Every gradient fill planned keeps a 64 KiB lookup table: a document of thousands of them +/// (or one that plans the same fills again at every nesting level) is refused. +#[test] +fn too_many_gradient_tables_refuse_the_plan() { + let doc = |n: usize| { + let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE); + for _ in 0..n { + let fill = Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, photocraft_doc::GradientStyle::Linear, false); + let mut l = Layer::new("fill", LayerContent::Fill(fill)); + l.opacity = 0.5; + d.layers.push(l); + } + d + }; + assert!(plan(&doc(16)).is_ok()); + let e = plan(&doc(1100)).unwrap_err().to_string(); + assert!(e.contains("gradient fills"), "{e}"); +} + /// Adjustments whose LUT rows the planner caches (#11498), with settings away from identity. fn row_cached_adjustments() -> Vec { use photocraft_doc::adjust::{CurvePoint, HueRange, LevelsChannel}; diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 2090bdb00f..a23ef2b2b3 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -28,7 +28,7 @@ photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-compose = { workspace = true } photocraft-algo = { workspace = true } -photocraft-psd = { workspace = true } +craft-psd = { workspace = true } photocraft-codecs = { workspace = true } photocraft-raw = { workspace = true } photocraft-affinity = { workspace = true } @@ -69,7 +69,7 @@ miniz_oxide = "0.9" crc32fast = "1.5" photocraft-affinity = { workspace = true, features = ["synth"] } flate2 = { workspace = true } -photocraft-psd = { workspace = true, features = ["testgen"] } +craft-psd = { workspace = true, features = ["testgen"] } photocraft-raw = { workspace = true, features = ["testgen"] } photocraft-testkit = { workspace = true } proptest = { workspace = true } diff --git a/crates/io/examples/bench_abr.rs b/crates/io/examples/bench_abr.rs index 17d4740962..4db94562ee 100644 --- a/crates/io/examples/bench_abr.rs +++ b/crates/io/examples/bench_abr.rs @@ -7,10 +7,10 @@ use std::time::Instant; +use craft_psd::abr::{AbrSample, write_v6}; +use craft_psd::descriptor::{Descriptor, UnicodeString, Value}; use photocraft_color::PixelFormat; use photocraft_paint::{StrokePoint, render_stroke}; -use photocraft_psd::abr::{AbrSample, write_v6}; -use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value}; use photocraft_raster::Surface; fn prc(v: f64) -> Value { diff --git a/crates/io/examples/big_psb_check.rs b/crates/io/examples/big_psb_check.rs index 3b1c21034b..a7c62a9a5e 100644 --- a/crates/io/examples/big_psb_check.rs +++ b/crates/io/examples/big_psb_check.rs @@ -1,10 +1,10 @@ -//! Opens the files written by `photocraft-psd`'s `big_psb` example and checks their pixels. +//! Opens the files written by `craft-psd`'s `big_psb` example and checks their pixels. //! //! `cargo run --release -p photocraft-io --example big_psb_check -- ...` //! //! The opt-in tests in `tests/it/large_files.rs` generate and check the same files. -use photocraft_psd::fixtures::sample; +use craft_psd::fixtures::sample; fn main() { for path in std::env::args().skip(1) { diff --git a/crates/io/examples/gen_abr_library.rs b/crates/io/examples/gen_abr_library.rs index c19e4a85d8..ce3c8d2e76 100644 --- a/crates/io/examples/gen_abr_library.rs +++ b/crates/io/examples/gen_abr_library.rs @@ -13,10 +13,10 @@ //! `--raw` store tips uncompressed (bigger files). Each file stays under the reader's decoded cap (1 GiB; 512 MiB on 32-bit). #![allow(clippy::unwrap_used, clippy::expect_used)] +use craft_psd::abr::{AbrSample, MAX_TOTAL_BYTES, write_v6}; +use craft_psd::descriptor::{Descriptor, UnicodeString, Value}; use photocraft_paint::procedural::{bristle_tip, chalk_tip, charcoal_tip, grass_tip, leaf_tip, rake_tip, spatter_tip, sponge_tip, star_tip}; use photocraft_paint::tile::GrayTile; -use photocraft_psd::abr::{AbrSample, MAX_TOTAL_BYTES, write_v6}; -use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value}; use std::path::PathBuf; use std::time::Instant; @@ -90,7 +90,7 @@ fn main() { let num = |name: &str, default: u32| arg(name).map_or(default, |v| v.parse().expect("numeric option")); let out = PathBuf::from(arg("--out").unwrap_or_else(|| "target/abr-library".into())); let brushes = num("--brushes", 600); - let max_edge = num("--edge", 2000).clamp(16, photocraft_psd::abr::MAX_EDGE); + let max_edge = num("--edge", 2000).clamp(16, craft_psd::abr::MAX_EDGE); let min_edge = num("--min-edge", 800).clamp(16, max_edge); let depth = num("--depth", 16) as u16; assert!(matches!(depth, 8 | 16), "--depth must be 8 or 16"); diff --git a/crates/io/examples/oracle_diff.rs b/crates/io/examples/oracle_diff.rs index 13977e1a61..1da97fefa1 100644 --- a/crates/io/examples/oracle_diff.rs +++ b/crates/io/examples/oracle_diff.rs @@ -27,7 +27,7 @@ fn main() { fn run_file(path: &str) { let bytes = std::fs::read(path).unwrap(); - let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); let mut imp = photocraft_io::import(path, &bytes).unwrap(); configure_visibility(&mut imp.document.layers); let doc = &imp.document; @@ -360,15 +360,15 @@ fn print_layer_details(doc: &photocraft_doc::Document) { for (k, v) in &l.psd_blocks { if k == b"lfx2" || k == b"lmfx" { // Recursively list descriptor keys (effects), skipping colour stop lists. - fn walk(d: &photocraft_psd::descriptor::Descriptor, depth: usize, out: &mut Vec) { + fn walk(d: &craft_psd::descriptor::Descriptor, depth: usize, out: &mut Vec) { for (k, v) in &d.items { let key = match k { - photocraft_psd::descriptor::Id::Code(c) => String::from_utf8_lossy(c).to_string(), + craft_psd::descriptor::Id::Code(c) => String::from_utf8_lossy(c).to_string(), other => String::from_utf8_lossy(other.as_bytes()).to_string(), }; let vs = format!("{v:?}"); match v { - photocraft_psd::descriptor::Value::Descriptor(sub) => { + craft_psd::descriptor::Value::Descriptor(sub) => { out.push(format!("{}{key}:", " ".repeat(depth))); walk(sub, depth + 1, out); } @@ -376,7 +376,7 @@ fn print_layer_details(doc: &photocraft_doc::Document) { } } } - if let Ok((vd, _)) = photocraft_psd::descriptor::VersionedDescriptor::parse_prefix(&v[4..]) { + if let Ok((vd, _)) = craft_psd::descriptor::VersionedDescriptor::parse_prefix(&v[4..]) { let mut out = Vec::new(); walk(&vd.descriptor, 3, &mut out); for l in out.iter().filter(|l| !l.trim_start().starts_with("Clrs") && !l.trim_start().starts_with("Trns")) { @@ -385,13 +385,13 @@ fn print_layer_details(doc: &photocraft_doc::Document) { } } if k == b"TySh" - && let Some(Ok((vd, _))) = v.get(52..).map(photocraft_psd::descriptor::VersionedDescriptor::parse_prefix) + && let Some(Ok((vd, _))) = v.get(52..).map(craft_psd::descriptor::VersionedDescriptor::parse_prefix) { // Text bounds (text space) and the transform. let t: Vec = (0..6).map(|i| f64::from_be_bytes(v[2 + i * 8..10 + i * 8].try_into().unwrap())).collect(); println!(" TySh transform {t:?}"); for key in ["bounds", "boundingBox"] { - if let Some(photocraft_psd::descriptor::Value::Descriptor(d)) = vd.descriptor.get(key) { + if let Some(craft_psd::descriptor::Value::Descriptor(d)) = vd.descriptor.get(key) { let n: Vec = d.items.iter().map(|(k, v)| format!("{}={v:?}", String::from_utf8_lossy(k.as_bytes()))).collect(); println!(" TySh {key}: {}", n.join(" ")); } @@ -399,7 +399,7 @@ fn print_layer_details(doc: &photocraft_doc::Document) { } if k == b"GdFl" { // Skip the 4-byte version before the descriptor. - if let Ok((vd, _)) = photocraft_psd::descriptor::VersionedDescriptor::parse_prefix(v) { + if let Ok((vd, _)) = craft_psd::descriptor::VersionedDescriptor::parse_prefix(v) { println!( " GdFl keys: {:?}", vd.descriptor @@ -409,7 +409,7 @@ fn print_layer_details(doc: &photocraft_doc::Document) { .map(|(k, v)| format!( "{:?}={}", match k { - photocraft_psd::descriptor::Id::Code(c) => String::from_utf8_lossy(c).to_string(), + craft_psd::descriptor::Id::Code(c) => String::from_utf8_lossy(c).to_string(), other => format!("{other:?}"), }, format!("{v:?}").chars().take(120).collect::() @@ -422,24 +422,24 @@ fn print_layer_details(doc: &photocraft_doc::Document) { } } -fn dump_filter_effects(file: &photocraft_psd::PsdFile) { +fn dump_filter_effects(file: &craft_psd::PsdFile) { if std::env::var_os("DUMP_FX").is_some() { - fn walk(d: &photocraft_psd::descriptor::Descriptor, depth: usize) { + fn walk(d: &craft_psd::descriptor::Descriptor, depth: usize) { for (k, v) in &d.items { let key = String::from_utf8_lossy(k.as_bytes()).to_string(); if key == "Clrs" || key == "Trns" { continue; } match v { - photocraft_psd::descriptor::Value::Descriptor(sub) => { + craft_psd::descriptor::Value::Descriptor(sub) => { println!("{}{key}:", " ".repeat(depth)); walk(sub, depth + 1); } - photocraft_psd::descriptor::Value::Text(t) => println!("{}{key} = {:?}", " ".repeat(depth), t.to_string_lossy()), - photocraft_psd::descriptor::Value::List(items) if items.iter().all(|i| matches!(i, photocraft_psd::descriptor::Value::Descriptor(_))) => { + craft_psd::descriptor::Value::Text(t) => println!("{}{key} = {:?}", " ".repeat(depth), t.to_string_lossy()), + craft_psd::descriptor::Value::List(items) if items.iter().all(|i| matches!(i, craft_psd::descriptor::Value::Descriptor(_))) => { println!("{}{key} = [{} items]", " ".repeat(depth), items.len()); for (i, it) in items.iter().enumerate() { - if let photocraft_psd::descriptor::Value::Descriptor(sub) = it { + if let craft_psd::descriptor::Value::Descriptor(sub) = it { println!("{}[{i}]:", " ".repeat(depth + 1)); walk(sub, depth + 2); } @@ -452,7 +452,7 @@ fn dump_filter_effects(file: &photocraft_psd::PsdFile) { for rec in file.layers() { println!("-- layer {:?} rect {:?}", String::from_utf8_lossy(&rec.name), rec.rect); if let Some(b) = rec.block(b"lmfx").or(rec.block(b"lfx2")).or(rec.block(b"lfxs")) - && let Ok((vd, _)) = photocraft_psd::descriptor::VersionedDescriptor::parse_prefix(&b.data[4..]) + && let Ok((vd, _)) = craft_psd::descriptor::VersionedDescriptor::parse_prefix(&b.data[4..]) { walk(&vd.descriptor, 1); } @@ -481,7 +481,7 @@ fn corpus_summary(root: &std::path::Path) { let row = |p: &std::path::PathBuf| -> Row { let name = p.strip_prefix(root).unwrap_or(p).display().to_string(); let Ok(bytes) = std::fs::read(p) else { return (name, None) }; - let Ok(file) = photocraft_psd::PsdFile::from_bytes(&bytes) else { return (name, None) }; + let Ok(file) = craft_psd::PsdFile::from_bytes(&bytes) else { return (name, None) }; let Ok(imp) = photocraft_io::import(&name, &bytes) else { return (name, None) }; if file.has_real_merged_data() == Some(false) || file.layers().is_empty() { return (name, None); diff --git a/crates/io/src/abr_map.rs b/crates/io/src/abr_map.rs index a41ba3ac01..9ca85b8830 100644 --- a/crates/io/src/abr_map.rs +++ b/crates/io/src/abr_map.rs @@ -1,6 +1,6 @@ //! Photoshop brushes (`.abr`) → brush presets. //! -//! [`photocraft_psd::abr`] reads the file; this module maps its tips and `brushPreset` +//! [`craft_psd::abr`] reads the file; this module maps its tips and `brushPreset` //! descriptors onto [`BrushSettings`] (Brush Tip Shape, Shape Dynamics, Scattering, Texture, //! Dual Brush, Color Dynamics, Transfer, Brush Pose, Noise, Wet Edges, Build-up, Smoothing and //! the captured tool options). Settings without an equivalent are listed in @@ -9,12 +9,12 @@ use std::collections::BTreeSet; +use craft_psd::abr::{self, AbrFile, AbrSample, LegacyTip}; +use craft_psd::descriptor::{Descriptor, Value}; +use craft_psd::patterns::PsdPattern; use photocraft_paint::{ BrushPreset, BrushSettings, Control, DualBrush, Dynamic, GrayTile, MaskMode, MixerSettings, Pattern, PatternStyle, Pose, ShapeDynamics, TipShape, Transfer, }; -use photocraft_psd::abr::{self, AbrFile, AbrSample, LegacyTip}; -use photocraft_psd::descriptor::{Descriptor, Value}; -use photocraft_psd::patterns::PsdPattern; /// Largest sampled tip edge kept as is; bigger tips are downsampled to it. pub const MAX_TIP_EDGE: u32 = 2500; diff --git a/crates/io/src/abr_map/tests.rs b/crates/io/src/abr_map/tests.rs index 26f68d7aa0..930af83fa6 100644 --- a/crates/io/src/abr_map/tests.rs +++ b/crates/io/src/abr_map/tests.rs @@ -1,6 +1,6 @@ use super::*; -use photocraft_psd::abr::{LegacyBrush, write_v6, write_v6_folders, write_v12}; -use photocraft_psd::descriptor::{Id, UnicodeString}; +use craft_psd::abr::{LegacyBrush, write_v6, write_v6_folders, write_v12}; +use craft_psd::descriptor::{Id, UnicodeString}; fn sample(id: &str, w: u32, h: u32, depth: u16) -> AbrSample { let bpp = usize::from(depth / 8); diff --git a/crates/io/src/adjust_map.rs b/crates/io/src/adjust_map.rs index f302fac30d..584deb3ff3 100644 --- a/crates/io/src/adjust_map.rs +++ b/crates/io/src/adjust_map.rs @@ -10,9 +10,9 @@ //! that cannot be read (noise gradients, profile lookups, CMYK channel mixers, unknown versions) //! stay [`Adjustment::Unsupported`] and are written back verbatim. +use craft_psd::descriptor::{Descriptor, Value, VersionedDescriptor}; use photocraft_doc::Adjustment; use photocraft_doc::adjust::{CURVE_MAP_LEN, CurvePoint, HueRange, LevelsChannel, LutFormat, LutSource, ToneSpace, curve_map}; -use photocraft_psd::descriptor::{Descriptor, Value, VersionedDescriptor}; mod encode; diff --git a/crates/io/src/adjust_map/encode.rs b/crates/io/src/adjust_map/encode.rs index 08d3075b57..3d7b660457 100644 --- a/crates/io/src/adjust_map/encode.rs +++ b/crates/io/src/adjust_map/encode.rs @@ -1,5 +1,5 @@ +use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; use photocraft_doc::adjust::{CurvePoint, HueRange, LevelsChannel, LutFormat, LutSource, ToneSpace, curve_map_outputs}; -use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; use super::{BW_KEYS, BW_TINT, clamp_i16, cube_file_name, levels_write, lut_source_for, psd_lut_format, put16, q255, rgb_desc}; diff --git a/crates/io/src/adjust_map/tests.rs b/crates/io/src/adjust_map/tests.rs index ce284bea36..9462bb6fc6 100644 --- a/crates/io/src/adjust_map/tests.rs +++ b/crates/io/src/adjust_map/tests.rs @@ -274,8 +274,8 @@ fn identity_look() -> Vec { /// A `clrL` block as Photoshop writes one for a loaded LUT file. fn clrl_block(format: &str, bytes: &[u8], name: &str) -> Vec { - let en = |t: &str, val: &str| Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new(t), value: photocraft_psd::descriptor::Id::new(val) }; - let text = |t: &str| Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul(t)); + let en = |t: &str, val: &str| Value::Enumerated { type_id: craft_psd::descriptor::Id::new(t), value: craft_psd::descriptor::Id::new(val) }; + let text = |t: &str| Value::Text(craft_psd::descriptor::UnicodeString::new_nul(t)); let desc = Descriptor::new("null") .with("lookupType", en("colorLookupType", "3DLUT")) .with("NM ", text(name)) @@ -355,10 +355,10 @@ fn color_lookup_table_without_matching_file_is_saved_as_cube_named_to_match() { #[test] fn color_lookup_synthetic_block() { let cube = b"TITLE \"t\"\nLUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n"; - let en = |t: &str, val: &str| Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new(t), value: photocraft_psd::descriptor::Id::new(val) }; + let en = |t: &str, val: &str| Value::Enumerated { type_id: craft_psd::descriptor::Id::new(t), value: craft_psd::descriptor::Id::new(val) }; let desc = Descriptor::new("null") .with("lookupType", en("colorLookupType", "3DLUT")) - .with("NM ", Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul("Id"))) + .with("NM ", Value::Text(craft_psd::descriptor::UnicodeString::new_nul("Id"))) .with("Dthr", Value::Boolean(true)) .with("LUTFormat", en("LUTFormatType", "LUTFormatCUBE")) .with("LUT3DFileData", Value::RawData(cube.to_vec())); @@ -389,10 +389,10 @@ fn color_lookup_synthetic_block() { } fn cube_lookup_block(cube: &[u8]) -> Vec { - let en = |t: &str, val: &str| Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new(t), value: photocraft_psd::descriptor::Id::new(val) }; + let en = |t: &str, val: &str| Value::Enumerated { type_id: craft_psd::descriptor::Id::new(t), value: craft_psd::descriptor::Id::new(val) }; let desc = Descriptor::new("null") .with("LUTFormat", en("LUTFormatType", "LUTFormatCUBE")) - .with("LUT3DFileName", Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul("domain.cube"))) + .with("LUT3DFileName", Value::Text(craft_psd::descriptor::UnicodeString::new_nul("domain.cube"))) .with("LUT3DFileData", Value::RawData(cube.to_vec())); let mut block = vec![0, 1]; block.extend(VersionedDescriptor::new(desc).to_bytes()); diff --git a/crates/io/src/affinity.rs b/crates/io/src/affinity.rs index 4e5ed90f86..927fa142d6 100644 --- a/crates/io/src/affinity.rs +++ b/crates/io/src/affinity.rs @@ -32,22 +32,36 @@ const MAX_SIDE: f64 = 300_000.0; /// container of embedded images could still decode (and keep) a surface each until the process /// dies. ORA and KRA budget their decoded pixels the same way. const MAX_PIXEL_BYTES: u64 = 1 << 30; +/// Bytes the import's optional pixel caches (shapes, type layers) may hold together. They are +/// drawn again on the first edit, so running out costs nothing but speed; raster layers and +/// embedded images are lost for good when they don't fit. A separate pool keeps thousands of +/// cheap caches early in a file from using up [`MAX_PIXEL_BYTES`] and dropping images later. +const MAX_CACHE_BYTES: u64 = 512 << 20; pub fn has_extension(name: &str) -> bool { name.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).is_some_and(|(_, ext)| EXTENSIONS.iter().any(|e| ext.eq_ignore_ascii_case(e))) } -pub(crate) fn import(name: &str, bytes: &[u8]) -> Result { +pub(crate) fn import(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt) -> Result { match photocraft_affinity::read(bytes, photocraft_affinity::Limits::default()) { Ok(d) => { let mut b = Builder::new(name, &d)?; + b.ctl = *ctl; b.document(&d)?; + ctl.check().map_err(|_| IoError::Cancelled)?; let mut warnings: Vec = d.warnings.iter().map(|w| format!("Affinity: not imported or approximated: {w}.")).collect(); warnings.extend(b.warnings.iter().map(|w| format!("Affinity: {w}."))); // Type layers draw from their model, within the import's raster bound: the sizes and - // frames come from an untrusted file. + // frames come from an untrusted file. They share the optional-cache budget with the + // shapes, so a file with thousands of type layers can't allocate without end. let mut document = b.doc; - crate::text_import::prepare(&mut document, None); + let unrendered = crate::text_import::prepare_within(&mut document, None, &mut b.cache_budget, ctl).map_err(|_| IoError::Cancelled)?; + if unrendered > 0 { + warnings.push(format!("Affinity: {unrendered} type layers beyond the import's memory limit were left without pixels until they are edited.")); + } + if b.uncached_shapes > 0 { + warnings.push(format!("Affinity: {} shapes beyond the import's memory limit were left without a pixel cache.", b.uncached_shapes)); + } // Save never writes back over the Affinity file. Ok(ImportResult { document, warnings, source_read_only: true, preview_only: false }) } @@ -80,7 +94,7 @@ fn preview(name: &str, bytes: &[u8], native: &photocraft_affinity::Error) -> Res Ok(r) } -struct Builder { +struct Builder<'a> { doc: Document, warnings: Vec, /// Document pixels (in the canvas) per Affinity document pixel: always 1; spreads are offset. @@ -88,6 +102,12 @@ struct Builder { canvas: Rect, /// Decoded pixel bytes left for embedded images and their resampled surfaces. pixel_budget: u64, + /// Bytes left for the optional shape and type caches ([`MAX_CACHE_BYTES`]). + cache_budget: u64, + /// Shapes that went without a cache because `cache_budget` ran out. + uncached_shapes: usize, + /// Checked per layer: a cancelled import stops building. + ctl: photocraft_raster::Interrupt<'a>, } /// Deduct `cost` bytes from a decoded-pixel budget; `false` (leaving the budget alone) when it @@ -110,7 +130,7 @@ fn point(p: af::Point) -> Point { Point::new(p.x, p.y) } -impl Builder { +impl Builder<'_> { fn new(name: &str, d: &af::Document) -> Result { // Spreads (Publisher pages) side by side, 64 px apart. let mut w: f64 = 0.0; @@ -126,7 +146,16 @@ impl Builder { let mut doc = Document::new(name, size, ColorMode::Rgb, SampleType::U8); doc.resolution_dpi = d.dpi as f32; let canvas = Rect::new(0, 0, size.width as i32, size.height as i32); - Ok(Self { doc, warnings: Vec::new(), format: PixelFormat::RGBA8, canvas, pixel_budget: MAX_PIXEL_BYTES }) + Ok(Self { + doc, + warnings: Vec::new(), + format: PixelFormat::RGBA8, + canvas, + pixel_budget: MAX_PIXEL_BYTES, + cache_budget: MAX_CACHE_BYTES, + uncached_shapes: 0, + ctl: photocraft_raster::Interrupt::NONE, + }) } fn warn(&mut self, w: &str) { @@ -249,6 +278,9 @@ impl Builder { /// One Affinity node and its subtree; `to_doc` maps Affinity document pixels to the canvas. fn layer(&mut self, n: &af::Node, to_doc: Affine, top: bool) -> Option { + if self.ctl.cancelled() { + return None; + } let children: Vec = n.children.iter().filter_map(|c| self.layer(c, to_doc, false)).collect(); let mut l = match &n.kind { Kind::Layer | Kind::Group => self.group(n, children), @@ -446,13 +478,26 @@ impl Builder { // The pixel cache is optional (the shape renders from its path without it), so charge the // area it would cover to the import's pixel budget and go without it when that is spent: // geometry across a 300000 px canvas would otherwise be rasterized for every shape. - let reach = sh.stroke.as_ref().map_or(0, |s| (s.width.ceil() as i32).saturating_add(1)); - let area = frame.inflate(reach).intersect(&self.canvas); - let cost = u64::from(area.width()).saturating_mul(u64::from(area.height())).saturating_mul(self.format.bytes_per_pixel() as u64); - if charge(&mut self.pixel_budget, cost) { - sh.cache = Some(photocraft_vector::render_shape(&sh, self.format, self.canvas)); + // Once not even one tile is left nothing can be charged, so skip compiling the shape + // (flattening and stroking its path) just to throw the result away. + let tile = crate::text_import::cache_bytes(Rect::new(0, 0, 1, 1), self.format.bytes_per_pixel()); + if self.cache_budget < tile { + if !sh.path.subpaths.is_empty() { + self.uncached_shapes += 1; + } + return sh; + } + // The compiled bounds are what `render` covers, an acute miter reaching past the stroke width included. + #[cfg(test)] + COMPILED_SHAPES.with(|n| n.set(n.get() + 1)); + let compiled = photocraft_vector::CompiledShape::new(&sh, photocraft_vector::DEFAULT_TOLERANCE, self.canvas); + let area = compiled.bounds().map_or(Rect::default(), |b| b.intersect(&self.canvas)); + // Whole tiles: even a 2x2 px shape keeps one, which 50 000 small shapes add up to gigabytes. + let cost = crate::text_import::cache_bytes(area, self.format.bytes_per_pixel()); + if charge(&mut self.cache_budget, cost) { + sh.cache = Some(compiled.render(self.format, self.canvas)); } else { - self.warn("shapes covering more pixels than the import's memory allows were left without a pixel cache"); + self.uncached_shapes += 1; } sh } @@ -580,7 +625,8 @@ impl Builder { let exact = a == 1.0 && d == 1.0 && b == 0.0 && c == 0.0 && e.fract() == 0.0 && f.fract() == 0.0; let inv = m.inverse()?; let (rw, rh) = (r.width() as usize, r.height() as usize); - if !charge(&mut self.pixel_budget, (rw as u64).saturating_mul(rh as u64).saturating_mul(channels as u64)) { + // The surface keeps whole tiles: a narrow image stores up to 256 times its pixels. + if !charge(&mut self.pixel_budget, photocraft_raster::tile_storage_bytes(r, &format)) { self.warn("the document's images need more pixel memory than the import allows; the rest were left out"); return None; } @@ -656,6 +702,12 @@ fn color(c: ap::Color) -> Color { } } +#[cfg(test)] +thread_local! { + /// How many shapes this thread compiled for a pixel cache (for the exhausted-budget test). + static COMPILED_SHAPES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + #[cfg(test)] mod tests { use super::*; @@ -697,11 +749,11 @@ mod tests { #[test] fn images_past_the_pixel_budget_are_left_out() { - // Two 64×64 RGBA images cost 16 KiB each when resampled; a 16 KiB budget admits one and + // Two 64×64 RGBA images each keep a whole 256×256 tile (256 KiB); a one-tile budget admits one and // the second is dropped with a warning instead of being staged anyway. let d = affinity_document(vec![(64, 64, Pixels::Rgba8(vec![0; 64 * 64 * 4])), (64, 64, Pixels::Rgba8(vec![0; 64 * 64 * 4]))]); let mut b = Builder::new("budget", &d).unwrap(); - b.pixel_budget = 64 * 64 * 4; + b.pixel_budget = 256 * 256 * 4; // one whole tile per image b.document(&d).unwrap(); assert_eq!(b.doc.layers.len(), 1, "the image past the budget must not import"); assert!(b.warnings.iter().any(|w| w.contains("pixel memory")), "{:?}", b.warnings); @@ -722,8 +774,170 @@ mod tests { assert!(b.warnings.iter().any(|w| w.contains("pixel memory")), "{:?}", b.warnings); // The same image imports when the budget covers the decode and the resample. let mut ok = Builder::new("room", &d).unwrap(); - ok.pixel_budget = 8 * 8 * 4 * 2; + ok.pixel_budget = 8 * 8 * 4 + 256 * 256 * 4; ok.document(&d).unwrap(); assert_eq!(ok.doc.layers.len(), 1, "within the budget the image imports as a smart object"); } + + fn node(kind: Kind) -> af::Node { + af::Node { + class: photocraft_affinity::synth::tag(b"ImgN"), + name: "n".into(), + visible: true, + locked: false, + opacity: 1.0, + blend: Blend::Normal, + kind, + mask: None, + pixel_mask: None, + children: Vec::new(), + } + } + + fn page(nodes: Vec) -> af::Document { + af::Document { + dpi: 72.0, + spreads: vec![af::Spread { bounds: af::Rect { x0: 0.0, y0: 0.0, x1: 64.0, y1: 64.0 }, pages: Vec::new(), transparent: true, nodes }], + saved_by: None, + warnings: Vec::new(), + } + } + + /// A 2×2 px solid rectangle. + fn tiny_shape(i: usize) -> af::Node { + let p = |x: f64, y: f64| af::Point { x, y }; + let (x, y) = ((i % 30) as f64, (i / 30 % 30) as f64); + let corners = [p(x, y), p(x + 2.0, y), p(x + 2.0, y + 2.0), p(x, y + 2.0)]; + let sub = af::SubPath { start: corners[0], segments: (1..=4).map(|k| [corners[k % 4]; 3]).collect(), closed: true }; + node(Kind::Shape { + path: af::Path { subpaths: vec![sub] }, + fills: vec![ap::Paint::Solid(ap::Color::Rgb { r: 1.0, g: 0.0, b: 0.0, a: 1.0 })], + strokes: Vec::new(), + even_odd: false, + }) + } + + #[test] + fn small_shapes_are_charged_a_whole_tile_each() { + // Surfaces keep whole tiles, so 2×2 px shapes cost a tile each: 50 000 of them were + // 7 GB. A budget of three tiles keeps the pixel cache of the first three only. + let d = page((0..10).map(tiny_shape).collect()); + let mut b = Builder::new("shapes", &d).unwrap(); + b.cache_budget = 3 * 256 * 256 * 4; + b.document(&d).unwrap(); + let cached = |l: &Layer| matches!(&l.content, LayerContent::Shape(s) if s.cache.is_some()); + assert_eq!(b.doc.layers.iter().filter(|l| cached(l)).count(), 3); + assert_eq!(b.doc.layers.iter().filter(|l| matches!(l.content, LayerContent::Shape(_))).count(), 10, "every shape still imports"); + assert_eq!(b.uncached_shapes, 7); + assert_eq!(b.cache_budget, 0); + assert_eq!(b.pixel_budget, MAX_PIXEL_BYTES, "caches don't draw on the pool images need"); + } + + #[test] + fn shapes_are_not_compiled_once_no_cache_tile_fits() { + // Three tiles pay for the first three shapes; the other 27 must not even be compiled. + let d = page((0..30).map(tiny_shape).collect()); + let mut b = Builder::new("shapes", &d).unwrap(); + b.cache_budget = 3 * 256 * 256 * 4; + COMPILED_SHAPES.with(|n| n.set(0)); + b.document(&d).unwrap(); + assert_eq!(COMPILED_SHAPES.with(std::cell::Cell::get), 3); + assert_eq!(b.uncached_shapes, 27, "the skipped-cache warning still counts them"); + assert_eq!(b.doc.layers.len(), 30, "every shape still imports"); + } + + #[test] + fn an_acute_miter_is_charged_for_the_tiles_it_reaches() { + // A thin spike at x = 250 with a 4 px miter stroke reaches x = 270, into the next 256 px + // tile, though the stroke width alone would stay in the first. + let p = |x: f64, y: f64| af::Point { x, y }; + let sub = af::SubPath { + start: p(250.0, 100.0), + segments: [p(200.0, 95.0), p(200.0, 105.0), p(250.0, 100.0)].iter().map(|c| [*c; 3]).collect(), + closed: true, + }; + let mut d = page(vec![node(Kind::Shape { + path: af::Path { subpaths: vec![sub] }, + fills: Vec::new(), + strokes: vec![ap::Stroke { + paint: ap::Paint::Solid(ap::Color::Rgb { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }), + width: 4.0, + cap: Cap::Butt, + join: Join::Miter, + miter_limit: 20.0, + align: ap::Align::Center, + dash: None, + behind: false, + }], + even_odd: false, + })]); + d.spreads[0].bounds.x1 = 600.0; + d.spreads[0].bounds.y1 = 600.0; + let mut b = Builder::new("miter", &d).unwrap(); + let tile = crate::text_import::cache_bytes(Rect::new(0, 0, 1, 1), b.format.bytes_per_pixel()); + b.cache_budget = tile; + b.document(&d).unwrap(); + assert_eq!(b.uncached_shapes, 1, "two tiles do not fit a budget of one"); + assert_eq!(b.cache_budget, tile, "nothing was charged"); + let mut b2 = Builder::new("miter", &d).unwrap(); + b2.cache_budget = 2 * tile; + b2.document(&d).unwrap(); + assert_eq!(b2.uncached_shapes, 0); + assert_eq!(b2.cache_budget, 0, "charged for both tiles"); + } + + #[test] + fn a_cancelled_import_stops_building_layers() { + let d = page((0..10).map(tiny_shape).collect()); + let mut b = Builder::new("cancel", &d).unwrap(); + let cancel = || true; + b.ctl = photocraft_raster::Interrupt::cancel_only(&cancel); + b.document(&d).unwrap(); + assert!(b.doc.layers.is_empty(), "no layer is built once cancelled"); + let mut doc = Document::new("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); + let mut budget = u64::MAX; + doc.layers.push(Layer::new("t", LayerContent::Text(TextLayer { text: "x".into(), ..TextLayer::default() }))); + assert!(crate::text_import::prepare_within(&mut doc, None, &mut budget, &b.ctl).is_err()); + } + + #[test] + fn type_layers_share_the_cache_budget_and_keep_going_without_pixels() { + // Each layer's ink is charged to the budget; one that doesn't fit keeps an empty cache and + // is counted, instead of every layer of a 2000-layer file drawing its own raster. + let mut doc = Document::new("t", Size::new(64, 64), ColorMode::Rgb, SampleType::U8); + for i in 0..20 { + let text = "Budget".to_string(); + let mut t = TextLayer { text, font_family: "sans-serif".into(), size_pt: 24.0, ..TextLayer::default() }; + t.runs = vec![TextRun { len: t.text.len(), style: CharStyle { size_pt: 24.0, ..CharStyle::default() } }]; + doc.layers.push(Layer::new(format!("t{i}"), LayerContent::Text(t))); + } + // What one layer costs, then room for two and a half. + let mut probe = u64::MAX; + let mut one = doc.clone(); + one.layers.truncate(1); + crate::text_import::prepare_within(&mut one, None, &mut probe, &photocraft_raster::Interrupt::NONE).unwrap(); + let cost = u64::MAX - probe; + assert!(cost > 0); + let mut budget = cost * 5 / 2; + let skipped = crate::text_import::prepare_within(&mut doc, None, &mut budget, &photocraft_raster::Interrupt::NONE).unwrap(); + let drawn = doc.layers.iter().filter(|l| matches!(&l.content, LayerContent::Text(t) if t.cache.as_ref().is_some_and(|c| c.tile_count() > 0))).count(); + assert_eq!((drawn, skipped), (2, 18)); + assert!(drawn + skipped == 20, "drawn {drawn} skipped {skipped}"); + assert!(doc.layers.iter().all(|l| matches!(&l.content, LayerContent::Text(t) if t.cache.is_some())), "every layer has a cache, empty or not"); + } + + #[test] + fn shape_caches_leave_room_for_images() { + // 64 shapes overrun the cache pool; the image after them still imports. + let mut nodes: Vec = (0..64).map(tiny_shape).collect(); + nodes.extend(affinity_document(vec![(64, 64, Pixels::Rgba8(vec![0; 64 * 64 * 4]))]).spreads.remove(0).nodes); + let d = page(nodes); + let mut b = Builder::new("mixed", &d).unwrap(); + b.cache_budget = 4 * 256 * 256 * 4; + b.pixel_budget = 256 * 256 * 4; // one whole tile for the image + b.document(&d).unwrap(); + assert_eq!(b.uncached_shapes, 60); + assert!(b.doc.layers.iter().any(|l| matches!(l.content, LayerContent::Smart(_) | LayerContent::Raster(_))), "the image must import"); + assert!(!b.warnings.iter().any(|w| w.contains("pixel memory")), "{:?}", b.warnings); + } } diff --git a/crates/io/src/annotations_map.rs b/crates/io/src/annotations_map.rs index 9c41899170..9f95f6eb3b 100644 --- a/crates/io/src/annotations_map.rs +++ b/crates/io/src/annotations_map.rs @@ -18,9 +18,9 @@ use std::sync::Arc; +use craft_psd::ImageResource; +use craft_psd::descriptor::{Descriptor, UnicodeString, Value, VersionedDescriptor}; use photocraft_doc::{Color, CountGroup, Document, MeasurementScale, Note}; -use photocraft_psd::ImageResource; -use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value, VersionedDescriptor}; pub const MEASUREMENT_SCALE: u16 = 1074; pub const COUNT_INFO: u16 = 1080; @@ -310,7 +310,7 @@ pub fn write_scale_resource(s: &MeasurementScale) -> Vec { let d = Descriptor::new("null") .with("pixelLength", Value::Double(s.pixel_length)) .with("logicalLength", Value::Double(s.logical_length)) - .with("logicalUnits", Value::Text(photocraft_psd::descriptor::UnicodeString::new(&s.units))); + .with("logicalUnits", Value::Text(craft_psd::descriptor::UnicodeString::new(&s.units))); let mut v = VersionedDescriptor::new(d).to_bytes(); if v.len() % 2 == 1 { v.push(0); diff --git a/crates/io/src/asl_map.rs b/crates/io/src/asl_map.rs index 9913406441..26fd4325d5 100644 --- a/crates/io/src/asl_map.rs +++ b/crates/io/src/asl_map.rs @@ -1,6 +1,6 @@ //! Layer style libraries (`.asl`) ⇄ PhotoCraft styles. //! -//! The container is parsed by [`photocraft_psd::asl`]. Each style's `Lefx` is the same effects +//! The container is parsed by [`craft_psd::asl`]. Each style's `Lefx` is the same effects //! tree as a layer's `lfx2` block ([`crate::effects_map`]); `blendOptions` ("Include Layer //! Blending Options") carries the blend mode, opacity and fill opacity; the file's patterns feed //! the styles' Pattern Overlays, pattern strokes and bevel textures. @@ -11,10 +11,10 @@ use std::collections::{BTreeSet, HashMap, HashSet}; +use craft_psd::asl::{self, AslFile}; +use craft_psd::descriptor::{Descriptor, Id, Value}; use photocraft_color::BlendMode; use photocraft_doc::{Effect, FxPaint, Pattern}; -use photocraft_psd::asl::{self, AslFile}; -use photocraft_psd::descriptor::{Descriptor, Id, Value}; use crate::blocks::{enum_of, get_desc, num}; use crate::effects_map::{blend_from_id, blend_value, effects_descriptor, effects_from_descriptor, is_known_effects_key}; @@ -208,9 +208,9 @@ pub fn write_asl(styles: &[AslStyle], patterns: &[Pattern]) -> Result, S #[cfg(test)] mod tests { use super::*; + use craft_psd::descriptor::UnicodeString; use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; use photocraft_doc::{BevelTexture, FxCommon, StrokePosition}; - use photocraft_psd::descriptor::UnicodeString; use photocraft_raster::Surface; fn pattern(id: &str, s: SampleType) -> Pattern { @@ -376,7 +376,7 @@ mod tests { let _ = read_asl(&c); } assert!(read_asl(b"").is_err()); - assert!(read_asl(&photocraft_psd::grd::write(&[])).is_err()); + assert!(read_asl(&craft_psd::grd::write(&[])).is_err()); } #[test] diff --git a/crates/io/src/blocks.rs b/crates/io/src/blocks.rs index c280747611..2f69330b60 100644 --- a/crates/io/src/blocks.rs +++ b/crates/io/src/blocks.rs @@ -1,11 +1,11 @@ //! Tagged-block helpers: the preserved block-list encoding, fills, text, //! smart objects, locks and label colors. +use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; +use craft_psd::layer::BlendingRanges; use photocraft_color::{Color, ColorMode}; use photocraft_doc::{AdvancedBlending, BlendIf, BlendRange, Fill, GradientStyle, Knockout, LabelColor, Locks}; use photocraft_geom::Affine; -use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; -use photocraft_psd::layer::BlendingRanges; /// `brst` (channel blending restrictions): a list of big-endian u32 channel indices left out of /// blending → a bit mask (bit `i` = channel `i`; indices above 31 are ignored). diff --git a/crates/io/src/blocks/more_tests.rs b/crates/io/src/blocks/more_tests.rs index 3c41296134..ec3ccd6867 100644 --- a/crates/io/src/blocks/more_tests.rs +++ b/crates/io/src/blocks/more_tests.rs @@ -183,7 +183,7 @@ fn plld_unreadable_warps() { /// `SoLd` data with a 50 × 25 source, the quad `trnf` and, when given, a custom warp whose /// 16 control points are `pts`. fn sold_with_warp(trnf: [f64; 8], pts: Option<&[[f64; 2]]>) -> Vec { - use photocraft_psd::descriptor::ObjectArray; + use craft_psd::descriptor::ObjectArray; let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; let mut d = Descriptor::new("null") .with("Idnt", Value::Text(UnicodeString::new_nul("uuid-1"))) @@ -214,7 +214,7 @@ fn sold_with_warp(trnf: [f64; 8], pts: Option<&[[f64; 2]]>) -> Vec { /// descriptor with `deformNumCols` × `deformNumRows` control points and the patch boundaries /// in `quiltSliceX` / `quiltSliceY`. With `plain_warp`, a `warpNone` `warp` key sits next to it. fn sold_with_quilt(trnf: [f64; 8], cols: f64, rows: f64, sx: &[f64], sy: &[f64], pts: &[[f64; 2]], plain_warp: bool) -> Vec { - use photocraft_psd::descriptor::ObjectArray; + use craft_psd::descriptor::ObjectArray; let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; let bounds = || { Descriptor::new("Rctn") diff --git a/crates/io/src/blocks/tests.rs b/crates/io/src/blocks/tests.rs index 59193a9344..45e9ec206b 100644 --- a/crates/io/src/blocks/tests.rs +++ b/crates/io/src/blocks/tests.rs @@ -64,9 +64,9 @@ fn gradient_fill_opacity_stops_become_alpha() { /// `gs99`, which Photoshop doesn't write, so every gradient opened as Classic. #[test] fn gradient_fill_reads_the_interpolation_method() { + use craft_psd::descriptor::{Id, Value}; use photocraft_color::Color; use photocraft_doc::{Fill, GradientStyle}; - use photocraft_psd::descriptor::{Id, Value}; let f = Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false); let (k, data) = super::write_fill(&f); let d = super::parse_prefix_versioned(&data).unwrap(); @@ -84,8 +84,8 @@ fn gradient_fill_reads_the_interpolation_method() { #[test] fn lab_descriptor_colours_round_trip() { + use craft_psd::descriptor::{Descriptor, Value}; use photocraft_color::ColorMode; - use photocraft_psd::descriptor::{Descriptor, Value}; let d = Descriptor::new("LbCl").with("Lmnc", Value::Double(19.07)).with("A ", Value::Double(52.29)).with("B ", Value::Double(-85.08)); let c = super::color_from_desc(&d).unwrap(); assert_eq!(c.mode, ColorMode::Lab); @@ -103,8 +103,8 @@ fn lab_descriptor_colours_round_trip() { /// psd-tools `stroke-color-descriptors-hsb-with-rgb-mode.psd`, used to be dropped (#6774). #[test] fn hsb_descriptor_colours_parse() { + use craft_psd::descriptor::{Descriptor, Value}; use photocraft_doc::Fill; - use photocraft_psd::descriptor::{Descriptor, Value}; let hsb = |h: f64, s: f64, b: f64| { Descriptor::new("HSBC").with("H ", Value::UnitFloat { unit: *b"#Ang", value: h }).with("Strt", Value::Double(s)).with("Brgh", Value::Double(b)) }; @@ -174,8 +174,8 @@ fn gradient_stop_alpha_round_trips_once() { #[test] fn blending_ranges_map_to_blend_if() { + use craft_psd::layer::BlendingRanges; use photocraft_doc::{BlendIf, BlendRange}; - use photocraft_psd::layer::BlendingRanges; // Full ranges (what every layer without Blend If carries) → the default setting. assert_eq!(super::blend_if_from_ranges(&BlendingRanges::full(3)), BlendIf::default()); assert_eq!(super::blend_if_from_ranges(&BlendingRanges::default()), BlendIf::default()); @@ -240,8 +240,8 @@ fn brst_round_trip() { #[test] fn placed_layer_warp_is_read() { + use craft_psd::descriptor::ObjectArray; use photocraft_geom::warp::WarpStyle; - use photocraft_psd::descriptor::ObjectArray; let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; let bounds = Descriptor::new("Rctn") .with("Top ", Value::UnitFloat { unit: *b"#Pxl", value: 0.0 }) diff --git a/crates/io/src/camera_raw_map.rs b/crates/io/src/camera_raw_map.rs index a53d6d40c6..5c057e173a 100644 --- a/crates/io/src/camera_raw_map.rs +++ b/crates/io/src/camera_raw_map.rs @@ -1,9 +1,9 @@ //! Camera Raw Filter descriptors observed in real PSD files (filter version 18.4, process 6). //! Verified develop controls are editable. Other processing versions //! or settings retain the entire filter through the existing opaque-filter path. +use craft_psd::descriptor::{Descriptor, UnicodeString, Value}; use photocraft_algo::camera_raw::CameraRaw; use photocraft_doc::SmartFilter; -use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value}; use serde_json::{Value as J, json}; use super::{blend_options, from_hex, get_desc, int, rgbc, set, to_hex}; @@ -297,11 +297,7 @@ pub(super) fn export_item(params: &J) -> Result { if get_param(&original, param) != Some(value) { write_number(&mut d, key, value)?; if matches!(*key, "Temp" | "Tint") { - set( - &mut d, - "WBal", - Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new("WBal"), value: photocraft_psd::descriptor::Id::new("Cst ") }, - ); + set(&mut d, "WBal", Value::Enumerated { type_id: craft_psd::descriptor::Id::new("WBal"), value: craft_psd::descriptor::Id::new("Cst ") }); } } } diff --git a/crates/io/src/camera_raw_map/tests.rs b/crates/io/src/camera_raw_map/tests.rs index ad40acb25d..24b3cce4fa 100644 --- a/crates/io/src/camera_raw_map/tests.rs +++ b/crates/io/src/camera_raw_map/tests.rs @@ -52,7 +52,7 @@ fn source_item() -> Descriptor { fn all_controls_item() -> Descriptor { let mut item = source_item(); let mut d = get_desc(&item, "Fltr").unwrap().clone(); - set(&mut d, "WBal", Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new("WBal"), value: photocraft_psd::descriptor::Id::new("Cst ") }); + set(&mut d, "WBal", Value::Enumerated { type_id: craft_psd::descriptor::Id::new("WBal"), value: craft_psd::descriptor::Id::new("Cst ") }); set(&mut d, "ShpR", Value::Double(1.2)); for (key, value) in [ ("Temp", -26), diff --git a/crates/io/src/comps_map.rs b/crates/io/src/comps_map.rs index 3348061b34..7fc7e1c145 100644 --- a/crates/io/src/comps_map.rs +++ b/crates/io/src/comps_map.rs @@ -14,11 +14,11 @@ use std::collections::HashMap; +use craft_psd::descriptor::{Descriptor, UnicodeString, Value, VersionedDescriptor}; +use craft_psd::metadata::{MetadataItem, parse_shmd, write_shmd}; use photocraft_doc::comps::layer_position; use photocraft_doc::{Artboard, ArtboardBackground, CompLayerState, Document, Guides, Layer, LayerComp}; use photocraft_geom::Rect; -use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value, VersionedDescriptor}; -use photocraft_psd::metadata::{MetadataItem, parse_shmd, write_shmd}; use crate::blocks::{color_from_desc, color_to_desc, num}; diff --git a/crates/io/src/count_resource_tests.rs b/crates/io/src/count_resource_tests.rs index fa84fc2233..ffe6a4e3c8 100644 --- a/crates/io/src/count_resource_tests.rs +++ b/crates/io/src/count_resource_tests.rs @@ -1,8 +1,8 @@ +use craft_psd::descriptor::{Descriptor, UnicodeString, Value, VersionedDescriptor}; +use craft_psd::{ColorMode as PsdMode, ImageResource, PsdFile}; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::{Color, ColorTable, CountGroup, Document}; use photocraft_geom::Size; -use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value, VersionedDescriptor}; -use photocraft_psd::{ColorMode as PsdMode, ImageResource, PsdFile}; use super::{COUNT_INFO, count_groups_from_resource}; diff --git a/crates/io/src/displace_map.rs b/crates/io/src/displace_map.rs index 792c8e72df..832479567b 100644 --- a/crates/io/src/displace_map.rs +++ b/crates/io/src/displace_map.rs @@ -21,10 +21,10 @@ use std::sync::Arc; +use craft_psd::descriptor::{Descriptor, Id, Value}; use photocraft_algo::Image; use photocraft_doc::SmartFilter; use photocraft_geom::Rect; -use photocraft_psd::descriptor::{Descriptor, Id, Value}; use serde_json::{Value as J, json}; use super::{blend_options, from_hex, get_desc, int, set, to_hex}; @@ -233,7 +233,7 @@ pub fn embed_map(params: &J, map: &Image) -> Option { // and when it is written to PSD (`export_item`). let neutral = SmartFilter { command: String::new(), params: J::Null, blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true }; let item = Descriptor::new("filterFX") - .with("Nm ", Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul("Displace..."))) + .with("Nm ", Value::Text(craft_psd::descriptor::UnicodeString::new_nul("Displace..."))) .with("blendOptions", blend_options(&neutral)) .with("enab", Value::Boolean(true)) .with("hasoptions", Value::Boolean(true)) @@ -305,7 +305,7 @@ mod tests { fn item(map: Vec) -> Descriptor { let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; Descriptor::new("filterFX") - .with("Nm ", Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul("Displace..."))) + .with("Nm ", Value::Text(craft_psd::descriptor::UnicodeString::new_nul("Displace..."))) .with( "blendOptions", blend_options(&SmartFilter { diff --git a/crates/io/src/duotone_map.rs b/crates/io/src/duotone_map.rs index 693264adec..77d60b249f 100644 --- a/crates/io/src/duotone_map.rs +++ b/crates/io/src/duotone_map.rs @@ -21,9 +21,9 @@ //! every ink's Lab equivalent in image resource 1066 (Alternate Duotone Colors): version 1, a //! count, then one 10-byte colour per ink in the same order. +use craft_psd::aco::AcoColor; use photocraft_doc::adjust::CurvePoint; use photocraft_doc::{Duotone, DuotoneInk}; -use photocraft_psd::aco::AcoColor; /// Length of the block Photoshop writes. pub(crate) const BLOCK_LEN: usize = 524; diff --git a/crates/io/src/effects_map.rs b/crates/io/src/effects_map.rs index 0c7f60154f..357f7e6493 100644 --- a/crates/io/src/effects_map.rs +++ b/crates/io/src/effects_map.rs @@ -3,13 +3,13 @@ //! Key names follow the descriptors Photoshop writes (documented by //! reverse-engineering in MIT-licensed psd-tools / ag-psd). +use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; use photocraft_color::{BlendMode, Color}; use photocraft_doc::adjust::CurvePoint; use photocraft_doc::{ Bevel, BevelContour, BevelStyle, BevelTechnique, BevelTexture, Contour, Effect, FxCommon, FxPaint, Glow, GlowSource, GlowTechnique, Gradient, Satin, Shadow, StrokeFx, StrokePosition, }; -use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; use crate::blocks::{ bool_of, color_from_desc, color_to_desc, enum_of, get_desc, gradient_desc, gradient_style, gradient_style_value, num, pattern_placement, pattern_ref, diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 096e32645b..96a0d69829 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -927,7 +927,7 @@ fn flat_document( warnings.extend(crate::unequal_resolution_warning(f64::from(x), f64::from(y))); } // Guides in the Photoshop resources a JPEG (APP13) or TIFF carries: resource 1032. - let guides = meta.photoshop_resources.as_deref().and_then(|r| photocraft_psd::tiff::resources_from_bytes(r).ok()); + let guides = meta.photoshop_resources.as_deref().and_then(|r| craft_psd::tiff::resources_from_bytes(r).ok()); if let Some(g) = guides.as_ref().and_then(|(res, _)| res.iter().find(|r| r.id == 1032)) { crate::psd_import::parse_guides(&g.data, &mut doc); } @@ -1141,7 +1141,7 @@ fn single_layer_document( warnings.extend(crate::unequal_resolution_warning(f64::from(x), f64::from(y))); } // Guides in the Photoshop resources a JPEG (APP13) or TIFF carries: resource 1032. - let guides = meta.photoshop_resources.as_deref().and_then(|r| photocraft_psd::tiff::resources_from_bytes(r).ok()); + let guides = meta.photoshop_resources.as_deref().and_then(|r| craft_psd::tiff::resources_from_bytes(r).ok()); if let Some(g) = guides.as_ref().and_then(|(res, _)| res.iter().find(|r| r.id == 1032)) { crate::psd_import::parse_guides(&g.data, &mut doc); } diff --git a/crates/io/src/gradient_bake.rs b/crates/io/src/gradient_bake.rs index 1d2aa5d296..6dee3dfd93 100644 --- a/crates/io/src/gradient_bake.rs +++ b/crates/io/src/gradient_bake.rs @@ -230,8 +230,8 @@ const OPACITY_RESPONSE: f32 = 0.65; /// Dense linear opacity stops reproducing Photoshop's interpolation of a gradient's transparency /// (Smoothness, opacity midpoints and the method, see [`OPACITY_RESPONSE`]). Returns the input -/// unchanged when it already interpolates linearly. Smooth keeps Classic's opacity curve: it was -/// not measured (the Photoshop build it was fitted on has no Smooth method). +/// unchanged when it already interpolates linearly. Smooth keeps Classic's opacity curve here: it +/// was measured only in the Gradient tool at 100 % Smoothness ([`bake_smooth_opacity`]). pub fn bake_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32], smoothness: f32, method: Method) -> Vec<(f32, f32)> { let method = if method == Method::Smooth { Method::Classic } else { method }; let plain_mids = midpoints.iter().all(|m| (m - 0.5).abs() < 1e-3); @@ -271,6 +271,38 @@ pub fn bake_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32], smoothness: f32, baked } +/// Gamma of Smooth's opacity response: the opacity of a fully transparent gradient ramp is the +/// Oklab lightness curve's linear value `y` raised to `1 / 2.2`. Photoshop 27.11, "Foreground to +/// Transparent" dragged over 600 px: alpha 255 / 179 / 100 / 35 / 0 at 50 / 250 / 400 / 550 / 750 +/// (#12010). The same ramp as an sRGB grey (`y` encoded with the sRGB curve) gives 30 at the dark +/// end, 5 levels off, where the 2.2 power gives 35. +const SMOOTH_OPACITY_GAMMA: f32 = 2.2; + +/// Smooth's transparency ramp: each opacity stop is a grey whose Oklab lightness is +/// `(opacity^2.2)^(1/3)`, which the colours' measured Smooth easing ([`SMOOTH_EASE`]) crosses +/// segment by segment, and the linear value `y = L^3` comes out as opacity `y^(1/2.2)`. Measured +/// in the Gradient tool at 100 % Smoothness with 50 % midpoints, the only case that uses it. +/// Constant opacity comes back as it is, clamped to 0..=1. +pub fn bake_smooth_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32]) -> Vec<(f32, f32)> { + let clamp = |o: f32| if o.is_finite() { o.clamp(0.0, 1.0) } else { 1.0 }; + if stops.len() < 2 || stops.windows(2).all(|w| w[0].1 == w[1].1) { + return stops.into_iter().map(|(t, o)| (t, clamp(o))).collect(); + } + let mut s = stops; + s.sort_by(|a, b| a.0.total_cmp(&b.0)); + let pts: Vec<(f32, [f32; 3])> = s.iter().map(|(t, o)| (*t, [clamp(*o).powf(SMOOTH_OPACITY_GAMMA).cbrt(); 3])).collect(); + const N: usize = 96; + let mut baked: Vec<(f32, f32)> = (0..=N) + .map(|k| { + let t = k as f32 / N as f32; + let l = eval(&pts, midpoints, 0.0, t, Method::Smooth)[0]; + (t, if l.is_finite() { l.clamp(0.0, 1.0).powi(3).powf(1.0 / SMOOTH_OPACITY_GAMMA) } else { 1.0 }) + }) + .collect(); + baked.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6); + baked +} + #[cfg(test)] mod tests { use super::*; @@ -426,6 +458,14 @@ mod tests { assert!((at(&s, 0.25)[0] - 0.5).abs() < 0.01); } + #[test] + fn smooth_opacity_clamps_constant_stops() { + let flat = vec![(0.0, 0.4), (1.0, 0.4)]; + assert_eq!(bake_smooth_opacity(flat.clone(), &[0.5]), flat); + assert_eq!(bake_smooth_opacity(vec![(0.0, 2.0), (1.0, 2.0)], &[0.5]), vec![(0.0, 1.0), (1.0, 1.0)]); + assert_eq!(bake_smooth_opacity(vec![(0.5, f32::NAN)], &[]), vec![(0.5, 1.0)]); + } + /// `eval` guards its own stops instead of relying on `bake`'s two-stop check. #[test] fn eval_with_fewer_than_two_stops_does_not_index_out_of_range() { diff --git a/crates/io/src/hue_sat_filter_map.rs b/crates/io/src/hue_sat_filter_map.rs index 05af178c27..b7b80fe5bb 100644 --- a/crates/io/src/hue_sat_filter_map.rs +++ b/crates/io/src/hue_sat_filter_map.rs @@ -14,9 +14,9 @@ //! when the smart object does. Anything else (an unknown key, a duplicated or unknown range, a //! value Photoshop's dialog can't hold) stays an opaque [`super::UNSUPPORTED_FILTER`]. +use craft_psd::descriptor::{Descriptor, UnicodeString, Value}; use photocraft_doc::SmartFilter; use photocraft_doc::adjust::HueRange; -use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value}; use serde_json::{Map, Value as J, json}; use super::{blend_options, enumv, is_meta, rgbc}; @@ -198,8 +198,8 @@ pub(super) fn export_item(f: &SmartFilter) -> Result { mod tests { use super::*; use crate::smart_map::{UNSUPPORTED_FILTER, filter_from_item, item_for_filter}; + use craft_psd::descriptor::Id; use photocraft_color::BlendMode; - use photocraft_psd::descriptor::Id; fn hst2(range: Option<(i32, [i32; 4])>, h: i32, s: i32, l: i32) -> Value { let mut d = Descriptor::new("Hst2"); diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index b5d01f8cdf..c5bf5ed63e 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -2,7 +2,7 @@ //! //! Import and export between [`photocraft_doc::Document`] and files: //! -//! * PSD / PSB (detected by the `8BPS` signature) via `photocraft-psd`, with +//! * PSD / PSB (detected by the `8BPS` signature) via `craft-psd`, with //! fidelity levels 1–3 (raster layers, masks, blend/opacity/fill, //! visibility, names, groups, clipping, adjustment and fill layers). //! Every layer keeps its unmodelled tagged blocks in `Layer::psd_blocks` @@ -53,7 +53,7 @@ mod flat; pub mod gradient_bake; pub mod guides_map; mod png_steps; -pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient}; +pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient, bake_smooth_opacity as bake_gradient_smooth_opacity}; mod duotone_map; mod kra; pub mod linked; @@ -91,11 +91,11 @@ pub mod vector_preview; mod xcf; pub mod xml; +use craft_psd::{PsdError, PsdFile}; pub use export_estimate::estimate_export_bytes; use photocraft_codecs::{CodecError, EncodeOptions}; pub use photocraft_codecs::{DdsCompression, DdsOptions, DpxBits}; use photocraft_doc::{Adjustment, Document, Layer, LayerContent}; -use photocraft_psd::{PsdError, PsdFile}; pub use adjust_map::ADJUSTMENT_KEYS; pub use flat::{ @@ -609,6 +609,9 @@ pub struct ImportOptions { pub max_group_depth: usize, /// The demosaic method camera raws are developed with. pub demosaic: raw::Demosaic, + /// Keep a developed raw's sensor data for its open-time Camera Raw dialog + /// ([`raw::take_kept_decode`]) instead of decoding the file again there. + pub keep_raw: bool, /// PSD layer/mask/merged pixel allowance, including conversion workspace, and the /// equivalent allowance for a layered TIFF's composite and retained decoded image. May /// lower the default cap; 0 uses the adaptive budget. Does not cover metadata or @@ -641,6 +644,7 @@ impl Default for ImportOptions { ImportOptions { max_group_depth: photocraft_doc::MAX_GROUP_DEPTH, demosaic: raw::Demosaic::default(), + keep_raw: false, psd_max_pixel_bytes: 0, flat_max_pixel_bytes: 0, pdf_dpi: 300.0, @@ -696,10 +700,7 @@ fn import_psd( ctl: &photocraft_raster::Interrupt, damaged: &mut bool, opts: &ImportOptions, - parse: impl FnOnce( - &dyn Fn(&PsdFile) -> photocraft_psd::Result, - &dyn Fn(&PsdFile) -> bool, - ) -> photocraft_psd::Result<(PsdFile, Option>>)>, + parse: impl FnOnce(&dyn Fn(&PsdFile) -> craft_psd::Result, &dyn Fn(&PsdFile) -> bool) -> craft_psd::Result<(PsdFile, Option>>)>, ) -> Result { let preflight_error = std::cell::RefCell::new(None); let admission_guard: std::cell::RefCell> = std::cell::RefCell::new(None); @@ -837,7 +838,7 @@ pub fn import_file_for_open_verified( ) -> Result<(ImportResult, bool), IoError> { let read_failed = |e: std::io::Error| IoError::Read(format!("{}: {e}", path.display())); ctl.check().map_err(|_| IoError::Cancelled)?; - let source = photocraft_psd::FileSource::open(path).map_err(read_failed)?; + let source = craft_psd::FileSource::open(path).map_err(read_failed)?; let metadata = source.file().metadata().map_err(read_failed)?; if !metadata.is_file() { return Err(IoError::Read(format!("{}: not a regular file", path.display()))); @@ -851,9 +852,9 @@ pub fn import_file_for_open_verified( // the identity from it after parsing, and never from a path that may point elsewhere now. let watch = source.file().try_clone().map_err(read_failed)?; let mut magic = [0u8; 4]; - let psd = !has_extension(name, photocraft_format::EXTENSION) && photocraft_psd::ReadAt::read_at(&source, 0, &mut magic).is_ok() && is_psd(&magic); + let psd = !has_extension(name, photocraft_format::EXTENSION) && craft_psd::ReadAt::read_at(&source, 0, &mut magic).is_ok() && is_psd(&magic); let result = if psd { - import_source_with_options(name, photocraft_psd::Source::new(source), ctl, opts) + import_source_with_options(name, craft_psd::Source::new(source), ctl, opts) } else { // Read from the handle that was just identified, not by opening the path again. let mut file = source.file(); @@ -881,7 +882,7 @@ pub fn import_file_for_open_verified( match streamed { Some(result) => Ok((result, false)), None => { - let bytes = photocraft_format::read::read_all(&mut file, photocraft_psd::ReadAt::len(&source)).map_err(read_failed)?; + let bytes = photocraft_format::read::read_all(&mut file, craft_psd::ReadAt::len(&source)).map_err(read_failed)?; import_for_open_with(name, &bytes, opts, ctl) } } @@ -898,15 +899,15 @@ pub fn import_file_for_open_verified( result } -/// [`import_file_for_open_with`] for a PSD/PSB in any [`photocraft_psd::ReadAt`] source. -pub fn import_source_for_open_with(name: &str, source: photocraft_psd::Source, ctl: &photocraft_raster::Interrupt) -> Result<(ImportResult, bool), IoError> { +/// [`import_file_for_open_with`] for a PSD/PSB in any [`craft_psd::ReadAt`] source. +pub fn import_source_for_open_with(name: &str, source: craft_psd::Source, ctl: &photocraft_raster::Interrupt) -> Result<(ImportResult, bool), IoError> { import_source_with_options(name, source, ctl, &ImportOptions::default()) } /// [`import_source_for_open_with`] with custom import options. pub fn import_source_with_options( name: &str, - source: photocraft_psd::Source, + source: craft_psd::Source, ctl: &photocraft_raster::Interrupt, opts: &ImportOptions, ) -> Result<(ImportResult, bool), IoError> { @@ -923,7 +924,7 @@ pub fn import_source_with_options( #[cfg(test)] pub(crate) fn import_source_with_limit( name: &str, - source: photocraft_psd::Source, + source: craft_psd::Source, ctl: &photocraft_raster::Interrupt, pixel_limit: u64, ) -> Result<(ImportResult, bool), IoError> { @@ -1022,13 +1023,19 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o Ok(ImportResult { warnings: open_warnings(&document), document, source_read_only: false, preview_only: false }) } Route::Psd | Route::NamedPsd => import_psd(name, ctl, damaged, opts, |want, recover| PsdFile::from_bytes_and_merged_preflight(bytes, want, recover)), - Route::Affinity => affinity::import(name, bytes), + Route::Affinity => affinity::import(name, bytes, ctl), Route::Ora => ora::import(name, bytes, ctl), Route::Kra => kra::import(name, bytes, ctl), Route::Xcf => xcf::import(name, bytes, ctl), Route::GzippedXcf => xcf::import(name, &xcf::gunzip(bytes)?, ctl), Route::Pdn => pdn::import(name, bytes, ctl), - Route::Raw => raw::import_raw_demosaic(name, bytes, opts.demosaic), + Route::Raw => { + if opts.keep_raw { + raw::import_raw_demosaic_keeping(name, bytes, opts.demosaic) + } else { + raw::import_raw_demosaic(name, bytes, opts.demosaic) + } + } Route::Svg => svg::import_svg_with_group_depth(name, bytes, opts.max_group_depth), Route::Flat => flat::import_flat_with_options(name, bytes, opts, ctl), } @@ -1266,7 +1273,7 @@ fn export_stages_with_renderer( match preview { // Beside the other resources Photoshop writes ahead of the version info. Ok(r) => { - let at = file.resources.iter().position(|r| r.id == photocraft_psd::resources::ids::VERSION_INFO).unwrap_or(file.resources.len()); + let at = file.resources.iter().position(|r| r.id == craft_psd::resources::ids::VERSION_INFO).unwrap_or(file.resources.len()); file.resources.insert(at, r); } Err(e) => warnings.push(format!("image preview not saved: {e}")), @@ -1347,7 +1354,7 @@ fn pcraft_full_composite_with(doc: &Document, ctl: &photocraft_raster::Interrupt pub fn merged_composite(file: &PsdFile) -> Result, IoError> { let h = &file.header; h.validate()?; - if h.color_mode == photocraft_psd::ColorMode::Rgb && file.merged_has_alpha() { + if h.color_mode == craft_psd::ColorMode::Rgb && file.merged_has_alpha() { // Preserve native sample precision before removing the white matte. let raw = file.decode_merged()?; let plane = raw.len() / usize::from(h.channels); @@ -1358,9 +1365,9 @@ pub fn merged_composite(file: &PsdFile) -> Result, IoError> { .chunks_exact(plane) .take(4) .map(|bytes| match h.depth { - 32 => Ok(photocraft_psd::pixels::samples_f32(bytes)), - 16 => Ok(photocraft_psd::pixels::samples_u16(bytes).into_iter().map(|v| f32::from(v) / 65535.0).collect()), - _ => photocraft_psd::pixels::plane_to_u8(bytes, h.depth, h.width as usize, h.height as usize) + 32 => Ok(craft_psd::pixels::samples_f32(bytes)), + 16 => Ok(craft_psd::pixels::samples_u16(bytes).into_iter().map(|v| f32::from(v) / 65535.0).collect()), + _ => craft_psd::pixels::plane_to_u8(bytes, h.depth, h.width as usize, h.height as usize) .map(|values| values.into_iter().map(|v| f32::from(v) / 255.0).collect()), }) .collect::, _>>()?; @@ -1388,7 +1395,7 @@ pub fn merged_composite(file: &PsdFile) -> Result, IoError> { let img = if h.depth == 32 { None } else { file.composite_rgba8().ok() }; // CMYK goes through the colour-managed model conversion (the PSD crate's RGBA preview is a // naive, profile-free conversion). - if let (Some(img), false) = (img, matches!(h.color_mode, photocraft_psd::ColorMode::Lab | photocraft_psd::ColorMode::Cmyk)) { + if let (Some(img), false) = (img, matches!(h.color_mode, craft_psd::ColorMode::Lab | craft_psd::ColorMode::Cmyk)) { let unmatte = file.merged_has_alpha(); return Ok(img .data @@ -1409,7 +1416,7 @@ pub fn merged_composite(file: &PsdFile) -> Result, IoError> { // Generic path (Lab, CMYK and others) via the raster model conversion. // Keep the merged-alpha marker while discarding layers: otherwise an extra // spot/alpha channel in an opaque composite is mistaken for transparency. - let layer_info = Some(photocraft_psd::LayerInfo { merged_alpha: file.merged_has_alpha(), layers: Vec::new(), padding: None }); + let layer_info = Some(craft_psd::LayerInfo { merged_alpha: file.merged_has_alpha(), layers: Vec::new(), padding: None }); 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 { @@ -1426,7 +1433,7 @@ pub fn merged_composite(file: &PsdFile) -> Result, IoError> { #[cfg(test)] mod tests { use super::{ImportOptions, ImportPreflight, import, import_for_open, import_preflight, is_psd_input, is_svg_input}; - use photocraft_psd::{Compression, Version, testgen}; + use craft_psd::{Compression, Version, testgen}; /// The callers that fit several imports into one budget choose their option from this /// classification, so it has to follow the same dispatch as [`super::import`]. diff --git a/crates/io/src/linked.rs b/crates/io/src/linked.rs index 62db468b33..13201ae1c1 100644 --- a/crates/io/src/linked.rs +++ b/crates/io/src/linked.rs @@ -9,8 +9,8 @@ //! Pascal uuid, Unicode file name, file type, creator, `u64` data length, open-descriptor flag (+ //! versioned descriptor), then for `liFD` the raw file bytes. +use craft_psd::descriptor::VersionedDescriptor; use photocraft_doc::Metadata; -use photocraft_psd::descriptor::VersionedDescriptor; /// An embedded file found in a linked-layer block. #[derive(Clone, Debug, PartialEq, Eq)] @@ -528,7 +528,7 @@ mod tests { assert_eq!(rebuild_block(&data, &|_| true, &[]), None); let out = rebuild_block(&data, &|u| u != "a", std::slice::from_ref(&c)).unwrap(); assert_eq!(parse_linked_files(&out), vec![b.clone(), c.clone()]); - photocraft_psd::TaggedBlock::new(*b"lnk2", out).check_structure().unwrap(); + craft_psd::TaggedBlock::new(*b"lnk2", out).check_structure().unwrap(); assert_eq!(file_type(&b.bytes), *b"8BPB"); assert_eq!(file_type(&a.bytes), *b"PNGf"); // A malformed tail is kept as is. diff --git a/crates/io/src/memory.rs b/crates/io/src/memory.rs index c4a304defa..d36eba24f3 100644 --- a/crates/io/src/memory.rs +++ b/crates/io/src/memory.rs @@ -54,7 +54,7 @@ pub const LOW_MEMORY_WARNING_MARGIN: u64 = 1 << 30; /// A layer plane, a decode buffer or a tile is one contiguous allocation, so each must fit this /// limit at the point it is allocated. An import's peak is the *sum* of many such buffers and /// may legitimately exceed this; decode paths enforce their own per-buffer limits -/// (`photocraft-psd::MAX_DECODED_BYTES`, `photocraft-codecs`' `Limits::max_alloc`) there. +/// (`craft-psd::MAX_DECODED_BYTES`, `photocraft-codecs`' `Limits::max_alloc`) there. pub const MAX_SINGLE_ALLOCATION: u64 = isize::MAX as u64; /// Architectural maximum linear memory of wasm32: 65,536 pages of 64 KiB (4 GiB). diff --git a/crates/io/src/multichannel_map.rs b/crates/io/src/multichannel_map.rs index dae96c4756..108b1931b1 100644 --- a/crates/io/src/multichannel_map.rs +++ b/crates/io/src/multichannel_map.rs @@ -7,12 +7,12 @@ //! alpha channels of every other mode (max = selected). Channel names come from resources 1006 / //! 1045 and ink colours from DisplayInfo (1077), exactly as for spot channels in the other modes. +use craft_psd::file::{GlobalLayerMask, LayerInfoPlacement}; +use craft_psd::resources::{ImageResource, ResolutionInfo, ids, version_info_resource}; +use craft_psd::{ColorMode as PsdMode, Compression, Header, ImageData, PsdFile, TaggedBlock}; use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; use photocraft_doc::{AlphaChannel, Document}; use photocraft_geom::Rect; -use photocraft_psd::file::{GlobalLayerMask, LayerInfoPlacement}; -use photocraft_psd::resources::{ImageResource, ResolutionInfo, ids, version_info_resource}; -use photocraft_psd::{ColorMode as PsdMode, Compression, Header, ImageData, PsdFile, TaggedBlock}; use photocraft_raster::Surface; use crate::pixels::{encode_be, psd_depth}; @@ -48,6 +48,7 @@ pub(crate) fn import(file: &PsdFile, all: &[u8], doc: &mut Document, names: &[St return Err(crate::IoError::Unsupported("multichannel channel depth does not match its pixel layout".into())); } let fmt = PixelFormat::new(ColorMode::Grayscale, depth, false); + // The PSD preflight (`psd_budget`) already admitted these channels' tile storage, at whatever limit it was given. for k in 0..usize::from(h.channels) { let start = k.checked_mul(plane).ok_or_else(invalid)?; let end = start.checked_add(plane).ok_or_else(invalid)?; @@ -157,7 +158,7 @@ pub(crate) fn document_to_psd( } // Alpha identifiers: one u32 per channel, only while they still match the channels. let keep = |id: u16, data: &[u8]| id != ALPHA_IDENTIFIERS || data.len() == channels.len().saturating_mul(4); - let color_mode_data = photocraft_psd::hdr::color_mode_data_for_depth(header.depth); + let color_mode_data = craft_psd::hdr::color_mode_data_for_depth(header.depth); let file = layerless_file(doc, header, image_data, color_mode_data, resources, keep, size_limit, &mut warnings, patterns); (file, warnings) } @@ -240,7 +241,7 @@ mod import_allocation_tests { #[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 file = craft_psd::testgen::merged_only(craft_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(); diff --git a/crates/io/src/ora.rs b/crates/io/src/ora.rs index 36ebbc7b0a..48ea0550f6 100644 --- a/crates/io/src/ora.rs +++ b/crates/io/src/ora.rs @@ -374,7 +374,7 @@ pub(crate) fn csample(depth: SampleType) -> CSample { } /// Builds the document tree bottom-to-top (stack.xml lists the topmost node first). -fn build(nodes: Vec, images: &[Image], fmt: PixelFormat, ctl: &Interrupt<'_>) -> Result> { +fn build(nodes: Vec, images: &[Image], fmt: PixelFormat, budget: &mut usize, ctl: &Interrupt<'_>) -> Result> { let mut out = Vec::with_capacity(nodes.len()); for node in nodes.into_iter().rev() { ctl.check().map_err(|_| IoError::Cancelled)?; @@ -388,14 +388,24 @@ fn build(nodes: Vec, images: &[Image], fmt: PixelFormat, ctl: &Interrupt<' if rect.width() != w || rect.height() != h || px.data().len() != (w as usize) * (h as usize) * fmt.bytes_per_pixel() { return Err(invalid("layer image does not fit its position")); } + // Admitted by decoded size; the surface stores whole tiles, many more for a + // narrow image or one offset across tile edges. + // The check stays before the write (it allocates the whole rect's tiles); only the + // tiles kept after `prune()` are charged. + let tiles = usize::try_from(photocraft_raster::tile_storage_bytes(rect, &fmt)).unwrap_or(usize::MAX); + if tiles > *budget { + return Err(invalid("decoded layers exceed the 1 GiB limit")); + } surface.write_interleaved(rect, px.data()); surface.prune(); + let kept = usize::try_from(photocraft_raster::stored_tiles_bytes(surface.tile_count() as u64, &fmt)).unwrap_or(usize::MAX); + *budget = budget.saturating_sub(kept); } layer.content = LayerContent::Raster(surface); out.push(layer); } Node::Group { mut layer, children } => { - let children = build(children, images, fmt, ctl)?; + let children = build(children, images, fmt, budget, ctl)?; if let Some(c) = layer.children_mut() { *c = children; } @@ -448,7 +458,7 @@ pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result 0.0 && xres < 1.0e6 { diff --git a/crates/io/src/palette_map.rs b/crates/io/src/palette_map.rs index ed2273175b..022bcaa24b 100644 --- a/crates/io/src/palette_map.rs +++ b/crates/io/src/palette_map.rs @@ -5,10 +5,10 @@ //! Data (768 bytes: 256 reds, 256 greens, 256 blues), its length in resource 1046 and the //! transparent entry in resource 1047; for Bitmap one plane of 1 bit per pixel, 1 = black. +use craft_psd::resources::{ImageResource, ResolutionInfo, ids}; +use craft_psd::{ColorMode as PsdMode, Compression, Header, ImageData, PsdFile}; use photocraft_color::ColorMode; use photocraft_doc::{ColorTable, Document}; -use photocraft_psd::resources::{ImageResource, ResolutionInfo, ids}; -use photocraft_psd::{ColorMode as PsdMode, Compression, Header, ImageData, PsdFile}; /// Indexed Color Table Count: the number of colours in the table (u16). pub(crate) const COLOR_TABLE_COUNT: u16 = 1046; diff --git a/crates/io/src/pattern_map.rs b/crates/io/src/pattern_map.rs index 53c69dc80b..1a7ba6d592 100644 --- a/crates/io/src/pattern_map.rs +++ b/crates/io/src/pattern_map.rs @@ -6,10 +6,10 @@ use std::sync::Arc; +use craft_psd::patterns::{PatternBudget, PsdPattern, block_has_user_mask, block_key, mode_channels, parse_pattern_block_with, write_pattern_block}; use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_doc::{Document, Pattern}; 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::{max_sample, psd_depth, sample_for_depth, try_interleave, zero_sample}; @@ -110,7 +110,7 @@ fn pattern_from_psd(p: &PsdPattern, oom: &mut Option) -> Option } let mut bytes = match try_interleave(&refs, &fill, n, s, &invert) { Ok(bytes) => bytes, - Err(photocraft_psd::PsdError::OutOfMemory(error)) => { + Err(craft_psd::PsdError::OutOfMemory(error)) => { *oom = Some(error.to_string()); return None; } @@ -230,7 +230,7 @@ pub fn try_from_global_blocks(doc: &Document) -> Result, String> { 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(craft_psd::PsdError::OutOfMemory(error)) => return Err(error.to_string()), Err(_) => continue, }; for p in patterns { @@ -331,14 +331,14 @@ fn repair_legacy_blocks(raw: &[photocraft_doc::PsdGlobalBlock]) -> Vec Result, String> { - let ps = photocraft_psd::patterns::parse_pat_file(bytes).map_err(|e| format!("not a readable .pat file: {e}"))?; + let ps = craft_psd::patterns::parse_pat_file(bytes).map_err(|e| format!("not a readable .pat file: {e}"))?; Ok(ps.iter().filter_map(from_psd).collect()) } /// Writes patterns as a `.pat` file. pub fn write_pat(patterns: &[Pattern]) -> Result, String> { let patterns = to_psd_patterns(patterns)?; - photocraft_psd::patterns::write_pat_file(&patterns).map_err(|e| e.to_string()) + craft_psd::patterns::write_pat_file(&patterns).map_err(|e| e.to_string()) } #[cfg(test)] diff --git a/crates/io/src/pdn.rs b/crates/io/src/pdn.rs index 1e2d99f7af..796c44f426 100644 --- a/crates/io/src/pdn.rs +++ b/crates/io/src/pdn.rs @@ -220,6 +220,10 @@ pub(super) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result MAX_PIXEL_BYTES { return Err(invalid("decoded pixels exceed the 1 GiB limit")); } diff --git a/crates/io/src/perspective_warp_map.rs b/crates/io/src/perspective_warp_map.rs index cb5815bb81..1216814f82 100644 --- a/crates/io/src/perspective_warp_map.rs +++ b/crates/io/src/perspective_warp_map.rs @@ -21,9 +21,9 @@ //! rewritten from the edited planes. Anything inconsistent (an index out of range, mismatched //! vertex counts, a non-finite or degenerate quad) stays an opaque [`super::UNSUPPORTED_FILTER`]. +use craft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value}; use photocraft_algo::perspective::{PerspectiveMap, Plane, Straighten, straighten}; use photocraft_doc::SmartFilter; -use photocraft_psd::descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value}; use serde_json::{Value as J, json}; use super::{blend_options, from_hex, get_desc, rgbc, set, to_hex, unit}; diff --git a/crates/io/src/pixels.rs b/crates/io/src/pixels.rs index 63c6742a1c..5a3a5c46e2 100644 --- a/crates/io/src/pixels.rs +++ b/crates/io/src/pixels.rs @@ -55,11 +55,11 @@ pub fn interleave(planes: &[Option<&[u8]>], fill: &[Vec], n: usize, s: Sampl /// Fallible interleave for file imports. Validate sizes and missing-plane fills before /// workers write disjoint slices of one reserved output buffer. -pub fn try_interleave(planes: &[Option<&[u8]>], fill: &[Vec], n: usize, s: SampleType, invert: &[bool]) -> photocraft_psd::Result> { - use photocraft_psd::PsdError; +pub fn try_interleave(planes: &[Option<&[u8]>], fill: &[Vec], n: usize, s: SampleType, invert: &[bool]) -> craft_psd::Result> { + use craft_psd::PsdError; let plane_bytes = n.checked_mul(s.bytes()).ok_or(PsdError::LimitExceeded("interleave size overflow"))?; let len = plane_bytes.checked_mul(planes.len()).ok_or(PsdError::LimitExceeded("interleave size overflow"))?; - if len as u64 > photocraft_psd::compression::MAX_DECODED_BYTES { + if len as u64 > craft_psd::compression::MAX_DECODED_BYTES { return Err(PsdError::LimitExceeded("interleave exceeds MAX_DECODED_BYTES")); } if n > 0 && planes.is_empty() { diff --git a/crates/io/src/psd_budget.rs b/crates/io/src/psd_budget.rs index 9a91469add..841450116a 100644 --- a/crates/io/src/psd_budget.rs +++ b/crates/io/src/psd_budget.rs @@ -4,11 +4,11 @@ //! 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. -use photocraft_geom::TILE_SIZE; -use photocraft_psd::{ +use craft_psd::{ PsdFile, layer::{CHANNEL_REAL_USER_MASK, CHANNEL_USER_MASK, Rect}, }; +use photocraft_geom::TILE_SIZE; use crate::IoError; @@ -174,7 +174,7 @@ pub fn estimate(file: &PsdFile) -> Result { let sample = u64::from(h.depth.div_ceil(8)); let cc = match h.color_mode { // Unknown modes use the RGB fallback, including its alpha channel. - photocraft_psd::ColorMode::Unknown(_) => 3, + craft_psd::ColorMode::Unknown(_) => 3, mode => u64::from(mode.color_channels().unwrap_or(3)), }; if super::psd_import::can_recover_layers(file) { @@ -219,15 +219,15 @@ pub fn estimate(file: &PsdFile) -> Result { 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(); + let mut patterns = craft_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); + let items = craft_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)); + let color = if p.mode == 2 { 3 } else { craft_psd::patterns::mode_channels(p.mode) as u64 }; + let alpha = u64::from(p.planes > craft_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. diff --git a/crates/io/src/psd_budget/tests.rs b/crates/io/src/psd_budget/tests.rs index edf83b7612..9767440ccb 100644 --- a/crates/io/src/psd_budget/tests.rs +++ b/crates/io/src/psd_budget/tests.rs @@ -1,5 +1,5 @@ use super::*; -use photocraft_psd::{ColorMode, Compression, Version, testgen}; +use craft_psd::{ColorMode, Compression, Version, testgen}; #[test] fn retained_storage_is_summed_but_workspace_is_reused() { @@ -58,7 +58,7 @@ fn large_off_canvas_layer_is_rejected_without_decoding_its_tiny_data() { // Unknown memory keeps a conservative automatic allowance, so this file is refused // pending approval (or by the hard platform limit on 32-bit) before any pixel decode. assert!(matches!(crate::import("huge.psd", &bytes), Err(IoError::PsdApprovalRequired { .. } | IoError::PsdImportBudget { .. }))); - let source = photocraft_psd::Source::new(bytes); + let source = craft_psd::Source::new(bytes); assert!(matches!( crate::import_source_for_open_with("huge.psd", source, &photocraft_raster::Interrupt::NONE), Err(IoError::PsdApprovalRequired { .. } | IoError::PsdImportBudget { .. }) @@ -71,7 +71,7 @@ fn user_mask_bounds_count_even_when_the_layer_is_small() { let mut file = testgen::small(Version::Psd, Compression::Raw); let before = estimate(&file); // The generator's first record has a user mask. Modify its parsed mask in place. - if let photocraft_psd::layer::MaskData::Mask(mask) = &mut file.layers_mut()[0].mask { + if let craft_psd::layer::MaskData::Mask(mask) = &mut file.layers_mut()[0].mask { mask.rect = Rect::from_xywh(0, 0, 20_000, 20_000); } else { panic!("fixture needs a parsed mask"); @@ -133,8 +133,8 @@ fn legacy_conversion_reports_a_rejected_import_instead_of_decoding_it() { }); } -fn pattern_block(mode: u32, depth: u16, width: u32, height: u32) -> photocraft_psd::TaggedBlock { - use photocraft_psd::patterns::{PsdPattern, mode_channels, write_pattern_block}; +fn pattern_block(mode: u32, depth: u16, width: u32, height: u32) -> craft_psd::TaggedBlock { + use craft_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, @@ -147,7 +147,7 @@ fn pattern_block(mode: u32, depth: u16, width: u32, height: u32) -> photocraft_p channels: vec![vec![0; len]; mode_channels(mode)], alpha: None, }; - photocraft_psd::TaggedBlock::new(*b"Patt", write_pattern_block(&[p]).unwrap()) + craft_psd::TaggedBlock::new(*b"Patt", write_pattern_block(&[p]).unwrap()) } #[test] @@ -190,14 +190,14 @@ fn an_unknown_color_mode_pays_for_the_layers_it_imports_as_rgb() { let rgb = testgen::small(Version::Psd, Compression::Raw); assert!(!rgb.layers().is_empty() && !super::super::psd_import::merged_needed(&rgb), "the fixture must import its layers alone"); let mut unknown = rgb.clone(); - unknown.header.color_mode = photocraft_psd::ColorMode::Unknown(5); + unknown.header.color_mode = craft_psd::ColorMode::Unknown(5); assert!(unknown.header.validate().is_ok()); let required = estimate(&unknown); assert!(required >= estimate(&rgb), "the layers import as RGB and are counted"); let bytes = unknown.to_bytes().unwrap(); let opts = crate::ImportOptions { psd_max_pixel_bytes: required - 1, ..Default::default() }; assert!(matches!(crate::import_with_options("mode5.psd", &bytes, &opts), Err(IoError::PsdImportBudget { .. }))); - let source = photocraft_psd::Source::new(bytes); + let source = craft_psd::Source::new(bytes); let refused = crate::import_source_with_limit("mode5.psd", source, &photocraft_raster::Interrupt::NONE, required - 1); assert!(matches!(refused, Err(IoError::PsdImportBudget { .. })), "{:?}", refused.map(|(r, _)| r.warnings)); } diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 8984de49c5..f8a01dd5af 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -1,13 +1,13 @@ //! [`Document`] → PSD/PSB. -use photocraft_color::{ColorMode, PixelFormat, SampleType}; -use photocraft_doc::{Document, Layer, LayerContent, LayerMask, SmartContentsId}; -use photocraft_psd::file::{GlobalLayerMask, LayerInfoPlacement}; -use photocraft_psd::layer::{BlendingRanges, ChannelData, LayerFlags, LayerInfo, LayerMask as PsdMask, MaskData, MaskParameters}; -use photocraft_psd::resources::{ImageResource, ResolutionInfo, ids, version_info_resource}; -use photocraft_psd::{ +use craft_psd::file::{GlobalLayerMask, LayerInfoPlacement}; +use craft_psd::layer::{BlendingRanges, ChannelData, LayerFlags, LayerInfo, LayerMask as PsdMask, MaskData, MaskParameters}; +use craft_psd::resources::{ImageResource, ResolutionInfo, ids, version_info_resource}; +use craft_psd::{ BlendMode as PsdBlend, ColorMode as PsdMode, Compression, Header, ImageData, LayerRecord, PsdFile, Rect as PsdRect, SectionType, TaggedBlock, Version, }; +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_doc::{Document, Layer, LayerContent, LayerMask, SmartContentsId}; use photocraft_raster::{Interrupt, Surface}; use crate::adjust_map; @@ -628,7 +628,7 @@ impl Ex<'_> { fn layer_xmp_block(&mut self, l: &Layer, raw: &mut Vec<([u8; 4], Vec)>) { let Some(xmp) = l.xmp.as_deref() else { return }; let pos = raw.iter().position(|(k, _)| k == b"shmd"); - match photocraft_psd::metadata::put_layer_xmp(pos.map(|i| raw[i].1.as_slice()), xmp) { + match craft_psd::metadata::put_layer_xmp(pos.map(|i| raw[i].1.as_slice()), xmp) { Ok(data) => match pos { Some(i) => raw[i].1 = data, None => raw.push((*b"shmd", data)), diff --git a/crates/io/src/psd_export/banded.rs b/crates/io/src/psd_export/banded.rs index a2aed97473..6a5ef0e955 100644 --- a/crates/io/src/psd_export/banded.rs +++ b/crates/io/src/psd_export/banded.rs @@ -15,8 +15,8 @@ use std::io::Write as _; -use photocraft_psd::compression::{PlaneLayout, encode_planes, predict}; -use photocraft_psd::{ChannelData, Compression, PsdError}; +use craft_psd::compression::{PlaneLayout, encode_planes, predict}; +use craft_psd::{ChannelData, Compression, PsdError}; use photocraft_raster::Surface; use super::Ex; @@ -76,7 +76,7 @@ impl Ex<'_> { } } - fn banded_pass(&self, s: &Surface, r: photocraft_geom::Rect, compression: Compression) -> photocraft_psd::Result> { + fn banded_pass(&self, s: &Surface, r: photocraft_geom::Rect, compression: Compression) -> craft_psd::Result> { let (w, h) = (r.width() as usize, r.height() as usize); let bpp = s.format().bytes_per_pixel(); let band_rows = (band_bytes() / (w * bpp).max(1)).max(1); @@ -115,7 +115,7 @@ impl Ex<'_> { // Alpha (planes[cc]) is channel 0, then the colour channels; each on its own thread. let work: Vec<(&mut Channel, Vec)> = channels.iter_mut().enumerate().map(|(k, c)| (c, planes[if k == 0 { self.cc } else { k - 1 }].take().unwrap_or_default())).collect(); - let done = crate::pixels::par_map(work, |(c, mut plane)| -> photocraft_psd::Result<()> { + let done = crate::pixels::par_map(work, |(c, mut plane)| -> craft_psd::Result<()> { check()?; match compression { Compression::Rle => { @@ -135,7 +135,7 @@ impl Ex<'_> { } Ok(()) }); - done.into_iter().collect::>()?; + done.into_iter().collect::>()?; #[cfg(test)] BANDS_DONE.set(BANDS_DONE.get() + 1); } diff --git a/crates/io/src/psd_export/document.rs b/crates/io/src/psd_export/document.rs index fb09a54ffc..1c8692dbc9 100644 --- a/crates/io/src/psd_export/document.rs +++ b/crates/io/src/psd_export/document.rs @@ -292,7 +292,7 @@ fn export_supported_document( // open a 32-bit file without them (#291). let color_mode_data = match duotone_inks { Some(raw) => raw, - None => photocraft_psd::hdr::color_mode_data_for_depth(header.depth), + None => craft_psd::hdr::color_mode_data_for_depth(header.depth), }; let mut file = PsdFile { header, diff --git a/crates/io/src/psd_export/estimate.rs b/crates/io/src/psd_export/estimate.rs index bb2d9b1c59..7c29bb3427 100644 --- a/crates/io/src/psd_export/estimate.rs +++ b/crates/io/src/psd_export/estimate.rs @@ -1,5 +1,5 @@ use super::{Document, PSD_SAVE_HEADROOM}; -use photocraft_psd::{PsdFile, Version, file::LayerInfoPlacement}; +use craft_psd::{PsdFile, Version, file::LayerInfoPlacement}; /// The signature a kept tagged block is written with. `8B64` exists only in PSB files: a PSD /// with an `8B64` block (kept from a PSB source, e.g. its global `FMsk` or `cinf`) is refused by @@ -10,7 +10,7 @@ use photocraft_psd::{PsdFile, Version, file::LayerInfoPlacement}; pub(crate) fn block_signature(sig: [u8; 4], key: [u8; 4], version: Version) -> [u8; 4] { match version { Version::Psd if sig == *b"8B64" => *b"8BIM", - Version::Psb if sig == *b"8BIM" && photocraft_psd::tagged::uses_long_length(version, &key) => *b"8B64", + Version::Psb if sig == *b"8BIM" && craft_psd::tagged::uses_long_length(version, &key) => *b"8B64", _ => sig, } } diff --git a/crates/io/src/psd_export/smart.rs b/crates/io/src/psd_export/smart.rs index 3bda3e3240..22d72d1760 100644 --- a/crates/io/src/psd_export/smart.rs +++ b/crates/io/src/psd_export/smart.rs @@ -63,11 +63,11 @@ pub(super) struct SmartOut { /// Source composites (document pixel format, source space) by uuid; `None` = unreadable. pub(super) composites: std::collections::HashMap, photocraft_geom::Rect)>>, /// Preserved `FEid` items (by placed id). - pub(super) old_fx: Vec, + pub(super) old_fx: Vec, /// Placed ids whose preserved `FEid` item stays. pub(super) keep_fx: std::collections::HashSet, /// Regenerated `FEid` items. - pub(super) new_fx: Vec, + pub(super) new_fx: Vec, /// The unfiltered pixels of each smart object whose filter mask shows: its layer record holds /// the filtered pixels without the mask, as Photoshop's do (`compose::filter_mask`). pub(super) unfiltered: std::collections::HashMap, @@ -82,7 +82,7 @@ pub(super) fn masked(sm: &photocraft_doc::SmartObject) -> bool { /// `FEid` data padded to 4 bytes inside the block length: Photoshop counts the padding in the /// length and can't open a file whose `FEid` is padded outside it. -fn padded_fx(fx: &photocraft_psd::filter_effects::FilterEffects) -> Vec { +fn padded_fx(fx: &craft_psd::filter_effects::FilterEffects) -> Vec { let mut d = fx.to_bytes(); d.resize(d.len().next_multiple_of(4), 0); d @@ -99,7 +99,7 @@ impl SmartOut { let old_fx = globals .iter() .filter(|(_, k, _)| FX_KEYS.contains(&k)) - .filter_map(|(_, _, d)| photocraft_psd::filter_effects::FilterEffects::parse(d).ok()) + .filter_map(|(_, _, d)| craft_psd::filter_effects::FilterEffects::parse(d).ok()) .flat_map(|fx| fx.items) .collect(); let mut linked_contents = std::collections::HashMap::new(); @@ -158,7 +158,7 @@ impl SmartOut { Some(d) => out.push((sig, key, Arc::new(d))), } } else if FX_KEYS.contains(&&key) { - let Ok(mut fx) = photocraft_psd::filter_effects::FilterEffects::parse(&data) else { + let Ok(mut fx) = craft_psd::filter_effects::FilterEffects::parse(&data) else { out.push((sig, key, data)); continue; }; @@ -190,7 +190,7 @@ impl SmartOut { } } if !fx_placed && !self.new_fx.is_empty() { - let fx = photocraft_psd::filter_effects::FilterEffects { version: 3, items: self.new_fx.clone() }; + let fx = craft_psd::filter_effects::FilterEffects { version: 3, items: self.new_fx.clone() }; out.push((*b"8BIM", *b"FEid", Arc::new(padded_fx(&fx)))); if !out.iter().any(|(_, k, _)| k == b"FMsk") { // Filter mask overlay: RGB red at 50 %, Photoshop's default. diff --git a/crates/io/src/psd_export/stage.rs b/crates/io/src/psd_export/stage.rs index 869208e319..15d3613f09 100644 --- a/crates/io/src/psd_export/stage.rs +++ b/crates/io/src/psd_export/stage.rs @@ -6,13 +6,13 @@ //! [`PsdExportOptions::stage_on_scratch_from`](super::PsdExportOptions::stage_on_scratch_from) //! set and spilling on, each channel is appended to a [`StageFile`] in the scratch directory as //! soon as it is encoded, and the model keeps only a [`Stored`] range: the writer then copies it -//! through in short reads (`photocraft_psd`'s `put_encoded`). A channel that cannot be staged +//! through in short reads (`craft_psd`'s `put_encoded`). A channel that cannot be staged //! (the disk is full, say) stays in memory: staging only ever saves memory. use std::sync::Arc; -use photocraft_psd::source::{ReadAt, Source, Stored}; -use photocraft_psd::{ChannelData, ImageData, PsdError}; +use craft_psd::source::{ReadAt, Source, Stored}; +use craft_psd::{ChannelData, ImageData, PsdError}; use photocraft_raster::stage_file::StageFile; /// Encoded data shorter than this stays in memory: a range costs more than it saves. @@ -34,7 +34,7 @@ impl ReadAt for Backing { self.0.len() } - fn read_at(&self, offset: u64, buf: &mut [u8]) -> photocraft_psd::Result<()> { + fn read_at(&self, offset: u64, buf: &mut [u8]) -> craft_psd::Result<()> { self.0.read_exact_at(buf, offset).map_err(|e| PsdError::Read(format!("staged export data, {} bytes at offset {offset}: {e}", buf.len()))) } } @@ -157,7 +157,7 @@ impl Parts { } /// The channel: `head` (of the length given to [`Parts::new`]) and then the parts. - pub(crate) fn finish(mut self, id: i16, compression: photocraft_psd::Compression, head: &[u8]) -> photocraft_psd::Result { + pub(crate) fn finish(mut self, id: i16, compression: craft_psd::Compression, head: &[u8]) -> craft_psd::Result { if head.len() != self.head_len { return Err(PsdError::Invalid("banded channel head has the wrong length".into())); } @@ -198,7 +198,7 @@ impl ReadAt for Joined { self.len } - fn read_at(&self, offset: u64, buf: &mut [u8]) -> photocraft_psd::Result<()> { + fn read_at(&self, offset: u64, buf: &mut [u8]) -> craft_psd::Result<()> { if offset.checked_add(buf.len() as u64).is_none_or(|end| end > self.len) { return Err(PsdError::Read(format!("staged export data, {} bytes at offset {offset} past its {} bytes", buf.len(), self.len))); } diff --git a/crates/io/src/psd_export/tests.rs b/crates/io/src/psd_export/tests.rs index a4044255be..13f11fca7b 100644 --- a/crates/io/src/psd_export/tests.rs +++ b/crates/io/src/psd_export/tests.rs @@ -37,7 +37,7 @@ fn a_background_is_written_without_a_transparency_channel() { /// PhotoCraft, and it is written back as one (no transparency channel). #[test] fn a_flat_bitmap_file_opens_and_saves_as_a_background() { - let file = photocraft_psd::testgen::merged_only(Version::Psd, PsdMode::Bitmap, 1, Compression::Raw, 8, 4); + let file = craft_psd::testgen::merged_only(Version::Psd, PsdMode::Bitmap, 1, Compression::Raw, 8, 4); let doc = crate::import("flat.psd", &file.to_bytes().unwrap()).unwrap().document; let bg = &doc.layers[0]; assert!(bg.name == "Background" && bg.locks.transparency && bg.locks.position, "{:?}", bg.locks); @@ -236,7 +236,7 @@ fn an_opaque_save_drops_a_kept_merged_transparency_marker() { #[test] fn unreadable_lr16_warns_on_import_and_is_not_saved_twice() { // #2700: a 16-bit file whose Lr16 block claims five layers but holds none. - let mut file = photocraft_psd::testgen::merged_only(Version::Psd, PsdMode::Rgb, 16, Compression::Raw, 8, 6); + let mut file = craft_psd::testgen::merged_only(Version::Psd, PsdMode::Rgb, 16, Compression::Raw, 8, 6); file.global_layer_mask = Some(GlobalLayerMask::default()); file.global_blocks.push(TaggedBlock::new(*b"Lr16", vec![0, 5, 0, 0])); let imported = crate::import("broken.psd", &file.to_bytes().unwrap()).unwrap(); @@ -320,7 +320,7 @@ fn photo_filter_version_3_is_kept_until_edited() { fn light_adjustment_is_kept_verbatim_and_warned() { // #6542: Photoshop 2026's Light layer is a `brit` block whose `CgEd` descriptor carries // more than Brightness/Contrast. Synthetic block: the extra key names are placeholders. - use photocraft_psd::descriptor::{Descriptor, Value, VersionedDescriptor}; + use craft_psd::descriptor::{Descriptor, Value, VersionedDescriptor}; let brit = vec![0, 0, 0xff, 0xfe, 0, 127, 0, 0]; let d = Descriptor::new("null") .with("Vrsn", Value::Integer(1)) diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 5e582ffd81..ac44ac6659 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -2,16 +2,16 @@ use std::sync::Arc; +use craft_psd::layer::{CHANNEL_REAL_USER_MASK, CHANNEL_TRANSPARENCY, CHANNEL_USER_MASK}; +use craft_psd::resources::ids; +use craft_psd::tagged::BlockData; +use craft_psd::{ColorMode as PsdMode, LayerNode, LayerRecord, PsdFile, TaggedBlock}; use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType}; use photocraft_doc::{ AlphaChannel, Document, Effects, FillCache, Group, Layer, LayerContent, LayerMask, PsdGlobalBlock, ShapeLayer, SmartContentsId, SmartObject, SmartSource, TextLayer, }; use photocraft_geom::{Rect, Size, TILE_SIZE}; -use photocraft_psd::layer::{CHANNEL_REAL_USER_MASK, CHANNEL_TRANSPARENCY, CHANNEL_USER_MASK}; -use photocraft_psd::resources::ids; -use photocraft_psd::tagged::BlockData; -use photocraft_psd::{ColorMode as PsdMode, LayerNode, LayerRecord, PsdFile, TaggedBlock}; use photocraft_raster::Surface; use crate::adjust_map::{self, ADJUSTMENT_KEYS}; @@ -63,7 +63,7 @@ pub(crate) struct Ctx<'a> { /// The parsed `Txt2` block (type settings EngineData lacks, e.g. optical kerning). pub txt2: Option, /// Smart-filter caches from the global `FEid`/`FXid` blocks (filter masks, by placed id). - pub filter_effects: Vec, + pub filter_effects: Vec, /// Filter masks already decoded, by placed id: every layer of a source reads the same item, and /// a surface clones by sharing its tiles. pub filter_masks: std::collections::HashMap>, @@ -139,7 +139,7 @@ fn doc_mode(m: PsdMode) -> Option { } // Real-mask metadata without a -3 channel still selects the synthetic -2 mask. -fn selected_real_mask(rec: &LayerRecord) -> Option { +fn selected_real_mask(rec: &LayerRecord) -> Option { rec.channel(CHANNEL_REAL_USER_MASK)?; rec.layer_mask()?.real } @@ -176,7 +176,7 @@ fn soft_shape_fill(rec: &LayerRecord, has_vector: bool, fill_key: Option<&[u8; 4 #[derive(Clone, Copy)] struct DecodedImport<'a> { file: &'a PsdFile, - merged: &'a Option>>, + merged: &'a Option>>, sizes: Option<(usize, usize)>, canvas: Rect, layered: bool, @@ -215,12 +215,12 @@ impl Ctx<'_> { /// A channel that failed to decode: a failed read of the file is kept to fail the open /// (`true`); damaged data is warned about, its layer left empty (`false`). - fn channel_failed(&mut self, name: &str, id: i16, e: &photocraft_psd::PsdError) -> bool { - if let photocraft_psd::PsdError::Read(msg) = e { + fn channel_failed(&mut self, name: &str, id: i16, e: &craft_psd::PsdError) -> bool { + if let craft_psd::PsdError::Read(msg) = e { self.fatal_error.get_or_insert_with(|| crate::IoError::Read(format!("layer \"{name}\": {msg}"))); return true; } - if let photocraft_psd::PsdError::OutOfMemory(_) = e { + if let craft_psd::PsdError::OutOfMemory(_) = e { self.allocation_failed(format!("layer \"{name}\" channel {id}: {e}")); return true; } @@ -275,7 +275,7 @@ impl Ctx<'_> { // tiles, so no buffer of the whole layer (planes or interleaved) is ever held. // par_map reuses the crate's worker pool (one OS thread per channel per layer would // spawn thousands on a file with many layers). - let decoders: Vec>>> = + let decoders: Vec>>> = crate::pixels::par_map(ids.to_vec(), |id| rec.channel(id).map(|ch| ch.row_decoder(w, h, depth, version))); let mut failed = false; for (&id, d) in ids.iter().zip(&decoders) { @@ -301,7 +301,7 @@ impl Ctx<'_> { invert.push(false); let mut surf = Surface::new(self.fmt); for (b0, b1) in band_rows(r.top, h, w * (self.cc + 1) * s.bytes()) { - let planes: Vec>>> = + let planes: Vec>>> = crate::pixels::par_map(decoders.iter().collect(), |d| d.as_ref().and_then(|d| d.as_ref().ok()).map(|d| d.rows(b0, b1))); let mut refs: Vec> = Vec::with_capacity(planes.len()); for (&id, p) in ids.iter().zip(&planes) { @@ -420,7 +420,7 @@ impl Ctx<'_> { mask } - fn apply_common(&mut self, l: &mut Layer, rec: &LayerRecord, blend_override: Option) { + fn apply_common(&mut self, l: &mut Layer, rec: &LayerRecord, blend_override: Option) { if l.is_group() && let Some(data) = rec.block(b"pcFr").filter(|b| b.data.len() <= 8 << 20) { @@ -490,7 +490,7 @@ impl Ctx<'_> { // The layer's XMP packet (`shmd` › `cust` › `layerXMP`) becomes the field; the rest of // `shmd` stays in `psd_blocks`, where export puts the packet back. if let Some(i) = l.psd_blocks.iter().position(|(k, _)| k == b"shmd") - && let Some((xmp, rest)) = photocraft_psd::metadata::take_layer_xmp(&l.psd_blocks[i].1) + && let Some((xmp, rest)) = craft_psd::metadata::take_layer_xmp(&l.psd_blocks[i].1) { l.xmp = Some(Arc::from(xmp)); match rest { @@ -684,9 +684,9 @@ impl Ctx<'_> { // Every distinct source is kept until the import ends, so what they add up to is // bounded: past the limit the layer keeps its stored pixels, unmixed. let item = self.filter_effects.iter().find(|i| i.id == p.placed); + // The surface keeps whole tiles over the item's rect, not its logical pixels. let cost = item - .and_then(|i| i.rect.size().ok()) - .map_or(0, |(w, h)| (w as u64).saturating_mul(h as u64).saturating_mul(self.fmt.bytes_per_pixel() as u64)); + .map_or(0, |i| photocraft_raster::tile_storage_bytes(Rect::new(i.rect.left, i.rect.top, i.rect.right, i.rect.bottom), &self.fmt)); let fits = self.unfiltered_bytes.saturating_add(cost) <= MAX_UNFILTERED_BYTES; let made = item.filter(|_| fits).and_then(|i| crate::smart_map::unfiltered_from_item(i, self.fmt)); if made.is_some() { @@ -776,7 +776,7 @@ impl Ctx<'_> { self.build(children, depth + 1) }; let sd = rec.section_divider(); - let expanded = sd.is_none_or(|s| s.kind != photocraft_psd::SectionType::ClosedFolder); + let expanded = sd.is_none_or(|s| s.kind != craft_psd::SectionType::ClosedFolder); let artboard = crate::comps_map::ARTBOARD_KEYS.iter().find_map(|k| rec.block(k)).and_then(|b| crate::comps_map::parse_artboard(&b.data)); // A Photoshop Frame's stroke: `vstk` on the frame group, in a shape's layout. let frame_stroke = rec.block(b"vstk").and_then(|b| crate::vector_map::parse_vstk(&b.data, self.dpi)).and_then(|v| v.stroke); @@ -850,7 +850,7 @@ pub(crate) fn check_group_depth(file: &PsdFile) -> Result<(), crate::IoError> { /// Deepest group nesting of the file's layer records (a layer inside this many groups is the /// deepest), computed like `layer_tree`'s stack — iteratively, so no file can make it recurse. pub(crate) fn group_depth(file: &PsdFile) -> usize { - use photocraft_psd::tagged::SectionType; + use craft_psd::tagged::SectionType; let (mut open, mut depth) = (0usize, 0usize); for rec in file.layers() { match rec.section_type() { @@ -899,7 +899,7 @@ fn preserved_blocks(rec: &LayerRecord) -> Vec<([u8; 4], Arc>)> { rec.blocks.iter().filter(|b| !REGENERATED.contains(&&b.key)).map(|b| (b.key, Arc::new(b.data.clone()))).collect() } -fn be_to_ne_plane(plane: &[u8], s: SampleType, n: usize) -> photocraft_psd::Result> { +fn be_to_ne_plane(plane: &[u8], s: SampleType, n: usize) -> craft_psd::Result> { crate::pixels::try_interleave(&[Some(plane)], &[zero_sample(s)], n, s, &[false]) } @@ -928,12 +928,8 @@ fn merged_plane(all: &[u8], i: usize, plane: usize) -> Option<&[u8]> { /// The merged image of a file the layered path does not open (Bitmap, Indexed, Duotone; 1-bit /// files) as RGBA8. What `composite_rgba8` can't read (Multichannel) shows its first channels as /// RGB. An output over `cap` bytes is refused, never allocated (#5200). -fn flat_composite( - file: &PsdFile, - merged: Option<&Result, photocraft_psd::PsdError>>, - cap: u64, -) -> Result { - use photocraft_psd::PsdError; +fn flat_composite(file: &PsdFile, merged: Option<&Result, craft_psd::PsdError>>, cap: u64) -> Result { + use craft_psd::PsdError; match file.composite_rgba8() { Ok(img) => return Ok(img), // Over the output budget: the fallback below would make the same allocation. @@ -958,12 +954,12 @@ fn flat_composite( data.resize(len, 255u8); for c in 0..3.min(usize::from(h.channels)) { let bytes = merged_plane(all, c, plane).ok_or_else(|| PsdError::Invalid("channel size mismatch".into()))?; - let p = photocraft_psd::pixels::plane_to_u8(bytes, h.depth, w, hh)?; + let p = craft_psd::pixels::plane_to_u8(bytes, h.depth, w, hh)?; for (px, v) in data.as_chunks_mut::<4>().0.iter_mut().zip(&p) { px[c] = *v; } } - Ok(photocraft_psd::RgbaImage { left: 0, top: 0, width: h.width, height: h.height, data }) + Ok(craft_psd::RgbaImage { left: 0, top: 0, width: h.width, height: h.height, data }) } /// Writes RGBA8 `data` covering `canvas` into `s`, a band of tile rows at a time (no full-size @@ -1065,7 +1061,7 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt) pub(crate) fn psd_to_document_owned( mut file: PsdFile, ctl: &photocraft_raster::Interrupt, - decoded: Option>>, + decoded: Option>>, ) -> Option<(Document, Vec, bool, Option)> { let global = file .global_blocks @@ -1105,8 +1101,8 @@ pub(crate) fn psd_to_document_owned( /// reads every file in Photoshop's polarity, at the cost of inverting the spot ink of PSDs saved /// by those versions. pub(crate) fn earlier_photocraft_spot_planes(file: &PsdFile) -> bool { - use photocraft_psd::descriptor::UnicodeString; - use photocraft_psd::resources::VersionInfo; + use craft_psd::descriptor::UnicodeString; + use craft_psd::resources::VersionInfo; let marks_spot = file.resource(crate::channel_map::DISPLAY_INFO).is_some_and(|r| crate::channel_map::display_info_marks_spot(&r.data)); let identifies_every_channel = match file.header.color_mode.color_channels() { @@ -1174,7 +1170,7 @@ fn read_initial_metadata( for resource in &file.resources { match resource.id { ids::RESOLUTION_INFO => { - if let Ok(info) = photocraft_psd::ResolutionInfo::from_bytes(&resource.data) { + if let Ok(info) = craft_psd::ResolutionInfo::from_bytes(&resource.data) { let (x, y) = (info.h_res(), info.v_res()); doc.resolution_dpi = x as f32; warnings.extend(crate::unequal_resolution_warning(x, y)); @@ -1250,7 +1246,7 @@ fn read_initial_metadata( pub(crate) fn psd_to_document_decoded( file: &PsdFile, ctl: &photocraft_raster::Interrupt, - decoded: Option>>, + decoded: Option>>, ) -> Option<(Document, Vec)> { psd_to_document_decoded_integrity(file, ctl, decoded).map(|(document, warnings, _)| (document, warnings)) } @@ -1261,7 +1257,7 @@ pub(crate) fn psd_to_document_decoded( pub(crate) fn psd_to_document_decoded_integrity( file: &PsdFile, ctl: &photocraft_raster::Interrupt, - decoded: Option>>, + decoded: Option>>, ) -> Option<(Document, Vec, bool)> { let global = file.global_blocks.iter().map(|b| (b.signature, b.key, Arc::new(b.data.clone()))).collect(); psd_to_document_global(file, ctl, decoded, global, false).map(|(doc, warnings, damaged, _)| (doc, warnings, damaged)) @@ -1294,7 +1290,7 @@ fn legacy_admission(est: &crate::psd_budget::PsdMemoryEstimate, ctl: &photocraft fn psd_to_document_global( file: &PsdFile, ctl: &photocraft_raster::Interrupt, - decoded: Option>>, + decoded: Option>>, global: Vec, preflighted: bool, ) -> Option<(Document, Vec, bool, Option)> { @@ -1364,7 +1360,7 @@ fn psd_to_document_global( if ctl.cancelled() { return None; } - match photocraft_psd::filter_effects::FilterEffects::parse(data) { + match craft_psd::filter_effects::FilterEffects::parse(data) { Ok(fx) => cx.filter_effects.extend(fx.items), Err(e) => cx.warn(format!("smart filter masks ({}) could not be read: {e}", String::from_utf8_lossy(key))), } @@ -1399,10 +1395,10 @@ fn finish_import(mut doc: Document, mut cx: Ctx<'_>, ctl: &photocraft_raster::In fn decode_merged( file: &PsdFile, - decoded: Option>>, + decoded: Option>>, ctl: &photocraft_raster::Interrupt, cx: &mut Ctx<'_>, -) -> Option>>> { +) -> Option>>> { if merged_needed(file) { let merged = decoded.unwrap_or_else(|| file.decode_merged()); if ctl.cancelled() { @@ -1410,7 +1406,7 @@ fn decode_merged( } ctl.progress(0.1); if let Err(error) = &merged { - if matches!(error, photocraft_psd::PsdError::OutOfMemory(_)) { + if matches!(error, craft_psd::PsdError::OutOfMemory(_)) { cx.allocation_failed(format!("merged image: {error}")); } cx.warn_unreadable_data(format!("merged image could not be decoded: {error}")); @@ -1445,7 +1441,7 @@ fn import_decoded_content(import: DecodedImport<'_>, doc: &mut Document, cx: &mu } } -fn import_multichannel(file: &PsdFile, merged: &Option>>, doc: &mut Document, cx: &mut Ctx<'_>) { +fn import_multichannel(file: &PsdFile, merged: &Option>>, doc: &mut Document, cx: &mut Ctx<'_>) { if let Some(Ok(all)) = merged { let names = file.alpha_channel_names(); if let Err(error) = crate::multichannel_map::import(file, all, doc, &names, &mut cx.warnings) { @@ -1464,8 +1460,8 @@ fn import_layered(import: DecodedImport<'_>, doc: &mut Document, cx: &mut Ctx<'_ let space = photocraft_compose::cmyk_space(doc); doc.layers = photocraft_color::convert::with_cmyk_space(space.as_ref(), || cx.build(&tree, 0)); mark_background(file, &mut doc.layers); - if let Some(Ok(photocraft_psd::resources::ResourceData::LayerGroupInfo(groups))) = - file.resources.iter().find(|r| r.id == ids::LAYER_GROUP_INFO).and_then(photocraft_psd::resources::ImageResource::parsed) + if let Some(Ok(craft_psd::resources::ResourceData::LayerGroupInfo(groups))) = + file.resources.iter().find(|r| r.id == ids::LAYER_GROUP_INFO).and_then(craft_psd::resources::ImageResource::parsed) { apply_link_groups(&tree, &mut doc.layers, file.layers(), &groups); } @@ -1523,7 +1519,7 @@ fn import_layered(import: DecodedImport<'_>, doc: &mut Document, cx: &mut Ctx<'_ fn import_flattened( file: &PsdFile, - merged: &Option>>, + merged: &Option>>, sizes: Option<(usize, usize)>, canvas: Rect, fmt: PixelFormat, @@ -1555,7 +1551,7 @@ fn import_flattened( } else if !file.color_mode_data.is_empty() { cx.warn("color mode data is not preserved"); } - match flat_composite(file, merged.as_ref(), photocraft_psd::compression::MAX_DECODED_BYTES) { + match flat_composite(file, merged.as_ref(), craft_psd::compression::MAX_DECODED_BYTES) { Ok(mut img) => { if h.color_mode == PsdMode::Indexed && let Some(t) = doc.color_table.as_ref().and_then(|t| t.transparent) @@ -1579,10 +1575,10 @@ fn import_flattened( Err(error) => cx.allocation_failed(format!("flattened image: {error}")), } } - Err(error @ photocraft_psd::PsdError::OutOfMemory(_)) => cx.allocation_failed(format!("flattened image: {error}")), + Err(error @ craft_psd::PsdError::OutOfMemory(_)) => cx.allocation_failed(format!("flattened image: {error}")), // A flattened file has nothing but its merged image: a failed source read fails the open // rather than opening it without the image. - Err(photocraft_psd::PsdError::Read(message)) => { + Err(craft_psd::PsdError::Read(message)) => { cx.fatal_error.get_or_insert(crate::IoError::Read(message)); } Err(_) if matches!(merged, Some(Err(_))) => {} diff --git a/crates/io/src/psd_import/tests.rs b/crates/io/src/psd_import/tests.rs index 3a0b751002..f34c81b8f6 100644 --- a/crates/io/src/psd_import/tests.rs +++ b/crates/io/src/psd_import/tests.rs @@ -1,7 +1,7 @@ use super::*; -use photocraft_psd::descriptor::UnicodeString; -use photocraft_psd::resources::VersionInfo; -use photocraft_psd::{Compression, ImageData, ImageResource, PsdError, Version, testgen}; +use craft_psd::descriptor::UnicodeString; +use craft_psd::resources::VersionInfo; +use craft_psd::{Compression, ImageData, ImageResource, PsdError, Version, testgen}; /// #5200: the Multichannel fallback checks its RGBA output against the budget before /// allocating it (here a 2x2 image, 16 bytes, against caps of 15 and 16 bytes). @@ -26,7 +26,7 @@ fn flat_fallback_does_not_retry_an_over_budget_composite() { file.header.width = 60_000; file.header.height = 60_000; let merged = Ok(vec![0u8; 16]); - let cap = photocraft_psd::compression::MAX_DECODED_BYTES; + let cap = craft_psd::compression::MAX_DECODED_BYTES; assert!(matches!(flat_composite(&file, Some(&merged), cap), Err(PsdError::LimitExceeded(_)))); } @@ -118,7 +118,7 @@ fn version_info_cs6(has_real_merged_data: bool) -> Vec { /// The 1057 PhotoCraft writes since 0.8.2: Photoshop 2026's bytes, no NUL. fn version_info_2026(has_real_merged_data: bool) -> Vec { - photocraft_psd::resources::version_info_resource(has_real_merged_data).data + craft_psd::resources::version_info_resource(has_real_merged_data).data } /// An opaque 4 × 1 RGB document with the Photoshop spot oracles' channels in their order: @@ -390,11 +390,11 @@ fn layer_bands_end_on_tile_rows_and_cover_the_layer() { } // Tall, narrow masks cross tile bands while keeping these cases only a few KiB. -fn banded_mask_file(depth: u16, compression: Compression, version: Version, real: bool) -> (PsdFile, Vec, photocraft_psd::Rect) { - use photocraft_psd::{ChannelData, LayerMask as PsdMask, MaskData, MaskParameters, RealMask}; +fn banded_mask_file(depth: u16, compression: Compression, version: Version, real: bool) -> (PsdFile, Vec, craft_psd::Rect) { + use craft_psd::{ChannelData, LayerMask as PsdMask, MaskData, MaskParameters, RealMask}; let mut file = testgen::layered(version, PsdMode::Rgb, depth, compression); file.layer_info.as_mut().unwrap().layers.truncate(1); - let rect = photocraft_psd::Rect::from_xywh(-3, -17, 5, 600); + let rect = craft_psd::Rect::from_xywh(-3, -17, 5, 600); let mut plane = Vec::new(); for i in 0..3000 { match depth { @@ -411,7 +411,7 @@ fn banded_mask_file(depth: u16, compression: Compression, version: Version, real record.channels.retain(|c| c.id != CHANNEL_USER_MASK && c.id != CHANNEL_REAL_USER_MASK); let id = if real { // Different synthetic bounds/defaults ensure -3's own metadata is selected. - mask.rect = photocraft_psd::Rect::from_xywh(1, 1, 1, 1); + mask.rect = craft_psd::Rect::from_xywh(1, 1, 1, 1); mask.real = Some(RealMask { flags: 3, background: 255, rect }); record.channels.push(ChannelData::encode(CHANNEL_USER_MASK, compression, &vec![0; usize::from(depth / 8)], 1, 1, depth, version).unwrap()); CHANNEL_REAL_USER_MASK @@ -423,7 +423,7 @@ fn banded_mask_file(depth: u16, compression: Compression, version: Version, real (file, plane, rect) } -fn assert_banded_mask(file: &PsdFile, plane: &[u8], rect: photocraft_psd::Rect, real: bool) { +fn assert_banded_mask(file: &PsdFile, plane: &[u8], rect: craft_psd::Rect, real: bool) { let (doc, warnings, damaged) = psd_to_document_decoded_integrity(file, &photocraft_raster::Interrupt::NONE, None).unwrap(); assert!(!damaged, "{warnings:?}"); let mask = doc.layers[0].mask.as_ref().unwrap(); @@ -447,7 +447,7 @@ fn mask_bands_preserve_samples_bounds_defaults_and_parameters() { assert_banded_mask(&file, &plane, rect, real); let bytes = file.to_bytes().unwrap(); let eager = PsdFile::from_bytes(&bytes).unwrap(); - let lazy = PsdFile::from_source(photocraft_psd::Source::new(bytes)).unwrap(); + let lazy = PsdFile::from_source(craft_psd::Source::new(bytes)).unwrap(); assert_banded_mask(&eager, &plane, rect, real); assert_banded_mask(&lazy, &plane, rect, real); } @@ -458,7 +458,7 @@ fn mask_bands_preserve_samples_bounds_defaults_and_parameters() { #[test] fn raw_and_rle_mask_sources_are_read_in_bands() { - use photocraft_psd::{ReadAt, Source, Stored}; + use craft_psd::{ReadAt, Source, Stored}; use std::sync::{Arc, Mutex}; struct Reads { bytes: Vec, @@ -468,7 +468,7 @@ fn raw_and_rle_mask_sources_are_read_in_bands() { fn len(&self) -> u64 { self.bytes.len() as u64 } - fn read_at(&self, offset: u64, buf: &mut [u8]) -> photocraft_psd::Result<()> { + fn read_at(&self, offset: u64, buf: &mut [u8]) -> craft_psd::Result<()> { self.sizes.lock().unwrap().push(buf.len()); self.bytes.read_at(offset, buf) } @@ -524,7 +524,7 @@ fn a_damaged_later_mask_band_discards_earlier_bands() { /// channel, asked for after the import was already reported as failing. #[test] fn a_fatal_layer_error_skips_the_extra_channel_conversion() { - use photocraft_psd::ReadAt; + use craft_psd::ReadAt; struct Failing { bytes: Vec, data: Vec<(u64, u64)>, @@ -534,7 +534,7 @@ fn a_fatal_layer_error_skips_the_extra_channel_conversion() { fn len(&self) -> u64 { self.bytes.len() as u64 } - fn read_at(&self, offset: u64, buf: &mut [u8]) -> photocraft_psd::Result<()> { + fn read_at(&self, offset: u64, buf: &mut [u8]) -> craft_psd::Result<()> { let end = offset + buf.len() as u64; if self.armed.load(std::sync::atomic::Ordering::SeqCst) && self.data.iter().any(|&(a, b)| offset < b && end > a) { return Err(PsdError::Read("the drive went away".into())); @@ -548,13 +548,13 @@ fn a_fatal_layer_error_skips_the_extra_channel_conversion() { let converted = psd_to_document_global(&whole, &photocraft_raster::Interrupt::NONE, None, Vec::new(), false).unwrap(); assert!(converted.3.is_none() && converted.0.channels.len() == 3, "the control file converts its channels"); - let lazy = PsdFile::from_source(photocraft_psd::Source::new(bytes.clone())).unwrap(); + let lazy = PsdFile::from_source(craft_psd::Source::new(bytes.clone())).unwrap(); let data: Vec<(u64, u64)> = lazy.layers().iter().flat_map(|l| &l.channels).filter_map(|c| c.stored.as_ref()).filter(|s| s.len > 0).map(|s| (s.offset, s.offset + s.len)).collect(); assert!(!data.is_empty()); // Reads fail only once the file is parsed: the layers decode lazily from the source. let armed = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let file = PsdFile::from_source(photocraft_psd::Source::new(Failing { bytes, data, armed: armed.clone() })).unwrap(); + let file = PsdFile::from_source(craft_psd::Source::new(Failing { bytes, data, armed: armed.clone() })).unwrap(); armed.store(true, std::sync::atomic::Ordering::SeqCst); let (doc, _, _, fatal) = psd_to_document_global(&file, &photocraft_raster::Interrupt::NONE, None, Vec::new(), false).unwrap(); assert!(matches!(fatal, Some(crate::IoError::Read(_))), "{fatal:?}"); @@ -608,7 +608,7 @@ fn only_allocation_failures_are_fatal_to_a_layer_channel() { fn legacy_conversion_refuses_before_waiting_for_the_decode_gate() { let mut file = testgen::small(Version::Psd, Compression::Zip); // 30,000² tiles are several GiB: far past the hard budget of the 4 GiB machine below. - file.layers_mut()[0].rect = photocraft_psd::Rect::from_xywh(0, 0, 30_000, 30_000); + file.layers_mut()[0].rect = craft_psd::Rect::from_xywh(0, 0, 30_000, 30_000); let snapshot = crate::memory::MemorySnapshot { available_ram: Some(4 << 30), swap_free: None, commit_headroom: None }; let ctl = photocraft_raster::Interrupt::NONE; let _guard = crate::psd_gate::acquire_decode_admission(&ctl).expect("active decode"); diff --git a/crates/io/src/psd_thumbnail.rs b/crates/io/src/psd_thumbnail.rs index 25b8c7821c..83cbf3318e 100644 --- a/crates/io/src/psd_thumbnail.rs +++ b/crates/io/src/psd_thumbnail.rs @@ -6,11 +6,11 @@ //! height, compressed size, bits per pixel 24, planes 1) followed by the JFIF stream. Photoshop //! keeps the long side at 160 px or less. +use craft_psd::resources::{ImageResource, ids}; use photocraft_cms::{Builtin, ColorSpace, Intent, Profile, Transform}; use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType as CSample}; use photocraft_color::ColorMode; use photocraft_doc::Document; -use photocraft_psd::resources::{ImageResource, ids}; use crate::IoError; diff --git a/crates/io/src/puppet_map.rs b/crates/io/src/puppet_map.rs index f1015af30b..cbadbf59a9 100644 --- a/crates/io/src/puppet_map.rs +++ b/crates/io/src/puppet_map.rs @@ -18,8 +18,8 @@ //! alone feed PhotoCraft's own solver once they are edited; the mode, density and rotation //! settings aren't mapped (their stored values aren't identified), so those stay at defaults. +use craft_psd::descriptor::{Descriptor, Value}; use photocraft_doc::SmartFilter; -use photocraft_psd::descriptor::{Descriptor, Value}; use serde_json::{Value as J, json}; use super::{blend_options, from_hex, get_desc, set, to_hex}; @@ -159,7 +159,7 @@ pub(super) fn export_item(params: &J) -> Result { mod tests { use super::*; use crate::smart_map::{UNSUPPORTED_FILTER, filter_from_item, item_for_filter, parse_sold}; - use photocraft_psd::descriptor::{UnicodeString, VersionedDescriptor}; + use craft_psd::descriptor::{UnicodeString, VersionedDescriptor}; const QUAD: [f64; 8] = [10.0, 20.0, 110.0, 22.0, 108.0, 220.0, 12.0, 218.0]; diff --git a/crates/io/src/raw.rs b/crates/io/src/raw.rs index 1ac0fc81e1..b0a37daccc 100644 --- a/crates/io/src/raw.rs +++ b/crates/io/src/raw.rs @@ -10,7 +10,7 @@ //! fit is not clearly better. use std::borrow::Cow; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use photocraft_cms::{Builtin, Intent, Profile, Transform}; use photocraft_codecs::{self as codecs, ChannelLayout, Format, Image, SampleType}; @@ -83,12 +83,31 @@ pub struct RawTuning { /// no as-shot white balance: Temperature / Tint were then not applied, and the caller keeps /// them as RGB adjustments. pub fn import_raw_tuned(name: &str, bytes: &[u8], tuning: &RawTuning) -> Result<(ImportResult, bool), IoError> { + import_raw_tuned_inner(name, bytes, tuning, None) +} + +/// [`import_raw_tuned`] from what the open already learned about `bytes` ([`take_kept_decode`], +/// [`RawDecode::new`]): the same pixels without decoding the file and fitting its look again. +/// A `decode` of another file is ignored. +pub fn import_raw_tuned_from(name: &str, bytes: &[u8], tuning: &RawTuning, decode: &RawDecode) -> Result<(ImportResult, bool), IoError> { + import_raw_tuned_inner(name, bytes, tuning, Some(decode)) +} + +fn import_raw_tuned_inner(name: &str, bytes: &[u8], tuning: &RawTuning, decode: Option<&RawDecode>) -> Result<(ImportResult, bool), IoError> { let format = photocraft_raw::identify(bytes).map(|f| f.name()).unwrap_or("camera raw"); let exposure = f64::from(tuning.exposure); if !exposure.is_finite() || !(-10.0..=10.0).contains(&exposure) { return Err(IoError::Raw(RawError::Malformed(format!("exposure {} EV is out of range", tuning.exposure)))); } - let sensor = photocraft_raw::decode(bytes, &limits()).map_err(IoError::Raw)?; + let fresh; + let decode = match decode.filter(|d| d.is_of(bytes)) { + Some(d) => d, + None => { + fresh = RawDecode::new(bytes)?; + &fresh + } + }; + let sensor = &decode.sensor; let slider = |v: f32| if v.is_finite() { v.clamp(-100.0, 100.0) } else { 0.0 }; let tone = photocraft_raw::Tone { shadows: slider(tuning.shadows), @@ -99,7 +118,7 @@ pub fn import_raw_tuned(name: &str, bytes: &[u8], tuning: &RawTuning) -> Result< }; // The colour rendering the default open used (a look fitted to the camera's JPEG for files // without colour calibration), so re-developing changes only what the sliders change. - let camera_look = default_look(bytes, &sensor); + let camera_look = decode.look.clone(); let mut opts = DevelopOptions { limits: limits(), exposure, demosaic: tuning.demosaic, tone, camera_look, ..Default::default() }; let wb_applied = match sensor.camera_wb { Some(m) => { @@ -109,7 +128,7 @@ pub fn import_raw_tuned(name: &str, bytes: &[u8], tuning: &RawTuning) -> Result< } None => false, }; - let mut dev = photocraft_raw::develop_sensor(&sensor, &opts).map_err(IoError::Raw)?; + let mut dev = photocraft_raw::develop_sensor(sensor, &opts).map_err(IoError::Raw)?; let cropped = match tuning.crop { Some(crop) => { let o = if opts.orient { dev.info.orientation } else { 1 }; @@ -153,13 +172,116 @@ fn crop_developed(dev: &mut photocraft_raw::Developed, crop: crate::camera_raw_x /// this crate decodes). For previews of the open-time raw-stage sliders /// ([`photocraft_raw::retone`]), in linear-light knots. pub fn tone_curve(bytes: &[u8]) -> Vec<[f32; 2]> { - let Ok(sensor) = photocraft_raw::decode(bytes, &limits()) else { return Vec::new() }; - match default_look(bytes, &sensor) { - Some(look) => look.tone.as_ref().map(look_knots).unwrap_or_default(), - None => sensor.tone_curve, + RawDecode::new(bytes).map(|d| d.tone_curve).unwrap_or_default() +} + +/// A raw file decoded once for the open-time Camera Raw dialog: the sensor data, the look fitted +/// to the camera's JPEG (for a file without colour calibration, see [`default_look`]) and the +/// tone curve the default develop uses. The dialog's preview and its Open re-develop +/// ([`import_raw_tuned_from`]) share one instead of decoding and fitting the file again each +/// (the sensor is 2 bytes per pixel: drop it when the dialog closes). +pub struct RawDecode { + fingerprint: Fingerprint, + sensor: Sensor, + look: Option, + tone_curve: Vec<[f32; 2]>, +} + +impl std::fmt::Debug for RawDecode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Not the sensor data: tens of millions of samples. + f.debug_struct("RawDecode").field("fingerprint", &self.fingerprint).field("look", &self.look.is_some()).finish_non_exhaustive() } } +impl RawDecode { + /// Decodes `bytes` and fits its look, as a default open does. + pub fn new(bytes: &[u8]) -> Result { + let sensor = decode_sensor(bytes, &limits())?; + let look = default_look(bytes, &sensor); + Ok(RawDecode::from_parts(bytes, sensor, look)) + } + + fn from_parts(bytes: &[u8], sensor: Sensor, look: Option) -> RawDecode { + let tone_curve = match &look { + Some(look) => look.tone.as_ref().map(look_knots).unwrap_or_default(), + None => sensor.tone_curve.clone(), + }; + RawDecode { fingerprint: Fingerprint::of(bytes), sensor, look, tone_curve } + } + + /// The tone curve a default develop uses, as [`tone_curve`] returns it. + pub fn tone_curve(&self) -> &[[f32; 2]] { + &self.tone_curve + } + + /// `true` if this was decoded from `bytes`. + fn is_of(&self, bytes: &[u8]) -> bool { + self.fingerprint == Fingerprint::of(bytes) + } +} + +/// The sensor data of `bytes` under `limits`. +fn decode_sensor(bytes: &[u8], limits: &Limits) -> Result { + DECODES.with(|n| n.set(n.get() + 1)); + photocraft_raw::decode(bytes, limits).map_err(IoError::Raw) +} + +thread_local! { + static DECODES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many raw files this thread has decoded so far (for tests that count decodes). +#[doc(hidden)] +pub fn decodes_on_this_thread() -> usize { + DECODES.with(std::cell::Cell::get) +} + +/// A file's length and a 64-bit digest of its bytes: tells the file a [`RawDecode`] was made +/// from from any other (not a cryptographic hash). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Fingerprint(usize, u64); + +impl Fingerprint { + fn of(bytes: &[u8]) -> Fingerprint { + const K: u64 = 0x9E37_79B9_7F4A_7C15; + let mix = |lane: u64, word: u64| (lane ^ word).wrapping_mul(K).rotate_left(29); + let mut lanes = [0x243F_6A88_85A3_08D3u64, 0x1319_8A2E_0370_7344, 0xA409_3822_299F_31D0, 0x082E_FA98_EC4E_6C89]; + let (blocks, rest) = bytes.as_chunks::<32>(); + let mut absorb = |block: &[u8; 32]| { + for (lane, word) in lanes.iter_mut().zip(block.as_chunks::<8>().0) { + *lane = mix(*lane, u64::from_le_bytes(*word)); + } + }; + blocks.iter().for_each(&mut absorb); + let mut tail = [0u8; 32]; + tail[..rest.len()].copy_from_slice(rest); + absorb(&tail); + let digest = lanes.iter().fold(bytes.len() as u64, |acc, &lane| mix(acc, lane)); + Fingerprint(bytes.len(), digest) + } +} + +/// The decodes of the last opens that await their Camera Raw dialog (see +/// [`ImportOptions::keep_raw`](crate::ImportOptions::keep_raw)): at most two, so several raws +/// opened at once each find theirs, and the oldest goes first. The dialog takes its own out. +static KEPT: Mutex>> = Mutex::new(Vec::new()); + +const KEPT_MAX: usize = 2; + +fn kept() -> std::sync::MutexGuard<'static, Vec>> { + KEPT.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Hands over (removes) the decode a default open of exactly `bytes` kept for its dialog, if it +/// is still there. Whoever takes it owns the sensor data: dropping it frees it. +pub fn take_kept_decode(bytes: &[u8]) -> Option> { + let want = Fingerprint::of(bytes); + let mut kept = kept(); + let at = kept.iter().position(|d| d.fingerprint == want)?; + Some(kept.remove(at)) +} + /// A fitted look's tone curve as knots for [`photocraft_raw::retone`] (which reads them /// log-linearly): sampled densely enough that the two agree within a fraction of a code value. fn look_knots(t: &photocraft_raw::ToneCurve) -> Vec<[f32; 2]> { @@ -225,6 +347,12 @@ pub fn import_raw_demosaic(name: &str, bytes: &[u8], demosaic: Demosaic) -> Resu import_raw_with(name, bytes, &DevelopOptions { limits: limits(), demosaic, ..Default::default() }) } +/// [`import_raw_demosaic`] that also keeps the sensor data and the fitted look for the file's +/// Camera Raw dialog ([`take_kept_decode`]). +pub fn import_raw_demosaic_keeping(name: &str, bytes: &[u8], demosaic: Demosaic) -> Result { + import_raw_with_inner(name, bytes, &DevelopOptions { limits: limits(), demosaic, ..Default::default() }, true) +} + /// Smallest preview long edge preferred for the colour fit (a smaller preview decodes faster; /// the fit grid is at most `PROXY_EDGE` cells and wants about two pixels per cell). const FIT_PREVIEW_EDGE: u32 = 2 * photocraft_raw::PROXY_EDGE as u32; @@ -270,10 +398,19 @@ pub fn fit_preview_look(raw: &[u8], sensor: &Sensor, opts: &DevelopOptions) -> R photocraft_raw::fit_look(sensor, opts, &Reference { width: w, height: h, rgb: &rgb }).map_err(|e| e.to_string()) } +/// A sensor and the look fitted to it, as [`develop_fitted`] hands them back. +type Kept = (Sensor, Option); + /// Decodes and develops; a file without colour calibration gets a look fitted to its preview. -fn develop_fitted(bytes: &[u8], opts: &DevelopOptions) -> Result { - let sensor = photocraft_raw::decode(bytes, &opts.limits)?; +/// With `keep`, also hands back the sensor and the look it fitted (the default look, when +/// `opts` named none) instead of freeing them. +fn develop_fitted(bytes: &[u8], opts: &DevelopOptions, keep: bool) -> Result<(photocraft_raw::Developed, Option), RawError> { + let sensor = decode_sensor(bytes, &opts.limits).map_err(|e| match e { + IoError::Raw(e) => e, + e => RawError::Malformed(e.to_string()), + })?; let mut opts = Cow::Borrowed(opts); + let named_look = opts.camera_look.is_some(); if opts.camera_look.is_none() && sensor.color.calibrations.is_empty() && !sensor.is_monochrome() @@ -281,7 +418,9 @@ fn develop_fitted(bytes: &[u8], opts: &DevelopOptions) -> Result Option { /// Develops a raw file with explicit settings. Without `opts.camera_look`, a file without /// colour calibration gets one fitted to its embedded JPEG when that clearly helps. pub fn import_raw_with(name: &str, bytes: &[u8], opts: &DevelopOptions) -> Result { + import_raw_with_inner(name, bytes, opts, false) +} + +fn import_raw_with_inner(name: &str, bytes: &[u8], opts: &DevelopOptions, keep: bool) -> Result { let format = photocraft_raw::identify(bytes).map(|f| f.name()).unwrap_or("camera raw"); - match develop_fitted(bytes, opts) { - Ok(dev) => { + match develop_fitted(bytes, opts, keep) { + Ok((dev, kept_parts)) => { + if let Some((sensor, look)) = kept_parts { + let mut kept = kept(); + if kept.len() == KEPT_MAX { + kept.remove(0); + } + kept.push(Arc::new(RawDecode::from_parts(bytes, sensor, look))); + } let summary = format!("{DEVELOPED_NOTE} ({} demosaic, as-shot white balance)", opts.demosaic.id()); developed_document(name, bytes, format, dev, &summary) } @@ -384,6 +534,17 @@ fn jxl_preview_image(raw: &[u8], p: photocraft_raw::DecodedPreview) -> Result Option<&[u8]> { doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == SLICES).map(|(_, _, d)| d.as_slice()) diff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rs index 53c0c258e3..49a0901b90 100644 --- a/crates/io/src/smart_map.rs +++ b/crates/io/src/smart_map.rs @@ -24,14 +24,14 @@ //! Warp (`perspective_warp_map.rs`), whose quads become the planes of its command. Hue/Saturation //! (`HStr`) maps to its adjustment command in `hue_sat_filter_map.rs`. +use craft_psd::Compression; +use craft_psd::Rect as PsdRect; +use craft_psd::descriptor::{Class, Descriptor, Id, ObjectArray, ReferenceItem, UnicodeString, Value, VersionedDescriptor}; +use craft_psd::filter_effects::{EffectsPlane, FilterEffectsItem}; use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType}; use photocraft_doc::{LayerMask, SmartFilter, SmartObject}; use photocraft_geom::warp::{BezierMesh, Warp, WarpStyle}; use photocraft_geom::{Affine, Rect as GeomRect}; -use photocraft_psd::Compression; -use photocraft_psd::Rect as PsdRect; -use photocraft_psd::descriptor::{Class, Descriptor, Id, ObjectArray, ReferenceItem, UnicodeString, Value, VersionedDescriptor}; -use photocraft_psd::filter_effects::{EffectsPlane, FilterEffectsItem}; use photocraft_raster::Surface; use serde_json::{Map, Value as J, json}; diff --git a/crates/io/src/smart_map/tests.rs b/crates/io/src/smart_map/tests.rs index 22808b08a2..0332b5558a 100644 --- a/crates/io/src/smart_map/tests.rs +++ b/crates/io/src/smart_map/tests.rs @@ -1752,9 +1752,9 @@ fn placed_blocks_parse_back() { assert!((a - b).abs() < 1e-9); } assert_eq!(p.stack, Some(stack)); - let tb = photocraft_psd::TaggedBlock::new(*b"SoLd", sold.clone()); + let tb = craft_psd::TaggedBlock::new(*b"SoLd", sold.clone()); tb.check_structure().unwrap(); - let pl = photocraft_psd::TaggedBlock::new(*b"PlLd", plld_bytes(&spec, &mut w)); + let pl = craft_psd::TaggedBlock::new(*b"PlLd", plld_bytes(&spec, &mut w)); pl.check_structure().unwrap(); // A template keeps its other keys; an unmoved transform keeps its exact quad. let mut tmpl = sold_descriptor(&sold).unwrap(); diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index bbbeeed475..1b84bf6cfb 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -1558,7 +1558,9 @@ impl Conv { } /// Check both retained and transient memory before rendering; charge only retained output. - fn can_retain_pixels(&mut self, pixels: u64) -> bool { + /// `pixels` are the output's whole-tile pixels; `scratch_pixels` are those of the temporary + /// pixmap and f32 buffers, which cover only the logical box. + fn can_retain_pixels(&mut self, pixels: u64, scratch_pixels: u64) -> bool { let bytes = pixels.saturating_mul(self.fmt.bytes_per_pixel() as u64); if bytes > self.pixel_budget { self.note("pixel-budget", "SVG: some rasterised elements were omitted because they exceeded the remaining pixel memory budget".into()); @@ -1566,7 +1568,7 @@ impl Conv { } // surface() converts the RGBA8 pixmap into f32 scratch space before writing // sample-format tiles. All three buffers briefly coexist with retained layers. - let temporary = pixels.saturating_mul(4 + self.fmt.channels() as u64 * 4 + self.fmt.bytes_per_pixel() as u64); + let temporary = scratch_pixels.saturating_mul(4 + self.fmt.channels() as u64 * 4) + pixels.saturating_mul(self.fmt.bytes_per_pixel() as u64); if self.retained_pixel_bytes.saturating_add(temporary) > MAX_PEAK_PIXEL_BYTES { self.note("pixel-peak", "SVG: some rasterised elements were omitted to bound temporary conversion memory".into()); return false; @@ -1770,11 +1772,14 @@ impl Conv { (b.bottom() + reach).ceil() as i32, ) .intersect(&self.canvas); - let pixels = u64::from(area.width()) * u64::from(area.height()); - if self.can_retain_pixels(pixels) { - sh.cache = Some(photocraft_vector::render_shape(&sh, self.fmt, self.canvas)); - let bytes = pixels * self.fmt.bytes_per_pixel() as u64; - self.pixel_budget -= bytes; + // Whole tiles, as the cache stores them: a narrow shape keeps far more than its area. + let pixels = area.tile_count() * (photocraft_geom::TILE_SIZE as u64).pow(2); + if self.can_retain_pixels(pixels, pixels) { + let cache = photocraft_vector::render_shape(&sh, self.fmt, self.canvas); + // The preflight above assumed every tile of the box; the cache keeps the ones it drew. + let bytes = photocraft_raster::stored_tiles_bytes(cache.tile_count() as u64, &self.fmt); + sh.cache = Some(cache); + self.pixel_budget = self.pixel_budget.saturating_sub(bytes); self.retained_pixel_bytes += bytes; } Some(Layer::new(self.name(p.id(), 0), LayerContent::Shape(sh))) @@ -1845,7 +1850,10 @@ impl Conv { self.note("raster-size", "SVG: an element too large to rasterise was dropped".to_string()); return None; } - if !self.can_retain_pixels(pixels) { + // The layer keeps whole tiles over its box, however narrow the box. + let logical = pixels; + let pixels = Rect::new(x0, y0, x1, y1).tile_count() * (photocraft_geom::TILE_SIZE as u64).pow(2); + if !self.can_retain_pixels(pixels, logical) { return None; } let Some(mut pixmap) = pixmap(w, h) else { @@ -1883,8 +1891,10 @@ impl Conv { return None; }; rendered?; - let layer = Layer::new(name, LayerContent::Raster(surface(&pixmap, Rect::new(x0, y0, x1, y1), self.fmt))); - let bytes = pixels * self.fmt.bytes_per_pixel() as u64; + let surf = surface(&pixmap, Rect::new(x0, y0, x1, y1), self.fmt); + // Charge what the layer keeps: surface() prunes transparent tiles. + let bytes = photocraft_raster::stored_tiles_bytes(surf.tile_count() as u64, &self.fmt); + let layer = Layer::new(name, LayerContent::Raster(surf)); self.pixel_budget -= bytes; self.retained_pixel_bytes += bytes; Some(layer) diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index 3052ba9ca3..28c6a0bf89 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -703,7 +703,7 @@ fn oversized_raster_does_not_consume_budget_for_later_layers() { "##; - let result = import_parsed_with_budget("budget", parse(svg).unwrap(), MAX_GROUP_DEPTH, 64 * 64 * 4).unwrap(); + let result = import_parsed_with_budget("budget", parse(svg).unwrap(), MAX_GROUP_DEPTH, 256 * 256 * 4).unwrap(); assert_eq!(result.document.layers.len(), 1, "the oversized group must not debit the budget"); assert_eq!(result.document.layers[0].name, "small"); assert!(result.warnings.iter().any(|w| w.contains("too large to rasterise")), "{:?}", result.warnings); @@ -712,15 +712,15 @@ fn oversized_raster_does_not_consume_budget_for_later_layers() { #[test] fn skipped_expensive_raster_does_not_hide_a_smaller_one() { - let svg = br##" + let svg = br##" - + - + "##; - let result = import_parsed_with_budget("budget", parse(svg).unwrap(), MAX_GROUP_DEPTH, 32 * 32 * 4).unwrap(); + let result = import_parsed_with_budget("budget", parse(svg).unwrap(), MAX_GROUP_DEPTH, 256 * 256 * 4).unwrap(); assert_eq!(result.document.layers.len(), 1); assert_eq!(result.document.layers[0].name, "small"); assert!(result.warnings.iter().any(|w| w.contains("some rasterised elements were omitted")), "{:?}", result.warnings); diff --git a/crates/io/src/text_import.rs b/crates/io/src/text_import.rs index 0522f39e90..cb5c0a3232 100644 --- a/crates/io/src/text_import.rs +++ b/crates/io/src/text_import.rs @@ -8,17 +8,45 @@ use photocraft_doc::{Document, Layer, LayerContent, TextLayer}; /// it is edited. pub(crate) const MAX_RENDER_PIXELS: u64 = 64 * 1024 * 1024; -/// Renders `t` from its model unless its ink would exceed [`MAX_RENDER_PIXELS`]. -fn render_bounded(eng: &mut photocraft_text::TextEngine, t: &mut TextLayer, dpi: f32, format: photocraft_color::PixelFormat) { +/// Bytes a pixel cache covering `area` holds: surfaces store whole tiles, so a 2x2 px shape +/// still keeps a tile. +pub(crate) fn cache_bytes(area: photocraft_geom::Rect, bytes_per_pixel: usize) -> u64 { + if area.is_empty() { + return 0; + } + let tile = i64::from(photocraft_geom::TILE_SIZE); + let tiles = |a: i32, b: i32| (i64::from(b) - 1).div_euclid(tile) - i64::from(a).div_euclid(tile) + 1; + let n = tiles(area.x0, area.x1) as u64 * tiles(area.y0, area.y1) as u64; + n.saturating_mul((tile * tile) as u64).saturating_mul(bytes_per_pixel as u64) +} + +/// Renders `t` from its model unless its ink would exceed [`MAX_RENDER_PIXELS`] or the +/// document-wide `budget` (bytes of cache still allowed). Returns `false` when the layer went +/// without pixels because of the budget. +fn render_bounded(eng: &mut photocraft_text::TextEngine, t: &mut TextLayer, dpi: f32, format: photocraft_color::PixelFormat, budget: &mut u64) -> bool { + let empty = || photocraft_raster::Surface::new(photocraft_color::PixelFormat { alpha: true, ..format }); + let tile_bytes = cache_bytes(photocraft_geom::Rect::new(0, 0, 1, 1), photocraft_color::PixelFormat { alpha: true, ..format }.bytes_per_pixel()); + if *budget < tile_bytes { + // Nothing with ink fits any more: don't lay the text out just to find that out. + t.cache = Some(empty()); + return false; + } let layout = eng.layout(t, dpi); let warp = photocraft_text::render::layout_deform(&layout, t); let ink = photocraft_text::render::ink_rect_warped(&layout, &t.transform, warp.as_ref()); if u64::from(ink.width()).saturating_mul(u64::from(ink.height())) > MAX_RENDER_PIXELS { - t.cache = Some(photocraft_raster::Surface::new(photocraft_color::PixelFormat { alpha: true, ..format })); - return; + t.cache = Some(empty()); + return true; } + let cost = cache_bytes(ink, photocraft_color::PixelFormat { alpha: true, ..format }.bytes_per_pixel()); + let Some(rest) = budget.checked_sub(cost) else { + t.cache = Some(empty()); + return false; + }; + *budget = rest; let r = photocraft_text::render::rasterize_warped(&layout, &t.transform, format, t.antialias, warp.as_ref()); t.cache = Some(r.surface); + true } /// Prepares the type layers of a document that was just imported: @@ -29,14 +57,32 @@ fn render_bounded(eng: &mut photocraft_text::TextEngine, t: &mut TextLayer, dpi: /// let Photoshop re-render on open) is rendered from its model, instead of staying empty /// until it is edited. pub(crate) fn prepare(doc: &mut Document, txt2: Option<&photocraft_text::engine_data::Value>) { + let mut unlimited = u64::MAX; + let _ = prepare_within(doc, txt2, &mut unlimited, &photocraft_raster::Interrupt::NONE); +} + +/// [`prepare`] with the pixels it may draw limited to `budget` bytes for the whole document +/// (type layers past it keep empty pixels, as past [`MAX_RENDER_PIXELS`]) and stopping early +/// when `ctl` is cancelled. Returns how many layers the budget left without pixels. +pub(crate) fn prepare_within( + doc: &mut Document, + txt2: Option<&photocraft_text::engine_data::Value>, + budget: &mut u64, + ctl: &photocraft_raster::Interrupt, +) -> Result { + #[allow(clippy::too_many_arguments)] fn visit( layers: &mut [Layer], eng: &mut photocraft_text::TextEngine, dpi: f32, format: photocraft_color::PixelFormat, txt2: Option<&photocraft_text::engine_data::Value>, - ) { + budget: &mut u64, + ctl: &photocraft_raster::Interrupt, + skipped: &mut usize, + ) -> Result<(), photocraft_raster::Cancelled> { for l in layers { + ctl.check()?; match &mut l.content { LayerContent::Text(t) => { let mut changed = false; @@ -63,17 +109,20 @@ pub(crate) fn prepare(doc: &mut Document, txt2: Option<&photocraft_text::engine_ t.sync_summary(); } photocraft_text::psd::refine_legacy_point_origin(t, dpi, eng, txt2); - if t.cache.is_none() { - render_bounded(eng, t, dpi, format); + if t.cache.is_none() && !render_bounded(eng, t, dpi, format, budget) { + *skipped += 1; } } - LayerContent::Group(g) => visit(&mut g.children, eng, dpi, format, txt2), + LayerContent::Group(g) => visit(&mut g.children, eng, dpi, format, txt2, budget, ctl, skipped)?, _ => {} } } + Ok(()) } let dpi = doc.resolution_dpi; let format = doc.pixel_format(); let mut eng = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()); - visit(&mut doc.layers, &mut eng, dpi, format, txt2); + let mut skipped = 0; + visit(&mut doc.layers, &mut eng, dpi, format, txt2, budget, ctl, &mut skipped)?; + Ok(skipped) } diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs index 413fee396e..6b210f8752 100644 --- a/crates/io/src/tiff_layers.rs +++ b/crates/io/src/tiff_layers.rs @@ -1,5 +1,5 @@ //! Layered TIFF: Photoshop layer data carried in the TIFF tags 37724 (`ImageSourceData`) and -//! 34377 (image resources), see [`photocraft_psd::tiff`]. +//! 34377 (image resources), see [`craft_psd::tiff`]. //! //! Import rebuilds a PSD model from the TIFF's pixels plus those two tags and hands it to the //! PSD importer, so everything the PSD path understands (groups, masks, effects, type, shapes, @@ -10,13 +10,13 @@ use std::sync::Arc; +use craft_psd::resources::ids; +use craft_psd::tiff::{ByteOrder, ImageSourceData, resources_from_bytes, resources_to_bytes}; +use craft_psd::{ColorMode as PsdMode, Compression, Header, ImageData, ImageResource, ResolutionInfo}; use photocraft_codecs::{self as codecs, ChannelLayout, Format, Image, SampleType as CSample}; use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_doc::{AlphaChannel, Document}; use photocraft_geom::Rect; -use photocraft_psd::resources::ids; -use photocraft_psd::tiff::{ByteOrder, ImageSourceData, resources_from_bytes, resources_to_bytes}; -use photocraft_psd::{ColorMode as PsdMode, Compression, Header, ImageData, ImageResource, ResolutionInfo}; use photocraft_raster::Surface; use crate::flat::{csample, encode_image, image_to_document, layout_for, single_layer, try_buffer}; @@ -72,7 +72,7 @@ pub(crate) struct LayeredPlan { struct LayeredModel { /// The PSD model with an empty merged image: the TIFF's pixels replace it after decoding. - file: photocraft_psd::PsdFile, + file: craft_psd::PsdFile, } impl LayeredPlan { @@ -389,7 +389,7 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr // The layers move out of the model rather than being copied, and are freed once written // (#6607); the model keeps its header, resources and composite for the image below. let (layers, w) = match tiff_image_source(doc, &mut file, save_transparency && has_alpha).into_bytes(order) { - Err(photocraft_psd::PsdError::LimitExceeded(_)) if !force_psb => { + Err(craft_psd::PsdError::LimitExceeded(_)) if !force_psb => { let psb_opts = PsdExportOptions { force_psb: true, ..psd_opts }; let (psb, w) = crate::with_span(ctl, 0.0, TIFF_MODEL_DONE, |ctl| crate::psd_export::document_to_psd_interruptible(doc, &psb_opts, ctl)); ctl.check().map_err(|_| IoError::Cancelled)?; @@ -489,7 +489,7 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr /// Photoshop writes it. The layers, global mask and global blocks move out of `file` (the /// export's own model), which keeps its header, resources and merged image. `ifd_alpha`: the /// composite in the IFD keeps its transparency as the first extra sample (Save Transparency). -fn tiff_image_source(doc: &Document, file: &mut photocraft_psd::PsdFile, ifd_alpha: bool) -> ImageSourceData { +fn tiff_image_source(doc: &Document, file: &mut craft_psd::PsdFile, ifd_alpha: bool) -> ImageSourceData { // Photoshop pairs alpha-name resources with samples past the colour channels and ignores // the ExtraSamples kind. Layer transparency stays in each layer's channel −1. let spot_extras = file.header.channels as usize > { @@ -522,7 +522,7 @@ fn tiff_image_source(doc: &Document, file: &mut photocraft_psd::PsdFile, ifd_alp // Photoshop sets flag bit 3 on every record it writes, group dividers included (299 of // the 305 dividers in the corpus's Photoshop files). PhotoCraft's PSDs set it on // layers only, unchanged here. - layer.flags.0 |= photocraft_psd::layer::LayerFlags::BIT4_USEFUL; + layer.flags.0 |= craft_psd::layer::LayerFlags::BIT4_USEFUL; photoshop_layer_blocks(&mut layer.blocks); } } @@ -532,17 +532,17 @@ fn tiff_image_source(doc: &Document, file: &mut photocraft_psd::PsdFile, ifd_alp if let Some(mask) = &mut isd.global_layer_mask && mask.data.len() < 14 { - *mask = photocraft_psd::GlobalLayerMask::photoshop_default(); + *mask = craft_psd::GlobalLayerMask::photoshop_default(); } if !isd.global_blocks.iter().any(|b| matches!(&b.key, b"Patt" | b"Pat2" | b"Pat3")) { - isd.global_blocks.insert(0, photocraft_psd::TaggedBlock::new(*b"Patt", Vec::new())); + isd.global_blocks.insert(0, craft_psd::TaggedBlock::new(*b"Patt", Vec::new())); } if !isd.global_blocks.iter().any(|b| &b.key == b"FMsk") { - isd.global_blocks.push(photocraft_psd::TaggedBlock::new(*b"FMsk", FILTER_MASK_DEFAULT.to_vec())); + isd.global_blocks.push(craft_psd::TaggedBlock::new(*b"FMsk", FILTER_MASK_DEFAULT.to_vec())); } // Photoshop writes the marker first, ahead of `Patt`. if ifd_alpha && spot_extras && !isd.global_blocks.iter().any(|b| b.is_merged_transparency_marker()) { - isd.global_blocks.insert(0, photocraft_psd::TaggedBlock::new(*b"MTrn", Vec::new())); + isd.global_blocks.insert(0, craft_psd::TaggedBlock::new(*b"MTrn", Vec::new())); } isd } @@ -628,32 +628,32 @@ fn drop_first_display_record(data: &[u8]) -> Vec { } /// Filter-mask block (`FMsk`) Photoshop writes next to a layered TIFF: the same red 50% -/// overlay as [`photocraft_psd::GlobalLayerMask::photoshop_default`], without the kind byte. +/// overlay as [`craft_psd::GlobalLayerMask::photoshop_default`], without the kind byte. const FILTER_MASK_DEFAULT: &[u8] = &[0, 0, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 50]; /// Blocks Photoshop writes on every layer of a layered TIFF, when the layer does not /// already carry them. Defaults match a plain pixel layer (clipped-as-group on, nothing /// locked, no label). -fn photoshop_layer_blocks(blocks: &mut Vec) { +fn photoshop_layer_blocks(blocks: &mut Vec) { let has = |k: &[u8; 4]| blocks.iter().any(|b| &b.key == k); let mut add = Vec::new(); if !has(b"lnsr") { - add.push(photocraft_psd::TaggedBlock::name_source(*b"layr")); + add.push(craft_psd::TaggedBlock::name_source(*b"layr")); } if !has(b"clbl") { - add.push(photocraft_psd::TaggedBlock::blend_clipped_as_group(true)); + add.push(craft_psd::TaggedBlock::blend_clipped_as_group(true)); } if !has(b"infx") { - add.push(photocraft_psd::TaggedBlock::blend_interior_elements(false)); + add.push(craft_psd::TaggedBlock::blend_interior_elements(false)); } if !has(b"knko") { - add.push(photocraft_psd::TaggedBlock::knockout(0)); + add.push(craft_psd::TaggedBlock::knockout(0)); } if !has(b"lspf") { - add.push(photocraft_psd::TaggedBlock::protection(0)); + add.push(craft_psd::TaggedBlock::protection(0)); } if !has(b"lclr") { - add.push(photocraft_psd::TaggedBlock::sheet_color(0)); + add.push(craft_psd::TaggedBlock::sheet_color(0)); } let at = blocks .iter() @@ -667,12 +667,12 @@ fn photoshop_layer_blocks(blocks: &mut Vec) { } /// Removes the blocks a document kept verbatim from a little-endian TIFF because their layout -/// is unknown ([`photocraft_psd::TaggedBlock::is_foreign_order`]) before `file` is written as a +/// is unknown ([`craft_psd::TaggedBlock::is_foreign_order`]) before `file` is written as a /// PSD: their bytes are in the wrong order for a PSD and cannot be converted. Returns a warning -/// per block dropped. A save back to TIFF keeps them (see [`photocraft_psd::tiff`]). -pub fn strip_foreign_order_blocks(file: &mut photocraft_psd::PsdFile) -> Vec { +/// per block dropped. A save back to TIFF keeps them (see [`craft_psd::tiff`]). +pub fn strip_foreign_order_blocks(file: &mut craft_psd::PsdFile) -> Vec { let mut warnings = Vec::new(); - let mut strip = |blocks: &mut Vec, owner: &str| { + let mut strip = |blocks: &mut Vec, owner: &str| { blocks.retain(|b| { let keep = !b.is_foreign_order(); if !keep { @@ -1245,7 +1245,7 @@ mod tests { let r = export(&doc, "x.tif", &ExportOptions { tiff_layers: true, ..Default::default() }).unwrap(); let (_, layers) = photocraft_codecs::tiff_photoshop_tags(&r.bytes); let layers = layers.unwrap(); - assert!(layers.starts_with(photocraft_psd::tiff::SIGNATURE), "{:?}", String::from_utf8_lossy(&layers[..36.min(layers.len())])); + assert!(layers.starts_with(craft_psd::tiff::SIGNATURE), "{:?}", String::from_utf8_lossy(&layers[..36.min(layers.len())])); assert!(!r.warnings.iter().any(|w| w.contains("PSB")), "{:?}", r.warnings); let back = crate::import("x.tif", &r.bytes).unwrap().document; assert_eq!(back.layers.len(), doc.layers.len()); @@ -1260,7 +1260,7 @@ mod tests { let doc = many_cheap_fills(); let r = export(&doc, "x.tif", &ExportOptions { tiff_layers: true, force_psb: true, ..Default::default() }).unwrap(); let (_, layers) = photocraft_codecs::tiff_photoshop_tags(&r.bytes); - assert!(layers.unwrap().starts_with(photocraft_psd::tiff::SIGNATURE_PSB)); + assert!(layers.unwrap().starts_with(craft_psd::tiff::SIGNATURE_PSB)); } /// The adaptive budget, not only the caller's pixel limit, decides a layered TIFF: a known diff --git a/crates/io/src/vector_map.rs b/crates/io/src/vector_map.rs index d7667d408b..afcf85094b 100644 --- a/crates/io/src/vector_map.rs +++ b/crates/io/src/vector_map.rs @@ -6,10 +6,10 @@ //! a preserved block is written back byte-identical while it still decodes to the layer's //! current model; otherwise it is regenerated from the model. +use craft_psd::descriptor::{Descriptor, Id, Value, VersionedDescriptor}; +use craft_psd::path::{PathData, PsdKnot, PsdSubpath, VectorMaskBlock}; use photocraft_doc::{Fill, FillRule, Knot, LineCap, LineJoin, LiveShape, Path, PathOp, ShapeLayer, ShapeStroke, StrokeAlign, Subpath, VectorMask}; use photocraft_geom::Point; -use photocraft_psd::descriptor::{Descriptor, Id, Value, VersionedDescriptor}; -use photocraft_psd::path::{PathData, PsdKnot, PsdSubpath, VectorMaskBlock}; use crate::blocks::{bool_of, enum_of, fill_from_desc, fill_to_desc, get_desc, num, parse_prefix_versioned}; @@ -420,7 +420,8 @@ pub fn live_from_vogk(data: &[u8]) -> Option { // 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 }; + // Photoshop's range is -50..50 % (#13258): keep a negative value. + let concavity = if concavity.is_finite() { concavity.clamp(-50.0, 50.0) } else { 0.0 }; Some(LiveShape::ArrowLine { from, to, weight, start, end, width, length, concavity }) } else { Some(LiveShape::Line { from, to, weight }) @@ -491,7 +492,7 @@ pub fn vogk_bytes(s: &LiveShape, dpi: f32) -> Option> { .with("keyOriginLineArrLngth", Value::Double(*length)) .with("keyOriginLineArrConc", Value::Integer(concavity.round() as i32)) } - LiveShape::Polygon { .. } => return None, + LiveShape::Polygon { .. } | LiveShape::Triangle { .. } => return None, }; let o = o.with("keyOriginIndex", Value::Integer(0)); let d = Descriptor::new("null").with("keyDescriptorList", Value::List(vec![Value::Descriptor(o)])); @@ -747,6 +748,21 @@ mod tests { assert!(vogk_bytes(&LiveShape::Polygon { rect: [0.0; 4], sides: 5, star_ratio: 1.0, corner_radius: 0.0 }, 72.0).is_none()); } + /// A PSD arrow keeps a negative concavity, and one past 50 % opens clamped to 50 (#13258). + #[test] + fn vogk_arrow_concavity_keeps_negatives_and_clamps_to_fifty() { + let arrow = + |concavity| LiveShape::ArrowLine { from: [0.0, 10.0], to: [20.0, 0.0], weight: 3.0, start: false, end: true, width: 5.0, length: 10.0, concavity }; + let read = |c| match live_from_vogk(&vogk_bytes(&arrow(c), 72.0).unwrap()) { + Some(LiveShape::ArrowLine { concavity, .. }) => concavity, + other => panic!("{other:?}"), + }; + assert_eq!(read(-50.0), -50.0); + assert_eq!(read(-20.0), -20.0); + assert_eq!(read(80.0), 50.0); + assert_eq!(read(-90.0), -50.0); + } + #[test] fn shape_blocks_keep_unchanged_and_regenerate_changed() { let sh = ShapeLayer { diff --git a/crates/io/src/vector_preview.rs b/crates/io/src/vector_preview.rs index 646d8c73f1..2d1186e7a3 100644 --- a/crates/io/src/vector_preview.rs +++ b/crates/io/src/vector_preview.rs @@ -384,7 +384,7 @@ mod tests { smart.vector_preview = Some(preview.clone()); doc.layers.push(Layer::new("native", LayerContent::Smart(smart))); let out = crate::export(&doc, "psd", &Default::default()).unwrap(); - let mut file = photocraft_psd::PsdFile::from_bytes(&out.bytes).unwrap(); + let mut file = craft_psd::PsdFile::from_bytes(&out.bytes).unwrap(); let record = file.layers()[0].clone(); *file.layers_mut() = vec![record; 100]; let before = HASHED_SOURCE_BYTES.with(std::cell::Cell::get); @@ -450,7 +450,7 @@ mod tests { assert_eq!(after.0 - before.0, source.len(), "the shared native source must not be hashed per layer or per use"); assert_eq!(after.1 - before.1, 1, "the shared preview must not be rendered per layer or per use"); assert_eq!(after.2 - before.2, source.len(), "the conversion cache must not re-hash the shared Embedded owner per layer"); - let file = photocraft_psd::PsdFile::from_bytes(&out.bytes).unwrap(); + let file = craft_psd::PsdFile::from_bytes(&out.bytes).unwrap(); assert!(file.layers().iter().all(|layer| layer.block(&PSD_KEY).is_some())); let back = check(&out.bytes); diff --git a/crates/io/src/xcf.rs b/crates/io/src/xcf.rs index e9a6b92a21..7761415563 100644 --- a/crates/io/src/xcf.rs +++ b/crates/io/src/xcf.rs @@ -581,15 +581,26 @@ fn label(tag: u32) -> LabelColor { } } -/// Writes `px` (its channels matching `surface`'s) at `x, y` of the document. -fn write_pixels(surface: &mut Surface, px: &Pixels, x: i32, y: i32) -> Result<()> { +/// Writes `px` (its channels matching `surface`'s) at `x, y` of the document, charging the +/// tiles that creates to `budget`: the drawable was admitted by its logical samples, and a +/// narrow drawable (or one referenced by many layer pointers) stores far more in whole tiles. +fn write_pixels(surface: &mut Surface, px: &Pixels, x: i32, y: i32, budget: &mut usize) -> Result<()> { let (w, h) = (px.width as i32, px.height as i32); let rect = Rect::new(x, y, x.checked_add(w).ok_or_else(|| invalid("offset overflow"))?, y.checked_add(h).ok_or_else(|| invalid("offset overflow"))?); if surface.channels() != px.channels || px.data.len() != (px.width as usize) * (px.height as usize) * px.channels { return Err(invalid("pixel data does not match the drawable")); } + // Checked before the write (it allocates the whole rect's tiles); only the tiles kept after + // `prune()` are charged. + let tiles = usize::try_from(photocraft_raster::tile_storage_bytes(rect, &surface.format())).unwrap_or(usize::MAX); + if tiles > *budget { + return Err(invalid("the layers exceed the 1 GiB pixel limit")); + } + let before = surface.tile_count(); surface.write_region(rect, &px.data); surface.prune(); + let added = surface.tile_count().saturating_sub(before) as u64; + *budget = budget.saturating_sub(usize::try_from(photocraft_raster::stored_tiles_bytes(added, &surface.format())).unwrap_or(usize::MAX)); Ok(()) } @@ -780,7 +791,7 @@ pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result Image<'a> { px = Pixels { width: px.width, height: px.height, channels: n + 1, data }; } let mut surface = Surface::new(fmt); - write_pixels(&mut surface, &px, x, y)?; + write_pixels(&mut surface, &px, x, y, &mut self.budget)?; layer.content = LayerContent::Raster(surface); if !alpha { layer.locks.transparency = true; @@ -1078,7 +1089,7 @@ impl<'a> Image<'a> { if mptr != 0 { let (_mname, _mprops, px) = self.channel(mptr, ctl)?; let mut surface = Surface::new(mask_fmt); - write_pixels(&mut surface, &px, x, y)?; + write_pixels(&mut surface, &px, x, y, &mut self.budget)?; layer.mask = Some(LayerMask { surface, enabled: apply_mask, linked: true, density: 1.0, feather: 0.0 }); } let linear = composite_space.unsigned_abs() == 1 || blend_space.unsigned_abs() == 1; diff --git a/crates/io/src/xcf/tests.rs b/crates/io/src/xcf/tests.rs index 24481f1956..5ad14f19b2 100644 --- a/crates/io/src/xcf/tests.rs +++ b/crates/io/src/xcf/tests.rs @@ -808,3 +808,30 @@ fn duplicate_parasites_keep_order_and_last_value() { assert_eq!(out[0].1, b"second", "last value wins"); assert_eq!(out[1].0, "gimp-image-grid", "insertion order preserved"); } + +#[test] +fn a_narrow_drawable_is_charged_the_tiles_it_stores() { + // One pixel wide and 300000 tall: 1.2 MB of samples a layer, but 1172 whole tiles (307 MB + // in RGBA8); four such layers pass the sample budget and exceed the 1 GiB of tiles. + let h = MAX_SIDE; + let mut img = TestImage::rgb8(1, h); + for name in ["a", "b", "c", "d"] { + img.layers.push(TestLayer::rgba(name, 1, h, rgba(1, h, |_, _| [1, 2, 3, 255]))); + } + let e = open(&img.write()).unwrap_err().to_string(); + assert!(e.contains("pixel limit"), "{e}"); + img.layers.truncate(3); + assert!(open(&img.write()).is_ok(), "three fit"); +} + +/// Blank content keeps no tiles after `prune()`, so it is not charged against the pixel budget. +#[test] +fn blank_layers_are_not_charged_for_pruned_tiles() { + let mut budget = MAX_PIXEL_BYTES; + for _ in 0..4 { + let mut surface = Surface::new(photocraft_color::PixelFormat::RGBA8); + let px = Pixels { width: 1, height: 300_000, channels: 4, data: vec![0.0; 1_200_000] }; + write_pixels(&mut surface, &px, 0, 0, &mut budget).unwrap(); + } + assert_eq!(budget, MAX_PIXEL_BYTES); +} diff --git a/crates/io/tests/it/adjust_blend_roundtrip.rs b/crates/io/tests/it/adjust_blend_roundtrip.rs index f6e255c6dd..81e4cc9611 100644 --- a/crates/io/tests/it/adjust_blend_roundtrip.rs +++ b/crates/io/tests/it/adjust_blend_roundtrip.rs @@ -9,13 +9,13 @@ use crate::common; use std::sync::Arc; use common::*; +use craft_psd::PsdFile; use photocraft_color::{BlendMode, ColorMode, SampleType}; use photocraft_doc::adjust::{CurvePoint, LevelsChannel}; use photocraft_doc::adjust::{HueRange, ToneSpace}; use photocraft_doc::*; use photocraft_geom::Rect; use photocraft_io::*; -use photocraft_psd::PsdFile; const TOL: f32 = 1.0 / 255.0 + 1e-5; @@ -280,7 +280,7 @@ fn every_blend_mode_round_trips() { let adj = Layer::new("inside", LayerContent::Adjustment(Adjustment::Invert)); d.layers.push(Layer::group("pass-through adj", vec![raster("px", fmt, Rect::new(0, 0, 6, 6), 6, true), adj])); let (back, _, file) = export_import(&d); - assert!(file.layers().iter().any(|l| l.blend_mode == photocraft_psd::BlendMode::PassThrough), "pass key written"); + assert!(file.layers().iter().any(|l| l.blend_mode == craft_psd::BlendMode::PassThrough), "pass key written"); assert_docs_eq(&d, &back); assert_composite_eq(&d, &back, "pass-through"); continue; diff --git a/crates/io/tests/it/adjust_warnings.rs b/crates/io/tests/it/adjust_warnings.rs index 0e4e822527..55220bb251 100644 --- a/crates/io/tests/it/adjust_warnings.rs +++ b/crates/io/tests/it/adjust_warnings.rs @@ -1,12 +1,12 @@ //! Opening a file whose adjustment layer can't be read warns, naming the layer and the reason, //! instead of opening it silently without its effect (#1763). +use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; +use craft_psd::{Compression, LayerFlags, LayerRecord, PsdFile, TaggedBlock, Version, testgen}; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::{Adjustment, Document, Layer, LayerContent}; use photocraft_geom::Size; use photocraft_io::*; -use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; -use photocraft_psd::{Compression, LayerFlags, LayerRecord, PsdFile, TaggedBlock, Version, testgen}; use photocraft_raster::Surface; fn reopen(adj: Adjustment, path: &str, opts: &ExportOptions) -> (Document, Vec) { @@ -73,7 +73,7 @@ fn identity_cube(domain: &str) -> Vec { fn synthetic_lookup_psd(version: Version, depth: u16, cube: &[u8]) -> Vec { const LAYER_NAME: &str = "Custom-domain LUT"; - let mut file = testgen::layered(version, photocraft_psd::ColorMode::Rgb, depth, Compression::Rle); + let mut file = testgen::layered(version, craft_psd::ColorMode::Rgb, depth, Compression::Rle); let mut flags = LayerFlags::default(); flags.set_pixel_data_irrelevant(true); // Photoshop stores layer-block alignment inside the block length. Make the source payload diff --git a/crates/io/tests/it/annotations.rs b/crates/io/tests/it/annotations.rs index 2f50b82909..a3984e9cc3 100644 --- a/crates/io/tests/it/annotations.rs +++ b/crates/io/tests/it/annotations.rs @@ -4,12 +4,12 @@ #[cfg(feature = "corpus")] use std::path::PathBuf; +use craft_psd::PsdFile; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::{Document, MeasurementScale, Note}; use photocraft_geom::Size; use photocraft_io::annotations_map::MEASUREMENT_SCALE; use photocraft_io::{ExportOptions, export, import}; -use photocraft_psd::PsdFile; #[cfg(feature = "corpus")] fn corpus(rel: &str) -> Vec { @@ -103,7 +103,7 @@ fn psd_with_anno(anno: Vec) -> Vec { let mut doc = Document::new("notes", Size::new(16, 16), ColorMode::Rgb, SampleType::U8); doc.layers.push(photocraft_doc::Layer::raster("Background", doc.pixel_format())); let mut file = PsdFile::from_bytes(&to_psd(&doc)).unwrap(); - let mut tb = photocraft_psd::TaggedBlock::new(*b"Anno", anno.clone()); + let mut tb = craft_psd::TaggedBlock::new(*b"Anno", anno.clone()); tb.padding = Some(vec![0; (4 - anno.len() % 4) % 4]); file.global_blocks.push(tb); file.to_bytes().unwrap() diff --git a/crates/io/tests/it/artboard_guide_order.rs b/crates/io/tests/it/artboard_guide_order.rs index a9adcad9b4..514c7e0b56 100644 --- a/crates/io/tests/it/artboard_guide_order.rs +++ b/crates/io/tests/it/artboard_guide_order.rs @@ -43,7 +43,7 @@ fn exported_artboard_indices_match_guides_resource() { use photocraft_io::ExportOptions; let d = doc_with_board(Rect::new(10, 0, 30, 50)); let bytes = export(&d, "x.psd", &ExportOptions::default()).expect("export").bytes; - let f = photocraft_psd::PsdFile::from_bytes(&bytes).expect("parse"); + let f = craft_psd::PsdFile::from_bytes(&bytes).expect("parse"); let res = f.resources.iter().find(|r| r.id == 1032).expect("guides resource"); // 1032: version(4) hRes(4) vRes(4) count(4), then 5 bytes per guide: loc(4) dir(1). let dta = &res.data; diff --git a/crates/io/tests/it/blend_modes_corpus.rs b/crates/io/tests/it/blend_modes_corpus.rs index 72980bed5b..df666a1bf5 100644 --- a/crates/io/tests/it/blend_modes_corpus.rs +++ b/crates/io/tests/it/blend_modes_corpus.rs @@ -2,10 +2,10 @@ //! one 64 × 64 cell per mode, a duck over a rainbow backdrop. #![cfg(feature = "corpus")] +use craft_psd::PsdFile; use photocraft_color::BlendMode; use photocraft_geom::Rect; use photocraft_io::{import, merged_composite}; -use photocraft_psd::PsdFile; const CELL: i32 = 64; diff --git a/crates/io/tests/it/cancel.rs b/crates/io/tests/it/cancel.rs index efd2b665b8..b42c5c1316 100644 --- a/crates/io/tests/it/cancel.rs +++ b/crates/io/tests/it/cancel.rs @@ -47,7 +47,7 @@ fn import_reports_monotonic_progress_per_layer() { #[test] fn cancelled_brush_import_fails() { - use photocraft_psd::abr::{LegacyBrush, LegacyTip, write_v12}; + use craft_psd::abr::{LegacyBrush, LegacyTip, write_v12}; let brush = |name: &str| LegacyBrush { name: name.into(), spacing: 10, diff --git a/crates/io/tests/it/channels.rs b/crates/io/tests/it/channels.rs index 72accd5a2c..0171d298ee 100644 --- a/crates/io/tests/it/channels.rs +++ b/crates/io/tests/it/channels.rs @@ -47,7 +47,7 @@ fn channel_options_spot_and_quick_mask_roundtrip() { full.quick_mask = Some(AlphaChannel::new("Quick Mask", Surface::new(PixelFormat::GRAY8))); let out = photocraft_io::export(&full, "full.psd", &Default::default()).unwrap(); assert!(out.warnings.iter().any(|warning| warning.contains("Quick Mask")), "{:?}", out.warnings); - let file = photocraft_psd::PsdFile::from_bytes(&out.bytes).unwrap(); + let file = craft_psd::PsdFile::from_bytes(&out.bytes).unwrap(); assert_eq!(file.header.channels, 56); assert!(file.resources.iter().all(|resource| resource.id != 1022)); } diff --git a/crates/io/tests/it/cmyk_composite_export.rs b/crates/io/tests/it/cmyk_composite_export.rs index 77f35a62d2..c37748f0da 100644 --- a/crates/io/tests/it/cmyk_composite_export.rs +++ b/crates/io/tests/it/cmyk_composite_export.rs @@ -357,7 +357,7 @@ fn merged_composite_of_a_tagged_cmyk_file_reads_through_its_profile() { } doc.layers.push(Layer::new("Background", LayerContent::Raster(surface))); let psd = export(&doc, "psd", &ExportOptions::default()).unwrap(); - let file = photocraft_psd::PsdFile::from_bytes(&psd.bytes).unwrap(); + let file = craft_psd::PsdFile::from_bytes(&psd.bytes).unwrap(); let merged = photocraft_io::merged_composite(&file).unwrap(); // The merged image's own inks (planar, 255 = no ink), shown through the file's profile. let raw = file.decode_merged().unwrap(); diff --git a/crates/io/tests/it/cmyk_export.rs b/crates/io/tests/it/cmyk_export.rs index 043da677f2..59daa5efab 100644 --- a/crates/io/tests/it/cmyk_export.rs +++ b/crates/io/tests/it/cmyk_export.rs @@ -222,7 +222,7 @@ fn psd_merged_image_keeps_exact_inks() { m.blend = BlendMode::Multiply; d.layers.push(m); let r = export(&d, "a.psd", &ExportOptions::default()).unwrap_or_else(|e| panic!("{e}")); - let f = photocraft_psd::PsdFile::from_bytes(&r.bytes).unwrap_or_else(|e| panic!("{e}")); + let f = craft_psd::PsdFile::from_bytes(&r.bytes).unwrap_or_else(|e| panic!("{e}")); let planes = f.decode_merged().unwrap_or_else(|e| panic!("{e}")); let n = 12 * 8; // Planar, inverted (255 = no ink). diff --git a/crates/io/tests/it/color.rs b/crates/io/tests/it/color.rs index 5da5df1c7e..a3458d2ed9 100644 --- a/crates/io/tests/it/color.rs +++ b/crates/io/tests/it/color.rs @@ -184,8 +184,8 @@ fn rgb_fill_colours_separate_through_the_document_cmyk_profile() { fn cmyk_merged_composite_reads_through_the_embedded_profile() { // The merged image of a CMYK file tagged with a non-default profile is turned into RGB through // that profile, as the layers are, or every comparison against it is off (#3778). + use craft_psd::{Compression, ImageResource, Version, testgen}; use photocraft_cms::{Intent, Transform}; - use photocraft_psd::{Compression, ImageResource, Version, testgen}; let profile = photocraft_cms::synth::cmyk_profile(&photocraft_cms::synth::CmykParams { tvi: [0.26, 0.26, 0.26, 0.3], grid_a2b: 5, @@ -199,7 +199,7 @@ fn cmyk_merged_composite_reads_through_the_embedded_profile() { [o[0].clamp(0.0, 1.0), o[1].clamp(0.0, 1.0), o[2].clamp(0.0, 1.0)] }; for depth in [8u16, 16] { - let mut f = testgen::merged_only(Version::Psd, photocraft_psd::ColorMode::Cmyk, depth, Compression::Raw, 4, 1); + let mut f = testgen::merged_only(Version::Psd, craft_psd::ColorMode::Cmyk, depth, Compression::Raw, 4, 1); let inks: [[f32; 4]; 4] = [[0.1, 0.6, 0.7, 0.05], [0.8, 0.2, 0.1, 0.0], [0.3, 0.3, 0.3, 0.5], [0.0, 0.0, 0.0, 0.0]]; let max = if depth == 8 { 255.0 } else { 65535.0 }; let mut data = Vec::new(); @@ -210,7 +210,7 @@ fn cmyk_merged_composite_reads_through_the_embedded_profile() { if depth == 8 { data.push(v as u8) } else { data.extend((v as u16).to_be_bytes()) } } } - f.image_data = photocraft_psd::ImageData { compression: Compression::Raw, data, stored: None }; + f.image_data = craft_psd::ImageData { compression: Compression::Raw, data, stored: None }; f.resources.push(ImageResource::new(1039, profile.to_bytes().to_vec())); let merged = merged_composite(&f).unwrap(); let mut seen_far = false; @@ -254,7 +254,7 @@ fn grdm_block(a: (u16, [u16; 4]), b: (u16, [u16; 4])) -> Vec { } fn saved_grdm(bytes: &[u8]) -> Vec { - let f = photocraft_psd::PsdFile::from_bytes(bytes).unwrap(); + let f = craft_psd::PsdFile::from_bytes(bytes).unwrap(); f.layers().iter().find_map(|l| l.block(b"grdm")).map(|b| b.data.clone()).expect("grdm block") } diff --git a/crates/io/tests/it/common/mod.rs b/crates/io/tests/it/common/mod.rs index 7bb010f1be..093c7985b1 100644 --- a/crates/io/tests/it/common/mod.rs +++ b/crates/io/tests/it/common/mod.rs @@ -360,7 +360,7 @@ fn tone_space(mode: ColorMode) -> photocraft_doc::adjust::ToneSpace { /// - blocks with inner lengths (`PlLd`, `SoLd`, `SoLE`, `lnk2`/`lnk3`/`lnkD`, `lfx2`) /// re-parse exactly (`TaggedBlock::check_structure`). pub fn strict_block_errors(bytes: &[u8]) -> Vec { - let file = match photocraft_psd::PsdFile::from_bytes(bytes) { + let file = match craft_psd::PsdFile::from_bytes(bytes) { Ok(f) => f, Err(e) => return vec![format!("parse: {e}")], }; @@ -374,8 +374,8 @@ pub fn strict_block_errors(bytes: &[u8]) -> Vec { let pad = li.padding.as_ref().map_or(body % 2, |p| p.len() as u64); // In a global `Lr16`/`Lr32` block the padding to 4 follows the block, outside its length. let after = match &file.layer_info_placement { - photocraft_psd::LayerInfoPlacement::GlobalBlock { padding, .. } => padding.as_ref().map_or((4 - (body + pad) % 4) % 4, |p| p.len() as u64), - photocraft_psd::LayerInfoPlacement::Section => 0, + craft_psd::LayerInfoPlacement::GlobalBlock { padding, .. } => padding.as_ref().map_or((4 - (body + pad) % 4) % 4, |p| p.len() as u64), + craft_psd::LayerInfoPlacement::Section => 0, }; if (body + pad + after) % 4 != 0 { errs.push(format!("layer info: {body} bytes + {pad} padding is not a multiple of 4")); diff --git a/crates/io/tests/it/composite.rs b/crates/io/tests/it/composite.rs index 5ab6ccace6..9e6e37e035 100644 --- a/crates/io/tests/it/composite.rs +++ b/crates/io/tests/it/composite.rs @@ -4,9 +4,9 @@ use crate::common; use common::*; +use craft_psd::{PixelData, PsdBuilder, PsdFile}; use photocraft_color::{BlendMode, ColorMode, SampleType}; use photocraft_io::*; -use photocraft_psd::{PixelData, PsdBuilder, PsdFile}; const TOL: f32 = 1.0 / 255.0 + 1e-4; @@ -72,8 +72,8 @@ fn builder_oracle(depth: u16, mode: ColorMode) { } }; let mut b = PsdBuilder::new(d.size.width, d.size.height).depth(depth).color_mode(match mode { - ColorMode::Grayscale => photocraft_psd::ColorMode::Grayscale, - _ => photocraft_psd::ColorMode::Rgb, + ColorMode::Grayscale => craft_psd::ColorMode::Grayscale, + _ => craft_psd::ColorMode::Rgb, }); for l in &d.layers { let s = l.surface().unwrap(); @@ -84,8 +84,8 @@ fn builder_oracle(depth: u16, mode: ColorMode) { let fmt = s.format(); s.read_region(r).chunks_exact(fmt.channels()).map(|p| photocraft_raster::to_rgba(&fmt, p)).collect() }; - let mut spec = photocraft_psd::LayerSpec::new(l.name.clone(), r.x0, r.y0, r.width(), r.height(), to_pixels(&buf)); - spec.blend_mode = photocraft_psd::BlendMode::from_key(l.blend.psd_key()); + let mut spec = craft_psd::LayerSpec::new(l.name.clone(), r.x0, r.y0, r.width(), r.height(), to_pixels(&buf)); + spec.blend_mode = craft_psd::BlendMode::from_key(l.blend.psd_key()); spec.opacity = (l.opacity * 255.0).round() as u8; spec.fill_opacity = Some((l.fill_opacity * 255.0).round() as u8); spec.visible = l.visible; @@ -93,8 +93,8 @@ fn builder_oracle(depth: u16, mode: ColorMode) { if let Some(m) = &l.mask { let mr = m.surface.content_bounds(); let data = m.surface.read_region(mr).iter().map(|v| (v * 255.0).round() as u8).collect(); - spec.mask = Some(photocraft_psd::MaskSpec { - rect: photocraft_psd::Rect { top: mr.y0, left: mr.x0, bottom: mr.y1, right: mr.x1 }, + spec.mask = Some(craft_psd::MaskSpec { + rect: craft_psd::Rect { top: mr.y0, left: mr.x0, bottom: mr.y1, right: mr.x1 }, data, default_color: (m.surface.default_pixel()[0] * 255.0).round() as u8, disabled: !m.enabled, diff --git a/crates/io/tests/it/comps_artboards.rs b/crates/io/tests/it/comps_artboards.rs index a5b553f5a8..3476560d1c 100644 --- a/crates/io/tests/it/comps_artboards.rs +++ b/crates/io/tests/it/comps_artboards.rs @@ -4,13 +4,13 @@ #[cfg(feature = "corpus")] use std::path::PathBuf; +use craft_psd::PsdFile; use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, SampleType}; use photocraft_doc::comps::capture_states; use photocraft_doc::{Artboard, ArtboardBackground, Document, Layer, LayerComp, LayerContent}; use photocraft_geom::{Rect, Size}; use photocraft_io::comps_map::LAYER_COMPS; use photocraft_io::{ExportOptions, export, import}; -use photocraft_psd::PsdFile; #[cfg(feature = "corpus")] fn corpus(rel: &str) -> Vec { @@ -71,7 +71,7 @@ fn corpus_layer_comps_import_and_verbatim_export() { assert_eq!(back.last_applied_comp, edited.last_applied_comp); // Other metadata items in shmd (`cust`) survive regeneration. let r = out2.layers().iter().find(|r| r.block(b"shmd").is_some()).unwrap(); - let items = photocraft_psd::metadata::parse_shmd(&r.block(b"shmd").unwrap().data).unwrap(); + let items = craft_psd::metadata::parse_shmd(&r.block(b"shmd").unwrap().data).unwrap(); assert!(items.iter().any(|i| &i.key == b"cust")); assert!(items.iter().any(|i| &i.key == b"cmls")); @@ -84,7 +84,7 @@ fn corpus_layer_comps_import_and_verbatim_export() { assert!(out3.resource(LAYER_COMPS).is_none()); for r in out3.layers() { if let Some(b) = r.block(b"shmd") { - assert!(photocraft_psd::metadata::parse_shmd(&b.data).unwrap().iter().all(|i| &i.key != b"cmls")); + assert!(craft_psd::metadata::parse_shmd(&b.data).unwrap().iter().all(|i| &i.key != b"cmls")); } } } @@ -251,8 +251,8 @@ fn synthetic_pcraft_roundtrip_keeps_everything() { /// A layer at (4, 4) whose preserved `shmd` block offsets it by `(dx, 0)` in comp 1, plus the /// matching resource 1065: what a PSD with that comp data imports to before decoding comps. fn doc_with_raw_comp_offset(dx: i32) -> Document { - use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value, VersionedDescriptor}; - use photocraft_psd::metadata::{MetadataItem, write_shmd}; + use craft_psd::descriptor::{Descriptor, UnicodeString, Value, VersionedDescriptor}; + use craft_psd::metadata::{MetadataItem, write_shmd}; let obj = |class: &str| Descriptor { name: UnicodeString(vec![0]), ..Descriptor::new(class) }; let mut d = Document::new("s", Size::new(32, 32), ColorMode::Rgb, SampleType::U8); let mut l = Layer::raster("A", PixelFormat::RGBA8); diff --git a/crates/io/tests/it/corpus.rs b/crates/io/tests/it/corpus.rs index 3c8ca3288a..fee3626fcb 100644 --- a/crates/io/tests/it/corpus.rs +++ b/crates/io/tests/it/corpus.rs @@ -50,8 +50,8 @@ use std::panic::{AssertUnwindSafe, catch_unwind}; use std::path::{Path, PathBuf}; use std::time::Instant; +use craft_psd::PsdFile; use photocraft_io::*; -use photocraft_psd::PsdFile; fn collect(dir: &Path, out: &mut Vec) { let Ok(rd) = std::fs::read_dir(dir) else { return }; @@ -191,7 +191,7 @@ const THUMB_BAD_FRAC: f32 = 0.02; /// Photoshop's embedded thumbnail (resource 1036: a 28-byte header, then JFIF) as RGB floats. fn thumbnail(file: &PsdFile) -> Option<(u32, u32, Vec<[f32; 3]>)> { - let r = file.resource(photocraft_psd::resources::ids::THUMBNAIL)?; + let r = file.resource(craft_psd::resources::ids::THUMBNAIL)?; let format = u32::from_be_bytes(r.data.get(..4)?.try_into().ok()?); if format != 1 { return None; @@ -325,7 +325,7 @@ fn check_file(name: &str, bytes: &[u8]) -> (Outcome, Option) { // whole image, decoded independently by the psd crate). When Photoshop wrote no real merged // image (Maximize Compatibility off) or it decodes through our own model code (Multichannel), // its embedded thumbnail is the oracle at thumbnail size. - let use_thumb = file.has_real_merged_data() == Some(false) || file.header.color_mode == photocraft_psd::ColorMode::Multichannel; + let use_thumb = file.has_real_merged_data() == Some(false) || file.header.color_mode == craft_psd::ColorMode::Multichannel; let merged = if use_thumb { None } else { merged_composite(&file).ok() }; let Some(merged) = merged else { let notes: Vec<&str> = imp.warnings.iter().map(String::as_str).take(2).collect(); diff --git a/crates/io/tests/it/corpus_regressions.rs b/crates/io/tests/it/corpus_regressions.rs index 26266c9f07..067ef79dcc 100644 --- a/crates/io/tests/it/corpus_regressions.rs +++ b/crates/io/tests/it/corpus_regressions.rs @@ -3,12 +3,12 @@ //! files themselves are never committed: each test rebuilds the relevant //! structure from our own documents. +use craft_psd::layer::CHANNEL_REAL_USER_MASK; +use craft_psd::{ChannelData, Compression, MaskData, PsdFile, RealMask, Version}; use photocraft_color::{Color, ColorMode, SampleType}; use photocraft_doc::{Document, Fill, Layer, LayerContent, LayerMask, Path, ShapeLayer, Size, Subpath, VectorMask}; use photocraft_geom::Rect; use photocraft_io::*; -use photocraft_psd::layer::CHANNEL_REAL_USER_MASK; -use photocraft_psd::{ChannelData, Compression, MaskData, PsdFile, RealMask, Version}; fn doc(depth: SampleType) -> Document { Document::with_background("t", Size::new(32, 32), ColorMode::Rgb, depth, Color::WHITE) @@ -100,7 +100,7 @@ fn real_user_mask_with_parameters_is_decoded() { let rec = file.layers_mut().last_mut().unwrap(); let MaskData::Mask(pm) = &mut rec.mask else { panic!("mask record") }; assert!(pm.parameters.is_some()); - let real_rect = photocraft_psd::Rect { top: 0, left: 0, bottom: 32, right: 16 }; + let real_rect = craft_psd::Rect { top: 0, left: 0, bottom: 32, right: 16 }; pm.real = Some(RealMask { flags: 0, background: 255, rect: real_rect }); pm.trailing.clear(); rec.channels.push(ChannelData::encode(CHANNEL_REAL_USER_MASK, Compression::Rle, &[0u8; 16 * 32], 16, 32, 8, Version::Psd).unwrap()); @@ -130,7 +130,7 @@ fn shape_with_vector_mask_density_imports_as_soft_shape() { // Photoshop stores the shape alone: replace the record's pixels with the path's coverage. let rec = file.layers_mut().last_mut().unwrap(); assert!(rec.block(b"SoCo").is_some() && rec.block(b"vmsk").is_some()); - rec.rect = photocraft_psd::Rect { top: 8, left: 8, bottom: 24, right: 24 }; + rec.rect = craft_psd::Rect { top: 8, left: 8, bottom: 24, right: 24 }; for ch in &mut rec.channels { if ch.id >= -1 { let v = if ch.id == -1 { 255 } else { 0 }; diff --git a/crates/io/tests/it/cylinder_warp.rs b/crates/io/tests/it/cylinder_warp.rs index 8ed1caa916..b52a786c50 100644 --- a/crates/io/tests/it/cylinder_warp.rs +++ b/crates/io/tests/it/cylinder_warp.rs @@ -3,12 +3,12 @@ use std::sync::Arc; +use craft_psd::PsdFile; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::{Document, Layer, LayerContent, SmartObject, SmartSource}; use photocraft_geom::warp::{Warp, WarpStyle}; use photocraft_geom::{Affine, Rect, Size}; use photocraft_io::{ExportOptions, export, import, smart_map}; -use photocraft_psd::PsdFile; use photocraft_raster::Surface; /// Silhouettes at x 10 and 90, edges at y 20 and 80, ellipses 0.3 deep, wrapped as little as @@ -79,8 +79,8 @@ fn a_cylinder_survives_psd_and_wraps_the_contents_again() { let (file, back) = round_trip(&doc); let layer = file.layers().iter().find(|l| l.name() == "label").unwrap(); let sold = smart_map::parse_sold(&layer.block(b"SoLd").unwrap().data).unwrap(); - let Some(photocraft_psd::descriptor::Value::Descriptor(w)) = sold.descriptor.get("warp") else { panic!("no warp") }; - assert!(matches!(w.get("warpStyle"), Some(photocraft_psd::descriptor::Value::Enumerated { value, .. }) if value.as_bytes() == b"warpCylinder")); + let Some(craft_psd::descriptor::Value::Descriptor(w)) = sold.descriptor.get("warp") else { panic!("no warp") }; + assert!(matches!(w.get("warpStyle"), Some(craft_psd::descriptor::Value::Enumerated { value, .. }) if value.as_bytes() == b"warpCylinder")); let sm = smart(&back); assert_eq!(sm.warp.as_ref().map(|w| w.style), Some(WarpStyle::Cylinder)); assert_eq!(sm.warp.as_ref(), Some(&warp)); diff --git a/crates/io/tests/it/deflate_compatibility.rs b/crates/io/tests/it/deflate_compatibility.rs index b6f4331b07..16f066703d 100644 --- a/crates/io/tests/it/deflate_compatibility.rs +++ b/crates/io/tests/it/deflate_compatibility.rs @@ -3,13 +3,13 @@ use crate::common; use std::io::Read; +use craft_psd::Compression; use photocraft_codecs::{ChannelLayout, Format, Image, SampleType as CodecSample}; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::{Document, Layer, LayerContent}; use photocraft_format::{SaveOptions, load_from_bytes, read_thumbnail, save_to_bytes}; use photocraft_geom::Size; use photocraft_io::{PsdExportOptions, document_to_psd_with, import}; -use photocraft_psd::Compression; use photocraft_raster::Rgba8Image; fn document(depth: SampleType, size: Size) -> Document { @@ -77,17 +77,17 @@ fn png_psd_and_pcraft_decode_identically() { let mut file = document_to_psd_with(&doc, &opts).0; // The IO exporter normally chooses Raw for float composites; also cover ZIP here. if depth == SampleType::F32 { - file.image_data = photocraft_psd::ImageData::encode(compression, &merged, &file.header).unwrap(); + file.image_data = craft_psd::ImageData::encode(compression, &merged, &file.header).unwrap(); } let bytes = file.to_bytes().unwrap(); - let parsed = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let parsed = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); assert_eq!(parsed.image_data.compression, compression); let (inflated, legacy) = old_and_new_inflate(&parsed.image_data.data); // The PSD streaming helper uses a different flate2 reader from plane decoding. - assert_eq!(photocraft_psd::compression::zip_decompress(&legacy, inflated.len()).unwrap(), inflated); + assert_eq!(craft_psd::compression::zip_decompress(&legacy, inflated.len()).unwrap(), inflated); file.image_data.data = legacy; for fixture in [bytes, file.to_bytes().unwrap()] { - let parsed = photocraft_psd::PsdFile::from_bytes(&fixture).unwrap(); + let parsed = craft_psd::PsdFile::from_bytes(&fixture).unwrap(); assert_eq!(parsed.image_data.decode(&parsed.header).unwrap(), merged); let back = import("compatibility.psd", &fixture).unwrap().document; assert_eq!(back.layers[0].surface().unwrap().read_region(doc.bounds()), pixels); diff --git a/crates/io/tests/it/flat.rs b/crates/io/tests/it/flat.rs index c40c76a12b..af9a29f782 100644 --- a/crates/io/tests/it/flat.rs +++ b/crates/io/tests/it/flat.rs @@ -490,7 +490,7 @@ fn psd_to_png_to_psd_chain() { let d3 = import("a.png", &png.bytes).unwrap().document; assert_eq!(d3.depth, SampleType::U16); let psd2 = export(&d3, "b.psd", &ExportOptions::default()).unwrap(); - assert!(photocraft_psd::PsdFile::from_bytes(&psd2.bytes).is_ok()); + assert!(craft_psd::PsdFile::from_bytes(&psd2.bytes).is_ok()); } /// A one-layer document of 16-pixel-wide columns, each one straight colour (colour channels, then alpha). diff --git a/crates/io/tests/it/guides_v2.rs b/crates/io/tests/it/guides_v2.rs index 651c814c89..031b5f2581 100644 --- a/crates/io/tests/it/guides_v2.rs +++ b/crates/io/tests/it/guides_v2.rs @@ -1,9 +1,9 @@ //! Image resources 1092 (guides with colours) and 1097 (guide GUIDs) next to 1032 (#5966). +use craft_psd::testgen; +use craft_psd::{Compression, ImageResource, PsdFile, Version}; use photocraft_io::guides_map::{DEFAULT_GUIDE_RGB, GUIDE_IDS, GUIDES_V2}; use photocraft_io::*; -use photocraft_psd::testgen; -use photocraft_psd::{Compression, ImageResource, PsdFile, Version}; const RED: [u8; 3] = [0xff, 0x00, 0x00]; diff --git a/crates/io/tests/it/lab16.rs b/crates/io/tests/it/lab16.rs index ff0707c11b..e4c4b7e39c 100644 --- a/crates/io/tests/it/lab16.rs +++ b/crates/io/tests/it/lab16.rs @@ -2,11 +2,11 @@ //! on the full 0..65535 range. Layer pixels, the merged image and patterns use that scale, and //! the documents' a*/b* stay on the 8-bit scale `(a + 128) / 255` at every depth. +use craft_psd::PsdFile; use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_doc::{Document, Layer, LayerContent}; use photocraft_geom::{Rect, Size}; use photocraft_io::*; -use photocraft_psd::PsdFile; use photocraft_raster::Surface; /// a* = 52.29, b* = −85.08 (a gradient stop of psd-tools 4x4_16bit_lab) on the document scale. diff --git a/crates/io/tests/it/large_files.rs b/crates/io/tests/it/large_files.rs index be4d5eeab7..55b774b49f 100644 --- a/crates/io/tests/it/large_files.rs +++ b/crates/io/tests/it/large_files.rs @@ -1,4 +1,4 @@ -//! Large-file fixtures (#216, #5107), generated at test time by `photocraft_psd::fixtures`: a 20 MP +//! Large-file fixtures (#216, #5107), generated at test time by `craft_psd::fixtures`: a 20 MP //! layered PSD, a 150-layer layout, a PSD just under Photoshop's 2 GB cap and a 4.4 GB PSB. Each //! is opened through `photocraft_io`, checked (size, layers, masks, effects, merged pixels), saved //! again and re-opened. @@ -9,10 +9,10 @@ use std::path::PathBuf; +use craft_psd::Version; +use craft_psd::fixtures::{Grid, LAYERED_20MP, LAYOUT_150, PSB_4GB, PSD_2GB, Streamed}; use photocraft_doc::{Document, LayerContent}; use photocraft_geom::Rect; -use photocraft_psd::Version; -use photocraft_psd::fixtures::{Grid, LAYERED_20MP, LAYOUT_150, PSB_4GB, PSD_2GB, Streamed}; /// Raster layers, groups, masked layers, layers with effects and hidden layers in `doc`. fn census(doc: &Document) -> [usize; 5] { @@ -137,7 +137,7 @@ fn streamed_roundtrip(case: &Streamed) { drop(res); // Version 2 = PSB: a re-save past 2 GB must switch to PSB; a smaller one stays PSD. let psb = out.bytes.get(4..6) == Some(&[0, 2]); - assert!(psb || (case.version == Version::Psd && (out.bytes.len() as u64) < photocraft_psd::fixtures::PSD_MAX_FILE_BYTES), "{}", case.name); + assert!(psb || (case.version == Version::Psd && (out.bytes.len() as u64) < craft_psd::fixtures::PSD_MAX_FILE_BYTES), "{}", case.name); eprintln!( "{}: saved {:.2} GB ({}) in {:.1} s, warnings {:?}", case.name, diff --git a/crates/io/tests/it/large_psb.rs b/crates/io/tests/it/large_psb.rs index da9f6ca9a1..67f969994d 100644 --- a/crates/io/tests/it/large_psb.rs +++ b/crates/io/tests/it/large_psb.rs @@ -1,9 +1,9 @@ //! Large PSB files (#375): planes past 2 GiB decode, and a channel that can't be decoded leaves //! its layer empty instead of painting it opaque black. +use craft_psd::testgen; +use craft_psd::{ColorMode, Compression, LayerSpec, PixelData, PsdBuilder, Version}; use photocraft_io::psd_to_document; -use photocraft_psd::testgen; -use photocraft_psd::{ColorMode, Compression, LayerSpec, PixelData, PsdBuilder, Version}; /// A layer whose red channel is damaged: the warning says "treated as empty", and the layer must /// be empty, not opaque black (the transparency channel is still fine). diff --git a/crates/io/tests/it/layer_labels.rs b/crates/io/tests/it/layer_labels.rs index 792d2d621f..8fbd02ecf2 100644 --- a/crates/io/tests/it/layer_labels.rs +++ b/crates/io/tests/it/layer_labels.rs @@ -48,6 +48,6 @@ fn layer_labels_psd_roundtrip_all_colors_and_depths() { #[test] fn layer_labels_truncated_sheet_color_is_not_a_label() { - let block = photocraft_psd::TaggedBlock::new(*b"lclr", vec![0]); + let block = craft_psd::TaggedBlock::new(*b"lclr", vec![0]); assert!(matches!(block.parsed(), Some(Err(_)))); } diff --git a/crates/io/tests/it/layer_xmp.rs b/crates/io/tests/it/layer_xmp.rs index 87a02b0876..88fbb60dd0 100644 --- a/crates/io/tests/it/layer_xmp.rs +++ b/crates/io/tests/it/layer_xmp.rs @@ -3,11 +3,11 @@ use std::sync::Arc; +use craft_psd::PsdFile; +use craft_psd::metadata::{layer_xmp, put_layer_xmp}; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::{Document, Layer, Size}; use photocraft_io::{ExportOptions, export, import}; -use photocraft_psd::PsdFile; -use photocraft_psd::metadata::{layer_xmp, put_layer_xmp}; const A: &str = r#"120"#; const G: &str = r#"Café 🎨"#; diff --git a/crates/io/tests/it/multichannel.rs b/crates/io/tests/it/multichannel.rs index 66f216368b..36aad15df5 100644 --- a/crates/io/tests/it/multichannel.rs +++ b/crates/io/tests/it/multichannel.rs @@ -1,10 +1,10 @@ //! Multichannel PSDs: alpha-type channels and the document's resources and global blocks survive //! an import → export → import round trip. +use craft_psd::resources::ImageResource; +use craft_psd::{ColorMode, Compression, PsdFile, TaggedBlock, Version, testgen}; use photocraft_doc::{ColorIndicates, Knot, NamedPath, Path, PathOp, Subpath}; use photocraft_io::*; -use photocraft_psd::resources::ImageResource; -use photocraft_psd::{ColorMode, Compression, PsdFile, TaggedBlock, Version, testgen}; /// DisplayInfo (1077) record: RGB colour, opacity (0..100) and kind (0/1 alpha, 2 spot). fn display_record(out: &mut Vec, rgb: [u16; 3], opacity: u16, kind: u8) { @@ -103,7 +103,7 @@ fn ink_and_alpha_file(depth: u16) -> PsdFile { let mut f = testgen::merged_only(Version::Psd, ColorMode::Multichannel, depth, Compression::Rle, 4, 1); let mut planes = plane(&[0.0, 1.0, 0.0, 1.0], depth); planes.extend(plane(&[1.0, 1.0, 0.0, 0.0], depth)); - f.image_data = photocraft_psd::ImageData::encode(Compression::Rle, &planes, &f.header).unwrap(); + f.image_data = craft_psd::ImageData::encode(Compression::Rle, &planes, &f.header).unwrap(); let mut info = 1u32.to_be_bytes().to_vec(); display_record(&mut info, [0, 65535, 65535], 0, 2); display_record(&mut info, [65535, 0, 0], 50, 0); diff --git a/crates/io/tests/it/native_vector_preview.rs b/crates/io/tests/it/native_vector_preview.rs index d1a8964eb9..a4009141ef 100644 --- a/crates/io/tests/it/native_vector_preview.rs +++ b/crates/io/tests/it/native_vector_preview.rs @@ -2,11 +2,11 @@ use std::sync::Arc; +use craft_psd::PsdFile; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::{Document, Layer, LayerContent, SmartObject, SmartSource, VectorPreview}; use photocraft_geom::{Affine, Size}; use photocraft_io::{ExportOptions, export, import, linked, smart_map, vector_preview}; -use photocraft_psd::PsdFile; use photocraft_raster::Surface; const PDF: &[u8] = b"%PDF-1.7\nopaque native source bytes\n%%EOF\n"; diff --git a/crates/io/tests/it/orientation.rs b/crates/io/tests/it/orientation.rs index 308041aefe..d976bb79c4 100644 --- a/crates/io/tests/it/orientation.rs +++ b/crates/io/tests/it/orientation.rs @@ -109,7 +109,7 @@ fn stale_orientation_in_document_metadata_is_never_exported() { assert_upright(&back, "jpg"); let psd = export(&d, "psd", &ExportOptions::default()).unwrap().bytes; - let file = photocraft_psd::PsdFile::from_bytes(&psd).unwrap(); + let file = craft_psd::PsdFile::from_bytes(&psd).unwrap(); let e = file.resources.iter().find(|r| r.id == 1058).expect("EXIF resource"); assert_eq!(exif_orientation(&e.data), 1); let x = file.resources.iter().find(|r| r.id == 1060).expect("XMP resource"); diff --git a/crates/io/tests/it/psd16_merged_transparency.rs b/crates/io/tests/it/psd16_merged_transparency.rs index 03030e557c..49208bbe27 100644 --- a/crates/io/tests/it/psd16_merged_transparency.rs +++ b/crates/io/tests/it/psd16_merged_transparency.rs @@ -8,11 +8,11 @@ use crate::common; use common::raster; +use craft_psd::PsdFile; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::Document; use photocraft_geom::{Rect, Size}; use photocraft_io::*; -use photocraft_psd::PsdFile; /// The unicode alpha channel names (resource 1045), empty without it. fn names(file: &PsdFile) -> Vec { @@ -47,7 +47,7 @@ fn resave_keeps_a_name_marked_merged_transparency() { assert!(!ps.merged_has_alpha(), "{case}: nothing marks it yet"); let name: Vec = [0u8, 0, 0, 13].into_iter().chain("Transparency\0".encode_utf16().flat_map(u16::to_be_bytes)).collect(); ps.resources.retain(|r| !matches!(r.id, 1006 | 1045)); - ps.resources.push(photocraft_psd::ImageResource::new(1045, name)); + ps.resources.push(craft_psd::ImageResource::new(1045, name)); assert!(ps.merged_has_alpha(), "{case}: the name marks the merged transparency"); let opened = import(path, &ps.to_bytes().expect("write")).expect("import").document; diff --git a/crates/io/tests/it/psd32_export.rs b/crates/io/tests/it/psd32_export.rs index a267b8ab8f..ec890ef922 100644 --- a/crates/io/tests/it/psd32_export.rs +++ b/crates/io/tests/it/psd32_export.rs @@ -9,11 +9,11 @@ use crate::common; use common::Features; +use craft_psd::{Compression, LayerInfoPlacement, PsdFile, hdr}; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::Document; use photocraft_geom::Size; use photocraft_io::*; -use photocraft_psd::{Compression, LayerInfoPlacement, PsdFile, hdr}; fn be32(b: &[u8], at: usize) -> u32 { u32::from_be_bytes(b[at..at + 4].try_into().unwrap()) @@ -300,7 +300,7 @@ fn merged_oracle_does_not_treat_extra_channels_as_transparency() { let mut file = PsdFile::from_bytes(&export_psd(&doc)).unwrap(); let color_channels = if mode == ColorMode::Rgb { 3 } else { 1 }; file.header.channels = color_channels + 1; - file.layer_info = Some(photocraft_psd::LayerInfo { merged_alpha: false, layers: Vec::new(), padding: None }); + file.layer_info = Some(craft_psd::LayerInfo { merged_alpha: false, layers: Vec::new(), padding: None }); file.image_data.compression = Compression::Raw; file.image_data.data = (0..color_channels).flat_map(|_| 2.0_f32.to_be_bytes()).chain(0.0_f32.to_be_bytes()).collect(); assert!(!file.merged_has_alpha()); @@ -332,9 +332,9 @@ fn mt32_marks_the_merged_transparency() { let name: Vec = [0u8, 0, 0, 13].into_iter().chain("Transparency\0".encode_utf16().flat_map(u16::to_be_bytes)).collect(); file.resources.retain(|r| !matches!(r.id, 1006 | 1045)); assert!(!file.merged_has_alpha(), "a positive layer count alone"); - file.global_blocks.push(photocraft_psd::TaggedBlock::new(*b"Mt32", Vec::new())); + file.global_blocks.push(craft_psd::TaggedBlock::new(*b"Mt32", Vec::new())); assert!(file.merged_has_alpha()); - file.resources.push(photocraft_psd::ImageResource::new(1045, name)); + file.resources.push(craft_psd::ImageResource::new(1045, name)); let merged = merged_composite(&file).unwrap(); assert_eq!(merged.iter().map(|p| p[3]).collect::>(), vec![1.0, 0.0]); let opened = import("transparent.psd", &file.to_bytes().unwrap()).unwrap(); diff --git a/crates/io/tests/it/psd_background.rs b/crates/io/tests/it/psd_background.rs index d24d24409e..699c78643f 100644 --- a/crates/io/tests/it/psd_background.rs +++ b/crates/io/tests/it/psd_background.rs @@ -2,8 +2,8 @@ //! stored without a transparency channel), whatever its name in the Photoshop language that //! saved the file. +use craft_psd::{ColorMode, Compression, PsdFile, TaggedBlock, Version, testgen}; use photocraft_io::psd_to_document; -use photocraft_psd::{ColorMode, Compression, PsdFile, TaggedBlock, Version, testgen}; /// `testgen::layered` with its bottom layer turned into a Photoshop Background named `name`. fn file(name: &str, transparency_channel: bool) -> PsdFile { diff --git a/crates/io/tests/it/psd_block_alignment.rs b/crates/io/tests/it/psd_block_alignment.rs index 3d9df8f191..30a8f2f08a 100644 --- a/crates/io/tests/it/psd_block_alignment.rs +++ b/crates/io/tests/it/psd_block_alignment.rs @@ -5,11 +5,11 @@ //! layer record's extra data unaligned: a Pattern Fill's `PtFl` came out 2 bytes short of the //! boundary for half of all pattern names. +use craft_psd::PsdFile; use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_doc::{Adjustment, Document, Fill, Layer, LayerContent, Pattern}; use photocraft_geom::{Rect, Size}; use photocraft_io::*; -use photocraft_psd::PsdFile; use photocraft_raster::Surface; fn pattern(name: &str) -> Pattern { diff --git a/crates/io/tests/it/psd_block_layout.rs b/crates/io/tests/it/psd_block_layout.rs index d081bfbc43..c0f037895e 100644 --- a/crates/io/tests/it/psd_block_layout.rs +++ b/crates/io/tests/it/psd_block_layout.rs @@ -5,10 +5,10 @@ use crate::common; +use craft_psd::descriptor::{Descriptor, VersionedDescriptor}; +use craft_psd::testgen; +use craft_psd::{Compression, LayerRecord, PsdFile, TaggedBlock, Version}; use photocraft_io::*; -use photocraft_psd::descriptor::{Descriptor, VersionedDescriptor}; -use photocraft_psd::testgen; -use photocraft_psd::{Compression, LayerRecord, PsdFile, TaggedBlock, Version}; /// `PlLd` data per the Adobe spec ("Placed Layer"): `plcL`, version 3, Pascal uuid, page, /// total pages, anti-alias policy, layer type, 8 transform doubles, warp version, warp @@ -37,10 +37,10 @@ fn plld(uuid: &str) -> Vec { fn sold(uuid: &str) -> Vec { let mut d = b"soLD".to_vec(); d.extend(4u32.to_be_bytes()); - use photocraft_psd::descriptor::Value; + use craft_psd::descriptor::Value; // The strict check wants what Photoshop needs to place the layer: its file id and transform. let quad = [0.0, 0.0, 4.0, 0.0, 4.0, 4.0, 0.0, 4.0].map(Value::Double).to_vec(); - let desc = Descriptor::new("null").with("Idnt", Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul(uuid))).with("Trnf", Value::List(quad)); + let desc = Descriptor::new("null").with("Idnt", Value::Text(craft_psd::descriptor::UnicodeString::new_nul(uuid))).with("Trnf", Value::List(quad)); d.extend(VersionedDescriptor::new(desc).to_bytes()); while !d.len().is_multiple_of(4) { d.push(0); diff --git a/crates/io/tests/it/psd_damaged_merged.rs b/crates/io/tests/it/psd_damaged_merged.rs index 51121d59b7..7661477a7c 100644 --- a/crates/io/tests/it/psd_damaged_merged.rs +++ b/crates/io/tests/it/psd_damaged_merged.rs @@ -1,10 +1,10 @@ //! #6152: intact layers can be recovered when only the merged preview is damaged. +use craft_psd::{Compression, GroupSpec, PsdBuilder, PsdFile}; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::{Document, Layer}; use photocraft_geom::Size; use photocraft_io::{ExportOptions, export, import}; -use photocraft_psd::{Compression, GroupSpec, PsdBuilder, PsdFile}; fn layered(depth: SampleType, extension: &str) -> PsdFile { layered_in_mode(ColorMode::Rgb, depth, extension) @@ -34,7 +34,7 @@ fn truncated_merged_image_keeps_layer_pixels_at_every_depth_and_compression() { let intact = import(extension, &file.to_bytes().unwrap()).unwrap(); 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 = craft_psd::ImageData::encode(compression, &pixels, &file.header).unwrap(); file.image_data.data.truncate(file.image_data.data.len() / 2); let bytes = file.to_bytes().unwrap(); assert!(PsdFile::from_bytes(&bytes).is_err(), "strict parsing stays strict"); @@ -55,7 +55,7 @@ fn truncated_merged_image_keeps_layer_pixels_at_every_depth_and_compression() { #[test] fn corrupt_zip_merged_image_keeps_the_layers() { let mut file = layered(SampleType::U8, "x.psd"); - file.image_data = photocraft_psd::ImageData::encode(Compression::Zip, &file.decode_merged().unwrap(), &file.header).unwrap(); + file.image_data = craft_psd::ImageData::encode(Compression::Zip, &file.decode_merged().unwrap(), &file.header).unwrap(); *file.image_data.data.last_mut().unwrap() ^= 0xff; let result = import("x.psd", &file.to_bytes().unwrap()).unwrap(); assert_eq!(result.document.layer_count(), 1); @@ -86,10 +86,10 @@ fn a_flattened_file_with_no_recoverable_layers_still_fails() { #[test] fn modes_imported_flattened_do_not_recover_from_unusable_layer_records() { - for mode in [photocraft_psd::ColorMode::Indexed, photocraft_psd::ColorMode::Multichannel, photocraft_psd::ColorMode::Duotone] { + for mode in [craft_psd::ColorMode::Indexed, craft_psd::ColorMode::Multichannel, craft_psd::ColorMode::Duotone] { let mut file = layered(SampleType::U8, "x.psd"); file.header.color_mode = mode; - file.image_data = photocraft_psd::ImageData::new(Compression::Raw, Vec::new()); + file.image_data = craft_psd::ImageData::new(Compression::Raw, Vec::new()); assert!(import("flat-mode.psd", &file.to_bytes().unwrap()).is_err(), "{mode:?}"); } } @@ -98,7 +98,7 @@ fn modes_imported_flattened_do_not_recover_from_unusable_layer_records() { fn lost_extra_channels_are_reported_while_layers_remain_usable() { let mut file = layered(SampleType::U8, "x.psd"); file.header.channels = 5; - file.image_data = photocraft_psd::ImageData::new(Compression::Raw, Vec::new()); + file.image_data = craft_psd::ImageData::new(Compression::Raw, Vec::new()); let result = import("extra-channel.psd", &file.to_bytes().unwrap()).unwrap(); assert_eq!(result.document.layer_count(), 1); assert!(result.document.channels.is_empty()); diff --git a/crates/io/tests/it/psd_empty_channels.rs b/crates/io/tests/it/psd_empty_channels.rs index 610bb145cc..def18d8ed4 100644 --- a/crates/io/tests/it/psd_empty_channels.rs +++ b/crates/io/tests/it/psd_empty_channels.rs @@ -1,8 +1,8 @@ use crate::common; use common::Features; +use craft_psd::{Compression, PsdFile}; use photocraft_color::{ColorMode, SampleType}; use photocraft_io::{ExportOptions, export}; -use photocraft_psd::{Compression, PsdFile}; #[test] fn empty_layer_and_mask_channels_use_raw_without_a_payload() { diff --git a/crates/io/tests/it/psd_flat_spot_channels.rs b/crates/io/tests/it/psd_flat_spot_channels.rs index 606f662fc0..c41c5bbf1c 100644 --- a/crates/io/tests/it/psd_flat_spot_channels.rs +++ b/crates/io/tests/it/psd_flat_spot_channels.rs @@ -6,12 +6,12 @@ #[cfg(feature = "corpus")] use std::path::PathBuf; +use craft_psd::PsdFile; +use craft_psd::resources::ImageResource; use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; use photocraft_doc::{AlphaChannel, Document}; use photocraft_geom::{Rect, Size}; use photocraft_io::{ExportOptions, export, import}; -use photocraft_psd::PsdFile; -use photocraft_psd::resources::ImageResource; use photocraft_raster::Surface; const W: u32 = 8; diff --git a/crates/io/tests/it/psd_frame_stroke.rs b/crates/io/tests/it/psd_frame_stroke.rs index 9b4b5267d7..da0d024ce9 100644 --- a/crates/io/tests/it/psd_frame_stroke.rs +++ b/crates/io/tests/it/psd_frame_stroke.rs @@ -2,11 +2,11 @@ //! vector mask (`vsms`) and its Properties › Stroke as a shape-style `vstk`. The stroke draws //! along the outline even when nothing is placed in the frame (#4381). +use craft_psd::{PsdFile, SectionType, TaggedBlock}; use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; use photocraft_doc::{Document, Fill, Group, Layer, LayerContent, Path, ShapeStroke, Size, StrokeAlign, Subpath, VectorMask}; use photocraft_io::vector_map::{parse_vstk, vstk_bytes}; use photocraft_io::*; -use photocraft_psd::{PsdFile, SectionType, TaggedBlock}; fn red_inside(width: f32) -> ShapeStroke { ShapeStroke { width, align: StrokeAlign::Inside, paint: Fill::Solid(Color::rgb(1.0, 0.0, 0.0)), ..ShapeStroke::default() } @@ -36,7 +36,7 @@ fn px(d: &Document, x: i32, y: i32) -> [f32; 4] { } /// The group's own record (its top, `lsct` 1 or 2) in a PSD file. -fn frame_record(f: &mut PsdFile) -> &mut photocraft_psd::LayerRecord { +fn frame_record(f: &mut PsdFile) -> &mut craft_psd::LayerRecord { f.layers_mut() .iter_mut() .find(|r| r.section_divider().is_some_and(|s| matches!(s.kind, SectionType::OpenFolder | SectionType::ClosedFolder))) diff --git a/crates/io/tests/it/psd_import_file.rs b/crates/io/tests/it/psd_import_file.rs index cd1b08761a..f04e69b353 100644 --- a/crates/io/tests/it/psd_import_file.rs +++ b/crates/io/tests/it/psd_import_file.rs @@ -1,8 +1,8 @@ //! `import_file` parses a PSD/PSB from the open file (channel data read as it is decoded) and must //! open the same document, with the same warnings, as importing the file's bytes. +use craft_psd::testgen; use photocraft_io::{ImportResult, import, import_file}; -use photocraft_psd::testgen; use photocraft_raster::Interrupt; struct TempDir(std::path::PathBuf); @@ -107,7 +107,7 @@ fn import_file_reads_other_formats_whole() { fn import_file_fails_cleanly() { let dir = TempDir::new("fail"); assert!(open("missing.psd", &dir.0.join("missing.psd")).is_err()); - let bytes = testgen::small(photocraft_psd::Version::Psd, photocraft_psd::Compression::Rle).to_bytes().unwrap(); + let bytes = testgen::small(craft_psd::Version::Psd, craft_psd::Compression::Rle).to_bytes().unwrap(); // Cut inside the layer records, inside the channel data, and inside the merged image. for cut in [10, 60, bytes.len() / 2, bytes.len() - 5] { let name = format!("cut{cut}.psd"); @@ -125,7 +125,7 @@ fn import_file_fails_cleanly() { #[test] fn a_cancelled_import_file_reports_cancelled() { let dir = TempDir::new("cancel"); - let bytes = testgen::small(photocraft_psd::Version::Psd, photocraft_psd::Compression::Zip).to_bytes().unwrap(); + let bytes = testgen::small(craft_psd::Version::Psd, craft_psd::Compression::Zip).to_bytes().unwrap(); let path = dir.write("c.psd", &bytes); let cancel = || true; let ctl = Interrupt::cancel_only(&cancel); @@ -136,7 +136,7 @@ fn a_cancelled_import_file_reports_cancelled() { /// its drive goes away) fails the open: no layer is left empty for a save to lose. #[test] fn a_read_failing_while_layers_decode_fails_the_open() { - use photocraft_psd::ReadAt; + use craft_psd::ReadAt; /// The file's bytes, failing every read of channel data (as a dropped network share or a /// truncated file would) except the 2-byte compression fields the parse reads. struct Failing { @@ -147,18 +147,18 @@ fn a_read_failing_while_layers_decode_fails_the_open() { fn len(&self) -> u64 { self.bytes.len() as u64 } - fn read_at(&self, offset: u64, buf: &mut [u8]) -> photocraft_psd::Result<()> { + fn read_at(&self, offset: u64, buf: &mut [u8]) -> craft_psd::Result<()> { let end = offset + buf.len() as u64; if self.data.iter().any(|&(a, b)| offset < b && end > a) { - return Err(photocraft_psd::PsdError::Read("the drive went away".into())); + return Err(craft_psd::PsdError::Read("the drive went away".into())); } self.bytes.as_slice().read_at(offset, buf) } } - for c in [photocraft_psd::Compression::Rle, photocraft_psd::Compression::Raw, photocraft_psd::Compression::Zip] { - let file = testgen::layered(photocraft_psd::Version::Psd, photocraft_psd::ColorMode::Rgb, 8, c); + for c in [craft_psd::Compression::Rle, craft_psd::Compression::Raw, craft_psd::Compression::Zip] { + let file = testgen::layered(craft_psd::Version::Psd, craft_psd::ColorMode::Rgb, 8, c); let bytes = file.to_bytes().unwrap(); - let lazy = photocraft_psd::PsdFile::from_source(photocraft_psd::Source::new(bytes.clone())).unwrap(); + let lazy = craft_psd::PsdFile::from_source(craft_psd::Source::new(bytes.clone())).unwrap(); let data: Vec<(u64, u64)> = lazy .layers() .iter() @@ -170,7 +170,7 @@ fn a_read_failing_while_layers_decode_fails_the_open() { assert!(!data.is_empty()); // Opening the same file whole succeeds: only the failed reads fail the open. assert!(import("x.psd", &bytes).is_ok()); - let r = photocraft_io::import_source_for_open_with("x.psd", photocraft_psd::Source::new(Failing { bytes, data }), &Interrupt::NONE); + let r = photocraft_io::import_source_for_open_with("x.psd", craft_psd::Source::new(Failing { bytes, data }), &Interrupt::NONE); match r { Err(photocraft_io::IoError::Read(msg)) => assert!(msg.contains("the drive went away"), "{c:?}: {msg}"), r => panic!("{c:?}: the open didn't fail: {:?}", r.map(|(r, damaged)| (r.warnings, damaged))), diff --git a/crates/io/tests/it/psd_kerning.rs b/crates/io/tests/it/psd_kerning.rs index a7c2313e24..7afbfe945b 100644 --- a/crates/io/tests/it/psd_kerning.rs +++ b/crates/io/tests/it/psd_kerning.rs @@ -114,7 +114,7 @@ fn fresh_metrics_text_writes_no_txt2_block() { photocraft_text::TextEngine::new().render_layer(&mut r, doc.resolution_dpi, doc.pixel_format()); doc.layers.push(Layer::new("t", LayerContent::Text(r))); let bytes = photocraft_io::export(&doc, "k.psd", &Default::default()).unwrap().bytes; - photocraft_psd::PsdFile::from_bytes(&bytes).unwrap().global_blocks.iter().any(|b| &b.key == b"Txt2") + craft_psd::PsdFile::from_bytes(&bytes).unwrap().global_blocks.iter().any(|b| &b.key == b"Txt2") }; assert!(!saves_txt2(Kerning::Metrics), "a plain Metrics layer must not write the empty Txt2 stub"); assert!(saves_txt2(Kerning::Optical), "Optical lives only in Txt2"); @@ -140,7 +140,7 @@ fn fresh_stylistic_sets_round_trip_through_psd() { photocraft_text::TextEngine::new().render_layer(&mut r, doc.resolution_dpi, doc.pixel_format()); doc.layers.push(Layer::new("t", LayerContent::Text(r))); let bytes = photocraft_io::export(&doc, "k.psd", &Default::default()).unwrap().bytes; - let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); let txt2 = file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)).expect("Txt2 written for stylistic sets"); let style = txt2 @@ -188,7 +188,7 @@ fn duplicate_preserved_text_indices_get_distinct_txt2_objects() { doc.layers.push(Layer::new(name, LayerContent::Text(t))); } let bytes = photocraft_io::export(&doc, "k.psd", &Default::default()).unwrap().bytes; - let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); let txt2 = file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)).unwrap(); assert_eq!(txt2.path(&["1", "1"]).and_then(E::as_array).unwrap().len(), 2); let back = photocraft_io::import("k.psd", &bytes).unwrap().document; @@ -278,7 +278,7 @@ fn add_type_layer(objects: &[(&str, &str)], kept: &[(&str, i32)], at: usize) -> t.psd_raw = Some(std::sync::Arc::new(photocraft_text::psd::build_tysh(&t, doc.resolution_dpi, None))); doc.layers.insert(at, Layer::new("Hi", LayerContent::Text(t))); let bytes = photocraft_io::export(&doc, "k.psd", &Default::default()).unwrap().bytes; - let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); let txt2 = file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)).unwrap(); let back = photocraft_io::import("k.psd", &bytes).unwrap().document; let layers: Vec<_> = back @@ -399,7 +399,7 @@ fn hostile_text_index_never_sizes_the_save() { r.psd_raw = Some(std::sync::Arc::new(photocraft_text::psd::set_text_index(&photocraft_text::psd::build_tysh(&r, 72.0, None), i32::MAX).unwrap())); doc.layers.push(Layer::new("hostile", LayerContent::Text(r))); let bytes = photocraft_io::export(&doc, "k.psd", &Default::default()).unwrap().bytes; - let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); let txt2 = file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)).unwrap(); let slots = txt2.path(&["1", "1"]).and_then(E::as_array).unwrap(); assert!(slots.len() <= 8, "a file-controlled TextIndex sized the save: {} slots", slots.len()); @@ -434,7 +434,7 @@ fn txt2_extras_survive_a_resave_of_unchanged_text() { doc.layers.push(Layer::new("kept", LayerContent::Text(r))); doc.metadata.psd_global_blocks.push((*b"8BIM", *b"Txt2", std::sync::Arc::new(prev.clone()))); let bytes = photocraft_io::export(&doc, "k.psd", &Default::default()).unwrap().bytes; - let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); photocraft_text::psd::parse_txt2(&file.global_blocks.iter().find(|b| &b.key == b"Txt2").unwrap().data).unwrap() }; let kept = save("AV"); @@ -507,7 +507,7 @@ fn photoshop_kerning_oracles() { ]; for (name, want, same_fields, worst_max, mean_max) in cases { let bytes = std::fs::read(dir.join(name)).unwrap_or_else(|e| panic!("{name}: {e}")); - let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); let txt2 = file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)).unwrap(); let doc = photocraft_io::import(name, &bytes).unwrap().document; let t = doc @@ -537,7 +537,7 @@ fn photoshop_kerning_oracles() { continue; } let index = match &tysh.text.get("TextIndex") { - Some(photocraft_psd::descriptor::Value::Integer(i)) => *i as usize, + Some(craft_psd::descriptor::Value::Integer(i)) => *i as usize, _ => panic!("{name}: no TextIndex"), }; let ps = photoshop_positions(&txt2, index).unwrap(); diff --git a/crates/io/tests/it/psd_layer_block_length.rs b/crates/io/tests/it/psd_layer_block_length.rs index 71f8e2552d..60c33ce7b2 100644 --- a/crates/io/tests/it/psd_layer_block_length.rs +++ b/crates/io/tests/it/psd_layer_block_length.rs @@ -7,9 +7,9 @@ use crate::common; use common::Features; +use craft_psd::PsdFile; use photocraft_color::{ColorMode, SampleType}; use photocraft_io::*; -use photocraft_psd::PsdFile; fn be(b: &[u8], at: usize, long: bool) -> usize { if long { u64::from_be_bytes(b[at..at + 8].try_into().unwrap()) as usize } else { u32::from_be_bytes(b[at..at + 4].try_into().unwrap()) as usize } diff --git a/crates/io/tests/it/psd_maximize_compatibility.rs b/crates/io/tests/it/psd_maximize_compatibility.rs index c8f277f6ee..825499b624 100644 --- a/crates/io/tests/it/psd_maximize_compatibility.rs +++ b/crates/io/tests/it/psd_maximize_compatibility.rs @@ -3,11 +3,11 @@ //! resource 1057 (`has_real_merged_data = false`). Layers, alpha channels and the Quick Mask are //! written as usual, so the file reopens the same. +use craft_psd::PsdFile; use photocraft_color::{ColorMode, PixelFormat, SampleType}; use photocraft_doc::{AlphaChannel, Document, Layer}; use photocraft_geom::{Rect, Size}; use photocraft_io::{ExportOptions, export, import}; -use photocraft_psd::PsdFile; use photocraft_raster::Surface; fn compat_off() -> ExportOptions { diff --git a/crates/io/tests/it/psd_noise_fill_roundtrip.rs b/crates/io/tests/it/psd_noise_fill_roundtrip.rs index e8fb38b88d..0dd55b1ec3 100644 --- a/crates/io/tests/it/psd_noise_fill_roundtrip.rs +++ b/crates/io/tests/it/psd_noise_fill_roundtrip.rs @@ -5,11 +5,11 @@ //! imported as pixels and the export dropped the `GdFl` (`RASTER_STALE_KEYS`), so opening and //! re-saving a file silently turned the fill layer into a plain pixel layer. +use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; +use craft_psd::testgen; +use craft_psd::{Compression, LayerRecord, PsdFile, TaggedBlock, Version}; use photocraft_doc::{Fill, LayerContent}; use photocraft_io::*; -use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; -use photocraft_psd::testgen; -use photocraft_psd::{Compression, LayerRecord, PsdFile, TaggedBlock, Version}; /// Photoshop's default Noise gradient (RGB, min 0/0/0, max 100/100/100) as `GdFl` block data. fn default_noise_gdfl() -> Vec { diff --git a/crates/io/tests/it/psd_recovery_generated.rs b/crates/io/tests/it/psd_recovery_generated.rs index 7b9e4bb2e7..51a7de340b 100644 --- a/crates/io/tests/it/psd_recovery_generated.rs +++ b/crates/io/tests/it/psd_recovery_generated.rs @@ -7,8 +7,8 @@ #[path = "../support/recovery_psd.rs"] mod recovery_psd; +use craft_psd::PsdFile; use photocraft_io::{ImportOptions, import, import_for_open}; -use photocraft_psd::PsdFile; /// Verifies a generated, two-layer PSD opens without source restrictions or damage prompts. #[test] @@ -68,7 +68,7 @@ fn damaged_composite_keeps_layers_and_requests_interactive_confirmation() { /// Verifies mismatched resolution metadata produces a warning but no damage prompt. #[test] fn ordinary_compatibility_warning_does_not_mean_damaged() { - use photocraft_psd::{ImageResource, ResolutionInfo, resources::ids}; + use craft_psd::{ImageResource, ResolutionInfo, resources::ids}; let mut file = PsdFile::from_bytes(&recovery_psd::make_psd(false)).unwrap(); let resolution = ResolutionInfo { v_res_fixed: ResolutionInfo::from_dpi(150.0).v_res_fixed, ..ResolutionInfo::from_dpi(300.0) }; file.resources.push(ImageResource::new(ids::RESOLUTION_INFO, resolution.to_bytes())); diff --git a/crates/io/tests/it/psd_roundtrip_bytes.rs b/crates/io/tests/it/psd_roundtrip_bytes.rs index dccd57856d..eb5dd2b45e 100644 --- a/crates/io/tests/it/psd_roundtrip_bytes.rs +++ b/crates/io/tests/it/psd_roundtrip_bytes.rs @@ -3,8 +3,8 @@ //! (verified by the corpus round-trip floors in `corpus.rs`; here the byte-equality of the //! codec layer itself is pinned). -use photocraft_psd::compression::{Compression, PlaneLayout, decode_planes, encode_planes}; -use photocraft_psd::header::Version; +use craft_psd::compression::{Compression, PlaneLayout, decode_planes, encode_planes}; +use craft_psd::header::Version; #[test] fn encode_decode_planes_round_trip_exactly() { diff --git a/crates/io/tests/it/psd_structure.rs b/crates/io/tests/it/psd_structure.rs index 900294af0f..104ab49c15 100644 --- a/crates/io/tests/it/psd_structure.rs +++ b/crates/io/tests/it/psd_structure.rs @@ -1,9 +1,9 @@ //! PSD (testgen / builder) → Document → PSD structural equality. +use craft_psd::testgen; +use craft_psd::{ColorMode, Compression, LayerNode, PsdFile, SectionType, Version}; use photocraft_doc::LayerContent; use photocraft_io::*; -use photocraft_psd::testgen; -use photocraft_psd::{ColorMode, Compression, LayerNode, PsdFile, SectionType, Version}; /// Sample of a layer channel in document coordinates (0 outside the rect). fn sample(f: &PsdFile, li: usize, id: i16, x: i32, y: i32, cache: &mut std::collections::HashMap<(usize, i16), Vec>) -> Vec { @@ -56,7 +56,7 @@ fn assert_structurally_equal(a: &PsdFile, b: &PsdFile) { let (ra, rb) = (&a.layers()[ia], &b.layers()[ib]); let n = ra.name(); assert_eq!(n, rb.name()); - let blend = if matches!(ra.blend_mode, photocraft_psd::BlendMode::Unknown(_)) { photocraft_psd::BlendMode::Normal } else { ra.blend_mode }; + let blend = if matches!(ra.blend_mode, craft_psd::BlendMode::Unknown(_)) { craft_psd::BlendMode::Normal } else { ra.blend_mode }; if ra.section_type().is_folder() { assert_eq!(ra.section_divider().and_then(|s| s.blend_mode), rb.section_divider().and_then(|s| s.blend_mode), "{n}"); } else { @@ -71,7 +71,7 @@ fn assert_structurally_equal(a: &PsdFile, b: &PsdFile) { continue; } // Pixels: compare every channel over the union of both rects. - let u = |r: photocraft_psd::Rect, s: photocraft_psd::Rect| (r.left.min(s.left), r.top.min(s.top), r.right.max(s.right), r.bottom.max(s.bottom)); + let u = |r: craft_psd::Rect, s: craft_psd::Rect| (r.left.min(s.left), r.top.min(s.top), r.right.max(s.right), r.bottom.max(s.bottom)); let mut ids: Vec = (-1..cc).collect(); if ra.layer_mask().is_some() && (ra.channel(-2).is_some() || ra.channel(-3).is_some()) { ids.push(-2); @@ -283,7 +283,7 @@ fn a_colour_book_ink_shows_its_lab_equivalent_or_the_grey_plate() { assert!(w.iter().any(|w| w.contains("shown as grayscale")), "{w:?}"); // With Photoshop's Lab equivalents (black, then the PANTONE teal) it shows in colour. let lab = vec![0, 1, 0, 2, 0, 7, 0x03, 0xB9, 0x01, 0xF2, 0x01, 0xA9, 0, 0, 0, 7, 0x11, 0xC5, 0xE6, 0x38, 0xFE, 0x0C, 0, 0]; - f.resources.push(photocraft_psd::ImageResource::new(1066, lab)); + f.resources.push(craft_psd::ImageResource::new(1066, lab)); let (d, w) = psd_to_document(&f); assert!(w.iter().all(|w| !w.contains("duotone")), "{w:?}"); let duo = d.duotone.as_ref().unwrap(); @@ -502,7 +502,7 @@ fn flattened_psd_becomes_background() { #[test] fn builder_psd_imports() { - use photocraft_psd::{GroupSpec, LayerSpec, MaskSpec, PixelData, PsdBuilder, Rect}; + use craft_psd::{GroupSpec, LayerSpec, MaskSpec, PixelData, PsdBuilder, Rect}; let mut b = PsdBuilder::new(4, 4); let mut s = LayerSpec::new("a", 0, 0, 2, 2, PixelData::Rgba8(vec![255, 0, 0, 255, 0, 255, 0, 128, 0, 0, 255, 0, 9, 9, 9, 9])); s.mask = Some(MaskSpec { rect: Rect::from_xywh(0, 0, 1, 1), data: vec![100], default_color: 255, disabled: true }); @@ -527,7 +527,7 @@ fn builder_psd_imports() { #[test] fn group_nesting_past_the_cap_is_rejected() { - use photocraft_psd::{GroupSpec, LayerSpec, PixelData, PsdBuilder}; + use craft_psd::{GroupSpec, LayerSpec, PixelData, PsdBuilder}; let mut b = PsdBuilder::new(4, 4); for _ in 0..101 { b.begin_group(GroupSpec::new("g")); @@ -541,14 +541,14 @@ fn group_nesting_past_the_cap_is_rejected() { assert!(err.to_string().contains("nested deeper than 100"), "{err}"); // The never-fail converter still returns a document — capped, with a warning // about the part that was not imported (it used to recurse to the file's depth). - let (d, warnings) = psd_to_document(&photocraft_psd::PsdFile::from_bytes(&bytes).unwrap()); + let (d, warnings) = psd_to_document(&craft_psd::PsdFile::from_bytes(&bytes).unwrap()); assert_eq!(d.max_group_depth(), 100); assert!(warnings.iter().any(|w| w.contains("deeper than 100")), "{warnings:?}"); } #[test] fn group_nesting_at_the_cap_imports() { - use photocraft_psd::{GroupSpec, LayerSpec, PixelData, PsdBuilder}; + use craft_psd::{GroupSpec, LayerSpec, PixelData, PsdBuilder}; let mut b = PsdBuilder::new(4, 4); for _ in 0..100 { b.begin_group(GroupSpec::new("g")); @@ -564,7 +564,7 @@ fn group_nesting_at_the_cap_imports() { #[test] fn layered_import_skips_the_unused_merged_composite() { - use photocraft_psd::{LayerSpec, PixelData, PsdBuilder}; + use craft_psd::{LayerSpec, PixelData, PsdBuilder}; // A layered file whose merged composite carries nothing behind the colour channels never // decodes it - that composite is roughly half a Photoshop save's bytes. Here its data is // garbage: the layered import does not touch it, while a file with an extra channel does @@ -572,7 +572,7 @@ fn layered_import_skips_the_unused_merged_composite() { let mut b = PsdBuilder::new(4, 4); b.push_layer(LayerSpec::new("a", 0, 0, 2, 2, PixelData::Rgba8(vec![7u8; 16]))); b.composite(PixelData::Rgba8(vec![128; 64])); - let mut f = photocraft_psd::PsdFile::from_bytes(&b.to_bytes().unwrap()).unwrap(); + let mut f = craft_psd::PsdFile::from_bytes(&b.to_bytes().unwrap()).unwrap(); f.image_data.data.clear(); f.layer_info.as_mut().unwrap().merged_alpha = true; let (d, warnings) = psd_to_document(&f); @@ -587,7 +587,7 @@ fn layered_import_skips_the_unused_merged_composite() { #[test] fn locks_and_labels_from_psd() { - use photocraft_psd::TaggedBlock; + use craft_psd::TaggedBlock; let mut f = testgen::small(Version::Psd, Compression::Raw); f.layers_mut()[0].blocks.push(TaggedBlock::protection(0b101)); f.layers_mut()[0].blocks.push(TaggedBlock::sheet_color(3)); @@ -602,7 +602,7 @@ fn artboard_lock_round_trips_byte_for_byte() { // Reference files write a Background layer's locks as lspf = 0x0D (transparency + position + // the bit-3 lock). PhotoCraft read the artboard lock at bit 4, so 0x0D came back as 0x05 // and the lock bytes drifted on every re-save. - use photocraft_psd::TaggedBlock; + use craft_psd::TaggedBlock; let mut f = testgen::small(Version::Psd, Compression::Raw); f.layers_mut()[0].blocks.push(TaggedBlock::protection(0x0D)); let g = via_doc(&f); @@ -612,7 +612,7 @@ fn artboard_lock_round_trips_byte_for_byte() { #[test] fn adjustment_and_fill_layers_from_psd() { - use photocraft_psd::{LayerRecord, TaggedBlock}; + use craft_psd::{LayerRecord, TaggedBlock}; let mut f = testgen::small(Version::Psd, Compression::Raw); let mk = |name: &str, key: &[u8; 4], data: Vec| LayerRecord { name: name.as_bytes().to_vec(), @@ -620,7 +620,7 @@ fn adjustment_and_fill_layers_from_psd() { ..Default::default() }; let soco = { - use photocraft_psd::descriptor::*; + use craft_psd::descriptor::*; let c = Descriptor::new("RGBC").with("Rd ", Value::Double(255.0)).with("Grn ", Value::Double(0.0)).with("Bl ", Value::Double(0.0)); VersionedDescriptor::new(Descriptor::new("null").with("Clr ", Value::Descriptor(c))).to_bytes() }; @@ -639,7 +639,7 @@ fn adjustment_and_fill_layers_from_psd() { #[test] fn unmodelled_blocks_are_preserved() { - use photocraft_psd::TaggedBlock; + use craft_psd::TaggedBlock; let mut f = testgen::small(Version::Psd, Compression::Raw); f.layers_mut()[0].blocks.push(TaggedBlock::new(*b"vmsk", vec![0; 8])); let (d, _) = psd_to_document(&f); @@ -650,10 +650,10 @@ fn unmodelled_blocks_are_preserved() { #[test] fn fill_layer_keeps_photoshop_pixels() { - use photocraft_psd::{ChannelData, LayerRecord, TaggedBlock}; + use craft_psd::{ChannelData, LayerRecord, TaggedBlock}; let mut f = testgen::small(Version::Psd, Compression::Raw); let soco = { - use photocraft_psd::descriptor::*; + use craft_psd::descriptor::*; let c = Descriptor::new("RGBC").with("Rd ", Value::Double(255.0)).with("Grn ", Value::Double(0.0)).with("Bl ", Value::Double(0.0)); VersionedDescriptor::new(Descriptor::new("null").with("Clr ", Value::Descriptor(c))).to_bytes() }; @@ -664,7 +664,7 @@ fn fill_layer_keeps_photoshop_pixels() { c.id = i as i16 - 1; } f.layers_mut().push(LayerRecord { - rect: photocraft_psd::Rect::from_xywh(0, 0, 2, 2), + rect: craft_psd::Rect::from_xywh(0, 0, 2, 2), name: b"fill".to_vec(), channels: chans, blocks: vec![TaggedBlock::unicode_name("fill"), TaggedBlock::new(*b"SoCo", soco)], @@ -689,7 +689,7 @@ fn fill_layer_keeps_photoshop_pixels() { #[test] fn text_and_smart_detected() { - use photocraft_psd::{LayerRecord, TaggedBlock}; + use craft_psd::{LayerRecord, TaggedBlock}; let mut f = testgen::small(Version::Psd, Compression::Raw); for (name, key) in [("t", b"TySh"), ("s", b"PlLd"), ("sh", b"vscg")] { // Type identification needs readable type data, not an eight-byte malformed stub. @@ -734,10 +734,10 @@ fn guides_and_alpha_names_roundtrip() { #[test] fn resolution_info_cm_display_unit_stays_pixels_per_inch() { let mut f = testgen::small(Version::Psd, Compression::Raw); - let mut ri = photocraft_psd::ResolutionInfo::from_dpi(300.0); + let mut ri = craft_psd::ResolutionInfo::from_dpi(300.0); ri.h_res_unit = 2; ri.v_res_unit = 2; - f.resources[0] = photocraft_psd::ImageResource::new(1005, ri.to_bytes()); + f.resources[0] = craft_psd::ImageResource::new(1005, ri.to_bytes()); let (d, _) = psd_to_document(&f); assert!((d.resolution_dpi - 300.0).abs() < 1e-3, "{}", d.resolution_dpi); let out = document_to_psd(&d).unwrap(); @@ -750,7 +750,7 @@ fn resolution_info_cm_display_unit_stays_pixels_per_inch() { fn stale_index_resources_dropped() { let mut f = testgen::small(Version::Psd, Compression::Raw); for id in [1024u16, 1026, 1036, 1057, 1069, 1072] { - f.resources.push(photocraft_psd::ImageResource::new(id, vec![0, 0])); + f.resources.push(craft_psd::ImageResource::new(id, vec![0, 0])); } let (d, _) = psd_to_document(&f); assert!(d.metadata.psd_resources.iter().all(|r| ![1024u16, 1026, 1036, 1057, 1069, 1072].contains(&r.0))); @@ -762,7 +762,7 @@ fn merged_composite_unmattes_photoshop_white() { let mut f = testgen::merged_only(Version::Psd, ColorMode::Rgb, 8, Compression::Raw, 1, 1); f.header.channels = 4; // straight red at alpha 0.5, matted: r = 1, g = b = 0.5 - f.image_data = photocraft_psd::ImageData::new(Compression::Raw, vec![255, 128, 128, 128]); + f.image_data = craft_psd::ImageData::new(Compression::Raw, vec![255, 128, 128, 128]); let m = merged_composite(&f).unwrap(); assert!((m[0][0] - 1.0).abs() < 0.01 && m[0][1] < 0.01 && m[0][2] < 0.01, "{:?}", m[0]); let (d, _) = psd_to_document(&f); @@ -772,7 +772,7 @@ fn merged_composite_unmattes_photoshop_white() { // HDR and negative straight samples must survive the actual F32 PSD import boundary. let mut hdr = testgen::merged_only(Version::Psd, ColorMode::Rgb, 32, Compression::Raw, 1, 1); hdr.header.channels = 4; - hdr.image_data = photocraft_psd::ImageData::new(Compression::Raw, [1.5_f32, 0.25, 0.5, 0.5].into_iter().flat_map(f32::to_be_bytes).collect()); + hdr.image_data = craft_psd::ImageData::new(Compression::Raw, [1.5_f32, 0.25, 0.5, 0.5].into_iter().flat_map(f32::to_be_bytes).collect()); assert_eq!(merged_composite(&hdr).unwrap(), vec![[2.0, -0.5, 0.0, 0.5]]); let mut deep = testgen::merged_only(Version::Psd, ColorMode::Rgb, 16, Compression::Raw, 1, 1); deep.header.channels = 4; @@ -785,14 +785,14 @@ fn merged_composite_unmattes_photoshop_white() { #[test] fn vector_rendered_mask_not_doubled_on_shapes() { - use photocraft_psd::{LayerRecord, TaggedBlock}; + use craft_psd::{LayerRecord, TaggedBlock}; let mut f = testgen::small(Version::Psd, Compression::Raw); - let mut mask = photocraft_psd::LayerMask::new(photocraft_psd::Rect::default(), 0, 8); + let mut mask = craft_psd::LayerMask::new(craft_psd::Rect::default(), 0, 8); mask.flags = 8; f.layers_mut().push(LayerRecord { name: b"shape".to_vec(), - mask: photocraft_psd::MaskData::Mask(mask), - channels: vec![photocraft_psd::ChannelData::new(-2, Some(Compression::Raw), vec![])], + mask: craft_psd::MaskData::Mask(mask), + channels: vec![craft_psd::ChannelData::new(-2, Some(Compression::Raw), vec![])], blocks: vec![TaggedBlock::unicode_name("shape"), TaggedBlock::new(*b"SoCo", vec![]), TaggedBlock::new(*b"vmsk", vec![0; 8])], ..Default::default() }); @@ -802,9 +802,9 @@ fn vector_rendered_mask_not_doubled_on_shapes() { assert!(l.mask.is_none()); let record = f.layers_mut().last_mut().unwrap(); - let photocraft_psd::MaskData::Mask(mask) = &mut record.mask else { panic!("fixture has a mask") }; - mask.real = Some(photocraft_psd::RealMask { flags: 0, background: 255, rect: photocraft_psd::Rect { top: 0, left: 0, bottom: 1, right: 1 } }); - record.channels.push(photocraft_psd::ChannelData::new(-3, Some(Compression::Raw), vec![64])); + let craft_psd::MaskData::Mask(mask) = &mut record.mask else { panic!("fixture has a mask") }; + mask.real = Some(craft_psd::RealMask { flags: 0, background: 255, rect: craft_psd::Rect { top: 0, left: 0, bottom: 1, right: 1 } }); + record.channels.push(craft_psd::ChannelData::new(-3, Some(Compression::Raw), vec![64])); let (imported, _) = psd_to_document(&f); assert_eq!(imported.layers.last().unwrap().content.kind_name(), "Shape"); let mask = imported.layers.last().unwrap().mask.as_ref().expect("selected real mask must survive synthetic cleanup"); @@ -817,8 +817,8 @@ fn vector_rendered_mask_not_doubled_on_shapes() { #[test] fn every_blend_mode_maps_both_ways() { for m in std::iter::once(photocraft_color::BlendMode::PassThrough).chain(photocraft_color::BlendMode::LAYER_MODES) { - let k = photocraft_psd::BlendMode::from_key(m.psd_key()); - assert!(!matches!(k, photocraft_psd::BlendMode::Unknown(_)), "{m:?}"); + let k = craft_psd::BlendMode::from_key(m.psd_key()); + assert!(!matches!(k, craft_psd::BlendMode::Unknown(_)), "{m:?}"); assert_eq!(photocraft_color::BlendMode::from_psd_key(k.key()), Some(m)); } } @@ -827,9 +827,9 @@ fn every_blend_mode_maps_both_ways() { fn layer_bounds_without_channel_data_allocate_nothing() { // A record can declare a 300000x300000 rectangle in a few bytes. With no channel data to // back it, import used to interleave a ~360 GB buffer and abort on the allocation (#755). - use photocraft_psd::LayerRecord; + use craft_psd::LayerRecord; let mut f = testgen::small(Version::Psd, Compression::Raw); - f.layers_mut().push(LayerRecord { rect: photocraft_psd::Rect::from_xywh(0, 0, 300_000, 300_000), name: b"huge".to_vec(), ..Default::default() }); + f.layers_mut().push(LayerRecord { rect: craft_psd::Rect::from_xywh(0, 0, 300_000, 300_000), name: b"huge".to_vec(), ..Default::default() }); let (d, warnings) = psd_to_document(&f); let l = d.layers.last().unwrap(); assert!(matches!(&l.content, LayerContent::Raster(s) if s.tile_count() == 0)); diff --git a/crates/io/tests/it/psd_style_sheets.rs b/crates/io/tests/it/psd_style_sheets.rs index 0634dd3f9c..292a4f8bb1 100644 --- a/crates/io/tests/it/psd_style_sheets.rs +++ b/crates/io/tests/it/psd_style_sheets.rs @@ -5,9 +5,9 @@ //! Reading only the Normal sheets left a centred paragraph style read as Left, so starting an //! edit re-laid the text out half a line to the side. +use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use photocraft_doc::text::TextAlign; use photocraft_geom::Affine; -use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use photocraft_text::engine_data::Value as E; use photocraft_text::psd::{TySh, text_layer_from_tysh, write_tysh}; diff --git a/crates/io/tests/it/psd_thumbnail.rs b/crates/io/tests/it/psd_thumbnail.rs index be6fbd360b..acfecfb05b 100644 --- a/crates/io/tests/it/psd_thumbnail.rs +++ b/crates/io/tests/it/psd_thumbnail.rs @@ -1,12 +1,12 @@ //! Preferences › File Handling › Image Previews: PSD/PSB saves embed Photoshop's thumbnail //! resource (1036: 28-byte header + JFIF, ≤ 160 px) unless the previews are turned off. +use craft_psd::PsdFile; +use craft_psd::resources::ids; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::{Document, Layer}; use photocraft_geom::Size; use photocraft_io::{ExportOptions, export, import}; -use photocraft_psd::PsdFile; -use photocraft_psd::resources::ids; /// A `w`×`h` document of `mode`/`depth` holding one layer of `rgba` (given as straight sRGB-ish /// RGBA and converted to the document's model), covering the left `cover` fraction. diff --git a/crates/io/tests/it/psd_type_bounds.rs b/crates/io/tests/it/psd_type_bounds.rs index 43ce38c674..571279efba 100644 --- a/crates/io/tests/it/psd_type_bounds.rs +++ b/crates/io/tests/it/psd_type_bounds.rs @@ -12,11 +12,11 @@ use crate::common; +use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::text::TextShape; use photocraft_doc::{Document, Layer, LayerContent, Size, TextLayer}; use photocraft_geom::{Affine, Rect}; -use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D}; use photocraft_raster::Surface; use photocraft_text::engine_data::Value as E; use photocraft_text::psd::{TySh, write_tysh}; @@ -246,7 +246,7 @@ fn import_case(c: &Case) -> (Rect, TextLayer, Document, Vec<[f32; 4]>) { t.psd_raw = Some(std::sync::Arc::new(data)); doc.layers.push(Layer::new(c.name, LayerContent::Text(t))); let bytes = photocraft_io::export(&doc, "t.psd", &Default::default()).unwrap().bytes; - let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); let merged = photocraft_io::merged_composite(&file).unwrap(); let back = photocraft_io::import("t.psd", &bytes).unwrap().document; let LayerContent::Text(bt) = &back.layers[0].content else { panic!("{}: not a type layer", c.name) }; @@ -370,10 +370,10 @@ fn hostile_type_sizes_without_pixels_import_without_a_huge_render() { let Some(mut t) = photocraft_text::psd::text_layer_from_tysh(&data, 72.0) else { // Unsafe affine data is now rejected at the boundary (#4758). Exercise the // actual file import too: with no saved pixels it must remain empty and safe. - let mut file = photocraft_psd::testgen::small(photocraft_psd::Version::Psd, photocraft_psd::Compression::Raw); - file.layers_mut().push(photocraft_psd::LayerRecord { + let mut file = craft_psd::testgen::small(craft_psd::Version::Psd, craft_psd::Compression::Raw); + file.layers_mut().push(craft_psd::LayerRecord { name: b"hostile".to_vec(), - blocks: vec![photocraft_psd::TaggedBlock::new(*b"TySh", data)], + blocks: vec![craft_psd::TaggedBlock::new(*b"TySh", data)], ..Default::default() }); let back = photocraft_io::import("t.psd", &file.to_bytes().unwrap()).unwrap(); diff --git a/crates/io/tests/it/psd_type_photoshop_bytes.rs b/crates/io/tests/it/psd_type_photoshop_bytes.rs index 98524892c4..1c8d642b37 100644 --- a/crates/io/tests/it/psd_type_photoshop_bytes.rs +++ b/crates/io/tests/it/psd_type_photoshop_bytes.rs @@ -9,8 +9,8 @@ use std::path::{Path, PathBuf}; -use photocraft_psd::PsdFile; -use photocraft_psd::descriptor::Value as D; +use craft_psd::PsdFile; +use craft_psd::descriptor::Value as D; use photocraft_text::engine_data::Value as E; fn corpus(rel: &str) -> PsdFile { @@ -69,6 +69,6 @@ fn tysh_trailing_bounds_match_photoshop() { fn version_info_matches_photoshop() { for file in ["text/antialias-smooth.psd", "text/warp-arc-50.psd"] { let theirs = corpus(file); - assert_eq!(photocraft_psd::resources::version_info_resource(true).data, theirs.resource(1057).unwrap().data, "{file}"); + assert_eq!(craft_psd::resources::version_info_resource(true).data, theirs.resource(1057).unwrap().data, "{file}"); } } diff --git a/crates/io/tests/it/psd_unknown_adjustment.rs b/crates/io/tests/it/psd_unknown_adjustment.rs index 58bc909c57..161c4a5e8c 100644 --- a/crates/io/tests/it/psd_unknown_adjustment.rs +++ b/crates/io/tests/it/psd_unknown_adjustment.rs @@ -3,10 +3,10 @@ //! of opening silently as an empty pixel layer (#6575). Pixel layers that merely carry an unknown //! block stay pixel layers. +use craft_psd::testgen; +use craft_psd::{ChannelData, Compression, LayerFlags, LayerRecord, PsdFile, Rect, TaggedBlock, Version}; use photocraft_doc::{Adjustment, Document, LayerContent}; use photocraft_io::*; -use photocraft_psd::testgen; -use photocraft_psd::{ChannelData, Compression, LayerFlags, LayerRecord, PsdFile, Rect, TaggedBlock, Version}; /// A layer record as Photoshop writes an adjustment layer: no pixels, "pixel data irrelevant" /// set, the adjustment block first, then the usual metadata. diff --git a/crates/io/tests/it/raw.rs b/crates/io/tests/it/raw.rs index 748aaa7c67..6d248fe930 100644 --- a/crates/io/tests/it/raw.rs +++ b/crates/io/tests/it/raw.rs @@ -615,3 +615,74 @@ fn a_re_develop_keeps_the_fitted_look() { let mid = curve.iter().find(|k| k[0] >= 0.18).unwrap(); assert!(mid[1] > mid[0], "{mid:?}"); } + +/// The open-time Camera Raw dialog decodes the file once, in the open: its preview curve and +/// Open's re-develop reuse that decode and fitted look, and the developed pixels are those of +/// decoding and fitting again (#9432). +#[test] +fn a_kept_decode_gives_the_same_pixels_and_decodes_once() { + use photocraft_io::raw::{ + Demosaic, RawDecode, RawTuning, decodes_on_this_thread, import_raw_demosaic_keeping, import_raw_tuned, import_raw_tuned_from, take_kept_decode, + }; + let pixels = |r: &photocraft_io::ImportResult| photocraft_io::document_to_image(&r.document, &mut Vec::new()).unwrap().data().to_vec(); + + let (w, h) = (480, 320); + let cam = patches(w, h); + let nef = nef_uncompressed(&cam, w, h, Some(camera_rendering(&cam, w, h))); + let (dw, dh) = (40, 24); + let mut dng = DngSpec::cfa(dw, dh, mosaic(&scene(dw, dh), dw, [0, 1, 1, 2], 0, 65535)); + dng.as_shot_neutral = Some([0.6, 1.0, 0.8]); + let dng = dng.build(); + let (cw, ch) = (48, 16); + let cr2 = Cr2Spec { + width: cw, + height: ch, + data: mosaic(&scene(cw, ch), cw, [0, 1, 1, 2], 256, 12000), + precision: 14, + components: 2, + slices: vec![24, 24], + borders: None, + wb_rggb: None, + orientation: 6, + model_id: None, + } + .build(); + + for (name, bytes) in [("a.nef", &nef), ("b.dng", &dng), ("c.cr2", &cr2)] { + // The open, keeping its decode: one decode in all. + let before = decodes_on_this_thread(); + let opened = import_raw_demosaic_keeping(name, bytes, Demosaic::default()).unwrap(); + assert_eq!(decodes_on_this_thread() - before, 1, "{name}: the open"); + let kept = take_kept_decode(bytes).expect("the open kept its decode"); + assert!(take_kept_decode(bytes).is_none(), "{name}: taking it removes it"); + let mut reference = pixels(&import(name, bytes).unwrap()); + assert_eq!(pixels(&opened), reference, "{name}: keeping changes nothing about the open"); + assert_eq!(kept.tone_curve(), photocraft_io::raw::tone_curve(bytes), "{name}: curve"); + + for tuning in [ + RawTuning::default(), + RawTuning { exposure: 0.5, temperature: 20.0, tint: -15.0, shadows: 30.0, clarity: 20.0, ..Default::default() }, + RawTuning { demosaic: Demosaic::Bilinear, highlights: -40.0, ..Default::default() }, + ] { + let (old, old_wb) = import_raw_tuned(name, bytes, &tuning).unwrap(); + let before = decodes_on_this_thread(); + let (new, new_wb) = import_raw_tuned_from(name, bytes, &tuning, &kept).unwrap(); + assert_eq!(decodes_on_this_thread() - before, 0, "{name}: Open decodes nothing again"); + assert_eq!((old_wb, &old.warnings), (new_wb, &new.warnings), "{name}"); + reference = pixels(&old); + assert_eq!(pixels(&new), reference, "{name}: {tuning:?}"); + } + // A decode made from the same bytes later (a miss of the open's) is as good. + let later = RawDecode::new(bytes).unwrap(); + let (a, _) = import_raw_tuned_from(name, bytes, &RawTuning::default(), &later).unwrap(); + assert_eq!(pixels(&a), pixels(&import_raw_tuned(name, bytes, &RawTuning::default()).unwrap().0)); + } + + // A decode of another file is not used for this one. + let other = RawDecode::new(&dng).unwrap(); + let before = decodes_on_this_thread(); + let (got, _) = import_raw_tuned_from("a.nef", &nef, &RawTuning::default(), &other).unwrap(); + assert_eq!(decodes_on_this_thread() - before, 1); + assert_eq!(pixels(&got), pixels(&import_raw_tuned("a.nef", &nef, &RawTuning::default()).unwrap().0)); + assert_eq!((got.document.size.width, got.document.size.height), (w as u32, h as u32)); +} diff --git a/crates/io/tests/it/resolution_axes.rs b/crates/io/tests/it/resolution_axes.rs index fb2bd209e2..5aa0cd990b 100644 --- a/crates/io/tests/it/resolution_axes.rs +++ b/crates/io/tests/it/resolution_axes.rs @@ -4,12 +4,12 @@ use crate::common; use common::*; +use craft_psd::resources::ids; +use craft_psd::testgen; +use craft_psd::{Compression, ImageResource, ResolutionInfo, Version}; use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, Metadata, SampleType as CSample}; use photocraft_color::{ColorMode, SampleType}; use photocraft_io::*; -use photocraft_psd::resources::ids; -use photocraft_psd::testgen; -use photocraft_psd::{Compression, ImageResource, ResolutionInfo, Version}; fn resolution_notes(r: &ImportResult) -> Vec<&String> { r.warnings.iter().filter(|w| w.contains("vertical resolution")).collect() @@ -75,7 +75,7 @@ fn resolution_info_cm_display_unit_is_pixels_per_inch() { assert!(resolution_notes(&r).is_empty(), "{:?}", r.warnings); let out = export(&r.document, "out.psd", &ExportOptions::default()).unwrap(); - let file = photocraft_psd::PsdFile::from_bytes(&out.bytes).unwrap(); + let file = craft_psd::PsdFile::from_bytes(&out.bytes).unwrap(); let written = file.resolution().unwrap(); assert!((written.h_res() - 300.0).abs() < 1e-3, "{}", written.h_res()); assert!((written.v_res() - 300.0).abs() < 1e-3, "{}", written.v_res()); diff --git a/crates/io/tests/it/roundtrip.rs b/crates/io/tests/it/roundtrip.rs index 484368790e..4aa501133f 100644 --- a/crates/io/tests/it/roundtrip.rs +++ b/crates/io/tests/it/roundtrip.rs @@ -3,9 +3,9 @@ use crate::common; use common::*; +use craft_psd::PsdFile; use photocraft_color::{ColorMode, SampleType}; use photocraft_io::*; -use photocraft_psd::PsdFile; fn roundtrip(doc: &photocraft_doc::Document) -> photocraft_doc::Document { let r = export(doc, "x.psd", &ExportOptions::default()).expect("export"); @@ -224,8 +224,8 @@ fn edited_adjustment_regenerates_block_unedited_keeps_raw() { #[test] fn text_layer_roundtrip_with_tysh() { + use craft_psd::descriptor::{Descriptor, UnicodeString, Value, VersionedDescriptor}; use photocraft_doc::*; - use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value, VersionedDescriptor}; // Minimal TySh: version, transform, text version, text descriptor, warp. let mut tysh = 1u16.to_be_bytes().to_vec(); for v in [1.0f64, 0.0, 0.0, 1.0, 3.0, 4.0] { @@ -268,7 +268,7 @@ fn text_layer_roundtrip_with_tysh() { fn effects_raw_roundtrip() { let mut d = gen_doc(ColorMode::Rgb, SampleType::U8, Features::PIXELS); let mut lfx = vec![0, 0, 0, 0]; - lfx.extend(photocraft_psd::testgen::sample_descriptor().to_bytes()); + lfx.extend(craft_psd::testgen::sample_descriptor().to_bytes()); // Typed items and the raw block must agree; the raw bytes are then kept. let (master, items) = photocraft_io::effects_map::parse_lfx2(&lfx).unwrap(); d.layers[1].effects.enabled = master; @@ -326,7 +326,7 @@ fn document_to_psd_direct_api() { fn big_document_goes_psb_with_warning() { let d = photocraft_doc::Document::new("big", photocraft_geom::Size::new(30_001, 1), ColorMode::Grayscale, SampleType::U8); let (f, w) = document_to_psd_with(&d, &PsdExportOptions::default()); - assert_eq!(f.header.version, photocraft_psd::Version::Psb); + assert_eq!(f.header.version, craft_psd::Version::Psb); assert!(w.iter().any(|w| w.contains("PSB"))); } @@ -551,7 +551,7 @@ fn blend_if_round_trips_as_blending_ranges() { assert_eq!(rec.blending_ranges.data, want); // Layers without Blend If keep full ranges for gray + R, G, B. let rb = f.layers().iter().find(|r| r.name() == "b").unwrap(); - assert_eq!(rb.blending_ranges, photocraft_psd::BlendingRanges::full(3)); + assert_eq!(rb.blending_ranges, craft_psd::BlendingRanges::full(3)); let back = roundtrip(&d); assert_eq!(back.layers[0].blend_if, bi); assert!(back.layers[1].blend_if.is_default()); diff --git a/crates/io/tests/it/smart_contents_identity.rs b/crates/io/tests/it/smart_contents_identity.rs index 5a0714b3d8..c5dd8145d8 100644 --- a/crates/io/tests/it/smart_contents_identity.rs +++ b/crates/io/tests/it/smart_contents_identity.rs @@ -2,11 +2,11 @@ use std::sync::Arc; +use craft_psd::{PsdFile, TaggedBlock}; use photocraft_color::{BlendMode, ColorMode, SampleType}; use photocraft_doc::{Document, Layer, LayerContent, SmartContentsId, SmartFilter, SmartObject, SmartSource}; use photocraft_geom::{Affine, Size}; use photocraft_io::{ExportOptions, export, import, linked, smart_map}; -use photocraft_psd::{PsdFile, TaggedBlock}; use photocraft_raster::Surface; fn fixture() -> Document { @@ -133,7 +133,7 @@ fn duplicated_imported_layer_keeps_source_but_gets_its_own_placement() { assert_eq!(original.placed, colliding); assert_ne!(original.placed, duplicate.placed); let filter_cache = after.global_blocks.iter().find(|b| &b.key == b"FEid").unwrap(); - let filter_cache = photocraft_psd::filter_effects::FilterEffects::parse(&filter_cache.data).unwrap(); + let filter_cache = craft_psd::filter_effects::FilterEffects::parse(&filter_cache.data).unwrap(); assert_eq!(filter_cache.items.len(), 1); assert_eq!(filter_cache.items[0].id, duplicate.placed); assert_eq!(after.layers().iter().find(|l| l.name() == "original").unwrap().block(b"SoLd").unwrap().data, original_raw); diff --git a/crates/io/tests/it/smart_corpus.rs b/crates/io/tests/it/smart_corpus.rs index f258c01103..db79a6119b 100644 --- a/crates/io/tests/it/smart_corpus.rs +++ b/crates/io/tests/it/smart_corpus.rs @@ -184,7 +184,7 @@ fn smart_objects_round_trip_through_psd() { Ok((back, out)) => { compare(&em, &back, true).into_iter().for_each(|e| fail("re-embedded", e)); // The old files are gone: one lnk2 item per distinct source. - let f = photocraft_psd::PsdFile::from_bytes(&out).unwrap(); + let f = craft_psd::PsdFile::from_bytes(&out).unwrap(); let items: Vec = f .global_blocks .iter() diff --git a/crates/io/tests/it/tiff_layers.rs b/crates/io/tests/it/tiff_layers.rs index 3c7815a37a..5eb2020e42 100644 --- a/crates/io/tests/it/tiff_layers.rs +++ b/crates/io/tests/it/tiff_layers.rs @@ -5,10 +5,10 @@ use crate::common; use common::*; +use craft_psd::tiff::{ByteOrder, ImageSourceData}; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::{Document, LayerContent}; use photocraft_io::*; -use photocraft_psd::tiff::{ByteOrder, ImageSourceData}; fn tiff(doc: &Document, layers: bool) -> ExportResult { export(doc, "x.tif", &ExportOptions { tiff_layers: layers, ..Default::default() }).expect("export") @@ -207,7 +207,7 @@ fn transparency_is_straight_in_the_composite() { /// transparency: it opens as no alpha channel, and a PSD save doesn't write it twice. #[test] fn photoshop_mtrn_marks_the_merged_transparency_of_a_layered_tiff() { - use photocraft_psd::{PsdFile, TaggedBlock}; + use craft_psd::{PsdFile, TaggedBlock}; for depth in [SampleType::U8, SampleType::U16] { let mut d = Document::new("t", photocraft_geom::Size::new(8, 6), ColorMode::Rgb, depth); let fmt = d.pixel_format(); @@ -248,7 +248,7 @@ fn big_documents_use_the_psb_signature() { let d = gen_doc(ColorMode::Rgb, SampleType::U8, Features::PIXELS); let r = export(&d, "x.tif", &ExportOptions { force_psb: true, tiff_layers: true, ..Default::default() }).unwrap(); let (_, layers) = tags(&r.bytes); - assert!(layers.unwrap().starts_with(photocraft_psd::tiff::SIGNATURE_PSB)); + assert!(layers.unwrap().starts_with(craft_psd::tiff::SIGNATURE_PSB)); let back = import("x.tif", &r.bytes).unwrap().document; assert_docs_eq(&d, &back); } @@ -509,7 +509,7 @@ fn dtf_like_spot_is_written_in_full() { } fn assert_spot_resources(resources: &[u8], name: &str) { - use photocraft_psd::tiff::resources_from_bytes; + use craft_psd::tiff::resources_from_bytes; let (blocks, warnings) = resources_from_bytes(resources).unwrap(); assert!(warnings.is_empty(), "{name} {warnings:?}"); let block = |id: u16| blocks.iter().find(|b| b.id == id).unwrap_or_else(|| panic!("{name} missing {id}")); @@ -693,7 +693,7 @@ fn ink(d: &Document) -> (f32, f32) { /// records. With `layers`, the layer data has a positive layer count and an `MTrn` block (the /// specification's key is `Mtrn`); without, the file is flat. Built from the PSD model of `doc`. fn photoshop_transparency_and_spot_tiff(doc: &Document, layers: bool) -> Vec { - use photocraft_psd::{Compression, TaggedBlock}; + use craft_psd::{Compression, TaggedBlock}; let opts = PsdExportOptions { merged_matte: false, merged_compression: Compression::Raw, ..Default::default() }; let (file, _) = document_to_psd_with(doc, &opts); @@ -703,7 +703,7 @@ fn photoshop_transparency_and_spot_tiff(doc: &Document, layers: bool) -> Vec let rgba: Vec = (0..n).flat_map(|i| (0..4).map(move |c| (i, c))).map(|(i, c)| planes[c * n + i]).collect(); let mut img = photocraft_codecs::Image::from_raw(4, 4, photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8, rgba).unwrap(); img.meta.extra_samples = vec![photocraft_codecs::ExtraSample { kind: 0, data: planes[4 * n..].to_vec() }]; - img.meta.photoshop_resources = Some(photocraft_psd::tiff::resources_to_bytes(&file.resources).unwrap()); + img.meta.photoshop_resources = Some(craft_psd::tiff::resources_to_bytes(&file.resources).unwrap()); if layers { let mut isd = ImageSourceData::from_psd(&file); if let Some(info) = &mut isd.layer_info { @@ -721,7 +721,7 @@ fn photoshop_transparency_and_spot_tiff(doc: &Document, layers: bool) -> Vec /// must also drop the `MTrn` marker, or the spot would read back as transparency. #[test] fn photoshop_mtrn_tiff_opens_without_a_transparency_channel() { - use photocraft_psd::TaggedBlock; + use craft_psd::TaggedBlock; let bytes = photoshop_transparency_and_spot_tiff(&transparent_art_with_white_spot(), true); let opened = import("t.tif", &bytes).unwrap().document; @@ -884,10 +884,10 @@ fn assert_photoshop_layered_tiff(bytes: &[u8], with_spot: bool) { /// here. Everything round-trips, PSD → TIFF → PSD included. #[test] fn spot_ink_is_stored_as_zero_and_alpha_is_not() { + use craft_psd::PsdFile; use photocraft_color::{Color, PixelFormat}; use photocraft_doc::{AlphaChannel, Layer}; use photocraft_geom::{Rect, Size}; - use photocraft_psd::PsdFile; use photocraft_raster::Surface; for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { @@ -977,7 +977,7 @@ fn identifiers(data: &[u8]) -> Vec { /// The identifiers in a TIFF's resource 1053 (none without one). fn tiff_alpha_identifiers(bytes: &[u8]) -> Vec { let resources = tags(bytes).0.expect("photoshop resources"); - let (blocks, _) = photocraft_psd::tiff::resources_from_bytes(&resources).unwrap(); + let (blocks, _) = craft_psd::tiff::resources_from_bytes(&resources).unwrap(); blocks.iter().find(|b| b.id == 1053).map(|b| identifiers(&b.data)).unwrap_or_default() } @@ -1054,7 +1054,7 @@ fn default_export_options_write_a_flat_tiff() { /// limit error as a PSD, instead of being converted. #[test] fn layered_tiff_nested_past_the_cap_is_rejected() { - use photocraft_psd::{GroupSpec, LayerSpec, PixelData, PsdBuilder, PsdFile}; + use craft_psd::{GroupSpec, LayerSpec, PixelData, PsdBuilder, PsdFile}; let tiff_nested = |levels: usize| { let mut b = PsdBuilder::new(4, 4); for _ in 0..levels { @@ -1116,7 +1116,7 @@ fn channels_past_sixteen_leave_no_resources_behind() { let r = tiff(&doc, true); assert!(r.warnings.iter().any(|w| w.contains("19 extra channels") && w.contains("first 16")), "{:?}", r.warnings); let (resources, _) = tags(&r.bytes); - let (resources, _) = photocraft_psd::tiff::resources_from_bytes(&resources.expect("resources")).expect("parse resources"); + let (resources, _) = craft_psd::tiff::resources_from_bytes(&resources.expect("resources")).expect("parse resources"); let data = |id: u16| resources.iter().find(|r| r.id == id).map(|r| r.data.clone()).unwrap_or_default(); let pascal = data(1006); let (mut at, mut names) = (0usize, 0usize); diff --git a/crates/io/tests/it/tiff_save_options.rs b/crates/io/tests/it/tiff_save_options.rs index dc1b564156..3bdedc71a3 100644 --- a/crates/io/tests/it/tiff_save_options.rs +++ b/crates/io/tests/it/tiff_save_options.rs @@ -2,11 +2,11 @@ //! channels, and Save Image Pyramid. Unset Save Transparency is covered in `tiff_layers`. use crate::common::*; +use craft_psd::tiff::ImageSourceData; use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; use photocraft_doc::{AlphaChannel, Document, Layer, LayerContent}; use photocraft_geom::{Rect, Size}; use photocraft_io::*; -use photocraft_psd::tiff::ImageSourceData; use photocraft_raster::Surface; /// A 4×4 document whose one layer is opaque red in its middle and transparent around it, with a @@ -41,7 +41,7 @@ fn extra_samples_tag(bytes: &[u8]) -> Vec { /// and the alpha identifiers (1053). fn channel_resources(bytes: &[u8]) -> (Vec, usize, usize) { let tag = photocraft_codecs::tiff_photoshop_tags(bytes).0.expect("resources"); - let (resources, _) = photocraft_psd::tiff::resources_from_bytes(tag).expect("parse resources"); + let (resources, _) = craft_psd::tiff::resources_from_bytes(tag).expect("parse resources"); let data = |id: u16| resources.iter().find(|r| r.id == id).map(|r| r.data.clone()).unwrap_or_default(); let pascal = data(1006); let (mut at, mut names) = (0usize, Vec::new()); diff --git a/crates/io/tests/it/tiff_type_geometry.rs b/crates/io/tests/it/tiff_type_geometry.rs index 326ec35cee..ecf83065e0 100644 --- a/crates/io/tests/it/tiff_type_geometry.rs +++ b/crates/io/tests/it/tiff_type_geometry.rs @@ -1,11 +1,11 @@ //! Photoshop's mixed-order Intel TIFF type blocks and unsafe/unresolved type fallback (#4758). +use craft_psd::descriptor::{Value, VersionedDescriptor}; use photocraft_color::{ColorMode, SampleType}; use photocraft_doc::text::{CharStyle, TextRun}; use photocraft_doc::{Document, Layer, LayerContent, Size, TextLayer}; use photocraft_geom::Affine; use photocraft_io::{ExportOptions, PsdExportOptions, document_to_psd_with, export, import, psd_to_document}; -use photocraft_psd::descriptor::{Value, VersionedDescriptor}; fn document() -> Document { document_in(ColorMode::Rgb, SampleType::U8) @@ -36,7 +36,7 @@ fn photoshop_mixed_order_tiff_import_keeps_editable_geometry_and_pixels() { let blocks = image.meta.photoshop_layers.as_mut().unwrap(); let at = blocks.windows(8).position(|b| b == b"MIB8hSyT").unwrap() + 12; // Only the text version/descriptor switch order; warp and bounds remain little-endian. - let (_, used) = photocraft_psd::descriptor::VersionedDescriptor::parse_prefix(&canonical[52..]).unwrap(); + let (_, used) = craft_psd::descriptor::VersionedDescriptor::parse_prefix(&canonical[52..]).unwrap(); blocks[at + 50..at + 52 + used].copy_from_slice(&canonical[50..52 + used]); let bytes = photocraft_codecs::encode(&image, photocraft_codecs::Format::Tiff, &Default::default()).unwrap(); let opened = import("photoshop.tif", &bytes).unwrap(); diff --git a/crates/io/tests/it/vector.rs b/crates/io/tests/it/vector.rs index 71bf66823c..685d6e0a5d 100644 --- a/crates/io/tests/it/vector.rs +++ b/crates/io/tests/it/vector.rs @@ -7,6 +7,8 @@ use std::path::{Path as FsPath, PathBuf}; #[cfg(feature = "corpus")] use std::sync::Arc; +#[cfg(feature = "corpus")] +use craft_psd::PsdFile; use photocraft_color::{Color, ColorMode, SampleType}; use photocraft_doc::{ Document, Fill, Knot, Layer, LayerContent, LineCap, LineJoin, LiveShape, NamedPath, Path, PathOp, ShapeLayer, ShapeStroke, Size, StrokeAlign, Subpath, @@ -14,8 +16,6 @@ use photocraft_doc::{ }; use photocraft_geom::{Point, Rect}; use photocraft_io::*; -#[cfg(feature = "corpus")] -use photocraft_psd::PsdFile; fn roundtrip(d: &Document) -> Document { let r = export(d, "x.psd", &ExportOptions::default()).unwrap(); @@ -222,7 +222,7 @@ fn shape_density_and_feather_roundtrip_through_mask_parameters() { sh.cache = Some(photocraft_vector::render_shape(&sh, d.pixel_format(), d.bounds())); d.layers.push(Layer::new("Shape", LayerContent::Shape(sh))); let bytes = export(&d, "x.psd", &ExportOptions::default()).unwrap().bytes; - let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); let rec = file.layers().last().unwrap(); let p = rec.layer_mask().and_then(|m| m.parameters).expect("mask parameters"); assert_eq!((p.vector_density, p.vector_feather), (Some(128), Some(6.0)), "{depth:?}"); @@ -241,7 +241,7 @@ fn shape_density_and_feather_roundtrip_through_mask_parameters() { let mut d = doc(); d.layers.push(shape_layer(ShapeLayer { path: square, fill: Some(Fill::Solid(Color::BLACK)), ..ShapeLayer::default() })); let bytes = export(&d, "x.psd", &ExportOptions::default()).unwrap().bytes; - let file = photocraft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let file = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); assert!(file.layers().last().unwrap().layer_mask().and_then(|m| m.parameters).is_none()); let LayerContent::Shape(back) = &import("x.psd", &bytes).unwrap().document.layers[1].content else { panic!("a shape") }; assert_eq!((back.density, back.feather), (1.0, 0.0)); diff --git a/crates/paint/src/bg_erase.rs b/crates/paint/src/bg_erase.rs index 8e783a02c9..a7597822c3 100644 --- a/crates/paint/src/bg_erase.rs +++ b/crates/paint/src/bg_erase.rs @@ -11,7 +11,7 @@ use serde::{Deserialize, Serialize}; use crate::Stroke; use crate::replace::{Limits, Sampling}; -use crate::retouch::{Footprint, Region, alpha_index, apply_dab_stroke}; +use crate::retouch::{Footprint, Region, StrokeTooLarge, alpha_index, apply_dab_stroke}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] @@ -109,9 +109,9 @@ fn graded_weight(d: f32, tol: f32) -> f32 { /// Erase along `stroke`. The brush opacity is ignored (Photoshop's Background Eraser has none); /// the selection limits the effect. Returns the damaged rectangle; empty when the surface has no -/// alpha channel. -pub fn apply_background_eraser(target: &mut Surface, stroke: &Stroke, bs: &BgEraseSettings, selection: Option<&Surface>) -> Rect { - let Some(effect) = background_eraser_effect(target, bs) else { return Rect::EMPTY }; +/// alpha channel, an error when the stroke is too large to run. +pub fn apply_background_eraser(target: &mut Surface, stroke: &Stroke, bs: &BgEraseSettings, selection: Option<&Surface>) -> Result { + let Some(effect) = background_eraser_effect(target, bs) else { return Ok(Rect::EMPTY) }; apply_dab_stroke(target, &background_eraser_stroke(stroke), selection, false, 0, effect) } @@ -340,7 +340,7 @@ mod tests { let fmt = PixelFormat::new(mode, sample, true); let mut s = setup(fmt); let bs = BgEraseSettings { sampling: Sampling::Once, limits: Limits::Discontiguous, tolerance: 0.05, ..Default::default() }; - let d = apply_background_eraser(&mut s, &stroke(&[(20.0, 20.0), (60.0, 20.0)]), &bs, None); + let d = apply_background_eraser(&mut s, &stroke(&[(20.0, 20.0), (60.0, 20.0)]), &bs, None).unwrap(); assert!(!d.is_empty()); assert_eq!(alpha(&s, 20, 20), 0.0, "{fmt:?} green under the hotspot erased"); assert_eq!(alpha(&s, 45, 20), 1.0, "{fmt:?} blue kept"); @@ -354,13 +354,13 @@ mod tests { let fmt = PixelFormat::RGBA8; let mut s = setup(fmt); let bs = BgEraseSettings { sampling: Sampling::Continuous, limits: Limits::Discontiguous, tolerance: 0.05, ..Default::default() }; - apply_background_eraser(&mut s, &stroke(&[(20.0, 20.0), (60.0, 20.0)]), &bs, None); + apply_background_eraser(&mut s, &stroke(&[(20.0, 20.0), (60.0, 20.0)]), &bs, None).unwrap(); assert_eq!(alpha(&s, 20, 20), 0.0); assert_eq!(alpha(&s, 60, 20), 0.0, "blue erased once the hotspot reached it"); // Background swatch = blue: only blue goes, wherever the hotspot is. let mut t = setup(fmt); let bs = BgEraseSettings { sampling: Sampling::BackgroundSwatch, background: BLUE, ..bs }; - apply_background_eraser(&mut t, &stroke(&[(30.0, 20.0), (50.0, 20.0)]), &bs, None); + apply_background_eraser(&mut t, &stroke(&[(30.0, 20.0), (50.0, 20.0)]), &bs, None).unwrap(); assert_eq!(alpha(&t, 30, 20), 1.0); assert_eq!(alpha(&t, 50, 20), 0.0); } @@ -375,14 +375,14 @@ mod tests { for (limits, island_erased) in [(Limits::Contiguous, false), (Limits::FindEdges, false), (Limits::Discontiguous, true)] { let mut t = s.clone(); let bs = BgEraseSettings { sampling: Sampling::Once, limits, tolerance: 0.05, ..Default::default() }; - apply_background_eraser(&mut t, &stroke(&[(20.0, 20.0)]), &bs, None); + apply_background_eraser(&mut t, &stroke(&[(20.0, 20.0)]), &bs, None).unwrap(); assert_eq!(alpha(&t, 31, 20) == 0.0, island_erased, "{limits:?}"); assert_eq!(alpha(&t, 20, 20), 0.0); } // Protecting a foreground equal to the sampled colour erases nothing. let mut t = s.clone(); let bs = BgEraseSettings { sampling: Sampling::Once, tolerance: 0.05, protect_foreground: true, foreground: GREEN, ..Default::default() }; - apply_background_eraser(&mut t, &stroke(&[(20.0, 20.0)]), &bs, None); + apply_background_eraser(&mut t, &stroke(&[(20.0, 20.0)]), &bs, None).unwrap(); assert_eq!(t, s); } @@ -399,25 +399,25 @@ mod tests { let base = BgEraseSettings { limits: Limits::Discontiguous, tolerance: 0.01, ..Default::default() }; let protect = BgEraseSettings { protect_foreground: true, foreground: STAND_IN, foreground_cmyk: picked, ..base.clone() }; let mut t = s.clone(); - apply_background_eraser(&mut t, &st, &protect, None); + apply_background_eraser(&mut t, &st, &protect, None).unwrap(); assert_eq!(alpha(&t, 40, 20), 1.0, "the picked foreground inks are protected"); assert_eq!(alpha(&t, 10, 20), 0.0, "white erased"); let swatch = BgEraseSettings { sampling: Sampling::BackgroundSwatch, background: STAND_IN, background_cmyk: picked, ..base.clone() }; let mut t = s.clone(); - apply_background_eraser(&mut t, &st, &swatch, None); + apply_background_eraser(&mut t, &st, &swatch, None).unwrap(); assert_eq!(alpha(&t, 40, 20), 0.0, "the picked background inks are erased fully"); assert_eq!(alpha(&t, 10, 20), 1.0, "white kept"); // Inks picked for another colour, and non-CMYK targets, use the stand-in as before. let stale = BgEraseSettings { background_cmyk: Some(([0.5; 3], [1.0, 0.0, 0.0, 0.0])), ..swatch.clone() }; let mut t = s.clone(); - apply_background_eraser(&mut t, &st, &stale, None); + apply_background_eraser(&mut t, &st, &stale, None).unwrap(); assert_eq!(alpha(&t, 40, 20), 1.0, "stale inks are ignored"); let rgb = PixelFormat::RGBA8; let mut r = Surface::new(rgb); r.fill_rect(Rect::new(0, 0, 80, 40), &from_rgba(&rgb, STAND_IN)); let (mut with, mut without) = (r.clone(), r.clone()); - apply_background_eraser(&mut with, &st, &swatch, None); - apply_background_eraser(&mut without, &st, &BgEraseSettings { background_cmyk: None, ..swatch }, None); + apply_background_eraser(&mut with, &st, &swatch, None).unwrap(); + apply_background_eraser(&mut without, &st, &BgEraseSettings { background_cmyk: None, ..swatch }, None).unwrap(); assert_eq!(with, without, "an RGB target ignores the inks"); } @@ -438,7 +438,7 @@ mod tests { background_cmyk: Some(([STAND_IN[0], STAND_IN[1], STAND_IN[2]], INKS)), ..Default::default() }; - apply_background_eraser(&mut s, &stroke(&[(10.0, 20.0), (70.0, 20.0)]), &bs, None); + apply_background_eraser(&mut s, &stroke(&[(10.0, 20.0), (70.0, 20.0)]), &bs, None).unwrap(); assert_eq!(alpha(&s, 40, 20), 0.0, "the stored inks are erased fully"); } @@ -453,7 +453,7 @@ mod tests { for sampling in [Sampling::Continuous, Sampling::Once] { let mut t = s.clone(); let bs = BgEraseSettings { sampling, limits: Limits::Contiguous, ..Default::default() }; - apply_background_eraser(&mut t, &st, &bs, None); + apply_background_eraser(&mut t, &st, &bs, None).unwrap(); // Everything within radius − 1 of the line. for y in 6..24 { for x in 10..51 { @@ -470,18 +470,18 @@ mod tests { let mut sel = Surface::new(PixelFormat::GRAY8); sel.fill_rect(Rect::new(0, 0, 20, 40), &[1.0]); let bs = BgEraseSettings { sampling: Sampling::Once, limits: Limits::Discontiguous, tolerance: 0.05, ..Default::default() }; - apply_background_eraser(&mut s, &stroke(&[(20.0, 20.0)]), &bs, Some(&sel)); + apply_background_eraser(&mut s, &stroke(&[(20.0, 20.0)]), &bs, Some(&sel)).unwrap(); assert_eq!(alpha(&s, 15, 20), 0.0); assert_eq!(alpha(&s, 25, 20), 1.0, "outside the selection kept"); // Sampling a transparent hotspot erases nothing; NaN tolerance acts as 0; no alpha → no-op. let mut t = Surface::new(fmt); - assert!(apply_background_eraser(&mut t, &stroke(&[(5.0, 5.0)]), &bs, None).width() > 0); + assert!(apply_background_eraser(&mut t, &stroke(&[(5.0, 5.0)]), &bs, None).unwrap().width() > 0); assert_eq!(t.content_bounds(), Rect::EMPTY); let mut u = setup(fmt); let nan = BgEraseSettings { tolerance: f32::NAN, ..bs.clone() }; - apply_background_eraser(&mut u, &stroke(&[(20.0, 20.0)]), &nan, None); + apply_background_eraser(&mut u, &stroke(&[(20.0, 20.0)]), &nan, None).unwrap(); assert_eq!(alpha(&u, 20, 20), 0.0, "exact match still erased at tolerance 0"); let mut g = Surface::new(PixelFormat::GRAY8); - assert!(apply_background_eraser(&mut g, &stroke(&[(5.0, 5.0)]), &bs, None).is_empty()); + assert!(apply_background_eraser(&mut g, &stroke(&[(5.0, 5.0)]), &bs, None).unwrap().is_empty()); } } diff --git a/crates/paint/src/bg_erase_decontamination_tests.rs b/crates/paint/src/bg_erase_decontamination_tests.rs index ffedc57f7c..7014ff0cf6 100644 --- a/crates/paint/src/bg_erase_decontamination_tests.rs +++ b/crates/paint/src/bg_erase_decontamination_tests.rs @@ -50,7 +50,7 @@ fn rgba(s: &Surface, i: usize) -> [i32; 4] { /// The reference's drag from block 0's centre to `to_x`, Sampling Once. fn drag(fmt: PixelFormat, tolerance_percent: f32, to_x: f64) -> Surface { let mut s = blocks(fmt); - apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (to_x, 150.0)]), &once(tolerance_percent), None); + apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (to_x, 150.0)]), &once(tolerance_percent), None).unwrap(); s } @@ -59,7 +59,7 @@ fn clicks(fmt: PixelFormat, tolerance_percent: f32, clicks: usize) -> Surface { let mut s = blocks(fmt); for _ in 0..clicks { for i in 0..8 { - apply_background_eraser(&mut s, &stroke(&[(100.0 * i as f64 + 50.0, 150.0)]), &swatch(tolerance_percent), None); + apply_background_eraser(&mut s, &stroke(&[(100.0 * i as f64 + 50.0, 150.0)]), &swatch(tolerance_percent), None).unwrap(); } } s @@ -191,7 +191,7 @@ fn it_works_in_the_documents_own_channels() { let bs = BgEraseSettings { background: [level(0), level(0), level(0), 1.0], ..swatch(50.0) }; let click_all = |s: &mut Surface| { for i in 0..8 { - apply_background_eraser(s, &stroke(&[(100.0 * i as f64 + 50.0, 150.0)]), &bs, None); + apply_background_eraser(s, &stroke(&[(100.0 * i as f64 + 50.0, 150.0)]), &bs, None).unwrap(); } }; click_all(&mut s); diff --git a/crates/paint/src/bg_erase_find_edges_tests.rs b/crates/paint/src/bg_erase_find_edges_tests.rs index ee95dd8c2e..8159408aaf 100644 --- a/crates/paint/src/bg_erase_find_edges_tests.rs +++ b/crates/paint/src/bg_erase_find_edges_tests.rs @@ -47,7 +47,7 @@ fn click(at: (f64, f64), size: f32, limits: Limits) -> Surface { points: vec![StrokePoint::new(at.0, at.1, 1.0)], }; let bs = BgEraseSettings { sampling: Sampling::Continuous, limits, tolerance: 0.5, ..Default::default() }; - apply_background_eraser(&mut s, &stroke, &bs, None); + apply_background_eraser(&mut s, &stroke, &bs, None).unwrap(); s } diff --git a/crates/paint/src/bg_erase_graded_alpha_tests.rs b/crates/paint/src/bg_erase_graded_alpha_tests.rs index 51e1bbc20d..8a665c329d 100644 --- a/crates/paint/src/bg_erase_graded_alpha_tests.rs +++ b/crates/paint/src/bg_erase_graded_alpha_tests.rs @@ -43,7 +43,7 @@ fn swatch(tolerance_percent: f32, background: [f32; 4]) -> BgEraseSettings { fn one_click(fmt: PixelFormat, colour: [f32; 4], bs: &BgEraseSettings) -> i32 { let mut s = Surface::new(fmt); s.fill_rect(Rect::new(0, 0, 100, 100), &from_rgba(&fmt, colour)); - apply_background_eraser(&mut s, &click((50.0, 50.0)), bs, None); + apply_background_eraser(&mut s, &click((50.0, 50.0)), bs, None).unwrap(); (s.rgba(50, 50)[3] * 255.0).round() as i32 } @@ -121,7 +121,7 @@ fn a_blurred_edge_keeps_its_transition_graded() { for limits in [Limits::Contiguous, Limits::Discontiguous] { let mut t = s.clone(); let bs = BgEraseSettings { sampling: Sampling::Once, limits, tolerance: 0.5, ..Default::default() }; - apply_background_eraser(&mut t, &click((190.0, 70.0)), &bs, None); + apply_background_eraser(&mut t, &click((190.0, 70.0)), &bs, None).unwrap(); for (i, want) in ALPHA.iter().enumerate() { let x = 185 + i as i32; let got = (t.rgba(x, 70)[3] * 255.0).round() as i32; diff --git a/crates/paint/src/bg_erase_protect_foreground_tests.rs b/crates/paint/src/bg_erase_protect_foreground_tests.rs index 4f0cf43915..86e190860c 100644 --- a/crates/paint/src/bg_erase_protect_foreground_tests.rs +++ b/crates/paint/src/bg_erase_protect_foreground_tests.rs @@ -47,7 +47,7 @@ fn settings(protect: Option) -> BgEraseSettings { /// centre. fn drag_with(fmt: PixelFormat, bs: &BgEraseSettings) -> [i32; 8] { let mut s = blocks(fmt); - apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), bs, None); + apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), bs, None).unwrap(); std::array::from_fn(|i| (s.rgba(100 * i as i32 + 50, 150)[3] * 255.0).round() as i32) } @@ -121,7 +121,7 @@ fn protection_narrows_the_tolerance_to_the_foreground_in_one_dab() { let mut s = blocks(fmt); let bs = BgEraseSettings { sampling: Sampling::BackgroundSwatch, background: block(0), tolerance, ..settings(protect) }; let x = 100.0 * i as f64 + 50.0; - apply_background_eraser(&mut s, &stroke(&[(x, 150.0)]), &bs, None); + apply_background_eraser(&mut s, &stroke(&[(x, 150.0)]), &bs, None).unwrap(); s.rgba(x as i32, 150)[3] }) .collect() @@ -146,7 +146,7 @@ fn a_foreground_equal_to_the_sample_erases_nothing() { let s = blocks(PixelFormat::RGBA8); let mut t = s.clone(); let bs = BgEraseSettings { limits, tolerance, ..settings(Some(0)) }; - apply_background_eraser(&mut t, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &bs, None); + apply_background_eraser(&mut t, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &bs, None).unwrap(); assert_eq!(t, s, "{limits:?} tolerance {tolerance}"); } } @@ -158,7 +158,7 @@ fn find_edges_keeps_the_foreground_colour_itself() { let fmt = PixelFormat::RGBA8; let mut s = blocks(fmt); let bs = BgEraseSettings { limits: Limits::FindEdges, ..settings(Some(1)) }; - apply_background_eraser(&mut s, &stroke(&[(80.0, 150.0), (120.0, 150.0)]), &bs, None); + apply_background_eraser(&mut s, &stroke(&[(80.0, 150.0), (120.0, 150.0)]), &bs, None).unwrap(); assert_eq!(s.rgba(75, 150)[3], 0.0, "the sample erased"); assert_eq!(s.rgba(110, 150)[3], 1.0, "the foreground colour kept"); } @@ -170,8 +170,8 @@ fn protect_off_is_unchanged() { let mut s = blocks(PixelFormat::RGBA8); let mut t = s.clone(); let on_far = BgEraseSettings { foreground: [0.0, 0.0, 1.0, 1.0], protect_foreground: true, ..settings(None) }; - apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &settings(None), None); - apply_background_eraser(&mut t, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &on_far, None); + apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &settings(None), None).unwrap(); + apply_background_eraser(&mut t, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &on_far, None).unwrap(); assert_eq!(s, t, "a foreground beyond the Tolerance protects nothing"); } @@ -193,7 +193,7 @@ fn protection_works_in_the_documents_own_channels() { } let fg = [level(3), level(3), level(3), 1.0]; let bs = BgEraseSettings { foreground: fg, ..settings(Some(3)) }; - apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &bs, None); + apply_background_eraser(&mut s, &stroke(&[(50.0, 150.0), (750.0, 150.0)]), &bs, None).unwrap(); let a: Vec = (0..8).map(|i| s.rgba(100 * i + 50, 150)[3]).collect(); assert_eq!(a[0], 0.0, "gray: the sample erased, {a:?}"); for (i, v) in a.iter().enumerate().skip(3) { @@ -222,14 +222,14 @@ fn the_foreground_is_matched_at_the_documents_precision() { let mut s = Surface::new(fmt); s.fill_rect(Rect::new(0, 0, 100, 100), &from_rgba(&fmt, [1.0; 4])); s.fill_rect(Rect::new(100, 0, 200, 100), &from_rgba(&fmt, grey)); - apply_background_eraser(&mut s, &stroke(&[(50.0, 50.0), (150.0, 50.0)]), &bs, None); + apply_background_eraser(&mut s, &stroke(&[(50.0, 50.0), (150.0, 50.0)]), &bs, None).unwrap(); assert_eq!(s.rgba(50, 50)[3], 0.0, "{fmt:?}: the sample erased"); assert_eq!(s.rgba(150, 50)[3], 1.0, "{fmt:?}: the stored foreground colour kept"); // The foreground grey is also the sample. let mut s = Surface::new(fmt); s.fill_rect(Rect::new(0, 0, 200, 100), &from_rgba(&fmt, grey)); let t = s.clone(); - apply_background_eraser(&mut s, &stroke(&[(50.0, 50.0), (150.0, 50.0)]), &bs, None); + apply_background_eraser(&mut s, &stroke(&[(50.0, 50.0), (150.0, 50.0)]), &bs, None).unwrap(); assert_eq!(s, t, "{fmt:?}: a foreground stored as the sample erases nothing"); } } diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index cf3e6c119b..ce70c53cbd 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -42,7 +42,7 @@ pub use brush::{ pub use curve::ResponseCurve; pub use mip_cache::{mip_cache_bytes, purge_mip_cache}; pub use mixer::MixerSettings; -pub use render::{BrushContext, StrokeRenderer, UnionLive, grid_center, grid_square, render_stroke}; +pub use render::{BrushContext, StrokeRenderer, UnionLive, grid_center, grid_square, render_stroke, render_stroke_clipped}; pub use tile::{GrayTile, StoredTile}; /// One input sample. Missing stylus data defaults to "mouse": full pressure, no tilt/rotation. @@ -410,6 +410,8 @@ mod tests { mod airbrush_rate_tests; #[cfg(test)] mod brush_tests; +#[cfg(test)] +mod mixer_click_empty_layer_tests; #[cfg(test)] mod smoothing_catch_up_default_tests; diff --git a/crates/paint/src/mixer.rs b/crates/paint/src/mixer.rs index 1b381f2a0f..370f2dc354 100644 --- a/crates/paint/src/mixer.rs +++ b/crates/paint/src/mixer.rs @@ -10,7 +10,7 @@ use photocraft_raster::{Surface, from_rgba, from_rgba_into, to_rgba}; use serde::{Deserialize, Serialize}; use crate::Stroke; -use crate::retouch::{alpha_index, apply_dab_stroke, over_native}; +use crate::retouch::{StrokeTooLarge, alpha_index, apply_dab_stroke, over_native}; use photocraft_geom::Rect; /// Fraction of the way the pickup colour moves towards the canvas colour per dab at 100 % Wet. @@ -175,7 +175,7 @@ pub fn apply_mixer_stroke( state: &mut MixerState, selection: Option<&Surface>, lock_transparency: bool, -) -> Rect { +) -> Result { let fmt = target.format(); let mut st = stroke.clone(); st.brush.opacity = 1.0; @@ -270,7 +270,13 @@ pub fn apply_mixer_dab_region( }); } } - let wr = if res.is_some() { amount * (1.0 - mix * wet) } else { 0.0 }; + // Nothing picked up (a transparent canvas under a clean pickup) leaves the load at full + // strength, as a dry dab: an empty layer does not thin the paint (#11944). + let wr = match (&res, &pickup) { + (None, _) => 0.0, + (Some(_), None) => amount, + (Some(_), Some(_)) => amount * (1.0 - mix * wet), + }; let wp = if pickup.is_some() { mix * wet } else { 0.0 }; let total = wr + wp; if total > 1e-6 { @@ -335,7 +341,8 @@ mod tests { let mut s = Surface::new(PixelFormat::RGBA8); let mut st = MixerState::default(); st.load([1.0, 0.0, 0.0, 1.0]); - apply_mixer_stroke(&mut s, None, &stroke(10.0), &MixerSettings { wet: 0.0, load, mix: 0.0, flow: 1.0, ..Default::default() }, &mut st, None, false); + apply_mixer_stroke(&mut s, None, &stroke(10.0), &MixerSettings { wet: 0.0, load, mix: 0.0, flow: 1.0, ..Default::default() }, &mut st, None, false) + .unwrap(); let (start, end) = (s.rgba(10, 10)[3], s.rgba(190, 10)[3]); assert!(start > 0.95, "{start}"); if expect_dry { @@ -364,7 +371,8 @@ mod tests { &mut st, None, false, - ); + ) + .unwrap(); // Blue is dragged into the white half. let c = s.rgba(115, 10); assert!(c[2] > c[1] + 0.05 && c[1] < 0.95, "{c:?}"); @@ -385,7 +393,7 @@ mod tests { // On red, the clean wet brush smears red and lays down none of the blue it was loaded with. let mut s = Surface::new(PixelFormat::RGBA8); s.fill_rect(Rect::new(0, 0, 200, 20), &[1.0, 0.0, 0.0, 1.0]); - apply_mixer_stroke(&mut s, None, &stroke(10.0), &MixerSettings::default(), &mut st, None, false); + apply_mixer_stroke(&mut s, None, &stroke(10.0), &MixerSettings::default(), &mut st, None, false).unwrap(); let c = s.rgba(100, 10); assert!(c[0] > 0.99 && c[1] < 0.01 && c[2] < 0.01, "{c:?}"); } @@ -453,7 +461,7 @@ mod tests { fn dry_empty_brush_paints_nothing() { let mut s = Surface::new(PixelFormat::RGBA8); let mut st = MixerState::default(); - let dmg = apply_mixer_stroke(&mut s, None, &stroke(10.0), &MixerSettings { wet: 0.0, ..Default::default() }, &mut st, None, false); + let dmg = apply_mixer_stroke(&mut s, None, &stroke(10.0), &MixerSettings { wet: 0.0, ..Default::default() }, &mut st, None, false).unwrap(); assert!(!dmg.is_empty()); assert_eq!(s.rgba(50, 10)[3], 0.0); } @@ -471,7 +479,8 @@ mod tests { for p in &mut k.points { p.pressure = pressure; } - apply_mixer_stroke(&mut s, None, &k, &MixerSettings { wet: 1.0, load: 1.0, mix: 1.0, flow: 1.0, ..Default::default() }, &mut st, None, false); + apply_mixer_stroke(&mut s, None, &k, &MixerSettings { wet: 1.0, load: 1.0, mix: 1.0, flow: 1.0, ..Default::default() }, &mut st, None, false) + .unwrap(); st.pickup }; assert!(run(0.0).is_none()); diff --git a/crates/paint/src/mixer_click_empty_layer_tests.rs b/crates/paint/src/mixer_click_empty_layer_tests.rs new file mode 100644 index 0000000000..6c0ec73cbf --- /dev/null +++ b/crates/paint/src/mixer_click_empty_layer_tests.rs @@ -0,0 +1,85 @@ +//! A single wet Mixer Brush click on an empty layer leaves a full-strength dab, as a dry click +//! does: picking up from a transparent layer does not thin the paint (#11944). Measured with a +//! 35 px soft round tip, a black load, Wet 80 / Load 75 / Mix 90 and Flow 100, one click at +//! 182,47: a full black dab with layer bounds 153,18–210,75. + +use crate::mixer::{MixerSettings, MixerState, apply_mixer_stroke}; +use crate::{BrushSettings, Stroke, StrokePoint}; +use photocraft_color::PixelFormat; +use photocraft_raster::Surface; + +fn click(s: &mut Surface, wet: f32) { + click_with(s, wet, 0.9, 1.0); +} + +fn click_with(s: &mut Surface, wet: f32, mix: f32, flow: f32) { + let stroke = Stroke { + brush: BrushSettings { size: 35.0, hardness: 0.0, spacing: 0.25, pressure_size: false, ..Default::default() }, + points: vec![StrokePoint::new(182.0, 47.0, 1.0)], + }; + let mut st = MixerState::default(); + st.load([0.0, 0.0, 0.0, 1.0]); + let m = MixerSettings { wet, load: 0.75, mix, flow, ..Default::default() }; + apply_mixer_stroke(s, None, &stroke, &m, &mut st, None, false).unwrap(); +} + +fn alpha(s: &Surface, x: i32, y: i32) -> i32 { + (s.rgba(x, y)[3] * 255.0).round() as i32 +} + +/// The bounds of the pixels with any alpha, as x0, y0, x1, y1 (exclusive). +fn bounds(s: &Surface) -> (i32, i32, i32, i32) { + let (mut x0, mut y0, mut x1, mut y1) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN); + for y in 0..120 { + for x in 120..260 { + if alpha(s, x, y) > 0 { + (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)); + } + } + } + (x0, y0, x1, y1) +} + +#[test] +fn a_wet_click_on_an_empty_layer_is_a_full_strength_dab() { + for wet in [0.8, 0.0] { + let mut s = Surface::new(PixelFormat::RGBA8); + click(&mut s, wet); + assert!(alpha(&s, 182, 47) >= 250, "Wet {wet}: centre alpha {}", alpha(&s, 182, 47)); + let c = s.rgba(182, 47); + assert!(c[..3].iter().all(|v| *v < 0.02), "Wet {wet}: the dab is black: {c:?}"); + let (x0, y0, x1, y1) = bounds(&s); + for (got, want) in [(x0, 153), (y0, 18), (x1, 210), (y1, 75)] { + assert!((got - want).abs() <= 2, "Wet {wet}: bounds {:?}, expected near 153,18-210,75", (x0, y0, x1, y1)); + } + } +} + +#[test] +fn a_wet_click_on_a_colour_still_mixes_it_in() { + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(photocraft_geom::Rect::new(0, 0, 400, 120), &[1.0, 0.0, 0.0, 1.0]); + click(&mut s, 0.8); + let c = s.rgba(182, 47); + assert!(c[0] > 0.3, "the red under the click is mixed in: {c:?}"); + assert!(c[0] < 0.99, "and the black load darkens it: {c:?}"); + assert!(c[1] < 0.02 && c[2] < 0.02 && c[3] > 0.99, "only red and black, opaque: {c:?}"); +} + +/// On an empty layer Wet and Mix change nothing: the dab is a dry dab at the same Flow, so its +/// centre is about 251 × Flow / 100. davidmann4 measured 126 at Flow 50 and 251 at Flow 100, +/// at Wet 80 with Mix 50 and with Mix 90 (#11944). +#[test] +fn at_flow_50_an_empty_layer_dab_is_half_the_flow_100_dab_at_any_mix() { + for mix in [0.5, 0.9] { + let centre = |flow| { + let mut s = Surface::new(PixelFormat::RGBA8); + click_with(&mut s, 0.8, mix, flow); + alpha(&s, 182, 47) + }; + let (full, half) = (centre(1.0), centre(0.5)); + assert!((half - 126).abs() <= 3, "Mix {mix}, Flow 50: centre alpha {half}, measured 126"); + assert!(full >= 250, "Mix {mix}, Flow 100: centre alpha {full}, measured 251"); + assert!((2 * half - full).abs() <= 6, "Mix {mix}: Flow 50 centre {half}, expected about half of {full}"); + } +} diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index ffe9b888ff..7b1ca43f96 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -760,6 +760,39 @@ pub struct StrokeRenderer { dual_buf: Vec, all_dabs: Option>, regions: RegionPool, + /// Dabs whose rectangle misses this one are not rasterized (see [`with_clip`](Self::with_clip)). + clip: Option, + /// Dab-rectangle pixels the stroke may still rasterize (see [`MAX_STROKE_DAB_AREA`]). + area_left: u64, + /// The same budget for the Dual Brush's dabs, so primary and dual dabs are charged apart and + /// the result does not depend on how the input was chunked. + dual_area_left: u64, + /// A dab was left out for want of budget. + refused: bool, +} + +/// Most dab-rectangle pixels one stroke rasterizes: past it the stroke stops painting, so a very +/// large brush at the finest spacing over a very long path costs bounded time and memory instead +/// of growing with path length times brush area. A soft round dab costs about 1.2 ns per pixel on +/// an idle four-thread machine, so the limit is a few seconds of work. 2^31 pixels is, for +/// example, 8 000 dabs of a 500 px brush (about a 40 000 px path at 1 % spacing) or 50 000 dabs of a +/// 200 px brush; a 20 000 px scribble with a 500 px brush at 5 % spacing uses a fifth of it. +pub const MAX_STROKE_DAB_AREA: u64 = 1 << 31; + +/// Whether a dab with rectangle `rect` is painted: it reaches `clip` and fits `area_left`, which +/// it is charged against. +fn admit(clip: Option, area_left: &mut u64, refused: &mut bool, rect: Rect) -> bool { + if rect.is_empty() || clip.is_some_and(|c| c.intersect(&rect).is_empty()) { + return false; + } + let area = u64::from(rect.width()) * u64::from(rect.height()); + // A dab that does not fit is skipped; a smaller later one (pressure) may still fit. + if area > *area_left { + *refused = true; + return false; + } + *area_left -= area; + true } /// The tile buffers [`StrokeRenderer::composite`] works in, kept from one composite to the next: @@ -865,6 +898,10 @@ impl StrokeRenderer { dual_buf: Vec::new(), all_dabs: None, regions: RegionPool::default(), + clip: p.clip, + area_left: p.area_left, + dual_area_left: p.dual_area_left, + refused: p.refused, }) } Some(m) => { @@ -917,9 +954,34 @@ impl StrokeRenderer { dual_buf: Vec::new(), all_dabs: None, regions: RegionPool::default(), + clip: None, + area_left: MAX_STROKE_DAB_AREA, + dual_area_left: MAX_STROKE_DAB_AREA, + refused: false, } } + /// Only paint where a dab can reach inside `clip` (the target's paintable area): a dab whose + /// rectangle misses it is counted but not rasterized, and allocates no coverage tiles. Pixels + /// inside `clip` come out exactly as without it. + pub fn with_clip(mut self, clip: Rect) -> Self { + self.clip = Some(clip); + self + } + + /// Override the dab-area budget ([`MAX_STROKE_DAB_AREA`]) for this stroke. Set it before the first + /// dab: it replaces what is left, so pixels already charged are not carried over. + pub fn with_dab_area_budget(mut self, pixels: u64) -> Self { + self.area_left = pixels; + self.dual_area_left = pixels; + self + } + + /// Whether a dab was left out because the stroke used up its dab-area budget. + pub fn budget_exhausted(&self) -> bool { + self.refused + } + /// Keep a copy of every primary dab (for tests and sequential tools). pub fn record_dabs(mut self) -> Self { self.all_dabs = Some(Vec::new()); @@ -943,6 +1005,9 @@ impl StrokeRenderer { let mut native = [0.0f32; 8]; for d in &dabs { let rect = self.ctx.dab_rect(d, false); + if !admit(self.clip, &mut self.area_left, &mut self.refused, rect) { + continue; + } // Wet Edges acts on the whole stroke (#2088): the dab records how deep it reaches each // pixel and the stroke darkens its own rim when composited, not every dab's. self.ctx.rasterize_into(d, false, rect, &mut self.scratch, wet.then_some(&mut self.depth_scratch)); @@ -960,6 +1025,9 @@ impl StrokeRenderer { if let Some(dm) = self.dual.as_mut() { for d in &duals { let rect = self.ctx.dab_rect(d, true); + if !admit(self.clip, &mut self.dual_area_left, &mut self.refused, rect) { + continue; + } self.ctx.rasterize(d, true, rect, &mut self.scratch); dm.accumulate(rect, &self.scratch, 1.0, None, None); } @@ -1048,6 +1116,10 @@ impl StrokeRenderer { dual_buf: duals, all_dabs: None, regions: RegionPool::default(), + clip: self.clip, + area_left: self.area_left, + dual_area_left: self.dual_area_left, + refused: self.refused, }; t.raster_pending(); // Tiles whose coverage the tail doesn't change still composite the same: redraw them all. @@ -1349,12 +1421,28 @@ pub fn render_stroke( selection: Option<&Surface>, lock_transparency: bool, zoom: f32, +) -> Rect { + render_stroke_clipped(target, brush, points, selection, lock_transparency, zoom, None) +} + +/// [`render_stroke`] that only rasterizes dabs reaching `clip` (see [`StrokeRenderer::with_clip`]). +pub fn render_stroke_clipped( + target: &mut Surface, + brush: &BrushSettings, + points: &[StrokePoint], + selection: Option<&Surface>, + lock_transparency: bool, + zoom: f32, + clip: Option, ) -> Rect { if points.is_empty() { return Rect::EMPTY; } let pre = target.clone(); let mut r = StrokeRenderer::new(brush, Some(target.format()), zoom); + if let Some(c) = clip { + r = r.with_clip(c); + } r.push(points); r.finish(); r.composite(&pre, target, selection, lock_transparency, true) @@ -1608,6 +1696,9 @@ mod reference; #[cfg(test)] mod coverage_tests; +#[cfg(test)] +mod budget_tests; + #[cfg(test)] #[path = "mip_cache_render_tests.rs"] mod mip_cache_tests; diff --git a/crates/paint/src/render/budget_tests.rs b/crates/paint/src/render/budget_tests.rs new file mode 100644 index 0000000000..f14c0bec09 --- /dev/null +++ b/crates/paint/src/render/budget_tests.rs @@ -0,0 +1,130 @@ +//! Stroke cost limits: the clip rectangle and the dab-area budget. + +use super::*; + +fn brush(size: f32, spacing: f32) -> BrushSettings { + BrushSettings { size, spacing, hardness: 0.5, ..BrushSettings::default() } +} + +fn line(r: &mut StrokeRenderer, from: f64, to: f64) { + r.push(&[StrokePoint::new(from, 50.0, 1.0), StrokePoint::new(to, 50.0, 1.0)]); + r.finish(); +} + +#[test] +fn clip_skips_far_dabs_and_leaves_the_pixels_inside_unchanged() { + let b = brush(20.0, 0.25); + let clip = Rect::new(0, 0, 200, 100); + let mut plain = StrokeRenderer::new(&b, None, 1.0); + let mut clipped = StrokeRenderer::new(&b, None, 1.0).with_clip(clip); + // A path that runs 20000 px, almost all of it far outside the clip. + line(&mut plain, -100.0, 20_000.0); + line(&mut clipped, -100.0, 20_000.0); + assert_eq!(plain.dab_count(), clipped.dab_count()); + for y in clip.y0..clip.y1 { + for x in clip.x0..clip.x1 { + assert_eq!(plain.coverage_at(x, y).to_bits(), clipped.coverage_at(x, y).to_bits(), "({x},{y})"); + } + } + assert!(plain.cov.tiles.len() > 20 * clipped.cov.tiles.len(), "{} vs {}", plain.cov.tiles.len(), clipped.cov.tiles.len()); + assert_eq!(clipped.coverage_at(10_000, 50), 0.0); + assert!(clipped.bounds().x1 < 400, "{:?}", clipped.bounds()); +} + +#[test] +fn a_dab_that_straddles_the_clip_edge_is_painted_in_full_inside() { + let b = brush(40.0, 0.25); + let clip = Rect::new(0, 0, 100, 100); + let mut plain = StrokeRenderer::new(&b, None, 1.0); + let mut clipped = StrokeRenderer::new(&b, None, 1.0).with_clip(clip); + plain.push(&[StrokePoint::new(110.0, 50.0, 1.0)]); + clipped.push(&[StrokePoint::new(110.0, 50.0, 1.0)]); + plain.finish(); + clipped.finish(); + assert!(plain.coverage_at(95, 50) > 0.0); + assert_eq!(plain.coverage_at(95, 50).to_bits(), clipped.coverage_at(95, 50).to_bits()); +} + +#[test] +fn a_huge_brush_at_the_finest_spacing_over_a_long_path_stays_cheap_with_a_clip() { + // 500 px brush at the 1 % minimum spacing over 2e6 px: 400 000 dabs; only those that reach the + // clip are rasterized. + let b = brush(500.0, 0.0); + let mut r = StrokeRenderer::new(&b, None, 1.0).with_clip(Rect::new(0, 0, 256, 256)); + line(&mut r, -1_000_000.0, 1_000_000.0); + assert!(r.dab_count() > 100_000, "{}", r.dab_count()); + assert!(r.cov.tiles.len() < 1000, "{}", r.cov.tiles.len()); + assert!(!r.budget_exhausted()); +} + +#[test] +fn the_budget_stops_painting_but_keeps_counting_dabs() { + let b = brush(20.0, 0.25); + // A 20 px brush has a dab rectangle of about 30x30; room for about ten of them. + let mut r = StrokeRenderer::new(&b, None, 1.0).with_dab_area_budget(10_000); + line(&mut r, 0.0, 2_000.0); + assert!(r.budget_exhausted()); + assert!(r.dab_count() > 300, "{}", r.dab_count()); + assert!(r.coverage_at(1_000, 50) == 0.0); + assert!(r.bounds().x1 < 200, "{:?}", r.bounds()); + // The first dabs did paint. + assert!(r.coverage_at(2, 50) > 0.0); + // Further input is ignored: no growth. + let tiles = r.cov.tiles.len(); + line(&mut r, 3_000.0, 4_000.0); + assert_eq!(r.cov.tiles.len(), tiles); +} + +#[test] +fn dual_dabs_are_charged_apart_and_chunking_does_not_change_the_result() { + let mut b = brush(20.0, 0.25); + b.dual_brush.enabled = true; + b.dual_brush.size = 10.0; + let pts: Vec<_> = (0..200).map(|i| StrokePoint::new(f64::from(i) * 7.0, 50.0, 1.0)).collect(); + let run = |chunk: usize| { + let mut r = StrokeRenderer::new(&b, None, 1.0).with_dab_area_budget(20_000); + for c in pts.chunks(chunk) { + r.push(c); + } + r.finish(); + r + }; + let (whole, chunked) = (run(1000), run(3)); + assert!(whole.budget_exhausted()); + for x in 0..1400 { + assert_eq!(whole.coverage_at(x, 50).to_bits(), chunked.coverage_at(x, 50).to_bits(), "x {x}"); + assert_eq!(whole.dual.as_ref().unwrap().get(x, 50).to_bits(), chunked.dual.as_ref().unwrap().get(x, 50).to_bits(), "dual x {x}"); + } + assert!(whole.dual.as_ref().unwrap().get(2, 50) > 0.0); +} + +#[test] +fn a_dab_too_big_for_what_is_left_does_not_end_the_stroke() { + let (mut left, mut refused) = (1000, false); + assert!(!admit(None, &mut left, &mut refused, Rect::new(0, 0, 100, 100))); + assert!(refused); + assert_eq!(left, 1000); + assert!(admit(None, &mut left, &mut refused, Rect::new(0, 0, 10, 10))); + assert_eq!(left, 900); +} + +/// How much of the budget everyday strokes use, so a limit change is judged against numbers. +#[test] +fn everyday_strokes_use_a_small_part_of_the_budget() { + // (size, spacing, path length in px): a 100 px brush at 1 % spacing over 6000 px, a 500 px + // brush at 5 % over 20 000 px (a scribble across a large document), 20 px at 25 % over 1e6 px. + for (size, spacing, len) in [(100.0, 0.01, 6_000.0), (500.0, 0.05, 20_000.0), (20.0, 0.25, 1.0e6)] { + let b = brush(size, spacing); + // The clip rejects every dab, so this measures the generator and `dab_rect` only. + let mut r = StrokeRenderer::new(&b, None, 1.0).with_clip(Rect::new(0, 0, 1, 1)).record_dabs(); + r.push(&[StrokePoint::new(0.0, 0.0, 1.0), StrokePoint::new(len, 0.0, 1.0)]); + r.finish(); + let used: u64 = r.dabs().iter().map(|d| r.ctx.dab_rect(d, false)).map(|q| u64::from(q.width()) * u64::from(q.height())).sum(); + println!( + "size {size} spacing {spacing} len {len}: {} dabs, {used} px = {:.1} % of the budget", + r.dab_count(), + used as f64 * 100.0 / MAX_STROKE_DAB_AREA as f64 + ); + assert!(used < MAX_STROKE_DAB_AREA / 4, "{used}"); + } +} diff --git a/crates/paint/src/replace.rs b/crates/paint/src/replace.rs index c4157fac81..3dd2c8f17e 100644 --- a/crates/paint/src/replace.rs +++ b/crates/paint/src/replace.rs @@ -8,7 +8,7 @@ use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use serde::{Deserialize, Serialize}; use crate::Stroke; -use crate::retouch::{Footprint, Region, apply_dab_stroke}; +use crate::retouch::{Footprint, Region, StrokeTooLarge, apply_dab_stroke}; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -77,8 +77,14 @@ fn dist(a: &[f32; 4], b: [f32; 3]) -> f32 { (a[0] - b[0]).abs().max((a[1] - b[1]).abs()).max((a[2] - b[2]).abs()) } -/// Replace colours along a stroke. Returns the damaged rectangle. -pub fn apply_color_replacement(target: &mut Surface, stroke: &Stroke, rs: &ReplaceSettings, selection: Option<&Surface>, lock_transparency: bool) -> Rect { +/// Replace colours along a stroke. Returns the damaged rectangle, or an error for a stroke too large to run. +pub fn apply_color_replacement( + target: &mut Surface, + stroke: &Stroke, + rs: &ReplaceSettings, + selection: Option<&Surface>, + lock_transparency: bool, +) -> Result { let effect = color_replacement_effect(target.clone(), rs.clone()); apply_dab_stroke(target, stroke, selection, lock_transparency, 0, effect) } @@ -189,29 +195,58 @@ pub fn color_replacement_effect(pre: Surface, rs: ReplaceSettings) -> impl FnMut } } } + // A pixel recoloured by `k` (0..1), into `out`. + let recolor = |px: &[f32], k: f32, out: &mut [f32; 8]| { + out[..n].copy_from_slice(px); + if lab_color { + out[1] += (fg_ab[0] - px[1]) * k; + out[2] += (fg_ab[1] - px[2]) * k; + return; + } + let c = to_rgba(&fmt, px); + let b = blend_rgb(mode, [c[0], c[1], c[2]], fg); + let o = [c[0] + (b[0] - c[0]) * k, c[1] + (b[1] - c[1]) * k, c[2] + (b[2] - c[2]) * k, c[3]]; + from_rgba_into(&fmt, o, out); + }; + // A sample as the document stores it. + let stored = |v: f32| match fmt.sample { + photocraft_color::SampleType::U8 => (v.clamp(0.0, 1.0) * 255.0).round(), + photocraft_color::SampleType::U16 => (v.clamp(0.0, 1.0) * 65535.0).round(), + photocraft_color::SampleType::F32 => v, + }; let mut enc = [0.0f32; 8]; for y in r.y0..r.y1 { for x in r.x0..r.x1 { - let k = fp.at(x, y) * weight[(y - r.y0) as usize * w + (x - r.x0) as usize]; + let wt = weight[(y - r.y0) as usize * w + (x - r.x0) as usize]; + let k = fp.at(x, y) * wt; if k <= 0.0 { continue; } let px = work.px_mut(x, y); - if lab_color { - px[1] += (fg_ab[0] - px[1]) * k; - px[2] += (fg_ab[1] - px[2]) * k; - continue; - } - let c = to_rgba(&fmt, px); - let b = blend_rgb(mode, [c[0], c[1], c[2]], fg); - let o = [c[0] + (b[0] - c[0]) * k, c[1] + (b[1] - c[1]) * k, c[2] + (b[2] - c[2]) * k, c[3]]; - from_rgba_into(&fmt, o, &mut enc); + // With Anti-alias off the tip has a hard edge (#11917): a pixel it reaches takes + // the dab's full strength (its flow and pressure), not its partial coverage. A soft + // tip too, over the same reach as with Anti-alias on: the pixels its blended edge + // would change as stored, not its faint tail past them. + let k = if rs.anti_alias { + k + } else { + recolor(px, k, &mut enc); + if enc[..n].iter().zip(px.iter()).all(|(a, b)| stored(*a) == stored(*b)) { + continue; + } + fp.dab.alpha * wt + }; + recolor(px, k, &mut enc); px.copy_from_slice(&enc[..n]); } } } } +#[cfg(test)] +#[path = "replace_anti_alias_tests.rs"] +mod replace_anti_alias_tests; + #[cfg(test)] #[path = "replace_lab_tests.rs"] mod replace_lab_tests; @@ -244,7 +279,7 @@ mod tests { for mode in [ReplaceMode::Hue, ReplaceMode::Saturation, ReplaceMode::Color, ReplaceMode::Luminosity] { let mut s = setup(PixelFormat::RGBA32F); let rs = ReplaceSettings { mode, sampling: Sampling::Once, limits: Limits::Discontiguous, tolerance: 0.1, color: fg, ..Default::default() }; - apply_color_replacement(&mut s, &stroke(), &rs, None, false); + apply_color_replacement(&mut s, &stroke(), &rs, None, false).unwrap(); let c = s.rgba(20, 20); let green = [0.2, 0.6, 0.2]; match mode { @@ -273,12 +308,12 @@ mod tests { color: [1.0, 0.0, 0.0, 1.0], ..Default::default() }; - apply_color_replacement(&mut s, &stroke(), &rs, None, false); + apply_color_replacement(&mut s, &stroke(), &rs, None, false).unwrap(); assert!(s.rgba(20, 20)[0] > 0.3 && s.rgba(70, 20)[0] > s.rgba(70, 20)[1], "both halves recoloured {:?} {:?}", s.rgba(20, 20), s.rgba(70, 20)); // Background swatch = white: nothing matches. let mut s2 = setup(PixelFormat::RGBA8); let rs2 = ReplaceSettings { sampling: Sampling::BackgroundSwatch, background: [1.0; 4], ..rs }; - apply_color_replacement(&mut s2, &stroke(), &rs2, None, false); + apply_color_replacement(&mut s2, &stroke(), &rs2, None, false).unwrap(); assert_eq!(s2.rgba(20, 20), setup(PixelFormat::RGBA8).rgba(20, 20)); } @@ -300,7 +335,7 @@ mod tests { color: [1.0, 0.0, 0.0, 1.0], ..Default::default() }; - apply_color_replacement(&mut t, &st, &rs, None, false); + apply_color_replacement(&mut t, &st, &rs, None, false).unwrap(); let changed = (t.rgba(34, 20)[0] - 0.2).abs() > 0.05; assert_eq!(changed, island_changed, "{limits:?}"); assert!(t.rgba(20, 20)[0] > 0.3); diff --git a/crates/paint/src/replace_anti_alias_tests.rs b/crates/paint/src/replace_anti_alias_tests.rs new file mode 100644 index 0000000000..75c0f8d8e9 --- /dev/null +++ b/crates/paint/src/replace_anti_alias_tests.rs @@ -0,0 +1,140 @@ +//! #11917: with Anti-alias off the Color Replacement tip has a hard edge: every pixel under the tip +//! is fully replaced or untouched. With it on the edge stays blended, and at a colour boundary the +//! edge is hard either way. The setup is the issue's: red (220,30,30) with a white gap at y 140-160, +//! blue foreground, Color mode, Continuous, Contiguous, tolerance 30 %, an 80 px hard tip clicked at +//! 100,120. + +use photocraft_color::PixelFormat; + +use super::*; +use crate::{BrushSettings, StrokePoint}; + +fn target() -> Surface { + let fmt = PixelFormat::RGBA8; + let mut s = Surface::new(fmt); + s.fill_rect(Rect::new(0, 0, 200, 300), &photocraft_raster::from_rgba(&fmt, [220.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0, 1.0])); + s.fill_rect(Rect::new(0, 140, 200, 160), &photocraft_raster::from_rgba(&fmt, [1.0, 1.0, 1.0, 1.0])); + s +} + +fn click(anti_alias: bool) -> Surface { + click_at_flow(anti_alias, 1.0) +} + +fn click_at_flow(anti_alias: bool, flow: f32) -> Surface { + click_with(anti_alias, flow, 1.0) +} + +fn click_with(anti_alias: bool, flow: f32, hardness: f32) -> Surface { + let mut s = target(); + let stroke = Stroke { + brush: BrushSettings { size: 80.0, hardness, spacing: 0.25, flow, pressure_size: false, ..Default::default() }, + points: vec![StrokePoint::new(100.0, 120.0, 1.0)], + }; + let rs = ReplaceSettings { + mode: ReplaceMode::Color, + sampling: Sampling::Continuous, + limits: Limits::Contiguous, + tolerance: 0.3, + anti_alias, + color: [0.0, 0.0, 1.0, 1.0], + ..Default::default() + }; + apply_color_replacement(&mut s, &stroke, &rs, None, false).unwrap(); + s +} + +fn px(s: &Surface, x: i32, y: i32) -> [i32; 3] { + let c = s.rgba(x, y); + [0, 1, 2].map(|i| (c[i] * 255.0).round() as i32) +} + +const RED: [i32; 3] = [220, 30, 30]; + +/// Fully replaced: the Color blend of the red with the blue foreground. +fn full() -> [i32; 3] { + let mut s = target(); + let b = blend_rgb(BlendMode::Color, [220.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0], [0.0, 0.0, 1.0]); + s.fill_rect(Rect::new(0, 0, 1, 1), &photocraft_raster::from_rgba(&PixelFormat::RGBA8, [b[0], b[1], b[2], 1.0])); + px(&s, 0, 0) +} + +#[test] +fn anti_alias_off_has_a_hard_edge() { + let s = click(false); + let full = full(); + // Along the row through the centre, from outside the tip inwards: untouched, then fully + // replaced, nothing in between. + let row: Vec<[i32; 3]> = (50..70).map(|x| px(&s, x, 120)).collect(); + for (x, c) in (50..70).zip(&row) { + assert!(*c == RED || c.iter().zip(&full).all(|(a, b)| (a - b).abs() <= 3), "x {x}: {c:?} is neither untouched nor fully replaced ({full:?})"); + } + let first = (50..70).find(|x| px(&s, *x, 120) != RED).expect("the tip replaced the row"); + assert_eq!(first, 58, "the hard edge sits at the tip's rim"); + // The whole tip: no partly replaced pixel anywhere. + for y in 70..170 { + for x in 50..150 { + let c = px(&s, x, y); + // White only in the gap: a red pixel turned white would be wrong. + let white = (140..160).contains(&y) && c == [255, 255, 255]; + assert!(white || c == RED || c.iter().zip(&full).all(|(a, b)| (a - b).abs() <= 3), "{x},{y}: {c:?}"); + } + } +} + +#[test] +fn anti_alias_on_keeps_the_blended_edge() { + let s = click(true); + let full = full(); + let partial = (58..=60).map(|x| px(&s, x, 120)).filter(|c| *c != RED && c.iter().zip(&full).any(|(a, b)| (a - b).abs() > 3)).count(); + assert!(partial >= 1, "a blended ring at the rim"); +} + +#[test] +fn a_colour_boundary_stays_hard_either_way() { + for anti_alias in [false, true] { + let s = click(anti_alias); + let c = px(&s, 100, 139); + assert!(c.iter().zip(&full()).all(|(a, b)| (a - b).abs() <= 3), "y 139 fully replaced (anti-alias {anti_alias}): {c:?}"); + assert_eq!(px(&s, 100, 140), [255, 255, 255], "y 140 white (anti-alias {anti_alias})"); + } +} + +#[test] +fn anti_alias_off_keeps_the_brush_flow() { + // A 50 % flow dab replaces half way inside the tip whichever the setting, and with Anti-alias + // off its rim pixel takes that same strength rather than the full replacement. + let (on, off) = (click_at_flow(true, 0.5), click_at_flow(false, 0.5)); + let centre = px(&on, 100, 120); + assert!(centre != RED && centre != full(), "a half-strength dab: {centre:?}"); + assert_eq!(px(&off, 100, 120), centre, "the centre keeps the flow"); + assert_eq!(px(&off, 58, 120), centre, "the hard rim takes the dab's strength"); +} + +#[test] +fn a_soft_tip_with_anti_alias_off_replaces_fully_over_the_same_reach() { + // The issue's soft tips (hardness 0 % and 50 %): with Anti-alias off every pixel the tip reaches + // is fully replaced, over the same pixels as with it on; with it on the falloff stays. + let full = full(); + let is_full = |c: &[i32; 3]| c.iter().zip(&full).all(|(a, b)| (a - b).abs() <= 3); + for hardness in [0.0, 0.5] { + let (on, off) = (click_with(true, 1.0, hardness), click_with(false, 1.0, hardness)); + let mut partial_on = 0; + for y in 40..200 { + for x in 20..180 { + let (a, b) = (px(&on, x, y), px(&off, x, y)); + let gap = (140..160).contains(&y); + if gap { + assert_eq!((a, b), ([255, 255, 255], [255, 255, 255]), "{x},{y} hardness {hardness}: the gap stays white"); + continue; + } + assert!(b == RED || is_full(&b), "{x},{y} hardness {hardness}: {b:?} is partly replaced"); + assert_eq!(a != RED, b != RED, "{x},{y} hardness {hardness}: the reach differs (on {a:?}, off {b:?})"); + if a != RED && !is_full(&a) { + partial_on += 1; + } + } + } + assert!(partial_on > 0, "hardness {hardness}: Anti-alias on keeps the falloff"); + } +} diff --git a/crates/paint/src/replace_lab_tests.rs b/crates/paint/src/replace_lab_tests.rs index caf024fb40..47373611bc 100644 --- a/crates/paint/src/replace_lab_tests.rs +++ b/crates/paint/src/replace_lab_tests.rs @@ -33,7 +33,7 @@ fn click(s: &mut Surface, mode: ReplaceMode, x: f64) { points: vec![StrokePoint::new(x, 50.0, 1.0)], }; let rs = ReplaceSettings { mode, color: BLUE, ..Default::default() }; - apply_color_replacement(s, &stroke, &rs, None, false); + apply_color_replacement(s, &stroke, &rs, None, false).unwrap(); } /// The stored L (0..100) and a, b (-128..127) at a pixel. diff --git a/crates/paint/src/retouch.rs b/crates/paint/src/retouch.rs index 1494ba9994..9ab36bf2de 100644 --- a/crates/paint/src/retouch.rs +++ b/crates/paint/src/retouch.rs @@ -161,6 +161,10 @@ pub fn over_native(fmt: &PixelFormat, dst: &mut [f32], src: &[f32], k: f32, lock match alpha_index(fmt) { Some(a) => { let (da, sa) = (dst[a], src[a] * k); + // Zero-weight source-over must preserve even the native float channel bits. + if sa <= 0.0 { + return; + } if lock_transparency { // Alpha kept: source atop, the colour moves by the source alpha alone (#5783). for c in 0..a { @@ -235,6 +239,11 @@ pub fn apply_coverage( if blend == BlendMode::Normal { over_native(&fmt, px, src, k, lock_transparency); } else { + // A transparent source cannot paint. Skip it before an RGB round trip changes + // untouched native CMYK/Lab values; Normal handles zero weight in over_native. + if a.and_then(|a| src.get(a)).is_some_and(|alpha| *alpha <= 0.0) { + continue; + } let d = to_rgba(&fmt, px); let s = to_rgba(&fmt, src); let o = @@ -253,7 +262,8 @@ pub fn apply_coverage( /// /// The working copy covers the stroke bounds grown by `halo` pixels so neighbourhood effects (blur, /// sharpen) can read around each dab; only the stroke bounds are written back. With -/// `lock_transparency`, alpha is preserved. Returns the damaged rectangle. +/// `lock_transparency`, alpha is preserved. Returns the damaged rectangle, or [`StrokeTooLarge`] +/// when the working copy would not fit the budget (nothing is painted). pub fn apply_dab_stroke( target: &mut Surface, stroke: &Stroke, @@ -261,21 +271,50 @@ pub fn apply_dab_stroke( lock_transparency: bool, halo: i32, mut effect: impl FnMut(&mut Region, &Footprint), -) -> Rect { +) -> Result { let ds = dabs(stroke); if ds.is_empty() { - return Rect::EMPTY; + return Ok(Rect::EMPTY); } let ctx = crate::BrushContext::new(&stroke.brush); let bounds = ds.iter().fold(Rect::EMPTY, |r, d| r.union(&ctx.dab_rect(d, false))); let outer = Rect::new(bounds.x0 - halo, bounds.y0 - halo, bounds.x1 + halo, bounds.y1 + halo); + // The working copy is dense over the whole stroke rectangle, so two distant dabs ask for the + // area between them. Refuse before reading it. + if !fits_dab_stroke_budget(outer, target.channels()) { + return Err(StrokeTooLarge); + } let orig = Region::read(target, outer); let mut work = orig.clone(); for (i, d) in ds.iter().enumerate() { effect(&mut work, &ctx.footprint(d, i)); } mix_back(target, &orig, &work, bounds, stroke.brush.opacity, selection, lock_transparency); - bounds + Ok(bounds) +} + +/// A sequential-dab stroke whose dense working copy would exceed the memory budget. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct StrokeTooLarge; + +impl std::fmt::Display for StrokeTooLarge { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("stroke too large") + } +} + +impl std::error::Error for StrokeTooLarge {} + +/// Bytes a sequential-dab stroke's dense buffers may take: the original and working copies over the +/// grown stroke rectangle and the mixed result, `f32` samples. +const MAX_DAB_STROKE_BYTES: u64 = if cfg!(target_pointer_width = "64") { 4 << 30 } else { 1 << 30 }; + +/// Whether [`apply_dab_stroke`]'s three `channels`-deep planes over `outer` fit [`MAX_DAB_STROKE_BYTES`]. +fn fits_dab_stroke_budget(outer: Rect, channels: usize) -> bool { + (outer.width() as u64) + .checked_mul(outer.height() as u64) + .and_then(|px| px.checked_mul(channels as u64)?.checked_mul(3 * size_of::() as u64)) + .is_some_and(|b| b <= MAX_DAB_STROKE_BYTES) } /// Mix a sequential-dab stroke's working pixels `work` back over the original `orig` at @@ -604,6 +643,38 @@ mod tests { } } + /// Missing source pixels must preserve native ink values even for non-Normal blend modes. + #[test] + fn transparent_retouch_source_preserves_native_channels_in_every_blend_mode() { + use photocraft_color::{ColorMode, SampleType}; + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] { + let fmt = PixelFormat::new(mode, sample, true); + for blend in std::iter::once(BlendMode::PassThrough).chain(BlendMode::layer_modes()) { + let mut target = Surface::with_default(fmt, &vec![0.3; fmt.channels()]); + let rect = Rect::new(0, 0, 2, 2); + let before = target.read_region(rect); + let paint = Region::new(rect, fmt.channels()); + apply_coverage(&mut target, rect, &[1.0; 4], 1.0, None, false, &paint, blend); + assert_eq!(target.read_region(rect), before, "{fmt:?}, {blend:?}"); + } + } + } + } + + #[test] + fn a_dab_stroke_between_distant_points_is_refused_before_reading() { + assert!(fits_dab_stroke_budget(Rect::new(0, 0, 4096, 4096), 4)); + assert!(!fits_dab_stroke_budget(Rect::new(0, 0, 300_000, 300_000), 1)); + assert!(!fits_dab_stroke_budget(Rect::new(i32::MIN, i32::MIN, i32::MAX, i32::MAX), usize::MAX)); + // Two small dabs 40000 px apart on both axes: a 1.6 Gpx working rectangle. + let mut s = Surface::new(PixelFormat::GRAY8); + let st = stroke(&[(0.0, 0.0), (40_000.0, 40_000.0)], 6.0, 1.0); + let mut called = false; + assert_eq!(apply_dab_stroke(&mut s, &st, None, false, 2, |_, _| called = true), Err(StrokeTooLarge)); + assert!(!called); + } + #[test] fn dab_stroke_runs_sequentially_and_respects_selection() { let mut s = Surface::new(PixelFormat::GRAY8); @@ -620,7 +691,8 @@ mod tests { } } } - }); + }) + .unwrap(); assert!(seen.windows(2).all(|w| w[1] == w[0] + 1)); assert!(s.pixel(20, 10)[0] > 0.1, "dabs accumulate"); assert_eq!(s.pixel(40, 10)[0], 0.0, "outside the selection untouched"); @@ -634,7 +706,7 @@ mod tests { s.fill_rect(Rect::new(0, 0, 30, 40), &[1.0, 0.0, 0.0, 1.0]); let st = stroke(&[(20.0, 20.0), (70.0, 20.0)], 12.0, 1.0); let mut sm = Smudge::new(0.8, None, 12.0); - apply_dab_stroke(&mut s, &st, None, false, 0, |w, fp| sm.dab(w, fp)); + apply_dab_stroke(&mut s, &st, None, false, 0, |w, fp| sm.dab(w, fp)).unwrap(); // Red dragged to the right of the edge, fading with distance. let g = |x| s.pixel(x, 20)[1]; assert!(g(35) < 0.5, "{fmt:?} {}", g(35)); @@ -644,7 +716,7 @@ mod tests { let mut s2 = Surface::new(fmt); s2.fill_rect(Rect::new(0, 0, 100, 40), &[1.0, 1.0, 1.0, 1.0]); let mut fg = Smudge::new(0.8, Some(vec![0.0, 0.0, 1.0, 1.0]), 12.0); - apply_dab_stroke(&mut s2, &st, None, false, 0, |w, fp| fg.dab(w, fp)); + apply_dab_stroke(&mut s2, &st, None, false, 0, |w, fp| fg.dab(w, fp)).unwrap(); assert!(s2.pixel(22, 20)[0] < 0.5); } } @@ -657,7 +729,7 @@ mod tests { s.fill_rect(Rect::new(0, 0, 30, 40), &[1.0, 0.8, 0.0, 1.0]); let st = stroke(&[(20.0, 20.0), (70.0, 20.0)], 12.0, 0.5); let mut sm = Smudge::new(0.8, None, 12.0).with_alpha(Some(3)); - apply_dab_stroke(&mut s, &st, None, false, 0, |w, fp| sm.dab(w, fp)); + apply_dab_stroke(&mut s, &st, None, false, 0, |w, fp| sm.dab(w, fp)).unwrap(); let mut smudged = 0; for x in 30..80 { for y in 14..27 { @@ -675,7 +747,7 @@ mod tests { let mut st = st.clone(); st.brush.opacity = 0.5; let mut sm = Smudge::new(0.8, None, 12.0).with_alpha(Some(3)); - apply_dab_stroke(&mut s, &st, None, false, 0, |w, fp| sm.dab(w, fp)); + apply_dab_stroke(&mut s, &st, None, false, 0, |w, fp| sm.dab(w, fp)).unwrap(); let p = s.rgba(34, 20); assert!(p[3] > 0.02 && p[0] > 0.97, "{fmt:?}: {p:?}"); } @@ -694,7 +766,8 @@ mod tests { sm.dab(&mut empty, fp); assert!(empty.data.is_empty() && sm.carry.is_none(), "no carry is built for zero channels"); calls += 1; - }); + }) + .unwrap(); assert!(calls > 0); } @@ -813,8 +886,8 @@ mod tests { let mut b = a.clone(); let mut sm_a = Smudge::new(0.7, finger.clone(), 14.0).with_alpha(alpha); let mut sm_b = sm_a.clone(); - apply_dab_stroke(&mut a, &st, None, false, 0, |w, fp| sm_a.dab(w, fp)); - apply_dab_stroke(&mut b, &st, None, false, 0, |w, fp| reference_dab(&mut sm_b, w, fp)); + apply_dab_stroke(&mut a, &st, None, false, 0, |w, fp| sm_a.dab(w, fp)).unwrap(); + apply_dab_stroke(&mut b, &st, None, false, 0, |w, fp| reference_dab(&mut sm_b, w, fp)).unwrap(); let rect = Rect::new(-20, -20, 120, 90); assert_eq!(a.read_region(rect), b.read_region(rect), "{fmt:?} finger {} {path:?}", finger.is_some()); assert_eq!(sm_a.carry, sm_b.carry, "{fmt:?} carry"); @@ -851,7 +924,7 @@ mod tests { } } }; - let bounds = apply_dab_stroke(&mut got, &st, Some(&sel), false, 0, effect); + let bounds = apply_dab_stroke(&mut got, &st, Some(&sel), false, 0, effect).unwrap(); let orig = Region::read(&want, bounds); let mut work = orig.clone(); let ctx = crate::BrushContext::new(&st.brush); diff --git a/crates/plugins/examples/wat2wasm.rs b/crates/plugins/examples/wat2wasm.rs index e72ee1d13e..dc36cc798a 100644 --- a/crates/plugins/examples/wat2wasm.rs +++ b/crates/plugins/examples/wat2wasm.rs @@ -17,9 +17,15 @@ fn main() { } }; match Plugin::load(&bytes, Limits::default()) { - Ok(p) => println!("{} ({}): {} bytes, params {}", p.manifest().name, p.id(), bytes.len(), p.manifest().params_notation()), + Ok(p) => println!( + "{} ({}): {} bytes, params {}", + p.manifest().name.escape_debug(), + p.id().escape_debug(), + bytes.len(), + p.manifest().params_notation().escape_debug() + ), Err(e) => { - eprintln!("not a valid plug-in: {e}"); + eprintln!("not a valid plug-in: {}", e.to_string().escape_debug()); std::process::exit(1); } } diff --git a/crates/psd/Cargo.toml b/crates/psd/Cargo.toml deleted file mode 100644 index 7ecce9ee67..0000000000 --- a/crates/psd/Cargo.toml +++ /dev/null @@ -1,31 +0,0 @@ -[package] -name = "photocraft-psd" -description = "Faithful, lossless reader and writer for Adobe Photoshop PSD (v1) and PSB (v2) files" -version.workspace = true -edition.workspace = true -license.workspace = true -rust-version.workspace = true - -[lib] -name = "photocraft_psd" -path = "src/lib.rs" - -[features] -# Real-file corpus tests (opt-in; `cargo xtask test-corpus`). Fail when the corpus is missing. -corpus = [] -default = [] -serde = ["dep:serde"] -testgen = [] - -[dependencies] -thiserror = { workspace = true } -flate2 = { workspace = true } -encoding_rs = { workspace = true } -serde = { workspace = true, optional = true } - -[dev-dependencies] -proptest = { workspace = true } -photocraft-psd = { path = ".", features = ["testgen"] } - -[lints] -workspace = true diff --git a/crates/psd/README.md b/crates/psd/README.md deleted file mode 100644 index 1f6c892af5..0000000000 --- a/crates/psd/README.md +++ /dev/null @@ -1,200 +0,0 @@ -# photocraft-psd - -A standalone reader and writer for Adobe Photoshop **PSD** (version 1) and **PSB** (version 2, "large document format") files. It keeps everything it reads, so an unmodified file writes back byte for byte. It depends on no other photocraft crate. - -* Clean-room implementation from Adobe's public *Photoshop File Formats Specification*. Where the spec is silent, behavior follows MIT-licensed psd-tools / ag-psd documentation, and the code comments say so. -* `#![forbid(unsafe_code)]`. Builds for `wasm32-unknown-unknown`. The core API works on byte slices; the file helpers only exist on native targets. -* Parsing never panics on malformed input. Limits: dimensions ≤ 300 000; allocations are checked against the remaining input; a single decode produces at most `MAX_DECODED_BYTES` (8 GiB on 64-bit targets, 2 GiB on 32-bit targets); descriptor nesting depth ≤ 64. - -## Guarantees - -| Property | How | -|---|---| -| `PsdFile::from_bytes(b)?.to_bytes()? == b` for unmodified files | Channel data keeps its original encoding. Unknown blocks and resources are stored raw. Exact padding is recorded wherever it can vary: tagged blocks, layer info, section trailers. | -| `from_bytes(to_bytes(f)) == f` for any model `f` | Canonical defaults: `padding: None` means "zero-pad to even", and the parser yields `None` whenever the file used that default. | -| Lazy decoding | The parser only copies encoded bytes. Channels are decoded when asked (`ChannelData::decode`, `ImageData::decode`). | -| Lazy reading | `PsdFile::from_source` reads only the structure. Channel data and the merged image stay in the source as `Stored` ranges and are read when decoded, so opening a 2 GB file doesn't need 2 GB for the file itself. The model equals what `from_bytes` builds, and it writes back the same bytes. | -| No compositing | `PsdBuilder` takes the merged image from the caller. Without one, it writes a white placeholder and sets `has_real_merged_data = false` in resource 1057. | - -## Public API (overview) - -```rust -// Top level -PsdFile::from_bytes(&[u8]) -> Result -PsdFile::from_bytes_and_merged(&[u8], want) -> Result<(PsdFile, Option>>)> - // + decode_merged() when want(&file): ZIP inflated once -PsdFile::from_source(Source) -> Result // channel data and merged image left in the source -PsdFile::from_source_and_merged_recovering(Source, want, recover) -PsdFile::to_bytes(&self) -> Result> -PsdFile::open(path) / save(path) // native only -PsdFile { header, color_mode_data, resources, layer_info, layer_info_placement, - global_layer_mask, global_blocks, layer_mask_trailing, image_data } -PsdFile::layers() -> &[LayerRecord] // file order = bottom-most first -PsdFile::layers_mut() -> &mut Vec -PsdFile::layer(i) -> Option>; iter_layers() -PsdFile::layer_tree() -> Vec // nested groups, children bottom-to-top -PsdFile::layer_tree_max_depth(n) -> Vec // same, groups nested n deep keep no children -PsdFile::decode_merged() -> Result> // planar big-endian samples -PsdFile::composite_rgba8() -> Result -PsdFile::resource(id), global_block(key), icc_profile(), resolution(), - has_real_merged_data(), merged_has_alpha(), validate() - -// Sources (lazy reading) -trait ReadAt { len(), read_at(offset, buf) } // [u8], Vec, Arc, FileSource (pread / seek_read) -Source::new(impl ReadAt) / read_vec(offset, len) // shared handle; equal when the same source -Stored { source, offset, len }::read() / read_part(at, len) - -// Header -Header { version: Version::{Psd,Psb}, channels, width, height, depth, color_mode, reserved } -ColorMode::{Bitmap, Grayscale, Indexed, Rgb, Cmyk, Multichannel, Duotone, Lab, Unknown(u16)} - -// Layers -LayerInfo { merged_alpha, layers: Vec, padding } -LayerRecord { rect, channels: Vec, blend_mode, opacity, clipping, flags, - filler, mask: MaskData, blending_ranges, name, blocks, extra_trailing } -LayerRecord::name() // prefers `luni` -LayerRecord::section_divider(), section_type(), layer_id(), fill_opacity(), is_visible(), - block(key), block_mut(key), channel(id), channel_rect(id), decode_channel(id, depth, version) -ChannelData { id, compression: Option, data, stored: Option } // encoded bytes kept verbatim -ChannelData::new(id, compression, data); encoded() -> Cow<[u8]>; encoded_len(); load() -ChannelData::encode(id, compression, decoded, w, h, depth, version) -ChannelData::decode(w, h, depth, version); set_decoded(...) -MaskData::{None, Mask(LayerMask), Raw(Vec)} -LayerMask { rect, default_color, flags, parameters: Option, real: Option, trailing, real_first } -BlendMode (27 modes + PassThrough + Unknown([u8;4])); BlendMode::key()/from_key() -Layer<'_>::rgba8() -> Result; user_mask() -> Option>; channel_bytes(id) - -// Tagged blocks -TaggedBlock { signature /* 8BIM | 8B64 */, key, data, padding: Option> } -TaggedBlock::parsed() -> Option> -BlockData::{UnicodeName, SectionDivider, LayerId, NameSource, BlendClippedAsGroup, - BlendInteriorElements, Knockout, Protection, SheetColor, FillOpacity, MetadataSetting} -constructors: unicode_name, section_divider, layer_id, name_source, blend_clipped_as_group, - blend_interior_elements, knockout, protection, sheet_color, fill_opacity -TaggedBlock::check_structure() -> Result<()> // strict inner re-parse of PlLd, SoLd, SoLE, lnk2/3/D, lfx2 -tagged::uses_long_length(version, key) // PSB 8-byte length keys (the spec's 13 + lnk3, lnkE, pths, extd, extn, FELS, cinf, artd) -LayerInfo::unpadded_len(version), LayerInfo::pad_to(version, 4) // Photoshop pads the layer info to 4 - -// Image resources -ImageResource { signature, id, name, data }; ImageResource::parsed() -> Option> -ResourceData::{ResolutionInfo, LayerState, LayerGroupInfo, Thumbnail, GlobalAngle, IccProfile, - GlobalAltitude, VersionInfo, Exif, Xmp, TimelineInfo, Animation} - -// Legacy animation syntax (no playback/document-model dependency) -animation::AnimationResource::from_bytes / to_bytes // maniIRFR; ordered raw records -animation::AnimationRecord::descriptor() // AnDs; version-16 descriptor -animation::{frame_info, frame_sets, layer_frame_states} // borrowed sparse views, opaque ids -animation::parse_descriptor // descriptor + up to 3 zero alignment bytes -metadata::MetadataItem::animation_descriptor() // mlst / tmln; leaves other metadata alone - -// Compression -Compression::{Raw, Rle, Zip, ZipPrediction, Unknown(u16)} -compression::{encode_planes, decode_planes, PlaneLayout, packbits::{encode, decode}, predict, unpredict} -pixels::{samples_u16, samples_f32, u16_to_bytes, f32_to_bytes, unpack_bits, plane_to_u8} - -// Descriptors -descriptor::{Descriptor, VersionedDescriptor, Value, Id, Class, ReferenceItem, UnicodeString, ObjectArray} -Descriptor::from_bytes / to_bytes; VersionedDescriptor::from_bytes / to_bytes (version 16) - -// Builder -PsdBuilder::new(w, h).color_mode(..).depth(8|16).version(..).compression(..).resolution(dpi).icc_profile(..) -builder.push_layer(LayerSpec) / begin_group(GroupSpec) / end_group()? / composite(PixelData) -builder.build() -> Result; builder.to_bytes() -PixelData::{Rgba8, Rgba16, GrayA8, GrayA16, Cmyka8, Cmyka16} // CMYK given as ink, stored inverted - -// Test generator (feature `testgen`) -testgen::{all_cases, merged_only, layered, small, sample_descriptor, pattern_plane} -``` - -## Feature matrix - -| Area | Read | Write | Typed | Notes | -|---|:-:|:-:|:-:|---| -| Header, PSD v1 / PSB v2 | ✓ | ✓ | ✓ | depth 1/8/16/32; all 8 color modes plus `Unknown` | -| Color mode data | ✓ | ✓ | raw | indexed palette is used by `composite_rgba8` | -| Image resources | ✓ | ✓ | partial | 1005, 1024, 1026, 1033/1036 (raw), 1037, 1039, 1049, 1057, 1058, 1060 | -| Layer records | ✓ | ✓ | ✓ | flags, clipping, filler, blending ranges (raw + accessor) | -| Layer masks | ✓ | ✓ | ✓ | 20 / 36-byte forms, mask parameters, real mask; unparseable masks stay raw | -| Channel ids -1 / -2 / -3 | ✓ | ✓ | ✓ | per-channel rect via `channel_rect` | -| Raw / RLE / ZIP / ZIP+prediction | ✓ | ✓ | – | prediction at 8/16/32 bits (32: byte-plane shuffle + delta); RLE counts are u16 in PSD, u32 in PSB | -| Merged image data | ✓ | ✓ | – | validated at parse time (sizes, RLE counts, zlib stream incl. checksum); a zlib stream declaring more than `MAX_DECODED_BYTES` is kept verbatim without inflating it, and decoding it reports the limit | -| Tagged blocks (raw passthrough) | ✓ | ✓ | – | keeps `8BIM` / `8B64` and exact padding | -| PSB 8-byte-length keys | ✓ | ✓ | – | LMsk Lr16 Lr32 Layr Mt16 Mt32 Mtrn Alph FMsk lnk2 FEid FXid PxSD | -| Lr16 / Lr32 / Layr layer info | ✓ | ✓ | ✓ | lifted into `layer_info`; re-inserted at its original position | -| luni lsct lsdk lyid lnsr clbl infx knko lspf lclr iOpa shmd | ✓ | ✓ | ✓ | `TaggedBlock::parsed()` | -| Layer XMP (`shmd` › `cust` › `layerXMP`) | ✓ | ✓ | ✓ | `metadata::layer_xmp` / `take_layer_xmp` / `put_layer_xmp`, laid out as Photoshop 2026 writes it | -| ActionDescriptor (all OSTypes) | ✓ | ✓ | ✓ | including references, `ObAr` (best effort), `UnFl`, `Pth `, version-16 wrapper | -| Legacy frame animation syntax | ✓ | ✓ | partial | `mani` / `AnDs`, `mlst`, `tmln`, resource 1075; raw-preserving descriptor views, not playback or keyframe evaluation | -| Layer tree (groups) | ✓ | ✓ | ✓ | open/closed folders plus bounding dividers; tolerant of malformed nesting | -| RGBA8 extraction | ✓ | – | – | RGB / gray / CMYK layers; merged image also supports indexed / bitmap / duotone | -| Builder | – | ✓ | – | RGB / gray / CMYK at 8/16 bit, masks, groups, blend modes, opacity, fill, visibility, clipping | -| Patterns | ✓ | ✓ | ✓ | `Patt` / `Pat2` / `Pat3`, `.pat`, and `.abr` embedded patterns; non-empty tiles allow in-bounds channel subrectangles, decoded size is capped and PackBits expansion is input-bounded | -| Actions (`.atn`) | ✓ | ✓ | ✓ | `atn::parse` / `atn::write`: version-16 sets (Photoshop 6+): actions with function key, modifiers and colour; steps with event code or string name, panel name, enabled/dialog flags and their descriptor. Exact round trip; version-12 (Photoshop 5) files are rejected as unsupported | - -Pattern channel subrectangles are padded with zeroes to the tile rectangle. All channel -metadata is checked before any plane is decoded, against one `PatternBudget` shared by every -pattern of a parse (a block, a `.pat` file): `MAX_DECODED_BYTES` decoded and 512 MiB of zero -padding in total. `parse_pattern_block_with` lets several blocks of one document share a budget; -`.abr` patterns are charged to the file's sample budget. All channels of a pattern must have the -same depth. Fully populated channels reuse their decoded buffer without a second copy; -allocations for padded channels return an error on failure. - -### Preserved raw, not yet typed (parsers planned for M8) - -* Layer effects: `lfx2`, `lrFX`, `lmfx`. The descriptors inside can be parsed on demand with `VersionedDescriptor::from_bytes(&block.data[4..])`. -* Type layers: `TySh`, `tySh`, and the EngineData inside them. -* Smart objects: `SoLd`, `PlLd`, `SoLE`, `lnk2`, `lnkD`, `lnk3`. -* Vector masks and shapes: `vmsk`, `vsms`, `vogk`, `vscg`. -* Adjustment and fill layers: `curv`, `levl`, `hue2`, `SoCo`, `GdFl`, `PtFl`, …, plus `Patt`, `Txt2`, `FMsk`, 3D and video blocks. -* Global layer mask info (raw, with accessors), thumbnails (raw), slices, guides, paths, and every other resource id. - -## Legacy animation inspection - -```sh -cargo run -p photocraft-psd --example animation_inspect -- /path/to/input.psd -cargo test -p photocraft-psd --test it animation:: -``` - -The inspection example accepts an explicit local PSD/PSB (up to 128 MiB), reports frame counts, -stored delays and descriptor counts, and checks byte-exact raw round-trips without modifying the -input. It does not print layer names, text or descriptor values. No personal file is bundled; -committed animation tests construct synthetic payloads and PSD/PSB containers. - -`mani` is detected by its payload signature within the plug-in resource range 4000–4999, not by -assuming that resource 4003 always belongs to animation. Unknown records and unsupported descriptor -versions stay raw. `FrIn` definitions and `FSts` playback order are separate; ids are opaque stored -`long` values. Missing frame delays remain absent, and sparse `mlst` properties are not filled with -guessed defaults. Timeline tracks, loops, inheritance and property evaluation are left to higher -layers. This parser alone does **not** make PSD animations play in PhotoCraft. - -## Testing - -`cargo test -p photocraft-psd --all-features` runs the unit tests, integration tests and proptests: - -* Byte stability and model round-trips for every generated case: all depths, color modes and compressions, PSD and PSB. -* PackBits edge cases. -* Known vectors for 8/16/32-bit prediction. -* PSD vs PSB length handling. -* Truncation sweeps: every prefix of several small files must return `Err`. -* Random-mutation and random-byte proptests: never panic. -* Layer tree cases. -* Builder → `rgba8` correctness. -* Unknown blend modes and unknown blocks pass through unchanged. - -`tests/it/corpus.rs` walks `corpus/psd/**/*.{psd,psb}` at the workspace root when that directory exists. For each file it asserts that parsing succeeds and the file round-trips byte for byte, and it prints a result per file. Without the directory it skips silently. - -A `cargo-fuzz` skeleton lives in `fuzz/`. It is its own workspace and is excluded from photocraft's. Run it with `cargo +nightly fuzz run parse` (or `descriptor`) from `crates/psd`. - -## Spec ambiguities and decisions - -* **Tagged block padding.** The spec says lengths are "rounded up to an even byte count". In practice writers either include the padding in the length or append it after the data, and pad to 2 or 4. The parser detects the padding that actually follows each block: the smallest k ≤ 3 after which the next signature or the end of the region appears. It stores that padding unless it matches the default. -* **Layer info padding** (2 vs 4) is recorded the same way. -* **16/32-bit layers** are read from global `Lr16` / `Lr32` blocks when the main layer info is empty. The block data is a layer-info body with no inner length field. -* **Mask record layout.** The order is: rect, default color, flags, parameters (when flag bit 4 is set), then the real flags, background and rect whenever at least 18 bytes remain. Anything left over (for example the 2 padding bytes of the 20-byte form) is kept in `trailing`. -* **Mask channel rects.** Channel -2 uses the mask rect. Channel -3 uses the real mask rect. -* **Merged ZIP data** is a single zlib stream over all planes. Prediction is applied per row across all planes. -* **ZIP prediction at depth 1** is treated as byte-wise delta. -* **`ObAr`** is read as a u32 prefix followed by a descriptor-shaped body, following ag-psd's reading. The spec does not document it. -* **Descriptor `bool`** bytes other than 0/1 are normalized to 1 on write. -* **Pascal names** have their pad bytes written as zeros. A layer & mask section that contains only a zero layer-info length is normalized to an empty section. These are the only known non-byte-exact cases, and both are pathological. -* **Header limits.** The parser accepts up to 300 000 × 300 000 for both versions. `PsdFile::validate()` enforces the spec's 30 000 limit for PSD. diff --git a/crates/psd/examples/animation_inspect.rs b/crates/psd/examples/animation_inspect.rs deleted file mode 100644 index 2b3f7391dc..0000000000 --- a/crates/psd/examples/animation_inspect.rs +++ /dev/null @@ -1,103 +0,0 @@ -//! Inspect a local PSD/PSB's animation structure without printing layer names, text, or metadata -//! values. No asset is bundled: pass a path explicitly. Does not decode pixels or modify the file. -//! `cargo run -p photocraft-psd --example animation_inspect -- /path/to/input.psd` - -#[cfg(not(target_arch = "wasm32"))] -fn inspect() -> Result<(), Box> { - use std::collections::BTreeMap; - use std::io::Read; - - use photocraft_psd::animation::{frame_info, frame_sets, layer_frame_states}; - use photocraft_psd::metadata::parse_shmd; - use photocraft_psd::{PsdFile, ResourceData}; - - let mut args = std::env::args_os().skip(1); - let path = args.next().ok_or("usage: animation_inspect ")?; - if args.next().is_some() { - return Err("expected exactly one input path".into()); - } - // Diagnostic tool, not the production large-file importer. Bound even a file growing while read. - const MAX_BYTES: u64 = 128 * 1024 * 1024; - let file = std::fs::File::open(path)?; - if !file.metadata()?.is_file() || file.metadata()?.len() > MAX_BYTES { - return Err("expected a regular PSD/PSB no larger than 128 MiB".into()); - } - let mut bytes = Vec::new(); - file.take(MAX_BYTES + 1).read_to_end(&mut bytes)?; - if bytes.len() as u64 > MAX_BYTES { - return Err("input exceeds the diagnostic tool's 128 MiB limit".into()); - } - let psd = PsdFile::from_bytes(&bytes)?; - println!("canvas={}x{} depth={} layers={}", psd.header.width, psd.header.height, psd.header.depth, psd.layers().len()); - let mut animations = 0; - for resource in &psd.resources { - match resource.parsed() { - Some(Ok(ResourceData::Animation(animation))) => { - animations += 1; - let back = animation.to_bytes()?; - if back != resource.data { - return Err("animation resource failed its byte-exact round trip".into()); - } - println!("animation resource: {} records; byte-exact round trip", animation.records.len()); - for record in &animation.records { - if let Some(d) = record.descriptor() { - let d = d?; - let frames = frame_info(&d.descriptor)?; - let sets = frame_sets(&d.descriptor)?; - let mut delays = BTreeMap::new(); - for frame in &frames { - *delays.entry(frame.delay_centiseconds).or_insert(0usize) += 1; - } - println!(" AnDs: {} definitions, {} frame sets", frames.len(), sets.len()); - println!(" stored delays (centiseconds -> frame count): {delays:?}"); - for set in sets { - let unresolved = set.frame_ids.iter().filter(|id| !frames.iter().any(|f| f.id == **id)).count(); - println!(" frame set: {} ordered references, {unresolved} unresolved", set.frame_ids.len()); - } - } - } - } - Some(Ok(ResourceData::TimelineInfo(d))) => println!("document timeline: {} descriptor fields", d.descriptor.items.len()), - Some(Err(e)) if resource.id == 1075 || (4000..=4999).contains(&resource.id) && resource.data.starts_with(b"mani") => return Err(e.into()), - _ => {} - } - } - let (mut states, mut tracks) = (0usize, 0usize); - for layer in psd.layers() { - for block in &layer.blocks { - if block.key != *b"shmd" { - continue; - } - let items = parse_shmd(&block.data)?; - for item in &items { - if let Some(d) = item.animation_descriptor() { - let d = d?; - if item.key == *b"mlst" { - layer_frame_states(&d.descriptor)?; - states += 1; - } else { - tracks += 1; - } - } - } - if photocraft_psd::metadata::write_shmd(&items) != block.data { - return Err("layer metadata failed its byte-exact round trip".into()); - } - } - } - if psd.to_bytes()? != bytes { - return Err("PSD/PSB failed its byte-exact round trip".into()); - } - println!("animation resources={animations}; layer frame-state descriptors={states}; layer timeline descriptors={tracks}"); - println!("whole PSD/PSB: byte-exact round trip; input unchanged"); - Ok(()) -} - -fn main() -> std::process::ExitCode { - #[cfg(not(target_arch = "wasm32"))] - if let Err(e) = inspect() { - eprintln!("animation inspection failed: {e}"); - return std::process::ExitCode::FAILURE; - } - std::process::ExitCode::SUCCESS -} diff --git a/crates/psd/examples/atn_dump.rs b/crates/psd/examples/atn_dump.rs deleted file mode 100644 index bd341c7b00..0000000000 --- a/crates/psd/examples/atn_dump.rs +++ /dev/null @@ -1,85 +0,0 @@ -//! Print the actions and steps of `.atn` files, one event per line, with the top-level keys of -//! each step's descriptor: `cargo run -p photocraft-psd --example atn_dump -- set.atn…` -//! -//! Handy when adding a Photoshop event to the engine's `.atn` import table: it shows the event -//! id, the panel name and the parameter keys Photoshop recorded. - -use photocraft_psd::atn; -use photocraft_psd::descriptor::{Descriptor, ReferenceItem, Value}; - -fn summary(v: &Value) -> String { - match v { - Value::Integer(i) => i.to_string(), - Value::Double(d) => format!("{d}"), - Value::UnitFloat { unit, value } => format!("{value}{}", String::from_utf8_lossy(unit)), - Value::Boolean(b) => b.to_string(), - Value::Text(t) => format!("{:?}", t.to_string_lossy()), - Value::Enumerated { type_id, value } => format!("{}.{}", String::from_utf8_lossy(type_id.as_bytes()), String::from_utf8_lossy(value.as_bytes())), - Value::Descriptor(d) | Value::GlobalObject(d) => format!("{{{}}}", keys(d)), - Value::List(l) => format!("[{}]", l.iter().map(summary).collect::>().join(", ")), - Value::Reference(r) => format!("ref[{}]", r.iter().map(reference).collect::>().join(" ")), - other => format!("{other:?}").chars().take(40).collect(), - } -} - -fn id(i: &photocraft_psd::descriptor::Id) -> String { - String::from_utf8_lossy(i.as_bytes()).trim().to_string() -} - -fn reference(item: &ReferenceItem) -> String { - match item { - ReferenceItem::Property { class, key } => format!("prop({},{})", id(&class.class_id), id(key)), - ReferenceItem::Class(c) => format!("Clss({})", id(&c.class_id)), - ReferenceItem::Enumerated { class, type_id, value } => format!("Enmr({},{}.{})", id(&class.class_id), id(type_id), id(value)), - ReferenceItem::Offset { class, offset } => format!("rele({},{offset})", id(&class.class_id)), - ReferenceItem::Identifier { class, id: v } => format!("Idnt({},{v})", id(&class.class_id)), - ReferenceItem::Index { class, index } => format!("indx({},{index})", id(&class.class_id)), - ReferenceItem::Name { class, name } => format!("name({},{:?})", id(&class.class_id), name.to_string_lossy()), - } -} - -fn keys(d: &Descriptor) -> String { - d.items.iter().map(|(k, v)| format!("{}={}", String::from_utf8_lossy(k.as_bytes()), summary(v))).collect::>().join(" ") -} - -fn main() { - let mut failed = false; - for path in std::env::args().skip(1) { - let bytes = match std::fs::read(&path) { - Ok(b) => b, - Err(e) => { - eprintln!("{path}: {e}"); - failed = true; - continue; - } - }; - match atn::parse(&bytes) { - Ok(f) => { - println!( - "== {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 { - println!(" action {:?} ({} steps)", a.name.to_string_lossy(), a.items.len()); - 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(), f.item_label(item), keys(d)), - None => println!(" {:<22} {:<28}{flags}", item.event.id(), f.item_label(item)), - } - } - } - } - Err(e) => { - println!("== {path}: {e}"); - failed = true; - } - } - } - if failed { - std::process::exit(1); - } -} diff --git a/crates/psd/examples/atn_roundtrip.rs b/crates/psd/examples/atn_roundtrip.rs deleted file mode 100644 index b73151b745..0000000000 --- a/crates/psd/examples/atn_roundtrip.rs +++ /dev/null @@ -1,54 +0,0 @@ -//! Check `.atn` files for byte-exact round trips: parse, write, compare, and show the first -//! difference with its context: `cargo run -p photocraft-psd --example atn_roundtrip -- set.atn…` -//! -//! Exit status 1 when any file differs or fails to parse. - -use photocraft_psd::atn; - -fn hex(b: &[u8]) -> String { - b.iter().map(|x| format!("{x:02x}")).collect::>().join(" ") -} - -fn main() { - let mut failed = false; - for path in std::env::args().skip(1) { - let bytes = match std::fs::read(&path) { - Ok(b) => b, - Err(e) => { - eprintln!("{path}: {e}"); - failed = true; - continue; - } - }; - let file = match atn::parse(&bytes) { - Ok(f) => f, - Err(e) => { - println!("{path}: parse failed: {e}"); - failed = true; - continue; - } - }; - let written = match atn::write(&file) { - Ok(w) => w, - Err(e) => { - println!("{path}: write failed: {e}"); - failed = true; - continue; - } - }; - if written == bytes { - println!("{path}: identical ({} bytes)", bytes.len()); - continue; - } - failed = true; - let at = bytes.iter().zip(&written).position(|(a, b)| a != b).unwrap_or(bytes.len().min(written.len())); - let lo = at.saturating_sub(24); - println!("{path}: differs at byte {at} (original {} bytes, rewritten {} bytes)", bytes.len(), written.len()); - println!(" original : {}", hex(bytes.get(lo..(at + 40).min(bytes.len())).unwrap_or(&[]))); - println!(" rewritten: {}", hex(written.get(lo..(at + 40).min(written.len())).unwrap_or(&[]))); - println!(" original : {}", String::from_utf8_lossy(bytes.get(lo..(at + 40).min(bytes.len())).unwrap_or(&[])).replace(|c: char| c.is_control(), ".")); - } - if failed { - std::process::exit(1); - } -} diff --git a/crates/psd/examples/bench_layer_block.rs b/crates/psd/examples/bench_layer_block.rs deleted file mode 100644 index 4e48f4b3dc..0000000000 --- a/crates/psd/examples/bench_layer_block.rs +++ /dev/null @@ -1,39 +0,0 @@ -//! Serialization of one 24 MP raw RGB layer in Lr16/Lr32, without compression or disk I/O. -//! Run with `cargo run --release -p photocraft-psd --example bench_layer_block`. -use photocraft_psd::{ChannelData, ColorMode, Compression, Header, ImageData, LayerInfo, LayerInfoPlacement, LayerRecord, Rect, Result, Version, testgen}; -use std::hint::black_box; -use std::time::Instant; - -fn main() -> Result<()> { - for depth in [16, 32] { - let mut file = testgen::small(Version::Psd, Compression::Raw); - file.header = Header::new(Version::Psd, 6000, 4000, 3, depth, ColorMode::Rgb); - let plane_bytes = 6000 * 4000 * usize::from(depth / 8); - let mut layer = LayerRecord { rect: Rect::from_xywh(0, 0, 6000, 4000), name: b"RGB".to_vec(), ..Default::default() }; - for id in 0..3 { - layer.channels.push(ChannelData::new(id, Some(Compression::Raw), vec![0; plane_bytes])); - } - file.layer_info = Some(LayerInfo { merged_alpha: false, layers: vec![layer], padding: None }); - file.layer_info_placement = - LayerInfoPlacement::GlobalBlock { index: 0, signature: *b"8BIM", key: if depth == 16 { *b"Lr16" } else { *b"Lr32" }, padding: None }; - file.image_data = ImageData::new(Compression::Raw, vec![0; plane_bytes * 3]); - black_box(file.to_bytes()?); - let mut samples = Vec::new(); - let mut size = 0; - for _ in 0..11 { - let t = Instant::now(); - let bytes = file.to_bytes()?; - samples.push(t.elapsed().as_secs_f64() * 1000.0); - size = bytes.len(); - black_box(bytes); - } - samples.sort_by(f64::total_cmp); - println!( - "{depth}-bit, {} bytes: p50={:.3} ms p95={:.3} ms", - size, - samples.get(5).copied().unwrap_or_default(), - samples.get(10).copied().unwrap_or_default() - ); - } - Ok(()) -} diff --git a/crates/psd/examples/big_psb.rs b/crates/psd/examples/big_psb.rs deleted file mode 100644 index 23bf4de776..0000000000 --- a/crates/psd/examples/big_psb.rs +++ /dev/null @@ -1,24 +0,0 @@ -//! Writes multi-gigabyte PSB files (and the 2 GB PSD) for large-file tests (#375, #216), straight -//! from the Adobe PSD spec and independent of this crate's writer, so the fixtures don't inherit -//! its limits. The generator is `photocraft_psd::fixtures` (feature `testgen`). -//! -//! `cargo run --release -p photocraft-psd --example big_psb -- [case...]` -//! -//! Every sample follows `fixtures::sample`, so a reader can check any pixel without the file. RLE -//! cases keep each row constant (tiny files, full decoded size); raw cases vary along x too. - -use photocraft_psd::fixtures::{PSB_CASES, PSD_2GB}; - -fn main() -> std::io::Result<()> { - let args: Vec = std::env::args().skip(1).collect(); - let out = args.first().map_or_else(|| std::env::temp_dir().join("photocraft-big-psb"), std::path::PathBuf::from); - std::fs::create_dir_all(&out)?; - let wanted = args.get(1..).unwrap_or(&[]); - for case in PSB_CASES.iter().chain([&PSD_2GB]).filter(|c| wanted.is_empty() || wanted.iter().any(|w| w == c.name)) { - let path = out.join(case.file_name()); - let t = std::time::Instant::now(); - let len = case.write_file(&path)?; - println!("{}: {:.2} GB in {:.1} s", path.display(), len as f64 / 1e9, t.elapsed().as_secs_f64()); - } - Ok(()) -} diff --git a/crates/psd/fuzz/.gitignore b/crates/psd/fuzz/.gitignore deleted file mode 100644 index 5c404b9583..0000000000 --- a/crates/psd/fuzz/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -target -corpus -artifacts -coverage -Cargo.lock diff --git a/crates/psd/fuzz/Cargo.toml b/crates/psd/fuzz/Cargo.toml deleted file mode 100644 index 8682bbb725..0000000000 --- a/crates/psd/fuzz/Cargo.toml +++ /dev/null @@ -1,114 +0,0 @@ -[package] -name = "photocraft-psd-fuzz" -version = "0.0.0" -publish = false -edition = "2024" -license = "MIT OR Apache-2.0" - -# Standalone: excluded from the photocraft workspace. -[workspace] - -[package.metadata] -cargo-fuzz = true - -[dependencies] -libfuzzer-sys = "0.4" -photocraft-psd = { path = ".." } - -[[bin]] -name = "parse" -path = "fuzz_targets/parse.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "descriptor" -path = "fuzz_targets/descriptor.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "abr" -path = "fuzz_targets/abr.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "asl" -path = "fuzz_targets/asl.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "image_source_data" -path = "fuzz_targets/image_source_data.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "grd" -path = "fuzz_targets/grd.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "ase" -path = "fuzz_targets/ase.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "aco" -path = "fuzz_targets/aco.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "patterns" -path = "fuzz_targets/patterns.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "filter_effects" -path = "fuzz_targets/filter_effects.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "metadata" -path = "fuzz_targets/metadata.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "tagged" -path = "fuzz_targets/tagged.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "resources" -path = "fuzz_targets/resources.rs" -test = false -doc = false -bench = false - -[[bin]] -name = "atn" -path = "fuzz_targets/atn.rs" -test = false -doc = false -bench = false diff --git a/crates/psd/fuzz/fuzz_targets/abr.rs b/crates/psd/fuzz/fuzz_targets/abr.rs deleted file mode 100644 index 1cada105ec..0000000000 --- a/crates/psd/fuzz/fuzz_targets/abr.rs +++ /dev/null @@ -1,14 +0,0 @@ -//! Fuzz the `.abr` brush parser: any input must return `Ok` or `Err`, never panic, and anything -//! that parses must keep its samples within the advertised bounds. -#![no_main] - -use libfuzzer_sys::fuzz_target; -use photocraft_psd::abr; - -fuzz_target!(|data: &[u8]| { - if let Ok(f) = abr::parse(data) { - for s in &f.samples { - assert_eq!(s.data.len(), s.width as usize * s.height as usize * usize::from(s.depth / 8)); - } - } -}); diff --git a/crates/psd/fuzz/fuzz_targets/aco.rs b/crates/psd/fuzz/fuzz_targets/aco.rs deleted file mode 100644 index c655bfab0f..0000000000 --- a/crates/psd/fuzz/fuzz_targets/aco.rs +++ /dev/null @@ -1,21 +0,0 @@ -//! Fuzz the `.aco` Photoshop Color Swatches parser: any input must return `Ok` or `Err`, never -//! panic; anything that parses must round-trip through `write` and re-parse with the same swatch -//! count, and no name may exceed the name-unit cap. -//! -//! `MAX_SWATCHES` is `u16::MAX` and the on-disk count is a `u16`, so the count is unfalsifiable by -//! construction; the assertion is kept as documentation of that invariant, not as a check that can -//! fail. The name cap, which is reachable, is the one that bites. -#![no_main] -use libfuzzer_sys::fuzz_target; -use photocraft_psd::aco; -fuzz_target!(|data: &[u8]| { - let Ok(f) = aco::parse(data) else { return }; - assert!(f.swatches.len() <= aco::MAX_SWATCHES, "{} swatches exceeds MAX_SWATCHES", f.swatches.len()); - for s in &f.swatches { - assert!(s.name.encode_utf16().count() <= aco::MAX_NAME_UNITS, "name longer than MAX_NAME_UNITS"); - } - let out = aco::write(&f.swatches).expect("a parsed .aco must be writable"); - let back = aco::parse(&out).expect("a written .aco must re-parse"); - assert_eq!(back.swatches.len(), f.swatches.len(), "swatch count changed across a round trip"); - assert_eq!(aco::write(&back.swatches).expect("rewritable"), out, "a second round trip is not byte-stable"); -}); diff --git a/crates/psd/fuzz/fuzz_targets/ase.rs b/crates/psd/fuzz/fuzz_targets/ase.rs deleted file mode 100644 index 23a1a9d6b9..0000000000 --- a/crates/psd/fuzz/fuzz_targets/ase.rs +++ /dev/null @@ -1,39 +0,0 @@ -//! Fuzz the `.ase` Adobe Swatch Exchange parser: any input must return `Ok` or `Err`, never panic; -//! anything that parses must hold only finite colour components, stay within the swatch cap and -//! round-trip through `write` and re-parse with the same number of entries. -//! -//! A colour outside any group is a legitimate `AseEntry::Swatch`, and a group left open at the -//! end is closed by the parser, so entry shape is checked only through the round trip below. -//! The cap assertion is an invariant, not a fast check: no 4 KB input can carry 100 001 blocks. -#![no_main] -use libfuzzer_sys::fuzz_target; -use photocraft_psd::ase::{self, AseColor, AseEntry}; -fuzz_target!(|data: &[u8]| { - let Ok(f) = ase::parse(data) else { return }; - assert!(f.swatch_count() <= ase::MAX_SWATCHES, "{} swatches exceeds MAX_SWATCHES", f.swatch_count()); - for e in &f.entries { - let swatches = match e { - AseEntry::Swatch(s) => std::slice::from_ref(s), - AseEntry::Group { swatches, .. } => swatches.as_slice(), - }; - for s in swatches { - assert!(s.name.encode_utf16().count() <= ase::MAX_NAME_UNITS, "name longer than MAX_NAME_UNITS"); - // Rgb/Lab carry three components, Cmyk four, Gray one. - let check = |c: &[f32]| { - for v in c { - assert!(v.is_finite(), "colour component {v} is not finite"); - } - }; - match &s.color { - AseColor::Rgb(v) | AseColor::Lab(v) => check(v), - AseColor::Cmyk(v) => check(v), - AseColor::Gray(v) => check(std::slice::from_ref(v)), - AseColor::Other { .. } => {} - } - } - } - let out = ase::write(&f).expect("a parsed .ase must be writable"); - let back = ase::parse(&out).expect("a written .ase must re-parse"); - assert_eq!(back.swatch_count(), f.swatch_count(), "swatch count changed across a round trip"); - assert_eq!(ase::write(&back).expect("rewritable"), out, "a second round trip is not byte-stable"); -}); diff --git a/crates/psd/fuzz/fuzz_targets/asl.rs b/crates/psd/fuzz/fuzz_targets/asl.rs deleted file mode 100644 index cbf2c9169c..0000000000 --- a/crates/psd/fuzz/fuzz_targets/asl.rs +++ /dev/null @@ -1,15 +0,0 @@ -//! Fuzz the `.asl` style library parser: any input must return `Ok` or `Err`, never panic, and -//! anything that parses must write back and parse to the same number of styles. -#![no_main] - -use libfuzzer_sys::fuzz_target; -use photocraft_psd::asl; - -fuzz_target!(|data: &[u8]| { - if let Ok(f) = asl::parse(data) - && let Ok(bytes) = asl::write(&f) - { - let back = asl::parse(&bytes).expect("a written library parses"); - assert_eq!(back.styles.len(), f.styles.len()); - } -}); diff --git a/crates/psd/fuzz/fuzz_targets/atn.rs b/crates/psd/fuzz/fuzz_targets/atn.rs deleted file mode 100644 index e02e25b073..0000000000 --- a/crates/psd/fuzz/fuzz_targets/atn.rs +++ /dev/null @@ -1,12 +0,0 @@ -//! 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. -#![no_main] - -use libfuzzer_sys::fuzz_target; - -#[path = "../../tests/it/common/atn_roundtrip.rs"] -mod atn_roundtrip; - -fuzz_target!(|data: &[u8]| { - atn_roundtrip::check(data); -}); diff --git a/crates/psd/fuzz/fuzz_targets/descriptor.rs b/crates/psd/fuzz/fuzz_targets/descriptor.rs deleted file mode 100644 index e487081563..0000000000 --- a/crates/psd/fuzz/fuzz_targets/descriptor.rs +++ /dev/null @@ -1,13 +0,0 @@ -//! Fuzz the ActionDescriptor parser; anything that parses must be byte -//! stable after one normalization pass (e.g. `bool` bytes other than 0/1). -#![no_main] - -use libfuzzer_sys::fuzz_target; -use photocraft_psd::descriptor::Descriptor; - -fuzz_target!(|data: &[u8]| { - if let Ok(d) = Descriptor::from_bytes(data) { - let b = d.to_bytes(); - assert_eq!(Descriptor::from_bytes(&b).expect("re-parse").to_bytes(), b); - } -}); diff --git a/crates/psd/fuzz/fuzz_targets/filter_effects.rs b/crates/psd/fuzz/fuzz_targets/filter_effects.rs deleted file mode 100644 index 611e639b8f..0000000000 --- a/crates/psd/fuzz/fuzz_targets/filter_effects.rs +++ /dev/null @@ -1,22 +0,0 @@ -//! Fuzz the `FEid` / `FXid` smart-filter cache parser: any input must return `Ok` or `Err`, never -//! panic. Decoding every cached plane and the filter mask must also stay panic-free (a size the -//! data cannot hold is refused before allocation, for RLE and zlib alike), and a parsed block must -//! re-parse to the same value and re-serialise byte for byte. -#![no_main] -use libfuzzer_sys::fuzz_target; -use photocraft_psd::filter_effects::FilterEffects; -fuzz_target!(|data: &[u8]| { - let Ok(fx) = FilterEffects::parse(data) else { return }; - for it in &fx.items { - let _ = it.decoded_mask(); - if let (Ok(depth), Ok((w, h))) = (u16::try_from(it.depth), it.rect.size()) { - for p in it.slots.iter().flatten() { - let _ = p.decode(w, h, depth); - } - } - } - let out = fx.to_bytes(); - let back = FilterEffects::parse(&out).expect("a written FEid block must re-parse"); - assert_eq!(back, fx, "a written FEid block does not re-parse to the same value"); - assert_eq!(back.to_bytes(), out, "a second round trip is not byte-stable"); -}); diff --git a/crates/psd/fuzz/fuzz_targets/grd.rs b/crates/psd/fuzz/fuzz_targets/grd.rs deleted file mode 100644 index 16ab26a137..0000000000 --- a/crates/psd/fuzz/fuzz_targets/grd.rs +++ /dev/null @@ -1,52 +0,0 @@ -//! Fuzz the `.grd` gradient parser: any input must return `Ok` or `Err`, never panic, and every -//! number it hands back must be finite and in range. -//! -//! The cap assertions below are invariants, not fast checks: at libFuzzer default `-max_len` -//! of 4096 no input can carry 10 001 gradients or 1001 stops, so they only fire on long runs with -//! a raised limit. The inputs that do reach those caps are in `crates/psd/tests/it/swatch_malformed.rs`. -#![no_main] -use libfuzzer_sys::fuzz_target; -use photocraft_psd::grd::{self, GrdColor}; -fuzz_target!(|data: &[u8]| { - let Ok(g) = grd::parse(data) else { return }; - assert!(g.len() <= grd::MAX_GRADIENTS, "{} gradients exceeds MAX_GRADIENTS", g.len()); - for grad in &g { - assert!(grad.stops.len() <= grd::MAX_STOPS, "{} stops exceeds MAX_STOPS", grad.stops.len()); - assert!(grad.opacity.len() <= grd::MAX_STOPS, "{} transparency stops exceeds MAX_STOPS", grad.opacity.len()); - for &(l, o, m) in &grad.opacity { - assert!(l.is_finite() && (0.0..=1.0).contains(&l), "transparency location {l} out of range"); - assert!((0.0..=1.0).contains(&o), "opacity {o} outside 0..=1"); - assert!(m.is_finite() && (0.0..=1.0).contains(&m), "transparency midpoint {m} out of range"); - } - for s in &grad.stops { - assert!(s.location.is_finite() && (0.0..=1.0).contains(&s.location), "stop location {} out of range", s.location); - assert!(s.midpoint.is_finite() && (0.0..=1.0).contains(&s.midpoint), "stop midpoint {} out of range", s.midpoint); - // Each model has its own documented range, not just "finite": the parser clamps RGB, - // CMYK and Gray to 0..=1, Hue to 0..=360, L* to 0..=100 and a*/b* to the CIELAB gamut. - let unit = |c: &[f32]| { - for v in c { - assert!(v.is_finite() && (0.0..=1.0).contains(v), "colour component {v} outside 0..=1"); - } - }; - match s.color { - GrdColor::Rgb(v) => unit(&v), - GrdColor::Cmyk(v) => unit(&v), - GrdColor::Hsb([h, sat, br]) => { - assert!(h.is_finite() && (0.0..=360.0).contains(&h), "hue {h} outside 0..=360"); - unit(&[sat, br]); - } - GrdColor::Lab([l, a, b]) => { - assert!(l.is_finite() && (0.0..=100.0).contains(&l), "L* {l} outside 0..=100"); - assert!(a.is_finite() && (-128.0..=127.0).contains(&a), "a* {a} outside the CIELAB gamut"); - assert!(b.is_finite() && (-128.0..=127.0).contains(&b), "b* {b} outside the CIELAB gamut"); - } - GrdColor::Gray(v) => unit(&[v]), - GrdColor::Foreground | GrdColor::Background => {} - } - } - } - let out = grd::write(&g); - let back = grd::parse(&out).expect("a written .grd must re-parse"); - assert_eq!(back.len(), g.len(), "gradient count changed across a round trip"); - assert_eq!(grd::write(&back), out, "a second round trip is not byte-stable"); -}); diff --git a/crates/psd/fuzz/fuzz_targets/image_source_data.rs b/crates/psd/fuzz/fuzz_targets/image_source_data.rs deleted file mode 100644 index 73e7289173..0000000000 --- a/crates/psd/fuzz/fuzz_targets/image_source_data.rs +++ /dev/null @@ -1,18 +0,0 @@ -//! Fuzz the layered-TIFF tag parsers (37724 image source data in either byte order, and 34377 -//! image resources), and the byte-order transcoder on anything that parses. -#![no_main] - -use libfuzzer_sys::fuzz_target; -use photocraft_psd::tiff::{ByteOrder, ImageSourceData, resources_from_bytes}; - -fuzz_target!(|data: &[u8]| { - let _ = resources_from_bytes(data); - let Ok((d, _)) = ImageSourceData::from_bytes(data) else { return }; - // Whatever parsed must write in both orders, and each output must parse again. - for order in [ByteOrder::Big, ByteOrder::Little] { - if let Ok((out, _)) = d.to_bytes(order) { - let (again, _) = ImageSourceData::from_bytes(&out).expect("re-parse of written data"); - let _ = again.to_bytes(order); - } - } -}); diff --git a/crates/psd/fuzz/fuzz_targets/metadata.rs b/crates/psd/fuzz/fuzz_targets/metadata.rs deleted file mode 100644 index 2bb23d7548..0000000000 --- a/crates/psd/fuzz/fuzz_targets/metadata.rs +++ /dev/null @@ -1,17 +0,0 @@ -//! Fuzz the `shmd` (metadata setting) parser: any input must return `Ok` or `Err`, never panic. -//! -//! The `copy` field is a bool, so a non-canonical copy byte (anything but 0 or 1) normalises to 1 -//! on write; exact byte equality therefore cannot hold for arbitrary input, only for canonical -//! files. The invariant that does hold, and that catches reader/writer drift, is that a -//! parsed-then-written block re-parses to the *same items* (semantic equality, not just byte -//! stability -- byte stability alone would also pass if the writer silently dropped a field). -#![no_main] -use libfuzzer_sys::fuzz_target; -use photocraft_psd::metadata::{parse_shmd, write_shmd}; -fuzz_target!(|data: &[u8]| { - let Ok(items) = parse_shmd(data) else { return }; - let out = write_shmd(&items); - let back = parse_shmd(&out).expect("a written shmd block must re-parse"); - assert_eq!(back, items, "a written shmd block does not re-parse to the same items"); - assert_eq!(write_shmd(&back), out, "shmd is not byte-stable across a round trip"); -}); diff --git a/crates/psd/fuzz/fuzz_targets/parse.rs b/crates/psd/fuzz/fuzz_targets/parse.rs deleted file mode 100644 index 3dab9cd93a..0000000000 --- a/crates/psd/fuzz/fuzz_targets/parse.rs +++ /dev/null @@ -1,27 +0,0 @@ -//! Fuzz the full parser, and exercise writer/decoders on anything that parses. -#![no_main] - -use libfuzzer_sys::fuzz_target; -use photocraft_psd::PsdFile; - -fuzz_target!(|data: &[u8]| { - let Ok(f) = PsdFile::from_bytes(data) else { return }; - // Anything written must re-parse and be byte stable from then on. - // (Byte comparison rather than model equality, since NaN != NaN.) - if let Ok(out) = f.to_bytes() { - let g = PsdFile::from_bytes(&out).expect("re-parse of written file"); - assert_eq!(g.to_bytes().expect("re-write"), out); - } - // Keep decoding bounded: only small images. - if u64::from(f.header.width) * u64::from(f.header.height) <= 1 << 20 { - let _ = f.decode_merged(); - let _ = f.composite_rgba8(); - for l in f.iter_layers() { - if l.record.rect.width() * l.record.rect.height() <= 1 << 20 { - let _ = l.rgba8(); - let _ = l.user_mask(); - } - } - } - let _ = f.layer_tree(); -}); diff --git a/crates/psd/fuzz/fuzz_targets/patterns.rs b/crates/psd/fuzz/fuzz_targets/patterns.rs deleted file mode 100644 index d7dbc6236b..0000000000 --- a/crates/psd/fuzz/fuzz_targets/patterns.rs +++ /dev/null @@ -1,20 +0,0 @@ -//! Fuzz the pattern parsers: the `Patt` / `Pat2` / `Pat3` tagged blocks and standalone `.pat` -//! files. Any input must return `Ok` or `Err`, never panic. The channel offsets and padding a -//! hostile file can carry are wire artifacts, not fields of `PsdPattern`, so a parsed pattern must -//! survive a write/parse round trip unchanged -- a stronger invariant than byte stability, which -//! would also hold if the writer silently normalised a field away. -#![no_main] -use libfuzzer_sys::fuzz_target; -use photocraft_psd::patterns::{parse_pat_file, parse_pattern_block, write_pat_file, write_pattern_block}; -fuzz_target!(|data: &[u8]| { - if let Ok(ps) = parse_pattern_block(data) { - let out = write_pattern_block(&ps).expect("a parsed pattern block must be writable"); - let back = parse_pattern_block(&out).expect("a written pattern block must re-parse"); - assert_eq!(back, ps, "a pattern block does not survive a write/parse round trip"); - } - if let Ok(ps) = parse_pat_file(data) { - let out = write_pat_file(&ps).expect("a parsed .pat must be writable"); - let back = parse_pat_file(&out).expect("a written .pat must re-parse"); - assert_eq!(back, ps, "a .pat file does not survive a write/parse round trip"); - } -}); diff --git a/crates/psd/fuzz/fuzz_targets/resources.rs b/crates/psd/fuzz/fuzz_targets/resources.rs deleted file mode 100644 index 51d7311731..0000000000 --- a/crates/psd/fuzz/fuzz_targets/resources.rs +++ /dev/null @@ -1,24 +0,0 @@ -//! Fuzz the typed image-resource views: `ImageResource::parsed` for an arbitrary resource id, plus -//! the standalone `ResolutionInfo` and `VersionInfo` parsers. All must return `Ok` / `Err` / `None` -//! (and `xmp_str` an `Option`), never panic. A parsed `ResolutionInfo` (16 fixed bytes) must be -//! stable across a byte round trip. The first two bytes pick the id so every typed branch is -//! reachable; the rest is the resource data. -#![no_main] -use libfuzzer_sys::fuzz_target; -use photocraft_psd::resources::{ImageResource, ResolutionInfo, VersionInfo}; -fuzz_target!(|data: &[u8]| { - let (id, body) = match data.split_first_chunk::<2>() { - Some((p, rest)) => (u16::from_be_bytes(*p), rest.to_vec()), - None => (0u16, data.to_vec()), - }; - let r = ImageResource::new(id, body.clone()); - let _ = r.parsed(); - let _ = r.xmp_str(); - if let Ok(ri) = ResolutionInfo::from_bytes(&body) { - let round = ResolutionInfo::from_bytes(&ri.to_bytes()).expect("resolution info re-parses"); - assert_eq!(round, ri, "ResolutionInfo is not stable across a round trip"); - } - if let Ok(vi) = VersionInfo::from_bytes(&body) { - let _ = vi.to_bytes(); - } -}); diff --git a/crates/psd/fuzz/fuzz_targets/tagged.rs b/crates/psd/fuzz/fuzz_targets/tagged.rs deleted file mode 100644 index 8f7c6517ca..0000000000 --- a/crates/psd/fuzz/fuzz_targets/tagged.rs +++ /dev/null @@ -1,28 +0,0 @@ -//! Fuzz the per-block views of a tagged block: `parsed` (typed, well-known keys) and -//! `check_structure` (strict re-parse of blocks that carry their own inner sizes: placed layers, -//! linked files, object effects, filter caches). Both must return `Ok` / `Err` / `None`, never -//! panic, for arbitrary data. -//! -//! The first byte selects the key from a table of every key with a typed or strict branch, so the -//! fuzzer reaches each branch deterministically instead of having to guess a 4-byte key from raw -//! bytes (which it would almost never do); the rest is the block data. -#![no_main] -use libfuzzer_sys::fuzz_target; -use photocraft_psd::tagged::TaggedBlock; - -const KEYS: [&[u8; 4]; 20] = [ - // typed (parsed) - b"luni", b"lsct", b"lsdk", b"lyid", b"lnsr", b"clbl", b"infx", b"knko", b"tsly", b"lmgm", b"vmgm", b"lspf", b"lclr", b"iOpa", b"shmd", - // strict (check_structure) - b"PlLd", b"SoLd", b"lnk2", b"lfx2", b"FEid", -]; - -fuzz_target!(|data: &[u8]| { - let (key, body) = match data.split_first() { - Some((&sel, rest)) => (*KEYS[sel as usize % KEYS.len()], rest.to_vec()), - None => (*b"luni", Vec::new()), - }; - let b = TaggedBlock::new(key, body); - let _ = b.parsed(); - let _ = b.check_structure(); -}); diff --git a/crates/psd/proptest-regressions/descriptor.txt b/crates/psd/proptest-regressions/descriptor.txt deleted file mode 100644 index d28a250e6b..0000000000 --- a/crates/psd/proptest-regressions/descriptor.txt +++ /dev/null @@ -1,7 +0,0 @@ -# Seeds for failure cases proptest has generated in the past. It is -# automatically read and these particular cases re-run before any -# novel cases are generated. -# -# It is recommended to check this file in to source control so that -# everyone who runs the test benefits from these saved cases. -cc 8089b21c70b7dfddf5697e3a0ec01fa8aeb5ea2e8e844f62ae6e8c2453382404 # shrinks to d = Descriptor { name: UnicodeString([]), class_id: Code([0, 0, 0, 0]), items: [(Code([0, 0, 0, 0]), Descriptor(Descriptor { name: UnicodeString([]), class_id: Code([0, 0, 0, 0]), items: [(Str([0]), Boolean(false))] }))] } diff --git a/crates/psd/src/abr.rs b/crates/psd/src/abr.rs deleted file mode 100644 index 35f4135a53..0000000000 --- a/crates/psd/src/abr.rs +++ /dev/null @@ -1,676 +0,0 @@ -//! Photoshop brush files (`.abr`): the legacy v1/v2 layout and the sectioned v6+ layout. -//! -//! Implemented clean-room from public descriptions of the format (the layout notes published with -//! open-source readers such as GIMP's and ag-psd's, and observation of files written by Photoshop). -//! No code was copied. All numbers are big-endian. -//! -//! ```text -//! v1 / v2 := version u16 (1|2), count u16, count × brush -//! brush := type u16 (1 computed, 2 sampled), length u32, body[length] -//! computed := misc u32, spacing u16 (%), diameter u16, roundness u16 (%), angle i16, hardness u16 (%) -//! sampled := misc u32, spacing u16 (%), [v2: name (u32 length + UTF-16 incl. NUL)], -//! anti-alias u8, short bounds 4 × i16, bounds 4 × i32 (top, left, bottom, right), -//! depth u16 (8|16), compression u8 (0 raw, 1 PackBits with a u16 row-length table) -//! -//! v6+ := version u16 (6..=10), subversion u16 (1|2), sections… -//! section := "8BIM", key [4], length u32, data[length] (padded to 4 bytes) -//! "samp" := entries: length u32 (padded to 4), Pascal uuid, skip (10 if subversion 1, -//! 264 if 2), bounds 4 × i32, depth i16, compression u8, data -//! "patt" := patterns as in the `Patt` global block -//! "desc" := version u32 (16) + ActionDescriptor; key `Brsh` lists `brushPreset` objects -//! "phry" := version u32 (16) + ActionDescriptor; key `hierarchy` lists objects read as a -//! token stream: `Grup` { `Nm ` name, `zuid` uuid } opens a folder, `preset` {} is -//! the next preset of `desc` (in order), `groupEnd` {} closes the current folder -//! ``` -//! -//! The `phry` (preset hierarchy) section keeps the Brushes panel folders of Photoshop CC (2018+) -//! files: [`AbrFile::folders`] gives each preset's folder path. Folders nest (a `Grup` inside a -//! `Grup`); presets outside any folder are at the top level. A damaged hierarchy never fails the -//! parse: mismatches become warnings and the presets they affect land at the top level. -//! -//! [`parse`] never panics: every length is bounds-checked, sizes are capped ([`MAX_EDGE`], -//! [`MAX_TOTAL_BYTES`]) and a damaged brush is skipped with a warning when the rest of the file -//! is still readable. [`write_v12`] and [`write_v6`] produce files in the same layouts (used by -//! the tests and fuzz seeds; exporting brushes reuses them). - -use crate::compression::{Compression, PlaneLayout, decode_planes, encode_planes}; -use crate::descriptor::{Descriptor, Value, VersionedDescriptor}; -use crate::error::{PsdError, Result}; -use crate::header::Version; -use crate::patterns::{PatternBudget, PsdPattern, parse_pattern_block_with, write_pattern_block}; - -/// Largest sampled tip edge accepted (Photoshop's own limit is 5000 px). -pub const MAX_EDGE: u32 = 8192; -/// Most brushes read from one file. -pub const MAX_BRUSHES: usize = 20_000; -/// Cap on decoded sample bytes over the whole file. 32-bit targets (wasm) keep 512 MiB: the file, -/// its base64 copies and the decoded tips must all fit a 4 GiB address space, and running out -/// there aborts instead of returning an error. -pub const MAX_TOTAL_BYTES: usize = if cfg!(target_pointer_width = "64") { 1 << 30 } else { 512 << 20 }; -const _: () = assert!(cfg!(target_pointer_width = "64") || MAX_TOTAL_BYTES == 512 << 20); - -/// A sampled tip: one grayscale plane where the maximum value is full paint. -#[derive(Debug, Clone, PartialEq)] -pub struct AbrSample { - /// The uuid that `sampledData` in a preset descriptor refers to (v6+), or empty. - pub id: String, - /// Width in pixels. - pub width: u32, - /// Height in pixels. - pub height: u32, - /// Bits per sample: 8 or 16. - pub depth: u16, - /// Decoded samples, row-major (`width × height × depth / 8` bytes, 16-bit big-endian). - pub data: Vec, -} - -impl AbrSample { - /// Samples as 0..1 paint amounts. - pub fn to_unit(&self) -> Vec { - if self.depth == 16 { - self.data.as_chunks::<2>().0.iter().map(|c| f32::from(u16::from_be_bytes(*c)) / 65535.0).collect() - } else { - self.data.iter().map(|&v| f32::from(v) / 255.0).collect() - } - } -} - -/// A legacy (v1/v2) tip. -#[derive(Debug, Clone, PartialEq)] -pub enum LegacyTip { - /// Computed elliptical tip. - Computed { - /// Diameter in pixels. - diameter: u16, - /// 0..100 %. - hardness: u16, - /// Degrees. - angle: i16, - /// 0..100 %. - roundness: u16, - }, - /// Sampled tip. - Sampled(AbrSample), -} - -/// A legacy (v1/v2) brush. -#[derive(Debug, Clone, PartialEq)] -pub struct LegacyBrush { - /// Name (v2 sampled brushes only; empty otherwise). - pub name: String, - /// Spacing in percent of the diameter (0 = spacing off). - pub spacing: u16, - /// Anti-aliasing flag (sampled tips). - pub anti_alias: bool, - /// The tip. - pub tip: LegacyTip, -} - -/// A parsed brush file. -#[derive(Debug, Clone, PartialEq, Default)] -pub struct AbrFile { - /// File version (1, 2, 6, 7, 9 or 10). - pub version: u16, - /// v6+ subversion (1 or 2); 0 for v1/v2. - pub subversion: u16, - /// v1/v2 brushes, in file order. - pub legacy: Vec, - /// v6+ sampled tips (`samp`), in file order. - pub samples: Vec, - /// v6+ embedded patterns (`patt`), referenced by texture settings. - pub patterns: Vec, - /// v6+ brush presets: the `brushPreset` objects of the `desc` section, in file order. - pub presets: Vec, - /// v6+ folder of each preset, parallel to [`AbrFile::presets`]: the folder names from the - /// outermost in, empty for a preset at the top level. Empty when the file has no readable - /// preset hierarchy (`phry`), i.e. every preset is at the top level. - pub folders: Vec>, - /// Problems that did not stop the parse (skipped brushes, unknown sections…). - pub warnings: Vec, -} - -struct Rd<'a> { - b: &'a [u8], - p: usize, -} - -impl<'a> Rd<'a> { - fn new(b: &'a [u8]) -> Self { - Rd { b, p: 0 } - } - fn left(&self) -> usize { - self.b.len().saturating_sub(self.p) - } - fn take(&mut self, n: usize) -> Result<&'a [u8]> { - let end = self.p.checked_add(n).ok_or(PsdError::LimitExceeded("abr length overflow"))?; - let s = self.b.get(self.p..end).ok_or(PsdError::UnexpectedEof { offset: self.p, needed: end.saturating_sub(self.b.len()) })?; - self.p = end; - Ok(s) - } - fn arr(&mut self) -> Result<[u8; N]> { - let s = self.take(N)?; - let mut a = [0u8; N]; - a.copy_from_slice(s); - Ok(a) - } - fn u8(&mut self) -> Result { - Ok(self.arr::<1>()?[0]) - } - fn u16(&mut self) -> Result { - Ok(u16::from_be_bytes(self.arr()?)) - } - fn u32(&mut self) -> Result { - Ok(u32::from_be_bytes(self.arr()?)) - } - fn i32(&mut self) -> Result { - Ok(i32::from_be_bytes(self.arr()?)) - } - fn skip(&mut self, n: usize) -> Result<()> { - self.take(n).map(|_| ()) - } -} - -/// Bytes budget shared by all samples of one file. -struct Budget(usize); - -impl Budget { - fn spend(&mut self, n: usize) -> Result<()> { - self.0 = self.0.checked_sub(n).ok_or(PsdError::LimitExceeded("abr samples exceed MAX_TOTAL_BYTES"))?; - Ok(()) - } -} - -/// Reads bounds (top, left, bottom, right), depth and compression, then the pixel data. -fn read_sample_body(r: &mut Rd, id: String, budget: &mut Budget) -> Result { - let (top, left, bottom, right) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?); - let w = i64::from(right) - i64::from(left); - let h = i64::from(bottom) - i64::from(top); - if w <= 0 || h <= 0 { - return Err(PsdError::invalid(format!("brush sample bounds {w}×{h}"))); - } - if w > i64::from(MAX_EDGE) || h > i64::from(MAX_EDGE) { - return Err(PsdError::LimitExceeded("brush sample larger than MAX_EDGE")); - } - let (w, h) = (w as u32, h as u32); - let depth = r.u16()?; - if depth != 8 && depth != 16 { - return Err(PsdError::invalid(format!("brush sample depth {depth}"))); - } - let comp = r.u8()?; - let compression = match comp { - 0 => Compression::Raw, - 1 => Compression::Rle, - c => return Err(PsdError::Unsupported(format!("brush sample compression {c}"))), - }; - let layout = PlaneLayout { planes: 1, width: w as usize, height: h as usize, depth, version: Version::Psd }; - budget.spend(layout.decoded_len()?)?; - let rest = r.take(r.left())?; - let data = decode_planes(compression, rest, &layout)?; - Ok(AbrSample { id, width: w, height: h, depth, data }) -} - -fn read_ucs2(r: &mut Rd) -> Result { - let n = r.u32()? as usize; - if n > 4096 { - return Err(PsdError::LimitExceeded("abr name length")); - } - let units: Vec = r.take(n * 2)?.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).collect(); - Ok(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string()) -} - -fn parse_v12(r: &mut Rd, version: u16, out: &mut AbrFile) -> Result<()> { - let count = r.u16()?; - let mut budget = Budget(MAX_TOTAL_BYTES); - for i in 0..count { - if r.left() == 0 { - out.warnings.push(format!("file ends after {i} of {count} brushes")); - break; - } - let ty = r.u16()?; - let len = r.u32()? as usize; - let body = match r.take(len) { - Ok(b) => b, - Err(_) => { - out.warnings.push(format!("brush {}: truncated", i + 1)); - break; - } - }; - let mut b = Rd::new(body); - let parsed = (|| -> Result> { - match ty { - 1 => { - let _misc = b.u32()?; - let spacing = b.u16()?; - let diameter = b.u16()?; - let roundness = b.u16()?; - let angle = b.u16()? as i16; - let hardness = b.u16()?; - Ok(Some(LegacyBrush { name: String::new(), spacing, anti_alias: true, tip: LegacyTip::Computed { diameter, hardness, angle, roundness } })) - } - 2 => { - let _misc = b.u32()?; - let spacing = b.u16()?; - let name = if version == 2 { read_ucs2(&mut b)? } else { String::new() }; - let anti_alias = b.u8()? != 0; - b.skip(8)?; // short bounds (superseded by the 32-bit bounds) - let s = read_sample_body(&mut b, String::new(), &mut budget)?; - Ok(Some(LegacyBrush { name, spacing, anti_alias, tip: LegacyTip::Sampled(s) })) - } - other => { - out.warnings.push(format!("brush {}: unknown brush type {other} skipped", i + 1)); - Ok(None) - } - } - })(); - match parsed { - Ok(Some(lb)) => out.legacy.push(lb), - Ok(None) => {} - Err(PsdError::LimitExceeded(m)) if m.contains("MAX_TOTAL_BYTES") => return Err(PsdError::LimitExceeded(m)), - Err(e) => out.warnings.push(format!("brush {}: {e}; skipped", i + 1)), - } - } - Ok(()) -} - -fn read_samp(data: &[u8], subversion: u16, out: &mut AbrFile, budget: &mut Budget) -> Result<()> { - let mut r = Rd::new(data); - while r.left() >= 4 { - if out.samples.len() >= MAX_BRUSHES { - out.warnings.push("too many sampled tips; the rest were skipped".into()); - break; - } - let len = r.u32()? as usize; - if len == 0 { - break; - } - let padded = len.checked_add(3).ok_or(PsdError::LimitExceeded("abr sample length"))? & !3; - let body = match r.take(padded.min(r.left())) { - Ok(b) if b.len() >= len => b, - _ => { - out.warnings.push(format!("sampled tip {}: truncated", out.samples.len() + 1)); - break; - } - }; - let mut b = Rd::new(body); - let parsed = (|| -> Result { - let n = b.u8()? as usize; - let id = String::from_utf8_lossy(b.take(n)?).to_string(); - b.skip(if subversion == 1 { 10 } else { 264 })?; - read_sample_body(&mut b, id, budget) - })(); - match parsed { - Ok(s) => out.samples.push(s), - Err(PsdError::LimitExceeded(m)) if m.contains("MAX_TOTAL_BYTES") => return Err(PsdError::LimitExceeded(m)), - Err(e) => out.warnings.push(format!("sampled tip {}: {e}; skipped", out.samples.len() + 1)), - } - } - Ok(()) -} - -fn read_desc(data: &[u8], out: &mut AbrFile) { - match VersionedDescriptor::parse_prefix(data) { - // Moves the presets out of the parsed descriptor instead of cloning each one. - Ok((vd, _)) => match vd.descriptor.items.into_iter().find(|(k, _)| k.is("Brsh")).map(|(_, v)| v) { - Some(Value::List(items)) => { - for v in items.into_iter().take(MAX_BRUSHES) { - if let Value::Descriptor(d) = v { - out.presets.push(d); - } - } - } - _ => out.warnings.push("brush settings (desc) hold no brush list".into()), - }, - Err(e) => out.warnings.push(format!("brush settings (desc) unreadable: {e}")), - } -} - -/// Deepest folder nesting read from or written to a preset hierarchy; deeper folders are merged -/// into their ancestor at this depth. -pub const MAX_FOLDER_DEPTH: usize = 32; -/// Longest folder name kept (characters). -const MAX_FOLDER_NAME: usize = 255; - -/// Most bytes of folder names held across all presets' folder paths (each name also counts its -/// `String`). Presets past it are imported at the top level. 20,000 presets three folders deep -/// with 20-character names take about 3 MB. -const MAX_FOLDER_BYTES: usize = 16 << 20; - -/// Reads the `phry` token stream into one folder path per preset (`presets` of them, the count -/// read from `desc`), in order. Paths are built only for those presets, within -/// [`MAX_FOLDER_BYTES`]: a small section can't make the reader allocate more than that. `None` -/// (with a warning) when the section is unreadable. -fn read_phry(data: &[u8], presets: usize, warnings: &mut Vec) -> Option>> { - let vd = match VersionedDescriptor::parse_prefix(data) { - Ok((vd, _)) => vd, - Err(e) => { - warnings.push(format!("brush folders (phry) unreadable: {e}; brushes imported without folders")); - return None; - } - }; - let Some(Value::List(items)) = vd.descriptor.get("hierarchy") else { - warnings.push("brush folders (phry) hold no hierarchy; brushes imported without folders".into()); - return None; - }; - let mut stack: Vec = Vec::new(); - // Folders opened past MAX_FOLDER_DEPTH: their `groupEnd`s close nothing on `stack`. - let mut overflow = 0usize; - let mut out = Vec::with_capacity(presets.min(MAX_BRUSHES)); - // Preset tokens seen (only counted past `presets`), and the bytes held by `out`'s paths. - let (mut listed, mut bytes) = (0usize, 0usize); - let (mut unbalanced, mut too_deep, mut too_big) = (false, false, false); - for v in items { - let Value::Descriptor(d) = v else { continue }; - if d.class_id.is("Grup") { - if stack.len() >= MAX_FOLDER_DEPTH { - overflow = overflow.saturating_add(1); - too_deep = true; - continue; - } - let name = match d.get("Nm ") { - Some(Value::Text(t)) => t.to_string_lossy(), - _ => String::new(), - }; - let name: String = name.trim().chars().take(MAX_FOLDER_NAME).collect(); - stack.push(if name.is_empty() { "Group".to_string() } else { name }); - } else if d.class_id.is("groupEnd") { - if overflow > 0 { - overflow -= 1; - } else if stack.pop().is_none() { - unbalanced = true; - } - } else if d.class_id.is("preset") { - listed = listed.saturating_add(1); - if out.len() >= presets { - continue; - } - let size = stack.iter().map(|n| n.len().saturating_add(size_of::())).fold(0usize, usize::saturating_add); - match bytes.checked_add(size).filter(|&b| b <= MAX_FOLDER_BYTES) { - Some(b) if !too_big => { - bytes = b; - out.push(stack.clone()); - } - _ => { - too_big = true; - out.push(Vec::new()); - } - } - } - } - if unbalanced { - warnings.push("brush folders (phry): a folder end without a folder was ignored".into()); - } - if too_deep { - warnings.push(format!("brush folders nested deeper than {MAX_FOLDER_DEPTH} levels were merged into their parent")); - } - if too_big { - warnings.push("brush folders (phry) too large; the remaining brushes were imported at the top level".into()); - } - if listed != presets { - warnings.push(format!( - "brush folders (phry) list {listed} brushes but the file holds {presets}; {}", - if listed > presets { "the extra entries were ignored" } else { "the rest were imported at the top level" } - )); - out.resize(presets, Vec::new()); - } - Some(out) -} - -/// Pairs the `phry` section's preset tokens with the presets read from `desc`, in order. -fn apply_hierarchy(out: &mut AbrFile, phry: Option<&[u8]>) { - let Some(data) = phry else { return }; - let Some(folders) = read_phry(data, out.presets.len(), &mut out.warnings) else { return }; - if folders.iter().any(|f| !f.is_empty()) { - out.folders = folders; - } -} - -fn parse_v6(r: &mut Rd, out: &mut AbrFile) -> Result<()> { - parse_v6_within(r, out, &mut Budget(MAX_TOTAL_BYTES)) -} - -/// [`parse_v6`] with the samples and patterns sharing `budget`. -fn parse_v6_within(r: &mut Rd, out: &mut AbrFile, budget: &mut Budget) -> Result<()> { - out.subversion = r.u16()?; - if !matches!(out.subversion, 1 | 2) { - return Err(PsdError::Unsupported(format!("brush file subversion {}", out.subversion))); - } - let mut hierarchy = None; - let mut patterns = PatternBudget::default(); - while r.left() >= 12 { - let sig = r.arr::<4>()?; - if &sig != b"8BIM" { - out.warnings.push(format!("unexpected data at offset {} ignored", r.p - 4)); - break; - } - let key = r.arr::<4>()?; - let len = r.u32()? as usize; - let data = match r.take(len) { - Ok(d) => d, - Err(_) => { - out.warnings.push(format!("section {} truncated", String::from_utf8_lossy(&key))); - r.take(r.left())? - } - }; - // Sections are padded to 4 bytes; tolerate writers that don't pad. - let pad = (4 - len % 4) % 4; - if pad > 0 && r.b.get(r.p..r.p + 4) != Some(b"8BIM") && r.b.get(r.p + pad..r.p + pad + 4) == Some(b"8BIM") { - r.p += pad; - } - match &key { - b"samp" => read_samp(data, out.subversion, out, budget)?, - b"patt" => { - // Patterns share the samples' budget and one padding budget across every `patt` - // section, so neither can be claimed twice and failed blocks still deduct their - // decoded charges. - let limit = u64::try_from(budget.0).unwrap_or(u64::MAX); - patterns.cap_decoded_to(limit); - let left = patterns.decoded_left(); - let res = parse_pattern_block_with(data, &mut patterns); - let spent = usize::try_from(left.saturating_sub(patterns.decoded_left())).unwrap_or(usize::MAX); - budget.spend(spent)?; - match res { - Ok(p) => out.patterns.extend(p), - Err(e) => out.warnings.push(format!("embedded patterns unreadable: {e}")), - } - } - b"desc" => read_desc(data, out), - // Read once `desc` gives the preset count; `phry` may come first. - b"phry" => hierarchy = Some(data), - // Tool presets: not needed for the brushes. - b"lPdc" => {} - k => out.warnings.push(format!("section {} ignored", String::from_utf8_lossy(k))), - } - } - apply_hierarchy(out, hierarchy); - Ok(()) -} - -/// Parses an `.abr` file. -pub fn parse(data: &[u8]) -> Result { - let mut r = Rd::new(data); - let version = r.u16()?; - let mut out = AbrFile { version, ..Default::default() }; - match version { - 1 | 2 => parse_v12(&mut r, version, &mut out)?, - 6..=10 => parse_v6(&mut r, &mut out)?, - v => return Err(PsdError::Unsupported(format!("brush file version {v}"))), - } - if out.legacy.is_empty() && out.samples.is_empty() && out.presets.is_empty() { - let why = out.warnings.first().map(|w| format!(" ({w})")).unwrap_or_default(); - return Err(PsdError::invalid(format!("the brush file holds no readable brushes{why}"))); - } - Ok(out) -} - -// ------------------------------------------------------------------ writing - -fn put_u16(o: &mut Vec, v: u16) { - o.extend_from_slice(&v.to_be_bytes()); -} -fn put_u32(o: &mut Vec, v: u32) { - o.extend_from_slice(&v.to_be_bytes()); -} - -fn write_sample_body(o: &mut Vec, s: &AbrSample, rle: bool) -> Result<()> { - if s.width == 0 || s.height == 0 || s.width > MAX_EDGE || s.height > MAX_EDGE || !matches!(s.depth, 8 | 16) { - return Err(PsdError::LimitExceeded("brush sample size or depth")); - } - for v in [0, 0, s.height as i32, s.width as i32] { - o.extend_from_slice(&v.to_be_bytes()); - } - put_u16(o, s.depth); - o.push(u8::from(rle)); - let layout = PlaneLayout { planes: 1, width: s.width as usize, height: s.height as usize, depth: s.depth, version: Version::Psd }; - o.extend_from_slice(&encode_planes(if rle { Compression::Rle } else { Compression::Raw }, &s.data, &layout)?); - Ok(()) -} - -/// Writes a v1 or v2 file. Sampled tips are PackBits-compressed when `rle`. -pub fn write_v12(version: u16, brushes: &[LegacyBrush], rle: bool) -> Result> { - if !matches!(version, 1 | 2) || brushes.len() > usize::from(u16::MAX) { - return Err(PsdError::Unsupported(format!("writing brush file version {version}"))); - } - let mut o = Vec::new(); - put_u16(&mut o, version); - put_u16(&mut o, brushes.len() as u16); - for b in brushes { - let mut body = Vec::new(); - put_u32(&mut body, 0); - put_u16(&mut body, b.spacing); - let ty = match &b.tip { - LegacyTip::Computed { diameter, hardness, angle, roundness } => { - for v in [*diameter, *roundness, *angle as u16, *hardness] { - put_u16(&mut body, v); - } - 1 - } - LegacyTip::Sampled(s) => { - if version == 2 { - let units: Vec = b.name.encode_utf16().chain(std::iter::once(0)).collect(); - put_u32(&mut body, units.len() as u32); - for u in units { - put_u16(&mut body, u); - } - } - body.push(u8::from(b.anti_alias)); - for v in [0u16, 0, s.height.min(0xffff) as u16, s.width.min(0xffff) as u16] { - put_u16(&mut body, v); - } - write_sample_body(&mut body, s, rle)?; - 2 - } - }; - put_u16(&mut o, ty); - put_u32(&mut o, body.len() as u32); - o.extend_from_slice(&body); - } - Ok(o) -} - -fn section(o: &mut Vec, key: &[u8; 4], data: &[u8]) { - o.extend_from_slice(b"8BIM"); - o.extend_from_slice(key); - let pad = (4 - data.len() % 4) % 4; - put_u32(o, (data.len() + pad) as u32); - o.extend_from_slice(data); - o.extend(std::iter::repeat_n(0u8, pad)); -} - -/// Writes a v6 (`subversion` 1 or 2) file: sampled tips, embedded patterns and the preset -/// descriptors (each a `brushPreset` object), listed under `Brsh`. Every preset is at the top -/// level ([`write_v6_folders`] keeps folders). -pub fn write_v6(subversion: u16, samples: &[AbrSample], patterns: &[PsdPattern], presets: &[Descriptor], rle: bool) -> Result> { - write_v6_folders(subversion, samples, patterns, presets, &[], rle) -} - -/// A stable uuid-shaped folder id (`zuid`) derived from the folder's path and position. -fn folder_uuid(path: &[&str], seq: usize) -> String { - // FNV-1a over the path, with two seeds, for 128 bits. - let hash = |seed: u64| { - let mut h = 0xcbf2_9ce4_8422_2325u64 ^ seed; - for b in path.iter().flat_map(|s| s.bytes().chain(std::iter::once(0))).chain(seq.to_le_bytes()) { - h ^= u64::from(b); - h = h.wrapping_mul(0x0000_0100_0000_01b3); - } - h - }; - let (a, b) = (hash(1), hash(2)); - format!("{:08x}-{:04x}-{:04x}-{:04x}-{:012x}", a >> 32, (a >> 16) & 0xffff, a & 0xffff, b >> 48, b & 0xffff_ffff_ffff) -} - -/// The `phry` descriptor for presets in `folders` (one path per preset, in preset order). -/// Presets of one folder that are not adjacent reopen it (a reader merges them by path). -fn hierarchy_descriptor(folders: &[Vec]) -> Descriptor { - let text = |s: &str| Value::Text(crate::descriptor::UnicodeString::new_nul(s)); - let mut items = Vec::new(); - let mut open: Vec<&str> = Vec::new(); - let mut seq = 0usize; - for path in folders { - let path: Vec<&str> = path.iter().take(MAX_FOLDER_DEPTH).map(String::as_str).collect(); - let common = open.iter().zip(&path).take_while(|(a, b)| a == b).count(); - while open.len() > common { - open.pop(); - items.push(Value::Descriptor(Descriptor::new("groupEnd"))); - } - for name in path.iter().skip(common) { - open.push(name); - seq += 1; - items.push(Value::Descriptor(Descriptor::new("Grup").with("Nm ", text(name)).with("zuid", text(&folder_uuid(&open, seq))))); - } - items.push(Value::Descriptor(Descriptor::new("preset"))); - } - for _ in open { - items.push(Value::Descriptor(Descriptor::new("groupEnd"))); - } - Descriptor::new("null").with("hierarchy", Value::List(items)) -} - -/// [`write_v6`] that also writes the preset hierarchy (`phry`): `folders` holds each preset's -/// folder path (outermost first; empty = top level), parallel to `presets`. With no folders (an -/// empty slice, or only empty paths) no hierarchy is written. -pub fn write_v6_folders( - subversion: u16, - samples: &[AbrSample], - patterns: &[PsdPattern], - presets: &[Descriptor], - folders: &[Vec], - rle: bool, -) -> Result> { - if !folders.is_empty() && folders.len() != presets.len() { - return Err(PsdError::invalid(format!("{} folder paths for {} brush presets", folders.len(), presets.len()))); - } - if !matches!(subversion, 1 | 2) { - return Err(PsdError::Unsupported(format!("brush file subversion {subversion}"))); - } - let mut o = Vec::new(); - put_u16(&mut o, 6); - put_u16(&mut o, subversion); - let mut samp = Vec::new(); - for s in samples { - let mut e = Vec::new(); - let id = s.id.as_bytes(); - let n = id.len().min(255); - e.push(n as u8); - e.extend_from_slice(&id[..n]); - e.extend(std::iter::repeat_n(0u8, if subversion == 1 { 10 } else { 264 })); - write_sample_body(&mut e, s, rle)?; - put_u32(&mut samp, e.len() as u32); - let pad = (4 - e.len() % 4) % 4; - samp.extend_from_slice(&e); - samp.extend(std::iter::repeat_n(0u8, pad)); - } - section(&mut o, b"samp", &samp); - if !patterns.is_empty() { - section(&mut o, b"patt", &write_pattern_block(patterns)?); - } - let list = Value::List(presets.iter().cloned().map(Value::Descriptor).collect()); - let desc = VersionedDescriptor::new(Descriptor::new("null").with("Brsh", list)); - section(&mut o, b"desc", &desc.to_bytes()); - if folders.iter().any(|f| !f.is_empty()) { - section(&mut o, b"phry", &VersionedDescriptor::new(hierarchy_descriptor(folders)).to_bytes()); - } - Ok(o) -} - -#[cfg(test)] -mod tests; diff --git a/crates/psd/src/abr/tests.rs b/crates/psd/src/abr/tests.rs deleted file mode 100644 index 29ed91ec6e..0000000000 --- a/crates/psd/src/abr/tests.rs +++ /dev/null @@ -1,298 +0,0 @@ -use super::*; -use crate::descriptor::UnicodeString; - -fn sample(id: &str, w: u32, h: u32, depth: u16) -> AbrSample { - let bpp = usize::from(depth / 8); - let data = (0..w as usize * h as usize * bpp).map(|i| if (i / bpp) % 3 == 0 { 255 } else { (i % 7) as u8 * 30 }).collect(); - AbrSample { id: id.into(), width: w, height: h, depth, data } -} - -#[test] -fn embedded_patterns_spend_the_samples_budget() { - let p = PsdPattern { - mode: 3, - width: 5, - height: 3, - name: "p".into(), - id: "id".into(), - palette: None, - depth: 8, - channels: vec![vec![1; 15], vec![2; 15], vec![3; 15]], - alpha: None, - }; - let abr = write_v6(2, &[sample("s", 10, 10, 8)], &[p.clone(), p], &[], true).unwrap(); - let parse_within = |left: usize| { - let mut out = AbrFile::default(); - let mut budget = Budget(left); - parse_v6_within(&mut Rd::new(&abr[2..]), &mut out, &mut budget).unwrap(); - (out, budget.0) - }; - // 100 sample bytes plus two 45-byte patterns. - let (out, left) = parse_within(190); - assert_eq!((out.samples.len(), out.patterns.len(), left), (1, 2, 0)); - // One byte short: the patterns no longer fit after the sample (they used not to count). - let (out, left) = parse_within(189); - assert_eq!((out.samples.len(), out.patterns.len(), left), (1, 0, 14)); - assert!(out.warnings.iter().any(|w| w.contains("embedded patterns unreadable")), "{:?}", out.warnings); -} - -#[test] -fn failed_pattern_section_does_not_refund_budget_to_later_sections() { - let p = PsdPattern { - mode: 3, - width: 5, - height: 3, - name: "p".into(), - id: "id".into(), - palette: None, - depth: 8, - channels: vec![vec![1; 15], vec![2; 15], vec![3; 15]], - alpha: None, - }; - let valid = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let mut malformed = valid.clone(); - malformed.extend_from_slice(&100u32.to_be_bytes()); - - let mut body = 2u16.to_be_bytes().to_vec(); - section(&mut body, b"patt", &malformed); - section(&mut body, b"patt", &valid); - let mut out = AbrFile::default(); - let mut budget = Budget(60); - parse_v6_within(&mut Rd::new(&body), &mut out, &mut budget).unwrap(); - - assert!(out.patterns.is_empty(), "a failed block is discarded atomically"); - assert_eq!(budget.0, 0, "the failed block's first 45 bytes and later partial 15-byte charge are retained"); - assert_eq!(out.warnings.iter().filter(|w| w.contains("embedded patterns unreadable")).count(), 2); -} - -#[test] -fn v1_v2_round_trip_raw_and_rle() { - for version in [1u16, 2] { - for rle in [false, true] { - let brushes = vec![ - LegacyBrush { - name: String::new(), - spacing: 25, - anti_alias: true, - tip: LegacyTip::Computed { diameter: 19, hardness: 80, angle: -30, roundness: 50 }, - }, - LegacyBrush { - name: if version == 2 { "Leaf ✓".into() } else { String::new() }, - spacing: 40, - anti_alias: false, - tip: LegacyTip::Sampled(sample("", 13, 9, 8)), - }, - LegacyBrush { name: String::new(), spacing: 10, anti_alias: true, tip: LegacyTip::Sampled(sample("", 4, 6, 16)) }, - ]; - let bytes = write_v12(version, &brushes, rle).unwrap(); - let f = parse(&bytes).unwrap(); - assert_eq!(f.version, version); - assert_eq!(f.legacy, brushes, "v{version} rle={rle}"); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); - } - } -} - -#[test] -fn v6_round_trip_both_subversions() { - let samples = vec![sample("$abc", 20, 11, 8), sample("$def", 5, 5, 16)]; - let preset = Descriptor::new("brushPreset") - .with("Nm ", Value::Text(UnicodeString::new_nul("Grass"))) - .with("Brsh", Value::Descriptor(Descriptor::new("sampledBrush").with("sampledData", Value::Text(UnicodeString::new_nul("$abc"))))); - for sub in [1u16, 2] { - for rle in [false, true] { - let bytes = write_v6(sub, &samples, &[], std::slice::from_ref(&preset), rle).unwrap(); - let f = parse(&bytes).unwrap(); - assert_eq!((f.version, f.subversion), (6, sub)); - assert_eq!(f.samples, samples); - assert_eq!(f.presets, vec![preset.clone()]); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); - } - } - assert_eq!(samples[1].to_unit().len(), 25); -} - -#[test] -fn hostile_input_errors_without_panicking() { - assert!(parse(&[]).is_err()); - assert!(parse(&[0, 3, 0, 0]).is_err()); - assert!(parse(&[0, 6, 0, 9]).is_err()); - // Absurd sample bounds. - let mut s = sample("", 2, 2, 8); - s.width = MAX_EDGE + 1; - assert!(write_v12(1, &[LegacyBrush { name: String::new(), spacing: 1, anti_alias: true, tip: LegacyTip::Sampled(s) }], false).is_err()); - let good = write_v6(2, &[sample("$a", 30, 30, 8)], &[], &[Descriptor::new("brushPreset")], true).unwrap(); - for cut in 0..good.len() { - let _ = parse(&good[..cut]); - } - let v2 = write_v12(2, &[LegacyBrush { name: "x".into(), spacing: 1, anti_alias: true, tip: LegacyTip::Sampled(sample("", 9, 9, 16)) }], true).unwrap(); - for cut in 0..v2.len() { - let _ = parse(&v2[..cut]); - } - // Flip every byte once: never panics. - for i in 0..good.len() { - let mut b = good.clone(); - b[i] ^= 0xa5; - let _ = parse(&b); - } - // A huge declared count with no data is an error, not an allocation. - assert!(parse(&[0, 2, 0xff, 0xff]).is_err()); -} - -fn named(n: &str) -> Descriptor { - Descriptor::new("brushPreset").with("Nm ", Value::Text(UnicodeString::new_nul(n))) -} - -/// Hierarchy tokens: `G(name)` opens, `P` is a preset, `E` closes. -enum Tok<'a> { - G(&'a str), - P, - E, -} - -/// A v6 file with `n` presets and a hand-made `phry` token stream. -fn with_phry(n: usize, toks: &[Tok]) -> Vec { - let presets: Vec = (0..n).map(|i| named(&format!("B{i}"))).collect(); - let mut bytes = write_v6(2, &[], &[], &presets, false).unwrap(); - section(&mut bytes, b"phry", &phry_bytes(toks)); - bytes -} - -/// A `phry` section body holding `toks`. -fn phry_bytes(toks: &[Tok]) -> Vec { - let items = toks - .iter() - .map(|t| { - Value::Descriptor(match t { - Tok::G(name) => Descriptor::new("Grup") - .with("Nm ", Value::Text(UnicodeString::new_nul(name))) - .with("zuid", Value::Text(UnicodeString::new_nul("c9ee8fd5-eb7d-924c-9e95-ddc98e40bb6c"))), - Tok::P => Descriptor::new("preset"), - Tok::E => Descriptor::new("groupEnd"), - }) - }) - .collect(); - VersionedDescriptor::new(Descriptor::new("null").with("hierarchy", Value::List(items))).to_bytes() -} - -fn path(p: &[&str]) -> Vec { - p.iter().map(|s| s.to_string()).collect() -} - -#[test] -fn phry_flat_folders_like_photoshop_25() { - // The layout of Photoshop 25.1's default brushes: four folders, every preset in one. - use Tok::*; - let f = parse(&with_phry(5, &[G("General"), P, P, E, G("Dry Media"), P, E, G("Wet Media"), P, E, G("Special Effects"), P, E])).unwrap(); - assert_eq!(f.folders, vec![path(&["General"]), path(&["General"]), path(&["Dry Media"]), path(&["Wet Media"]), path(&["Special Effects"])]); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); -} - -#[test] -fn phry_nested_folders_and_top_level_presets() { - use Tok::*; - let f = parse(&with_phry(5, &[P, G("Animals"), G("Birds"), P, E, P, G("Fish"), P, E, E, P])).unwrap(); - assert_eq!(f.folders, vec![path(&[]), path(&["Animals", "Birds"]), path(&["Animals"]), path(&["Animals", "Fish"]), path(&[])]); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); - // No folder at all: no hierarchy. - let f = parse(&with_phry(2, &[P, P])).unwrap(); - assert!(f.folders.is_empty()); -} - -#[test] -fn phry_mismatches_become_warnings() { - use Tok::*; - // A stray groupEnd is ignored; an unclosed folder still holds its presets. - let f = parse(&with_phry(2, &[E, G("A"), P, E, E, G("B"), P])).unwrap(); - assert_eq!(f.folders, vec![path(&["A"]), path(&["B"])]); - assert!(f.warnings.iter().any(|w| w.contains("folder end")), "{:?}", f.warnings); - // Fewer preset tokens than presets: the rest are at the top level. - let f = parse(&with_phry(3, &[G("A"), P, E])).unwrap(); - assert_eq!(f.folders, vec![path(&["A"]), path(&[]), path(&[])]); - assert!(f.warnings.iter().any(|w| w.contains("list 1 brushes but the file holds 3")), "{:?}", f.warnings); - // More preset tokens than presets: extras ignored. - let f = parse(&with_phry(1, &[G("A"), P, P, P, E])).unwrap(); - assert_eq!(f.folders, vec![path(&["A"])]); - assert_eq!(f.presets.len(), 1); - assert!(!f.warnings.is_empty()); - // A depth bomb: folders deeper than the limit merge into their ancestor at the limit. - let mut toks: Vec = (0..10_000).map(|_| G("deep")).collect(); - toks.push(P); - toks.extend((0..10_000).map(|_| E)); - toks.extend([G("next"), P, E]); - let f = parse(&with_phry(2, &toks)).unwrap(); - assert_eq!(f.folders[0].len(), MAX_FOLDER_DEPTH); - assert_eq!(f.folders[1], path(&["next"])); - assert!(f.warnings.iter().any(|w| w.contains("deeper")), "{:?}", f.warnings); - // An unreadable hierarchy: imported flat, with a warning. - let mut bytes = write_v6(2, &[], &[], &[named("x")], false).unwrap(); - section(&mut bytes, b"phry", &[0, 0, 0, 16, 0xff, 0xff]); - let f = parse(&bytes).unwrap(); - assert!(f.folders.is_empty() && f.presets.len() == 1); - assert!(f.warnings.iter().any(|w| w.contains("phry")), "{:?}", f.warnings); - // Truncations and bit flips of a file with a hierarchy never panic. - let good = with_phry(3, &[G("A"), P, G("B"), P, E, E, P]); - for cut in 0..good.len() { - let _ = parse(&good[..cut]); - } - for i in 0..good.len() { - let mut b = good.clone(); - b[i] ^= 0x5a; - let _ = parse(&b); - } -} - -#[test] -fn phry_builds_paths_only_for_the_files_presets() { - use Tok::*; - // A few-KB section listing 100,000 deep presets for a file with 2: two paths are built. - let mut toks: Vec = (0..MAX_FOLDER_DEPTH).map(|_| G("folder")).collect(); - toks.extend((0..100_000).map(|_| P)); - let mut warnings = Vec::new(); - let folders = read_phry(&phry_bytes(&toks), 2, &mut warnings).unwrap(); - assert_eq!(folders.len(), 2); - assert_eq!(folders.capacity(), 2); - assert_eq!(folders[1].len(), MAX_FOLDER_DEPTH); - assert!(warnings.iter().any(|w| w.contains("list 100000 brushes but the file holds 2")), "{warnings:?}"); - // `phry` before `desc` still pairs with the file's presets. - let mut bytes = write_v6(2, &[], &[], &[named("a"), named("b")], false).unwrap(); - let at = bytes.windows(8).position(|w| w == b"8BIMdesc").unwrap(); - let mut phry = Vec::new(); - section(&mut phry, b"phry", &phry_bytes(&[G("A"), P, E, P])); - bytes.splice(at..at, phry); - let f = parse(&bytes).unwrap(); - assert_eq!(f.folders, vec![path(&["A"]), path(&[])]); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); -} - -#[test] -fn phry_folder_paths_stay_within_their_byte_budget() { - use Tok::*; - // Thousands of presets under 32 folders of 255-character names would need ~27 MB of paths. - let long = "x".repeat(MAX_FOLDER_NAME); - let mut toks: Vec = (0..MAX_FOLDER_DEPTH).map(|_| G(&long)).collect(); - toks.extend((0..3_000).map(|_| P)); - let mut warnings = Vec::new(); - let folders = read_phry(&phry_bytes(&toks), 3_000, &mut warnings).unwrap(); - assert_eq!(folders.len(), 3_000); - let held: usize = folders.iter().flatten().map(|n| n.len() + size_of::()).sum(); - assert!(held <= MAX_FOLDER_BYTES, "{held}"); - assert_eq!(folders[0].len(), MAX_FOLDER_DEPTH); - assert!(folders[2_999].is_empty(), "past the budget: top level"); - assert!(warnings.iter().any(|w| w.contains("too large")), "{warnings:?}"); -} - -#[test] -fn phry_round_trips_through_the_writer() { - let presets: Vec = (0..6).map(|i| named(&format!("B{i}"))).collect(); - let folders = vec![path(&[]), path(&["Set", "Ink"]), path(&["Set", "Ink"]), path(&["Set"]), path(&["Other"]), path(&["Set", "Ink"])]; - let bytes = write_v6_folders(2, &[], &[], &presets, &folders, true).unwrap(); - let f = parse(&bytes).unwrap(); - assert_eq!(f.presets, presets); - assert_eq!(f.folders, folders); - assert!(f.warnings.is_empty(), "{:?}", f.warnings); - // No folders: no phry section, same bytes as write_v6. - assert_eq!(write_v6_folders(2, &[], &[], &presets, &vec![Vec::new(); 6], true).unwrap(), write_v6(2, &[], &[], &presets, true).unwrap()); - // Mismatched lengths are an error. - assert!(write_v6_folders(2, &[], &[], &presets, &folders[..2], true).is_err()); -} diff --git a/crates/psd/src/aco.rs b/crates/psd/src/aco.rs deleted file mode 100644 index 24f0b1c6f1..0000000000 --- a/crates/psd/src/aco.rs +++ /dev/null @@ -1,341 +0,0 @@ -//! Photoshop Color Swatches files (`.aco`), versions 1 and 2. -//! -//! Layout from Adobe's public "Photoshop File Formats Specification" (Color Swatches): a -//! version 1 section (`u16` version = 1, `u16` count, then `count` colour records of a `u16` -//! colour space id and four `u16` values), usually followed by a version 2 section with the -//! same colours plus a name each (a `u32` UTF-16 code-unit count that includes the trailing -//! null, then the big-endian units). Files that start with the version 2 section are read too. -//! -//! Colour encodings (spec, "Color structure"): RGB and HSB are full 16-bit values; CMYK stores -//! 0 for 100 % ink; Lab stores L* × 100 (0..=10000) and signed a*, b* × 100; grayscale stores a -//! gray level 0..=10000 where 0 is black (public notes on the format convert it with -//! `level / 39.0625` to 0..255). Colours are kept at their 16-bit precision in the space they -//! were stored in; any other colour space (colour books, wide CMYK, …) is kept verbatim so a -//! read → write round trip never loses it. Converting colours is the caller's job. - -use crate::error::{PsdError, Result}; -use crate::io::{Reader, WriteExt}; - -/// Most swatches in one file (the counts are 16-bit). -pub const MAX_SWATCHES: usize = u16::MAX as usize; -/// Longest name read or written, in UTF-16 code units (Photoshop's own limit is far lower). -pub const MAX_NAME_UNITS: usize = 1024; - -/// Colour space ids of the `.aco` colour record. -pub mod space { - /// RGB. - pub const RGB: u16 = 0; - /// HSB. - pub const HSB: u16 = 1; - /// CMYK. - pub const CMYK: u16 = 2; - /// CIE L*a*b*. - pub const LAB: u16 = 7; - /// Grayscale. - pub const GRAY: u16 = 8; -} - -/// A swatch colour as stored, at full 16-bit precision. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum AcoColor { - /// Red, green, blue, 0..=65535. - Rgb([u16; 3]), - /// Hue (0..=65535 for 0..360°), saturation and brightness (0..=65535). - Hsb([u16; 3]), - /// Cyan, magenta, yellow, black **ink** amounts, 0..=65535 (65535 = 100 % ink; the file - /// stores the complement). - Cmyk([u16; 4]), - /// L* × 100 (0..=10000), a* × 100 and b* × 100 (−12800..=12700). - Lab { - /// Lightness × 100. - l: u16, - /// a* × 100. - a: i16, - /// b* × 100. - b: i16, - }, - /// Gray level 0..=10000 (0 = black, 10000 = white). - Gray(u16), - /// Any other colour space, kept verbatim (the four values as stored). - Other { - /// Colour space id. - space: u16, - /// The four stored values. - values: [u16; 4], - }, -} - -impl AcoColor { - /// Decode a colour record (space id + four stored values). - pub fn from_record(space: u16, v: [u16; 4]) -> AcoColor { - match space { - space::RGB => AcoColor::Rgb([v[0], v[1], v[2]]), - space::HSB => AcoColor::Hsb([v[0], v[1], v[2]]), - space::CMYK => AcoColor::Cmyk(v.map(|x| u16::MAX - x)), - space::LAB => AcoColor::Lab { l: v[0], a: v[1] as i16, b: v[2] as i16 }, - space::GRAY => AcoColor::Gray(v[0]), - _ => AcoColor::Other { space, values: v }, - } - } - - /// The colour record (space id + four stored values) for this colour. - pub fn to_record(self) -> (u16, [u16; 4]) { - match self { - AcoColor::Rgb([r, g, b]) => (space::RGB, [r, g, b, 0]), - AcoColor::Hsb([h, s, b]) => (space::HSB, [h, s, b, 0]), - AcoColor::Cmyk(c) => (space::CMYK, c.map(|x| u16::MAX - x)), - AcoColor::Lab { l, a, b } => (space::LAB, [l, a as u16, b as u16, 0]), - AcoColor::Gray(g) => (space::GRAY, [g, 0, 0, 0]), - AcoColor::Other { space, values } => (space, values), - } - } -} - -/// One swatch: a colour and its name (empty in version 1 only files). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct AcoSwatch { - /// Name (from the version 2 section). - pub name: String, - /// Colour. - pub color: AcoColor, -} - -/// A parsed `.aco` file. -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub struct AcoFile { - /// Swatches in file order. - pub swatches: Vec, - /// Whether the file had a version 2 section (names). - pub has_names: bool, -} - -fn read_record(r: &mut Reader<'_>) -> Result { - let space = r.u16()?; - let v = [r.u16()?, r.u16()?, r.u16()?, r.u16()?]; - Ok(AcoColor::from_record(space, v)) -} - -fn read_name(r: &mut Reader<'_>) -> Result { - let n = u64::from(r.u32()?); - r.check_count(n, 2)?; - let n = usize::try_from(n).map_err(|_| PsdError::LimitExceeded("swatch name length"))?; - let mut units = Vec::with_capacity(n.min(MAX_NAME_UNITS)); - for _ in 0..n { - let u = r.u16()?; - if units.len() < MAX_NAME_UNITS { - units.push(u); - } - } - while units.last() == Some(&0) { - units.pop(); - } - Ok(String::from_utf16_lossy(&units)) -} - -fn read_section(r: &mut Reader<'_>, named: bool) -> Result> { - let count = r.u16()? as usize; - // Each record is at least 10 bytes (plus a 4-byte name length in version 2). - r.check_count(count as u64, if named { 14 } else { 10 })?; - let mut out = Vec::with_capacity(count); - for _ in 0..count { - let color = read_record(r)?; - let name = if named { read_name(r)? } else { String::new() }; - out.push(AcoSwatch { name, color }); - } - Ok(out) -} - -/// Parse an `.aco` file. Truncated sections, unknown versions and impossible counts are errors; -/// never panics. -pub fn parse(data: &[u8]) -> Result { - let mut r = Reader::new(data); - match r.u16()? { - 1 => { - let v1 = read_section(&mut r, false)?; - // A version 2 section follows in files written by Photoshop 6 and later; anything - // else after version 1 (padding some writers add) is ignored. - if r.remaining() >= 4 && r.peek_rest().get(..2) == Some(&[0, 2]) { - r.u16()?; - let v2 = read_section(&mut r, true)?; - return Ok(AcoFile { swatches: v2, has_names: true }); - } - Ok(AcoFile { swatches: v1, has_names: false }) - } - 2 => Ok(AcoFile { swatches: read_section(&mut r, true)?, has_names: true }), - v => Err(PsdError::UnsupportedVersion(v)), - } -} - -/// How many bytes the `.aco` sections at the start of `data` span (what [`parse`] reads), or -/// `None` when they are truncated or the version is unknown. Tells a real `.aco` apart from -/// bytes that only start like one, such as an `.act` whose first colour is `0, 1, x`. -pub fn sections_len(data: &[u8]) -> Option { - fn skip_section(r: &mut Reader<'_>, named: bool) -> Result<()> { - let count = r.u16()?; - for _ in 0..count { - r.skip(10)?; - if named { - let n = u64::from(r.u32()?); - r.bytes_u64(n * 2)?; - } - } - Ok(()) - } - let mut r = Reader::new(data); - match r.u16().ok()? { - 1 => { - skip_section(&mut r, false).ok()?; - if r.remaining() >= 4 && r.peek_rest().get(..2) == Some(&[0, 2]) { - r.u16().ok()?; - skip_section(&mut r, true).ok()?; - } - } - 2 => skip_section(&mut r, true).ok()?, - _ => return None, - } - Some(r.pos()) -} - -/// Write an `.aco` file: a version 1 section followed by a version 2 section with the names, -/// as Photoshop writes them. Fails when there are more than [`MAX_SWATCHES`] swatches. -pub fn write(swatches: &[AcoSwatch]) -> Result> { - let count = u16::try_from(swatches.len()).map_err(|_| PsdError::LimitExceeded("an .aco file holds at most 65535 swatches"))?; - let mut out = Vec::with_capacity(8 + swatches.len() * 40); - for version in [1u16, 2] { - out.put_u16(version); - out.put_u16(count); - for s in swatches { - let (space, v) = s.color.to_record(); - out.put_u16(space); - for x in v { - out.put_u16(x); - } - if version == 2 { - let units = crate::io::utf16_units(&s.name, MAX_NAME_UNITS); - // The length counts the terminating null. - out.put_u32(units.len() as u32 + 1); - for u in units { - out.put_u16(u); - } - out.put_u16(0); - } - } - } - Ok(out) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn sample() -> Vec { - vec![ - AcoSwatch { name: "Pure Red".into(), color: AcoColor::Rgb([65535, 0, 0]) }, - AcoSwatch { name: "Hue".into(), color: AcoColor::Hsb([12000, 65535, 40000]) }, - AcoSwatch { name: "Cyan ink".into(), color: AcoColor::Cmyk([65535, 0, 0, 1234]) }, - AcoSwatch { name: "Lab −".into(), color: AcoColor::Lab { l: 5321, a: -12800, b: 12700 } }, - AcoSwatch { name: "Gray".into(), color: AcoColor::Gray(5000) }, - AcoSwatch { name: "Book 日本".into(), color: AcoColor::Other { space: 3, values: [1, 2, 3, 4] } }, - AcoSwatch { name: String::new(), color: AcoColor::Rgb([1, 2, 3]) }, - ] - } - - #[test] - fn sections_len_is_what_parse_reads() { - let file = write(&sample()).unwrap(); - assert_eq!(sections_len(&file), Some(file.len())); - let mut padded = file.clone(); - padded.extend_from_slice(&[0; 6]); - assert_eq!(sections_len(&padded), Some(file.len()), "trailing bytes are not part of it"); - assert_eq!(sections_len(&file[..file.len() - 1]), None, "truncated"); - assert_eq!(sections_len(&[0, 3, 0, 0]), None, "unknown version"); - assert_eq!(sections_len(&[0, 1, 0, 0]), Some(4)); - } - - #[test] - fn round_trips_every_space_at_16_bits() { - let s = sample(); - let bytes = write(&s).unwrap(); - let f = parse(&bytes).unwrap(); - assert!(f.has_names); - assert_eq!(f.swatches, s); - assert_eq!(write(&f.swatches).unwrap(), bytes, "byte-stable"); - } - - #[test] - fn decodes_the_spec_encodings() { - // Pure cyan as the spec gives it: 0, 65535, 65535, 65535 (0 = 100 % ink). - assert_eq!(AcoColor::from_record(2, [0, 65535, 65535, 65535]), AcoColor::Cmyk([65535, 0, 0, 0])); - // White Lab = 10000, 0, 0; negative chrominance is two's complement. - assert_eq!(AcoColor::from_record(7, [10000, 0xFF38, 200, 0]), AcoColor::Lab { l: 10000, a: -200, b: 200 }); - assert_eq!(AcoColor::from_record(8, [10000, 0, 0, 0]), AcoColor::Gray(10000)); - assert_eq!(AcoColor::from_record(9, [7, 8, 9, 10]), AcoColor::Other { space: 9, values: [7, 8, 9, 10] }); - } - - #[test] - fn reads_version_1_only_and_version_2_only() { - // Version 1: two RGB colours, no names. - let v1 = [0u8, 1, 0, 2, 0, 0, 255, 255, 0, 0, 0, 0, 0, 0, 0, 8, 0x13, 0x88, 0, 0, 0, 0, 0, 0]; - let f = parse(&v1).unwrap(); - assert!(!f.has_names); - assert_eq!(f.swatches.iter().map(|s| s.color).collect::>(), vec![AcoColor::Rgb([65535, 0, 0]), AcoColor::Gray(5000)]); - // Trailing padding after a version 1 section is ignored. - let mut padded = v1.to_vec(); - padded.extend_from_slice(&[0, 0, 0, 0]); - assert_eq!(parse(&padded).unwrap().swatches.len(), 2); - // Version 2 only (the v1 section is skipped by some writers); name without its null. - let mut v2 = vec![0u8, 2, 0, 1, 0, 0, 0, 1, 0, 2, 0, 3, 0, 0]; - v2.extend_from_slice(&[0, 0, 0, 2, 0, b'O', 0, b'K']); - let f = parse(&v2).unwrap(); - assert_eq!(f.swatches, vec![AcoSwatch { name: "OK".into(), color: AcoColor::Rgb([1, 2, 3]) }]); - } - - #[test] - fn hostile_input_is_an_error_not_a_panic() { - let good = write(&sample()).unwrap(); - for n in 0..good.len() { - // Every truncation inside a section fails (a cut exactly after v1 reads v1). - let r = parse(&good[..n]); - let v1_end = 4 + sample().len() * 10; - if n == v1_end || (n > v1_end && n < v1_end + 4) { - assert!(r.is_ok(), "{n}"); - } else { - assert!(r.is_err(), "{n}"); - } - } - assert!(parse(&[]).is_err()); - assert!(parse(&[0, 3, 0, 0]).is_err(), "unknown version"); - assert!(parse(&[0, 1, 0xFF, 0xFF]).is_err(), "huge count"); - // A name length far beyond the data. - let mut bad = vec![0u8, 2, 0, 1, 0, 0, 0, 1, 0, 2, 0, 3, 0, 0]; - bad.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0xFF, 0, 65]); - assert!(parse(&bad).is_err()); - // Garbage of every length never panics. - let mut seed = 0x1234_5678u32; - for len in 0..300 { - let junk: Vec = (0..len) - .map(|_| { - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - (seed >> 24) as u8 - }) - .collect(); - let _ = parse(&junk); - let mut v = vec![0, 1]; - v.extend_from_slice(&junk); - let _ = parse(&v); - } - } - - #[test] - fn too_many_swatches_is_an_error() { - let many = vec![AcoSwatch { name: String::new(), color: AcoColor::Gray(0) }; MAX_SWATCHES + 1]; - assert!(write(&many).is_err()); - } - - #[test] - fn long_names_are_capped() { - let long = AcoSwatch { name: "x".repeat(5000), color: AcoColor::Gray(0) }; - let f = parse(&write(&[long]).unwrap()).unwrap(); - assert_eq!(f.swatches[0].name.len(), MAX_NAME_UNITS); - } -} diff --git a/crates/psd/src/act.rs b/crates/psd/src/act.rs deleted file mode 100644 index 58e872bf97..0000000000 --- a/crates/psd/src/act.rs +++ /dev/null @@ -1,143 +0,0 @@ -//! Photoshop Color Table files (`.act`): raw 8-bit RGB palettes. -//! -//! Layout from Adobe's public "Photoshop File Formats Specification" (Color Table): 256 RGB -//! triplets (768 bytes), optionally followed by a 4-byte trailer: a big-endian `u16` color -//! count ("the number of colors to use") and a big-endian `u16` transparent color index. -//! There are no names, no groups and no other color spaces. The trailer is kept verbatim so a -//! read → write round trip never loses it; interpreting it is the caller's job. - -use crate::error::{PsdError, Result}; -use crate::io::{Reader, WriteExt}; - -/// Colors in a `.act` palette. -pub const COLOR_COUNT: usize = 256; -/// Palette bytes: 256 RGB triplets. -pub const PALETTE_LEN: usize = COLOR_COUNT * 3; -/// Trailer bytes (color count + transparent index). -pub const TRAILER_LEN: usize = 4; - -/// A parsed `.act` file: the full 256-color palette plus the optional trailer, kept verbatim. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ActFile { - /// All 256 palette colors as RGB triplets. - pub colors: [[u8; 3]; COLOR_COUNT], - /// Trailer color count ("the number of colors to use"), if the file has one. - pub count: Option, - /// Trailer transparent color index, if the file has one. - pub transparent: Option, -} - -impl ActFile { - /// Colors to use: the trailer count clamped to the palette, else the whole palette. - pub fn used(&self) -> &[[u8; 3]] { - let n = self.count.map_or(COLOR_COUNT, |c| (c as usize).min(COLOR_COUNT)); - &self.colors[..n] - } - - /// The transparent color index, if the trailer names one inside the used colors. - pub fn transparent_index(&self) -> Option { - let t = usize::from(self.transparent?); - (t < self.used().len()).then_some(t) - } -} - -/// Parse an `.act` file. Anything but 768 bytes (palette only) or 772 bytes (plus the -/// trailer) is an error; never panics. -pub fn parse(data: &[u8]) -> Result { - if data.len() != PALETTE_LEN && data.len() != PALETTE_LEN + TRAILER_LEN { - return Err(PsdError::invalid("an .act file is 768 bytes, or 772 with the count trailer")); - } - let mut r = Reader::new(data); - let raw = r.bytes(PALETTE_LEN)?; - let mut colors = [[0u8; 3]; COLOR_COUNT]; - for (i, c) in colors.iter_mut().enumerate() { - let o = i * 3; - c.copy_from_slice(&raw[o..o + 3]); - } - let (count, transparent) = if r.remaining() >= TRAILER_LEN { (Some(r.u16()?), Some(r.u16()?)) } else { (None, None) }; - Ok(ActFile { colors, count, transparent }) -} - -/// Write an `.act` file: the 256-color palette plus the trailer when `count` or `transparent` is given. -/// Short palettes are padded with black; fails on a palette longer than 256 colors. -pub fn write(colors: &[[u8; 3]], count: Option, transparent: Option) -> Result> { - if colors.len() > COLOR_COUNT { - return Err(PsdError::LimitExceeded("an .act file holds at most 256 colors")); - } - let mut out = Vec::with_capacity(PALETTE_LEN + TRAILER_LEN); - for c in colors { - out.extend_from_slice(c); - } - out.resize(PALETTE_LEN, 0); - if count.is_some() || transparent.is_some() { - out.put_u16(count.unwrap_or(COLOR_COUNT as u16)); - out.put_u16(transparent.unwrap_or(0xFFFF)); - } - Ok(out) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn sample() -> [[u8; 3]; COLOR_COUNT] { - let mut colors = [[0u8; 3]; COLOR_COUNT]; - for (i, c) in colors.iter_mut().enumerate() { - let v = i as u8; - *c = [v, v.wrapping_mul(7), v.wrapping_add(13)]; - } - colors[0] = [255, 255, 255]; - colors - } - - #[test] - fn round_trips_with_and_without_the_trailer() { - let colors = sample(); - let bare = write(&colors, None, None).unwrap(); - assert_eq!(bare.len(), PALETTE_LEN); - let f = parse(&bare).unwrap(); - assert_eq!((f.count, f.transparent), (None, None)); - assert_eq!(f.used(), &colors); - assert_eq!(f.transparent_index(), None); - assert_eq!(write(&f.colors, f.count, f.transparent).unwrap(), bare, "byte-stable"); - - let trailer = write(&colors, Some(40), Some(7)).unwrap(); - assert_eq!(trailer.len(), PALETTE_LEN + TRAILER_LEN); - let f = parse(&trailer).unwrap(); - assert_eq!((f.count, f.transparent), (Some(40), Some(7))); - assert_eq!(f.used().len(), 40); - assert_eq!(f.transparent_index(), Some(7)); - assert_eq!(write(&f.colors, f.count, f.transparent).unwrap(), trailer, "byte-stable"); - } - - #[test] - fn short_palettes_pad_and_long_ones_fail() { - let few = vec![[1u8, 2, 3]; 3]; - let bytes = write(&few, None, None).unwrap(); - assert_eq!(bytes.len(), PALETTE_LEN); - assert_eq!(&bytes[..9], &[1u8, 2, 3, 1, 2, 3, 1, 2, 3]); - assert_eq!(&bytes[9..12], &[0u8, 0, 0]); - let many = vec![[0u8; 3]; COLOR_COUNT + 1]; - assert!(write(&many, None, None).is_err()); - } - - #[test] - fn hostile_lengths_are_errors_not_panics() { - let good = write(&sample(), Some(256), Some(255)).unwrap(); - assert_eq!(good.len(), PALETTE_LEN + TRAILER_LEN); - for n in 0..good.len() { - // Only the two exact lengths parse (768 reads as a trailer-less palette). - if n == PALETTE_LEN { - assert!(parse(&good[..n]).is_ok(), "{n}"); - } else { - assert!(parse(&good[..n]).is_err(), "{n}"); - } - } - assert!(parse(&[]).is_err()); - assert!(parse(&vec![0u8; PALETTE_LEN + TRAILER_LEN + 1]).is_err(), "trailing byte"); - // A count past the palette clamps; a transparent index past it is none. - let f = parse(&write(&sample(), Some(1000), Some(999)).unwrap()).unwrap(); - assert_eq!(f.used().len(), COLOR_COUNT); - assert_eq!(f.transparent_index(), None); - } -} diff --git a/crates/psd/src/animation.rs b/crates/psd/src/animation.rs deleted file mode 100644 index de29693f6c..0000000000 --- a/crates/psd/src/animation.rs +++ /dev/null @@ -1,228 +0,0 @@ -//! Legacy Photoshop frame-animation syntax, independent of playback or document semantics. -//! -//! Observed in a CS5-authored PSD: a plug-in image resource (id in 4000..=4999) starts with -//! `maniIRFR`, a big-endian u32 byte length, then `8BIM` / key / u32 length / data records. -//! `AnDs` holds a version-16 ActionDescriptor; other records (including `Roll`) stay opaque. -//! Layer `shmd` items `mlst` and `tmln`, and image resource 1075, also hold versioned descriptors. -//! These undocumented layouts were established by inspecting file structure, not proprietary code. -//! -//! Raw records remain the source of truth: typed accessors do not rewrite them, discard unknown -//! fields, interpret sparse layer-state inheritance, or assume a frame id is its sequence index. -//! This module does **not** import an animation into PhotoCraft or evaluate timeline tracks. - -use crate::descriptor::{Descriptor, Value, VersionedDescriptor}; -use crate::error::{PsdError, Result}; -use crate::io::{Reader, WriteExt}; - -/// A record in a `mani` resource. Data includes any padding counted in its stored length. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct AnimationRecord<'a> { - /// Record key (`AnDs`, `Roll`, or an unknown key). - pub key: [u8; 4], - /// Borrowed, unmodified payload. - pub data: &'a [u8], -} - -impl AnimationRecord<'_> { - /// Typed view of `AnDs`; `None` for other records, including `Roll`. - pub fn descriptor(&self) -> Option> { - (self.key == *b"AnDs").then(|| parse_descriptor(self.data)) - } -} - -/// The records of a legacy frame-animation plug-in resource, in stored order. -/// -/// Unknown keys and duplicate records are preserved, not silently collapsed. The observed -/// envelope has no alignment bytes outside record lengths. Unsupported envelopes return an error; -/// callers should keep their original image resource unchanged in that case. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct AnimationResource<'a> { - /// Ordered records, borrowing their payloads from the input. - pub records: Vec>, -} - -impl<'a> AnimationResource<'a> { - /// Parses a complete `maniIRFR` payload, checking the outer and every inner length. - /// Descriptor decoding is lazy, so unknown/future `AnDs` versions can still round-trip raw. - pub fn from_bytes(data: &'a [u8]) -> Result { - let mut r = Reader::new(data); - signature(&mut r, *b"mani", "mani")?; - signature(&mut r, *b"IRFR", "IRFR animation envelope")?; - let len = r.u32()?; - let mut body = r.sub(u64::from(len))?; - if !r.is_empty() { - return Err(PsdError::invalid("trailing bytes after animation envelope")); - } - let mut records = Vec::new(); - while !body.is_empty() { - signature(&mut body, *b"8BIM", "8BIM animation record")?; - let key = body.array()?; - let len = body.u32()?; - let data = body.bytes_u64(u64::from(len))?; - records.push(AnimationRecord { key, data }); - } - Ok(Self { records }) - } - - /// Writes the raw records, preserving their payloads exactly, including unknown fields, - /// unknown descriptor versions and noncanonical descriptor encodings. - pub fn to_bytes(&self) -> Result> { - // Check all lengths before constructing the output; no unchecked 32-bit length casts. - let mut len = 0u32; - for record in &self.records { - let n = u32::try_from(record.data.len()).map_err(|_| PsdError::LimitExceeded("animation record exceeds u32 length"))?; - len = len.checked_add(12).and_then(|v| v.checked_add(n)).ok_or(PsdError::LimitExceeded("animation envelope exceeds u32 length"))?; - } - let mut out = Vec::new(); - out.put(b"maniIRFR"); - out.put_u32(len); - for record in &self.records { - out.put(b"8BIM"); - out.put(&record.key); - out.put_len(record.data.len() as u64, false)?; - out.put(record.data); - } - Ok(out) - } -} - -fn signature(r: &mut Reader<'_>, expected: [u8; 4], name: &'static str) -> Result<()> { - let found = r.array()?; - if found != expected { - return Err(PsdError::InvalidSignature { expected: name, found }); - } - Ok(()) -} - -/// Parses a version-16 animation descriptor, allowing up to three zero alignment bytes. -/// -/// Raw payloads should be retained separately for byte-exact writing. This accessor is strict -/// about non-padding trailing bytes and does not guess how to read a future descriptor version. -/// It is shared by `AnDs`, layer `mlst` / `tmln`, and document timeline resource 1075. -pub fn parse_descriptor(data: &[u8]) -> Result { - let (value, consumed) = VersionedDescriptor::parse_prefix(data)?; - let tail = data.get(consumed..).ok_or_else(|| PsdError::invalid("animation descriptor length"))?; - if tail.len() > 3 || tail.iter().any(|&b| b != 0) { - return Err(PsdError::invalid("trailing bytes after animation descriptor")); - } - Ok(value) -} - -/// A frame-definition view. Its id is an opaque signed `long`, not a frame index. -#[derive(Debug, Clone, PartialEq)] -pub struct FrameInfo<'a> { - /// `FrID`, preserved without reinterpreting its bit pattern. - pub id: i32, - /// `FrDl` in centiseconds, or absent. No playback default or browser clamping is applied. - pub delay_centiseconds: Option, - /// All fields, including unknown ones, in their original order. - pub descriptor: &'a Descriptor, -} - -/// Reads the `FrIn` list from an `AnDs` descriptor. A missing list is not an empty animation. -/// Wrong types, missing frame ids and negative delays return errors. Duplicate ids are retained -/// for the document importer to diagnose rather than being silently overwritten here. -pub fn frame_info(descriptor: &Descriptor) -> Result>> { - let Some(Value::List(list)) = descriptor.get("FrIn") else { - return Err(PsdError::invalid("animation FrIn must be a list")); - }; - list.iter() - .map(|v| { - let Value::Descriptor(d) = v else { return Err(PsdError::invalid("animation frame must be a descriptor")) }; - let Some(Value::Integer(id)) = d.get("FrID") else { return Err(PsdError::invalid("animation frame FrID must be a long")) }; - let delay_centiseconds = match d.get("FrDl") { - None => None, - Some(Value::Integer(n)) => Some(u32::try_from(*n).map_err(|_| PsdError::invalid("negative animation frame delay"))?), - _ => return Err(PsdError::invalid("animation frame FrDl must be a long")), - }; - Ok(FrameInfo { id: *id, delay_centiseconds, descriptor: d }) - }) - .collect() -} - -/// A stored frame set: explicit playback order is separate from the `FrIn` definitions. -#[derive(Debug, Clone, PartialEq)] -pub struct FrameSet<'a> { - /// `FsID`, an opaque identifier. - pub id: i32, - /// `AFrm`, when present. Kept uninterpreted for the importer to validate. - pub active_frame: Option, - /// `FsFr` frame ids in stored order (including any duplicate or unresolved ids). - pub frame_ids: Vec, - /// Complete original descriptor, including fields not yet understood. - pub descriptor: &'a Descriptor, -} - -/// One sparse layer-state entry from `mlst` / `LaSt`. -#[derive(Debug, Clone, PartialEq)] -pub struct LayerFrameState<'a> { - /// `FrLs`: frame ids to which this entry refers. They are not frame indices. - pub frame_ids: Vec, - /// Complete sparse state, including visibility, blend options, offsets, masks, effects, - /// text settings and unknown fields. Omitted properties are deliberately not defaulted. - pub descriptor: &'a Descriptor, -} - -/// A layer's sparse animation states, without attempting to resolve their inheritance. -#[derive(Debug, Clone, PartialEq)] -pub struct LayerFrameStates<'a> { - /// `LaID`: PSD layer identifier, not the layer's record index. - pub layer_id: i32, - /// `LaSt` entries in stored order. - pub states: Vec>, -} - -/// Reads the identifiers and sparse entries of an `mlst` descriptor. This is a syntax view: -/// missing properties stay missing, and duplicate/unresolved references remain available for -/// the importer to validate. The original descriptor remains available to the caller. -pub fn layer_frame_states(descriptor: &Descriptor) -> Result> { - let Some(Value::Integer(layer_id)) = descriptor.get("LaID") else { - return Err(PsdError::invalid("animation layer LaID must be a long")); - }; - let Some(Value::List(list)) = descriptor.get("LaSt") else { - return Err(PsdError::invalid("animation layer LaSt must be a list")); - }; - let states = list - .iter() - .map(|v| { - let Value::Descriptor(d) = v else { return Err(PsdError::invalid("animation layer state must be a descriptor")) }; - let Some(Value::List(ids)) = d.get("FrLs") else { return Err(PsdError::invalid("animation layer FrLs must be a list")) }; - let frame_ids = ids - .iter() - .map(|v| match v { - Value::Integer(n) => Ok(*n), - _ => Err(PsdError::invalid("animation layer frame reference must be a long")), - }) - .collect::>>()?; - Ok(LayerFrameState { frame_ids, descriptor: d }) - }) - .collect::>>()?; - Ok(LayerFrameStates { layer_id: *layer_id, states }) -} - -/// Reads `FSts` without inferring order from frame ids or interpreting loop-related fields. -pub fn frame_sets(descriptor: &Descriptor) -> Result>> { - let Some(Value::List(list)) = descriptor.get("FSts") else { - return Err(PsdError::invalid("animation FSts must be a list")); - }; - list.iter() - .map(|v| { - let Value::Descriptor(d) = v else { return Err(PsdError::invalid("animation frame set must be a descriptor")) }; - let Some(Value::Integer(id)) = d.get("FsID") else { return Err(PsdError::invalid("animation frame set FsID must be a long")) }; - let active_frame = match d.get("AFrm") { - None => None, - Some(Value::Integer(n)) => Some(*n), - _ => return Err(PsdError::invalid("animation frame set AFrm must be a long")), - }; - let Some(Value::List(ids)) = d.get("FsFr") else { return Err(PsdError::invalid("animation frame set FsFr must be a list")) }; - let frame_ids = ids - .iter() - .map(|v| match v { - Value::Integer(n) => Ok(*n), - _ => Err(PsdError::invalid("animation frame reference must be a long")), - }) - .collect::>>()?; - Ok(FrameSet { id: *id, active_frame, frame_ids, descriptor: d }) - }) - .collect() -} diff --git a/crates/psd/src/ase.rs b/crates/psd/src/ase.rs deleted file mode 100644 index f63db5481a..0000000000 --- a/crates/psd/src/ase.rs +++ /dev/null @@ -1,439 +0,0 @@ -//! Adobe Swatch Exchange files (`.ase`), shared by Photoshop, Illustrator and InDesign. -//! -//! Layout from public descriptions of the format (big-endian throughout): the signature -//! `ASEF`, version `u16` major (1) and minor (0), a `u32` block count, then blocks of a `u16` -//! type, a `u32` body length and the body: -//! -//! - `0xC001` group start: a name; -//! - `0xC002` group end: empty; -//! - `0x0001` colour entry: a name, a four-character colour model (`RGB `, `CMYK`, `LAB `, -//! `Gray`), its components as `f32` (3, 4, 3 and 1 of them) and a `u16` colour type -//! (0 global, 1 spot, 2 normal/process). -//! -//! A name is a `u16` UTF-16 code-unit count that includes the trailing null, then the units. -//! Components are kept exactly as stored: RGB, CMYK and gray in 0..1 (gray 1 = white), Lab as -//! L*/100 followed by a* and b*. Unknown colour models and block types are kept verbatim -//! (colour models) or skipped (block types). Converting colours is the caller's job. - -use crate::error::{PsdError, Result}; -use crate::io::{Reader, WriteExt}; - -/// File signature. -pub const SIGNATURE: &[u8; 4] = b"ASEF"; -/// Most colour entries read from one file. -pub const MAX_SWATCHES: usize = 100_000; -/// Most groups read from one file. -pub const MAX_GROUPS: usize = 10_000; -/// Longest name read or written, in UTF-16 code units. -pub const MAX_NAME_UNITS: usize = 1024; -// `put_name` writes the name length as `units.len() as u16 + 1`, so the cap must leave room in a -// u16; this guards that invariant if the constant is ever raised. -const _: () = assert!(MAX_NAME_UNITS < u16::MAX as usize); - -const GROUP_START: u16 = 0xC001; -const GROUP_END: u16 = 0xC002; -const COLOR: u16 = 0x0001; - -/// A colour as stored. -#[derive(Debug, Clone, PartialEq)] -pub enum AseColor { - /// Red, green, blue, 0..1. - Rgb([f32; 3]), - /// Cyan, magenta, yellow, black ink, 0..1. - Cmyk([f32; 4]), - /// L*/100 (0..1), a*, b*. - Lab([f32; 3]), - /// Gray level 0..1 (1 = white). - Gray(f32), - /// Any other colour model, kept verbatim: the model tag and the bytes after it, up to the - /// colour type. - Other { - /// Four-character model tag. - model: [u8; 4], - /// Component bytes as stored. - data: Vec, - }, -} - -/// The colour type of an entry. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum AseKind { - /// A global colour (edits update every use). - Global, - /// A spot colour (its own ink). - Spot, - /// A normal (process) colour. - #[default] - Process, -} - -impl AseKind { - fn from_u16(v: u16) -> AseKind { - match v { - 0 => AseKind::Global, - 1 => AseKind::Spot, - _ => AseKind::Process, - } - } - fn to_u16(self) -> u16 { - match self { - AseKind::Global => 0, - AseKind::Spot => 1, - AseKind::Process => 2, - } - } -} - -/// One colour entry. -#[derive(Debug, Clone, PartialEq)] -pub struct AseSwatch { - /// Name. - pub name: String, - /// Colour. - pub color: AseColor, - /// Colour type. - pub kind: AseKind, -} - -/// A top-level entry: a colour, or a group of colours (the format has one level of groups). -#[derive(Debug, Clone, PartialEq)] -pub enum AseEntry { - /// A colour outside any group. - Swatch(AseSwatch), - /// A named group. - Group { - /// Group name. - name: String, - /// Its colours. - swatches: Vec, - }, -} - -/// A parsed `.ase` file. -#[derive(Debug, Clone, PartialEq, Default)] -pub struct AseFile { - /// Entries in file order. - pub entries: Vec, -} - -impl AseFile { - /// Number of colour entries (in and outside groups). - pub fn swatch_count(&self) -> usize { - self.entries - .iter() - .map(|e| match e { - AseEntry::Swatch(_) => 1, - AseEntry::Group { swatches, .. } => swatches.len(), - }) - .sum() - } -} - -fn f32_be(r: &mut Reader<'_>) -> Result { - let v = f32::from_bits(r.u32()?); - // Non-finite components would poison every conversion downstream. - Ok(if v.is_finite() { v } else { 0.0 }) -} - -fn read_name(r: &mut Reader<'_>) -> Result { - if r.is_empty() { - return Ok(String::new()); - } - let n = r.u16()? as usize; - r.check_count(n as u64, 2)?; - let mut units = Vec::with_capacity(n.min(MAX_NAME_UNITS)); - for _ in 0..n { - let u = r.u16()?; - if units.len() < MAX_NAME_UNITS { - units.push(u); - } - } - while units.last() == Some(&0) { - units.pop(); - } - Ok(String::from_utf16_lossy(&units)) -} - -fn read_color(body: &mut Reader<'_>) -> Result { - let name = read_name(body)?; - let model: [u8; 4] = body.array()?; - let color = match &model { - b"RGB " => AseColor::Rgb([f32_be(body)?, f32_be(body)?, f32_be(body)?]), - b"CMYK" => AseColor::Cmyk([f32_be(body)?, f32_be(body)?, f32_be(body)?, f32_be(body)?]), - b"LAB " => AseColor::Lab([f32_be(body)?, f32_be(body)?, f32_be(body)?]), - b"Gray" => AseColor::Gray(f32_be(body)?), - _ => { - // Unknown model: everything but the trailing colour type is its data. - let n = body.remaining().saturating_sub(2); - AseColor::Other { model, data: body.bytes(n)?.to_vec() } - } - }; - // Some writers omit the colour type; it defaults to process. - let kind = if body.remaining() >= 2 { AseKind::from_u16(body.u16()?) } else { AseKind::Process }; - Ok(AseSwatch { name, color, kind }) -} - -/// Parse an `.ase` file. A wrong signature or version, a truncated block, a block count beyond -/// the data, more than [`MAX_SWATCHES`] colors or more than [`MAX_GROUPS`] groups is an error; -/// never panics. Unknown block types are skipped, a group end without a start is ignored, and a -/// group left open at the end (or a group started inside another) is closed. -pub fn parse(data: &[u8]) -> Result { - let mut r = Reader::new(data); - let sig: [u8; 4] = r.array()?; - if &sig != SIGNATURE { - return Err(PsdError::InvalidSignature { expected: "ASEF", found: sig }); - } - let major = r.u16()?; - let _minor = r.u16()?; - if major != 1 { - return Err(PsdError::UnsupportedVersion(major)); - } - let count = u64::from(r.u32()?); - // Every block has at least a type and a length. - r.check_count(count, 6)?; - let mut entries = Vec::new(); - let mut open: Option<(String, Vec)> = None; - let mut total = 0usize; - let mut groups = 0usize; - for _ in 0..count { - let kind = r.u16()?; - let len = u64::from(r.u32()?); - let mut body = r.sub(len)?; - match kind { - GROUP_START => { - groups += 1; - if groups > MAX_GROUPS { - return Err(PsdError::LimitExceeded("too many groups in an .ase file")); - } - if let Some((name, swatches)) = open.take() { - entries.push(AseEntry::Group { name, swatches }); - } - open = Some((read_name(&mut body)?, Vec::new())); - } - GROUP_END => { - if let Some((name, swatches)) = open.take() { - entries.push(AseEntry::Group { name, swatches }); - } - } - COLOR => { - total += 1; - if total > MAX_SWATCHES { - return Err(PsdError::LimitExceeded("too many swatches in an .ase file")); - } - let s = read_color(&mut body)?; - match open.as_mut() { - Some((_, v)) => v.push(s), - None => entries.push(AseEntry::Swatch(s)), - } - } - _ => {} - } - } - if let Some((name, swatches)) = open.take() { - entries.push(AseEntry::Group { name, swatches }); - } - Ok(AseFile { entries }) -} - -fn put_name(out: &mut Vec, name: &str) { - let units = crate::io::utf16_units(name, MAX_NAME_UNITS); - out.put_u16(units.len() as u16 + 1); - for u in units { - out.put_u16(u); - } - out.put_u16(0); -} - -fn put_block(out: &mut Vec, kind: u16, body: &[u8]) -> Result<()> { - out.put_u16(kind); - out.put_u32(u32::try_from(body.len()).map_err(|_| PsdError::LimitExceeded("swatch block too large"))?); - out.put(body); - Ok(()) -} - -fn put_color(out: &mut Vec, s: &AseSwatch) -> Result<()> { - let mut b = Vec::with_capacity(64); - put_name(&mut b, &s.name); - let floats = |b: &mut Vec, v: &[f32]| { - for x in v { - b.put_u32(x.to_bits()); - } - }; - match &s.color { - AseColor::Rgb(c) => { - b.put(b"RGB "); - floats(&mut b, c); - } - AseColor::Cmyk(c) => { - b.put(b"CMYK"); - floats(&mut b, c); - } - AseColor::Lab(c) => { - b.put(b"LAB "); - floats(&mut b, c); - } - AseColor::Gray(g) => { - b.put(b"Gray"); - floats(&mut b, &[*g]); - } - AseColor::Other { model, data } => { - b.put(model); - b.put(data); - } - } - b.put_u16(s.kind.to_u16()); - put_block(out, COLOR, &b) -} - -/// Write an `.ase` file (version 1.0). Fails only when a block or the block count overflows the -/// format's 32-bit fields or there are more than [`MAX_SWATCHES`] colors or more than -/// [`MAX_GROUPS`] groups. -pub fn write(file: &AseFile) -> Result> { - if file.swatch_count() > MAX_SWATCHES { - return Err(PsdError::LimitExceeded("too many swatches for an .ase file")); - } - if file.entries.iter().filter(|e| matches!(e, AseEntry::Group { .. })).count() > MAX_GROUPS { - return Err(PsdError::LimitExceeded("too many groups for an .ase file")); - } - let mut body = Vec::with_capacity(64 * file.swatch_count().max(1)); - let mut blocks = 0u64; - for e in &file.entries { - match e { - AseEntry::Swatch(s) => { - put_color(&mut body, s)?; - blocks += 1; - } - AseEntry::Group { name, swatches } => { - let mut b = Vec::with_capacity(name.len() * 2 + 4); - put_name(&mut b, name); - put_block(&mut body, GROUP_START, &b)?; - for s in swatches { - put_color(&mut body, s)?; - } - put_block(&mut body, GROUP_END, &[])?; - blocks += 2 + swatches.len() as u64; - } - } - } - let mut out = Vec::with_capacity(12 + body.len()); - out.put(SIGNATURE); - out.put_u16(1); - out.put_u16(0); - out.put_u32(u32::try_from(blocks).map_err(|_| PsdError::LimitExceeded("too many blocks"))?); - out.put(&body); - Ok(out) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn sw(name: &str, color: AseColor, kind: AseKind) -> AseSwatch { - AseSwatch { name: name.into(), color, kind } - } - - fn sample() -> AseFile { - AseFile { - entries: vec![ - AseEntry::Swatch(sw("Loose red", AseColor::Rgb([1.0, 0.0, 0.0]), AseKind::Process)), - AseEntry::Group { - name: "Brand ✓".into(), - swatches: vec![ - sw("Ink", AseColor::Cmyk([0.1, 0.2, 0.3, 0.4]), AseKind::Spot), - sw("Lab", AseColor::Lab([0.5321, -12.25, 40.5]), AseKind::Global), - sw("Mid gray", AseColor::Gray(0.5), AseKind::Process), - sw("Odd", AseColor::Other { model: *b"HSV ", data: vec![1, 2, 3, 4, 5, 6] }, AseKind::Process), - ], - }, - AseEntry::Group { name: String::new(), swatches: vec![] }, - ], - } - } - - #[test] - fn round_trips_groups_models_and_types() { - let f = sample(); - let bytes = write(&f).unwrap(); - assert_eq!(&bytes[..4], b"ASEF"); - // 1 loose + (start + 4 + end) + (start + end). - assert_eq!(u32::from_be_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]), 9); - let back = parse(&bytes).unwrap(); - assert_eq!(back, f); - assert_eq!(write(&back).unwrap(), bytes, "byte-stable"); - assert_eq!(back.swatch_count(), 5); - } - - #[test] - fn lenient_structure() { - // A colour without a type, an unknown block, an end without start, an unclosed group. - let mut body = Vec::new(); - let mut c = Vec::new(); - put_name(&mut c, "A"); - c.put(b"Gray"); - c.put_u32(0.25f32.to_bits()); - put_block(&mut body, GROUP_END, &[]).unwrap(); - put_block(&mut body, 0x7777, &[9, 9, 9]).unwrap(); - let mut g = Vec::new(); - put_name(&mut g, "G"); - put_block(&mut body, GROUP_START, &g).unwrap(); - put_block(&mut body, COLOR, &c).unwrap(); - let mut f = b"ASEF\0\x01\0\0\0\0\0\x04".to_vec(); - f.extend_from_slice(&body); - let p = parse(&f).unwrap(); - assert_eq!(p.entries, vec![AseEntry::Group { name: "G".into(), swatches: vec![sw("A", AseColor::Gray(0.25), AseKind::Process)] }]); - } - - #[test] - fn non_finite_components_become_zero() { - let f = AseFile { entries: vec![AseEntry::Swatch(sw("n", AseColor::Rgb([f32::NAN, f32::INFINITY, 0.5]), AseKind::Process))] }; - let p = parse(&write(&f).unwrap()).unwrap(); - assert_eq!(p.entries, vec![AseEntry::Swatch(sw("n", AseColor::Rgb([0.0, 0.0, 0.5]), AseKind::Process))]); - } - - #[test] - fn hostile_input_is_an_error_not_a_panic() { - let good = write(&sample()).unwrap(); - for n in 0..good.len() { - assert!(parse(&good[..n]).is_err(), "truncated at {n}"); - } - assert!(parse(b"ASEX\0\x01\0\0\0\0\0\0").is_err(), "signature"); - assert!(parse(b"ASEF\0\x02\0\0\0\0\0\0").is_err(), "version"); - assert!(parse(b"ASEF\0\x01\0\0\xff\xff\xff\xff").is_err(), "huge block count"); - // A block length beyond the data. - assert!(parse(b"ASEF\0\x01\0\0\0\0\0\x01\0\x01\xff\xff\xff\xff").is_err()); - // A name length beyond the block. - assert!(parse(b"ASEF\0\x01\0\0\0\0\0\x01\0\x01\0\0\0\x04\xff\xff\0A").is_err()); - // A colour block too short for its components. - assert!(parse(b"ASEF\0\x01\0\0\0\0\0\x01\0\x01\0\0\0\x0a\0\x01\0\0RGB \0\0").is_err()); - let mut seed = 0xDEAD_BEEFu32; - for len in 0..400 { - let junk: Vec = (0..len) - .map(|_| { - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - (seed >> 24) as u8 - }) - .collect(); - let mut v = b"ASEF\0\x01\0\0\0\0\0\x10".to_vec(); - v.extend_from_slice(&junk); - let _ = parse(&v); - let _ = parse(&junk); - } - } - - #[test] - fn too_many_swatches() { - let s = sw("", AseColor::Gray(0.0), AseKind::Process); - let f = AseFile { entries: vec![AseEntry::Group { name: "g".into(), swatches: vec![s; MAX_SWATCHES + 1] }] }; - assert!(write(&f).is_err()); - } - - #[test] - fn too_many_groups() { - let g = AseEntry::Group { name: "g".into(), swatches: vec![] }; - let mut f = AseFile { entries: vec![g; MAX_GROUPS + 1] }; - assert!(write(&f).is_err()); - // At the limit the file is written, and every group reads back. - f.entries.pop(); - assert_eq!(parse(&write(&f).unwrap()).unwrap().entries.len(), MAX_GROUPS); - } -} diff --git a/crates/psd/src/asl.rs b/crates/psd/src/asl.rs deleted file mode 100644 index 26cd27b9bc..0000000000 --- a/crates/psd/src/asl.rs +++ /dev/null @@ -1,276 +0,0 @@ -//! Photoshop layer style libraries (`.asl`, the Styles panel's Import Styles… / Export Styles…). -//! -//! Layout of a version 3 style library: -//! -//! ```text -//! file := u16 2, "8BSL", u16 3 (sub-version), -//! u32 pattern section length, patterns (the `Patt` block record format), -//! u32 style count, style × count -//! style := u32 length, then that many bytes: identity, style descriptor, zero padding -//! identity:= versioned descriptor (class `null`): `Nm ` name, `Idnt` id (Unicode strings) -//! style descriptor := versioned descriptor (class `Styl`): `documentMode`, `Lefx` (the same -//! tree as a layer's `lfx2` block), optional `blendOptions` (`Md `, `Opct`, -//! `fillOpacity`) -//! ``` -//! -//! The reader skips up to three padding bytes after each style record whatever its length says, -//! so it reads files whose record length counts the padding and files whose length does not. -//! The writer counts the padding in the record length, which reads correctly either way. -//! -//! Malformed input is an error, never a panic. A pattern section that doesn't decode is reported -//! in [`AslFile::pattern_error`] and skipped (its length is known), so the styles still load. - -use crate::descriptor::{Descriptor, UnicodeString, Value, VersionedDescriptor}; -use crate::error::{PsdError, Result}; -use crate::patterns::{PsdPattern, parse_pattern_block, write_pattern_block}; - -/// Most styles read from one file. -pub const MAX_STYLES: usize = 10_000; - -/// One style of a library. -#[derive(Debug, Clone, PartialEq)] -pub struct AslStyle { - /// The name shown in the Styles panel (may be empty or repeated). - pub name: String, - /// The style's unique id (usually a UUID). - pub id: String, - /// The style descriptor (class `Styl`): `Lefx`, `blendOptions`, `documentMode`. - pub style: Descriptor, -} - -/// A parsed style library. -#[derive(Debug, Clone, PartialEq, Default)] -pub struct AslFile { - /// Patterns embedded for the styles' Pattern Overlays, pattern strokes and bevel textures. - pub patterns: Vec, - /// Why the pattern section was skipped, if it didn't decode (read only). - pub pattern_error: Option, - /// Styles in file order. - pub styles: Vec, -} - -struct Rd<'a> { - b: &'a [u8], - p: usize, -} - -impl<'a> Rd<'a> { - fn take(&mut self, n: usize) -> Result<&'a [u8]> { - let end = self.p.checked_add(n).filter(|&e| e <= self.b.len()).ok_or(PsdError::UnexpectedEof { offset: self.p, needed: n })?; - let s = self.b.get(self.p..end).ok_or(PsdError::UnexpectedEof { offset: self.p, needed: n })?; - self.p = end; - Ok(s) - } - fn u16(&mut self) -> Result { - let b = self.take(2)?; - Ok(u16::from_be_bytes([b[0], b[1]])) - } - fn u32(&mut self) -> Result { - let b = self.take(4)?; - Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]])) - } - fn remaining(&self) -> usize { - self.b.len().saturating_sub(self.p) - } -} - -fn text(d: &Descriptor, key: &str) -> String { - match d.get(key) { - Some(Value::Text(t)) => t.to_string_lossy(), - _ => String::new(), - } -} - -fn read_style(body: &[u8]) -> Result { - let (identity, used) = VersionedDescriptor::parse_prefix(body)?; - let rest = body.get(used..).ok_or(PsdError::UnexpectedEof { offset: used, needed: 4 })?; - let (style, _) = VersionedDescriptor::parse_prefix(rest)?; - let id = &identity.descriptor; - Ok(AslStyle { name: text(id, "Nm "), id: text(id, "Idnt"), style: style.descriptor }) -} - -/// Parses an `.asl` style library. -pub fn parse(data: &[u8]) -> Result { - let mut r = Rd { b: data, p: 0 }; - let version = r.u16()?; - let sig = r.take(4)?; - if sig != b"8BSL" { - return Err(PsdError::InvalidSignature { expected: "8BSL", found: [sig[0], sig[1], sig[2], sig[3]] }); - } - let sub = r.u16()?; - if version != 2 || sub != 3 { - return Err(PsdError::Unsupported(format!("style library version {version}.{sub} (only 2.3, Photoshop 6 and later)"))); - } - let plen = r.u32()? as usize; - let section = r.take(plen)?; - let (patterns, pattern_error) = match parse_pattern_block(section) { - Ok(p) => (p, None), - Err(e) => (Vec::new(), Some(e.to_string())), - }; - let count = r.u32()? as usize; - // Every style needs at least its own length word. - if count > r.remaining() / 4 { - return Err(PsdError::invalid(format!("{count} styles cannot fit in the remaining {} bytes", r.remaining()))); - } - if count > MAX_STYLES { - return Err(PsdError::LimitExceeded("too many styles in one library")); - } - let mut styles = Vec::with_capacity(count); - for _ in 0..count { - let len = r.u32()? as usize; - let body = r.take(len)?; - styles.push(read_style(body)?); - let pad = (4 - len % 4) % 4; - r.p = r.p.saturating_add(pad).min(data.len()); - } - Ok(AslFile { patterns, pattern_error: pattern_error.filter(|_| !section.is_empty()), styles }) -} - -/// Writes a version 3 `.asl` style library. -pub fn write(file: &AslFile) -> Result> { - let mut out = Vec::new(); - out.extend_from_slice(&2u16.to_be_bytes()); - out.extend_from_slice(b"8BSL"); - out.extend_from_slice(&3u16.to_be_bytes()); - let patterns = write_pattern_block(&file.patterns)?; - let plen = u32::try_from(patterns.len()).map_err(|_| PsdError::LimitExceeded("pattern section larger than 4 GB"))?; - out.extend_from_slice(&plen.to_be_bytes()); - out.extend_from_slice(&patterns); - let count = u32::try_from(file.styles.len()).map_err(|_| PsdError::LimitExceeded("too many styles"))?; - out.extend_from_slice(&count.to_be_bytes()); - for s in &file.styles { - let identity = - Descriptor::new("null").with("Nm ", Value::Text(UnicodeString::new_nul(&s.name))).with("Idnt", Value::Text(UnicodeString::new_nul(&s.id))); - let mut body = VersionedDescriptor::new(identity).to_bytes(); - body.extend(VersionedDescriptor::new(s.style.clone()).to_bytes()); - body.resize(body.len().div_ceil(4) * 4, 0); - let len = u32::try_from(body.len()).map_err(|_| PsdError::LimitExceeded("style larger than 4 GB"))?; - out.extend_from_slice(&len.to_be_bytes()); - out.extend_from_slice(&body); - } - Ok(out) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::descriptor::Id; - - fn pattern() -> PsdPattern { - PsdPattern { - mode: 3, - width: 3, - height: 2, - name: "Dots".into(), - id: "a1b2".into(), - palette: None, - depth: 8, - channels: vec![vec![1, 2, 3, 4, 5, 6], vec![9; 6], vec![200; 6]], - alpha: None, - } - } - - fn style(name: &str) -> AslStyle { - let lefx = Descriptor::new("null").with("masterFXSwitch", Value::Boolean(true)).with( - "SoFi", - Value::Descriptor(Descriptor::new("SoFi").with("enab", Value::Boolean(true)).with("Opct", Value::UnitFloat { unit: *b"#Prc", value: 50.0 })), - ); - let blend = Descriptor::new("blendOptions") - .with("Md ", Value::Enumerated { type_id: Id::new("BlnM"), value: Id::new("Mltp") }) - .with("fillOpacity", Value::UnitFloat { unit: *b"#Prc", value: 25.0 }); - AslStyle { - name: name.into(), - id: format!("id-{name}"), - style: Descriptor::new("Styl") - .with("documentMode", Value::Descriptor(Descriptor::new("documentMode"))) - .with("Lefx", Value::Descriptor(lefx)) - .with("blendOptions", Value::Descriptor(blend)), - } - } - - fn sample() -> AslFile { - AslFile { patterns: vec![pattern()], pattern_error: None, styles: vec![style("Gold"), style(""), style("Ünïcode ✓")] } - } - - #[test] - fn round_trip() { - let f = sample(); - let b = write(&f).unwrap(); - assert_eq!(&b[..8], b"\0\x028BSL\0\x03"); - assert_eq!(b.len() % 4, 0); - assert_eq!(parse(&b).unwrap(), f); - let empty = AslFile::default(); - assert_eq!(parse(&write(&empty).unwrap()).unwrap(), empty); - } - - #[test] - fn record_lengths_without_padding_also_read() { - // A writer that leaves the padding out of each record length. - let f = sample(); - let mut out = write(&AslFile { styles: vec![], ..f.clone() }).unwrap(); - out.truncate(out.len() - 4); - out.extend_from_slice(&(f.styles.len() as u32).to_be_bytes()); - for s in &f.styles { - let identity = - Descriptor::new("null").with("Nm ", Value::Text(UnicodeString::new_nul(&s.name))).with("Idnt", Value::Text(UnicodeString::new_nul(&s.id))); - let mut body = VersionedDescriptor::new(identity).to_bytes(); - body.extend(VersionedDescriptor::new(s.style.clone()).to_bytes()); - body.push(7); // odd length - out.extend_from_slice(&(body.len() as u32).to_be_bytes()); - let pad = (4 - body.len() % 4) % 4; - out.extend_from_slice(&body); - out.extend(std::iter::repeat_n(0, pad)); - } - assert_eq!(parse(&out).unwrap().styles, f.styles); - } - - #[test] - fn bad_pattern_section_is_skipped() { - let mut b = write(&AslFile { patterns: vec![], pattern_error: None, styles: vec![style("A")] }).unwrap(); - // Replace the empty pattern section with 8 bytes of garbage. - let tail = b.split_off(12); - b.truncate(8); - b.extend_from_slice(&8u32.to_be_bytes()); - b.extend_from_slice(&[0, 0, 0, 4, 0xff, 0xff, 0xff, 0xff]); - b.extend(tail); - let f = parse(&b).unwrap(); - assert!(f.pattern_error.is_some()); - assert_eq!(f.styles.len(), 1); - } - - #[test] - fn hostile_input_errors() { - assert!(parse(b"").is_err()); - assert!(parse(b"\0\x028BSL\0\x02").is_err()); - assert!(parse(b"\0\x028BPS\0\x03").is_err()); - // A count far beyond the data. - let mut b = b"\0\x028BSL\0\x03\0\0\0\0".to_vec(); - b.extend_from_slice(&u32::MAX.to_be_bytes()); - assert!(parse(&b).is_err()); - // A pattern length beyond the data. - assert!(parse(b"\0\x028BSL\0\x03\xff\xff\xff\xff").is_err()); - let b = write(&sample()).unwrap(); - for cut in 0..b.len() { - assert!(parse(&b[..cut]).is_err(), "cut at {cut}"); - } - for i in 0..b.len() { - for x in [0x5a, 0xff, 0x01] { - let mut c = b.clone(); - c[i] ^= x; - let _ = parse(&c); - } - } - // Seeded random noise after a valid header. - let mut seed = 0x1234_5678u32; - for _ in 0..500 { - let mut c = b"\0\x028BSL\0\x03".to_vec(); - for _ in 0..(seed % 200) { - seed ^= seed << 13; - seed ^= seed >> 17; - seed ^= seed << 5; - c.push(seed as u8); - } - let _ = parse(&c); - } - } -} diff --git a/crates/psd/src/atn.rs b/crates/psd/src/atn.rs deleted file mode 100644 index 384070f286..0000000000 --- a/crates/psd/src/atn.rs +++ /dev/null @@ -1,860 +0,0 @@ -//! Photoshop Actions files (`.atn`): one action set, its actions and their steps. -//! -//! Implemented clean-room from Adobe's "Photoshop File Formats" specification (the *Actions* -//! and *Descriptor structure* sections) and observation of files Photoshop writes. No code was -//! copied. All numbers are big-endian; strings are the Unicode strings of descriptors (u32 -//! code-unit count + UTF-16BE, usually NUL-terminated) unless noted. -//! -//! ```text -//! file := version u32 (12 or 16), set name UnicodeString, expanded u8, count u32, count × action -//! action := function key u16 (0 = none, n = Fn), shift u8, command u8, colour u16, -//! name UnicodeString, expanded u8, count u32, count × item -//! item := expanded u8, enabled u8, with dialog u8, dialog options u8, -//! event kind [4]: "TEXT" (u32 length + ASCII event name) | "long" (4-char event code), -//! dictionary name (u32 length + ASCII: the name the Actions panel shows), -//! has descriptor i32 (-1 = a descriptor follows, 0 = none), [descriptor] -//! ``` -//! -//! The descriptor is a plain ActionDescriptor body ([`Descriptor`], no version prefix): the -//! event's parameters, exactly as Photoshop's own "Make", "Set", "Gaussian Blur"… events -//! carry them. The event name and the panel name are byte strings (ASCII, or the platform's -//! legacy encoding for a localised panel name: Mac Roman "Définir"), kept verbatim; -//! [`AtnItem::label`] gives a readable name. Photoshop 5-era files (version 12) use a -//! legacy descriptor layout: bare four-byte identifiers and no top-level class or name. -//! -//! 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`] always produces version 16, so -//! `parse(write(f)) == f` for files [`parse`] read, and `write(parse(b)) == b` for version 16 files -//! Photoshop wrote; a version 12 file's legacy descriptors keep their meaning, not their layout. - -use crate::codepage; -use crate::descriptor::{Descriptor, UnicodeString}; -use crate::error::{PsdError, Result}; -use crate::io::{Reader, WriteExt, decode_legacy_name}; - -mod legacy; - -/// The version written by this module (Photoshop 6 and every later release). -pub const VERSION: u32 = 16; -/// Most actions read from one set (Photoshop's own sets hold a few dozen). -pub const MAX_ACTIONS: usize = 10_000; -/// Most steps read from one action. -pub const MAX_ITEMS: usize = 100_000; - -/// A parsed action set. -#[derive(Debug, Clone, PartialEq, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct AtnFile { - /// The set's name (the Actions panel folder). - pub name: UnicodeString, - /// Whether the set is shown expanded in the Actions panel. - pub expanded: bool, - /// The actions, in panel order. - pub actions: Vec, - /// 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. -#[derive(Debug, Clone, PartialEq, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct AtnAction { - /// Function key that plays the action: 0 = none, `n` = F`n`. - pub function_key: u16, - /// Shift modifier of the function key. - pub shift: bool, - /// Command (Control on Windows) modifier of the function key. - pub command: bool, - /// Button Mode colour index (0 = none, then red, orange, yellow, green, blue, violet, gray). - pub color: u16, - /// The action's name. - pub name: UnicodeString, - /// Whether the action is shown expanded in the Actions panel. - pub expanded: bool, - /// The steps, in playback order. - pub items: Vec, -} - -/// One step of an action: a Photoshop event with its parameters. -#[derive(Debug, Clone, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct AtnItem { - /// Whether the step's parameters are shown expanded in the Actions panel. - pub expanded: bool, - /// The panel's check mark: a switched-off step is skipped by playback. - pub enabled: bool, - /// The panel's dialog toggle: playback shows the step's dialog. - pub with_dialog: bool, - /// Dialog options (0 = none, 2 = show the dialog, 3 = don't show), kept verbatim. - pub dialog_options: u8, - /// The event. - pub event: AtnEvent, - /// The name the Actions panel shows for the step ("Gaussian Blur", "Make", …), as stored: - /// ASCII, or the authoring platform's legacy encoding when localised. See [`Self::label`]. - pub dictionary: Vec, - /// The event's parameters; `None` for events without any. - pub descriptor: Option, -} - -impl Default for AtnItem { - fn default() -> Self { - AtnItem { - expanded: false, - enabled: true, - with_dialog: false, - dialog_options: 0, - event: AtnEvent::Code(*b" "), - dictionary: Vec::new(), - descriptor: None, - } - } -} - -impl AtnItem { - /// The panel name as text: UTF-8 when it is, otherwise decoded byte by byte (Latin-1). - pub fn dictionary(&self) -> String { - decode_legacy_name(&self.dictionary) - } - - /// 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 { - if let Some(class) = class_name(self) { - return class; - } - let dict = self.dictionary(); - if dict.trim().is_empty() { self.event.id() } else { dict } - } -} - -/// 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))] -pub enum AtnEvent { - /// Stored as `long` + 4 bytes. - Code([u8; 4]), - /// Stored as `TEXT` + length-prefixed bytes (ASCII in every file seen). - Name(Vec), -} - -impl AtnEvent { - /// A string-named event. - pub fn name(s: &str) -> Self { - AtnEvent::Name(s.as_bytes().to_vec()) - } - /// The event id as text: the code's four characters, or the name. - pub fn id(&self) -> String { - match self { - AtnEvent::Code(c) => String::from_utf8_lossy(c).into_owned(), - AtnEvent::Name(n) => String::from_utf8_lossy(n).into_owned(), - } - } - /// `true` if the event is the code or name `s`. - pub fn is(&self, s: &str) -> bool { - match self { - AtnEvent::Code(c) => c == s.as_bytes(), - AtnEvent::Name(n) => n == s.as_bytes(), - } - } -} - -/// Reads a u32 length + bytes (event and dictionary names), verbatim. -fn read_ascii(r: &mut Reader<'_>) -> Result> { - let n = r.u32()?; - Ok(r.bytes_u64(u64::from(n))?.to_vec()) -} - -fn write_ascii(out: &mut Vec, s: &[u8]) -> Result<()> { - let n = u32::try_from(s.len()).map_err(|_| PsdError::LimitExceeded("action name too long"))?; - out.put_u32(n); - out.put(s); - Ok(()) -} - -/// Read one step with the descriptor dialect selected by the file version. -fn read_item(r: &mut Reader<'_>, legacy: bool) -> Result { - let expanded = r.u8()? != 0; - let enabled = r.u8()? != 0; - let with_dialog = r.u8()? != 0; - let dialog_options = r.u8()?; - let event = match &r.array::<4>()? { - b"TEXT" => AtnEvent::Name(read_ascii(r)?), - b"long" => AtnEvent::Code(r.array()?), - other => return Err(PsdError::invalid(format!("unknown event kind {:?}", String::from_utf8_lossy(other)))), - }; - let dictionary = read_ascii(r)?; - let descriptor = match r.i32()? { - 0 => None, - -1 => Some(if legacy { legacy::read(r)? } else { Descriptor::read(r)? }), - n => return Err(PsdError::invalid(format!("bad descriptor flag {n}"))), - }; - Ok(AtnItem { expanded, enabled, with_dialog, dialog_options, event, dictionary, descriptor }) -} - -/// Read an action and its steps using the file's descriptor dialect. -fn read_action(r: &mut Reader<'_>, legacy: bool) -> Result { - let function_key = r.u16()?; - let shift = r.u8()? != 0; - let command = r.u8()? != 0; - let color = r.u16()?; - let name = UnicodeString::read(r)?; - let expanded = r.u8()? != 0; - let n = r.u32()?; - // Each item needs at least its 4 flags, the event kind, two empty names and the descriptor flag. - r.check_count(u64::from(n), 20)?; - if n as usize > MAX_ITEMS { - return Err(PsdError::LimitExceeded("too many steps in one action")); - } - let mut items = Vec::with_capacity((n as usize).min(1024)); - for _ in 0..n { - items.push(read_item(r, legacy)?); - } - Ok(AtnAction { function_key, shift, command, color, name, expanded, items }) -} - -/// Parses a version 12 or 16 `.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 !matches!(version, 12 | VERSION) { - return Err(PsdError::Unsupported(format!("actions file version {version} (supported versions: 12 and 16)"))); - } - let name = UnicodeString::read(&mut r)?; - let expanded = r.u8()? != 0; - let n = r.u32()?; - // Each action needs at least its key, modifiers, colour, an empty name, the flag and a count. - r.check_count(u64::from(n), 15)?; - if n as usize > MAX_ACTIONS { - return Err(PsdError::LimitExceeded("too many actions in one set")); - } - let mut actions = Vec::with_capacity((n as usize).min(256)); - for _ in 0..n { - actions.push(read_action(&mut r, version == 12)?); - } - let mut warnings = Vec::new(); - if !r.is_empty() { - warnings.push(format!("{} trailing bytes ignored", r.remaining())); - } - 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<()> { - out.put_u8(u8::from(item.expanded)); - out.put_u8(u8::from(item.enabled)); - out.put_u8(u8::from(item.with_dialog)); - out.put_u8(item.dialog_options); - match &item.event { - AtnEvent::Name(n) => { - out.put(b"TEXT"); - write_ascii(out, n)?; - } - AtnEvent::Code(c) => { - out.put(b"long"); - out.put(c); - } - } - write_ascii(out, &item.dictionary)?; - match &item.descriptor { - None => out.put_i32(0), - Some(d) => { - out.put_i32(-1); - d.write(out); - } - } - Ok(()) -} - -fn count(n: usize, what: &'static str) -> Result { - u32::try_from(n).map_err(|_| PsdError::LimitExceeded(what)) -} - -/// Writes an `.atn` file (version 16). -pub fn write(f: &AtnFile) -> Result> { - let mut out = Vec::new(); - out.put_u32(VERSION); - f.name.write(&mut out); - out.put_u8(u8::from(f.expanded)); - out.put_u32(count(f.actions.len(), "too many actions")?); - for a in &f.actions { - out.put_u16(a.function_key); - out.put_u8(u8::from(a.shift)); - out.put_u8(u8::from(a.command)); - out.put_u16(a.color); - a.name.write(&mut out); - out.put_u8(u8::from(a.expanded)); - out.put_u32(count(a.items.len(), "too many steps")?); - for item in &a.items { - write_item(&mut out, item)?; - } - } - Ok(out) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::descriptor::Value; - - fn px(v: f64) -> Value { - Value::UnitFloat { unit: *b"#Pxl", value: v } - } - - fn set() -> AtnFile { - let blur = AtnItem { - expanded: true, - enabled: true, - with_dialog: true, - dialog_options: 2, - event: AtnEvent::Code(*b"GsnB"), - dictionary: b"Gaussian Blur".to_vec(), - descriptor: Some(Descriptor::new("null").with("Rds ", px(2.5))), - }; - let trim = AtnItem { - event: AtnEvent::name("trim"), - dictionary: b"Trim".to_vec(), - descriptor: Some( - Descriptor { name: UnicodeString::new_nul("Trim"), class_id: crate::descriptor::Id::Str(b"trim".to_vec()), items: Vec::new() } - .with( - "trimBasedOn", - Value::Enumerated { type_id: crate::descriptor::Id::new("trimBasedOn"), value: crate::descriptor::Id::new("topLeftPixelColor") }, - ) - .with("Top ", Value::Boolean(true)), - ), - ..Default::default() - }; - let flatten = AtnItem { enabled: false, event: AtnEvent::Code(*b"Fltn"), dictionary: b"Flatten Image".to_vec(), ..Default::default() }; - AtnFile { - name: UnicodeString::new_nul("Set ✓"), - expanded: true, - actions: vec![ - AtnAction { - function_key: 2, - shift: true, - command: false, - color: 3, - name: UnicodeString::new_nul("Soften"), - expanded: true, - items: vec![blur, flatten], - }, - AtnAction { name: UnicodeString::new_nul("Tidy"), items: vec![trim], ..Default::default() }, - AtnAction { name: UnicodeString::new_nul("Empty"), ..Default::default() }, - ], - warnings: Vec::new(), - ..Default::default() - } - } - - #[test] - fn round_trip() { - let f = set(); - let bytes = write(&f).unwrap(); - let parsed = parse(&bytes).unwrap(); - assert_eq!(parsed, f); - assert_eq!(write(&parsed).unwrap(), bytes, "writing is stable"); - assert_eq!(parsed.actions[0].items[0].event.id(), "GsnB"); - assert!(parsed.actions[1].items[0].event.is("trim")); - assert_eq!(parsed.actions[1].items[0].event.id(), "trim"); - assert_eq!(parsed.actions[0].items[0].label(), "Gaussian Blur"); - assert_eq!(parsed.actions[1].items[0].label(), "Trim"); - // A localised panel name in the platform's legacy encoding survives a round trip and - // the Unicode class name is the readable label. - let localised = AtnItem { - event: AtnEvent::name("set"), - dictionary: b"D\x8efinir".to_vec(), - descriptor: Some(Descriptor { name: UnicodeString::new_nul("Définir"), class_id: crate::descriptor::Id::new("setd"), items: Vec::new() }), - ..Default::default() - }; - assert_eq!(localised.label(), "Définir"); - let f = AtnFile { actions: vec![AtnAction { items: vec![localised.clone()], ..Default::default() }], ..Default::default() }; - let bytes = write(&f).unwrap(); - assert_eq!(parse(&bytes).unwrap().actions[0].items[0], localised); - assert_eq!(AtnItem { event: AtnEvent::name("x"), ..Default::default() }.label(), "x"); - } - - /// The layout Photoshop writes for a one-step Trim action, assembled by hand from the - /// format description: field by field, so a mistake names the field. - #[test] - fn layout_matches_the_specification() { - let f = AtnFile { - name: UnicodeString::new_nul("Trim"), - expanded: false, - actions: vec![AtnAction { - name: UnicodeString::new_nul("Action 1"), - expanded: true, - items: vec![AtnItem { - expanded: true, - event: AtnEvent::name("trim"), - dictionary: b"Trim".to_vec(), - descriptor: Some(Descriptor { - name: UnicodeString::new_nul("Trim"), - class_id: crate::descriptor::Id::Str(b"trim".to_vec()), - items: Vec::new(), - }), - ..Default::default() - }], - ..Default::default() - }], - warnings: Vec::new(), - ..Default::default() - }; - let mut expect = Vec::new(); - expect.extend_from_slice(&[0, 0, 0, 16]); // version - expect.extend_from_slice(&[0, 0, 0, 5, 0, b'T', 0, b'r', 0, b'i', 0, b'm', 0, 0]); // set name - expect.push(0); // set collapsed - expect.extend_from_slice(&[0, 0, 0, 1]); // one action - expect.extend_from_slice(&[0, 0, 0, 0, 0, 0]); // no function key, no modifiers, no colour - expect.extend_from_slice(&[0, 0, 0, 9]); - for c in "Action 1\0".encode_utf16() { - expect.extend_from_slice(&c.to_be_bytes()); - } - expect.push(1); // action expanded - expect.extend_from_slice(&[0, 0, 0, 1]); // one step - expect.extend_from_slice(&[1, 1, 0, 0]); // expanded, enabled, no dialog, options 0 - expect.extend_from_slice(b"TEXT\0\0\0\x04trim"); - expect.extend_from_slice(b"\0\0\0\x04Trim"); - expect.extend_from_slice(&[0xff; 4]); // a descriptor follows - expect.extend_from_slice(&[0, 0, 0, 5, 0, b'T', 0, b'r', 0, b'i', 0, b'm', 0, 0]); // class name - expect.extend_from_slice(b"\0\0\0\x04trim"); // class id, length-4 string form - expect.extend_from_slice(&[0, 0, 0, 0]); // no items - assert_eq!(write(&f).unwrap(), expect); - assert_eq!(parse(&expect).unwrap(), f); - } - - #[test] - fn truncation_never_parses_and_never_panics() { - let bytes = write(&set()).unwrap(); - for cut in 0..bytes.len() { - assert!(parse(&bytes[..cut]).is_err(), "cut at {cut}/{}", bytes.len()); - } - let mut padded = bytes.clone(); - padded.extend_from_slice(b"junk"); - let f = parse(&padded).unwrap(); - assert_eq!(f.warnings, ["4 trailing bytes ignored"]); - assert_eq!(f.actions, set().actions); - } - - #[test] - fn rejects_other_versions_and_bad_structure() { - let mut bytes = write(&set()).unwrap(); - bytes[3] = 7; - assert!(matches!(parse(&bytes), Err(PsdError::Unsupported(_)))); - // A count far beyond the data must fail before allocating. - let mut huge = vec![0, 0, 0, 16, 0, 0, 0, 0, 0]; - huge.extend_from_slice(&u32::MAX.to_be_bytes()); - assert!(matches!(parse(&huge), Err(PsdError::UnexpectedEof { .. }))); - // Unknown event kinds and descriptor flags are reported, not guessed. - let mut bad_kind = write(&set()).unwrap(); - let at = bad_kind.windows(4).position(|w| w == b"long").unwrap(); - bad_kind[at..at + 4].copy_from_slice(b"what"); - assert!(matches!(parse(&bad_kind), Err(PsdError::Invalid(_)))); - let mut bad_flag = write(&set()).unwrap(); - let at = bad_flag.windows(4).position(|w| w == [0xff; 4]).unwrap(); - bad_flag[at..at + 4].copy_from_slice(&[0, 0, 0, 7]); - 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 latin1_symbol_names_read_as_windows_1252() { - // 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(); - assert_eq!(f.encoding.as_deref(), Some("macintosh")); - 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 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 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", "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] - 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-1251")); - assert_eq!(f.warnings.len(), 1, "{:?}", f.warnings); - assert!(f.warnings[0].contains("windows-1251"), "{:?}", f.warnings); - assert_eq!(labels(&f), ["ЂяЂ"]); - } - - #[test] - fn unresolved_codepage_tie_keeps_a_top_candidate_and_the_original_bytes() { - // GBK 保存 ties with other CJK pages. No Unicode name settles it, but windows-1252 - // scored lower, so its "±£´æ" must not replace the tied candidates' readable text. - let bytes = one_action("Set 1", "Action 1", vec![bare(AtnEvent::name("x"), b"\xb1\xa3\xb4\xe6")]); - let f = parse(&bytes).unwrap(); - assert_eq!(f.encoding.as_deref(), Some("GBK")); - assert_eq!(labels(&f), ["保存"]); - assert_eq!(f.warnings.len(), 1, "{:?}", f.warnings); - assert!(f.warnings[0].contains("read as GBK"), "{:?}", f.warnings); - assert_eq!(write(&f).unwrap(), bytes); - // Callers can still resolve an ambiguous guess explicitly. - let forced = parse_with_encoding(&bytes, Some("windows-1252")).unwrap(); - assert_eq!(labels(&forced), ["±£´æ"]); - assert!(forced.warnings.is_empty(), "{:?}", forced.warnings); - assert_eq!(write(&forced).unwrap(), bytes); - } - - #[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(); - let mut x: u32 = 0x9e37_79b9; - for i in 0..2000 { - let mut bytes = seed.clone(); - for _ in 0..(i % 7 + 1) { - x ^= x << 13; - x ^= x >> 17; - x ^= x << 5; - let at = (x as usize) % bytes.len(); - bytes[at] = (x >> 8) as u8; - } - let _ = parse(&bytes); - } - } -} diff --git a/crates/psd/src/atn/legacy.rs b/crates/psd/src/atn/legacy.rs deleted file mode 100644 index c0f5053cbd..0000000000 --- a/crates/psd/src/atn/legacy.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! Version 12 descriptors use bare codes and omit Unicode class names. - -use crate::descriptor::{Class, Descriptor, Id, MAX_DEPTH, ObjectArray, ReferenceItem, UnicodeString, Value, vec_for_count}; -use crate::error::{PsdError, Result}; -use crate::io::Reader; - -/// Read the unnamed, classless descriptor at the root of a legacy action step. -pub(super) fn read(r: &mut Reader<'_>) -> Result { - descriptor(r, Id::Code(*b"null"), 0) -} - -fn class(r: &mut Reader<'_>) -> Result { - Ok(Class { name: UnicodeString::default(), class_id: Id::Code(r.array()?) }) -} - -/// Read items after their enclosing class, with the same depth bound as modern descriptors. -fn descriptor(r: &mut Reader<'_>, class_id: Id, depth: usize) -> Result { - if depth > MAX_DEPTH { - return Err(PsdError::LimitExceeded("descriptor nesting too deep")); - } - let n = r.u32()?; - // A bare key, type and Boolean need nine bytes, without a modern ID length. - r.check_count(u64::from(n), 9)?; - let mut items = vec_for_count(n); - for _ in 0..n { - items.push((Id::Code(r.array()?), value(r, depth + 1)?)); - } - Ok(Descriptor { name: UnicodeString::default(), class_id, items }) -} - -/// Decode a legacy value without trying the modern dialect on malformed input. -fn value(r: &mut Reader<'_>, depth: usize) -> Result { - if depth > MAX_DEPTH { - return Err(PsdError::LimitExceeded("descriptor nesting too deep")); - } - Ok(match &r.array::<4>()? { - b"obj " => { - let n = r.u32()?; - r.check_count(u64::from(n), 8)?; - let mut items = vec_for_count(n); - for _ in 0..n { - items.push(reference(r)?); - } - Value::Reference(items) - } - ty @ (b"Objc" | b"GlbO") => { - let class_id = Id::Code(r.array()?); - let d = descriptor(r, class_id, depth + 1)?; - if ty == b"Objc" { Value::Descriptor(d) } else { Value::GlobalObject(d) } - } - b"VlLs" => { - let n = r.u32()?; - r.check_count(u64::from(n), 4)?; - let mut items = vec_for_count(n); - for _ in 0..n { - items.push(value(r, depth + 1)?); - } - Value::List(items) - } - b"doub" => Value::Double(r.f64()?), - b"UntF" => Value::UnitFloat { unit: r.array()?, value: r.f64()? }, - b"UnFl" => { - let unit = r.array()?; - let n = r.u32()?; - r.check_count(u64::from(n), 8)?; - let mut values = vec_for_count(n); - for _ in 0..n { - values.push(r.f64()?); - } - Value::UnitFloats { unit, values } - } - b"TEXT" => Value::Text(UnicodeString::read(r)?), - b"enum" => Value::Enumerated { type_id: Id::Code(r.array()?), value: Id::Code(r.array()?) }, - b"long" => Value::Integer(r.i32()?), - b"comp" => Value::LargeInteger(r.i64()?), - b"bool" => Value::Boolean(r.u8()? != 0), - b"type" => Value::Class(class(r)?), - b"GlbC" => Value::GlobalClass(class(r)?), - ty @ (b"alis" | b"Pth " | b"tdta") => { - let n = r.u32()?; - let bytes = r.bytes_u64(u64::from(n))?.to_vec(); - match ty { - b"alis" => Value::Alias(bytes), - b"Pth " => Value::Path(bytes), - _ => Value::RawData(bytes), - } - } - b"ObAr" => { - let class_id = Id::Code(r.array()?); - let prefix = r.u32()?; - Value::ObjectArray(ObjectArray { prefix, body: descriptor(r, class_id, depth + 1)? }) - } - other => return Err(PsdError::Unsupported(format!("legacy descriptor OSType {:?}", String::from_utf8_lossy(other)))), - }) -} - -/// Every legacy reference form carries a bare class, including index and identifier forms. -fn reference(r: &mut Reader<'_>) -> Result { - let ty = r.array::<4>()?; - let class = class(r)?; - Ok(match &ty { - b"prop" => ReferenceItem::Property { class, key: Id::Code(r.array()?) }, - b"Clss" => ReferenceItem::Class(class), - b"Enmr" => ReferenceItem::Enumerated { class, type_id: Id::Code(r.array()?), value: Id::Code(r.array()?) }, - b"rele" => ReferenceItem::Offset { class, offset: r.i32()? }, - b"Idnt" => ReferenceItem::Identifier { class, id: r.u32()? }, - b"indx" => ReferenceItem::Index { class, index: r.u32()? }, - b"name" => ReferenceItem::Name { class, name: UnicodeString::read(r)? }, - other => return Err(PsdError::Unsupported(format!("legacy reference item type {:?}", String::from_utf8_lossy(other)))), - }) -} diff --git a/crates/psd/src/blend.rs b/crates/psd/src/blend.rs deleted file mode 100644 index a968c10c8b..0000000000 --- a/crates/psd/src/blend.rs +++ /dev/null @@ -1,143 +0,0 @@ -//! Layer blend modes (the 4-character keys stored after the `8BIM` signature). - -/// Photoshop blend mode keys. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[allow(missing_docs)] -pub enum BlendMode { - PassThrough, - #[default] - Normal, - Dissolve, - Darken, - Multiply, - ColorBurn, - LinearBurn, - DarkerColor, - Lighten, - Screen, - ColorDodge, - LinearDodge, - LighterColor, - Overlay, - SoftLight, - HardLight, - VividLight, - LinearLight, - PinLight, - HardMix, - Difference, - Exclusion, - Subtract, - Divide, - Hue, - Saturation, - Color, - Luminosity, - /// A key not known to this crate, preserved verbatim. - Unknown([u8; 4]), -} - -impl BlendMode { - /// All known modes (27 layer modes plus pass-through for groups). - pub const ALL: [BlendMode; 28] = [ - BlendMode::PassThrough, - BlendMode::Normal, - BlendMode::Dissolve, - BlendMode::Darken, - BlendMode::Multiply, - BlendMode::ColorBurn, - BlendMode::LinearBurn, - BlendMode::DarkerColor, - BlendMode::Lighten, - BlendMode::Screen, - BlendMode::ColorDodge, - BlendMode::LinearDodge, - BlendMode::LighterColor, - BlendMode::Overlay, - BlendMode::SoftLight, - BlendMode::HardLight, - BlendMode::VividLight, - BlendMode::LinearLight, - BlendMode::PinLight, - BlendMode::HardMix, - BlendMode::Difference, - BlendMode::Exclusion, - BlendMode::Subtract, - BlendMode::Divide, - BlendMode::Hue, - BlendMode::Saturation, - BlendMode::Color, - BlendMode::Luminosity, - ]; - - /// The stored 4-byte key. - pub fn key(self) -> [u8; 4] { - *match self { - BlendMode::PassThrough => b"pass", - BlendMode::Normal => b"norm", - BlendMode::Dissolve => b"diss", - BlendMode::Darken => b"dark", - BlendMode::Multiply => b"mul ", - BlendMode::ColorBurn => b"idiv", - BlendMode::LinearBurn => b"lbrn", - BlendMode::DarkerColor => b"dkCl", - BlendMode::Lighten => b"lite", - BlendMode::Screen => b"scrn", - BlendMode::ColorDodge => b"div ", - BlendMode::LinearDodge => b"lddg", - BlendMode::LighterColor => b"lgCl", - BlendMode::Overlay => b"over", - BlendMode::SoftLight => b"sLit", - BlendMode::HardLight => b"hLit", - BlendMode::VividLight => b"vLit", - BlendMode::LinearLight => b"lLit", - BlendMode::PinLight => b"pLit", - BlendMode::HardMix => b"hMix", - BlendMode::Difference => b"diff", - BlendMode::Exclusion => b"smud", - BlendMode::Subtract => b"fsub", - BlendMode::Divide => b"fdiv", - BlendMode::Hue => b"hue ", - BlendMode::Saturation => b"sat ", - BlendMode::Color => b"colr", - BlendMode::Luminosity => b"lum ", - BlendMode::Unknown(ref k) => k, - } - } - - /// Parses a stored key; unknown keys map to [`BlendMode::Unknown`]. - pub fn from_key(key: [u8; 4]) -> Self { - BlendMode::ALL.iter().copied().find(|m| m.key() == key).unwrap_or(BlendMode::Unknown(key)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn all_keys_roundtrip_and_unique() { - let mut keys = std::collections::HashSet::new(); - for m in BlendMode::ALL { - assert_eq!(BlendMode::from_key(m.key()), m); - assert!(keys.insert(m.key())); - } - assert_eq!(keys.len(), 28); - } - - #[test] - fn unknown_preserved() { - let m = BlendMode::from_key(*b"zzzz"); - assert_eq!(m, BlendMode::Unknown(*b"zzzz")); - assert_eq!(m.key(), *b"zzzz"); - } - - #[test] - fn specific_keys() { - assert_eq!(BlendMode::Multiply.key(), *b"mul "); - assert_eq!(BlendMode::from_key(*b"smud"), BlendMode::Exclusion); - assert_eq!(BlendMode::from_key(*b"idiv"), BlendMode::ColorBurn); - assert_eq!(BlendMode::default(), BlendMode::Normal); - } -} diff --git a/crates/psd/src/builder.rs b/crates/psd/src/builder.rs deleted file mode 100644 index 6606bdb351..0000000000 --- a/crates/psd/src/builder.rs +++ /dev/null @@ -1,471 +0,0 @@ -//! [`PsdBuilder`]: construct PSD/PSB files from pixel buffers. -//! -//! The builder never composites. Supply the merged image with -//! [`PsdBuilder::composite`]; otherwise a white placeholder is written and -//! resource 1057 records `has_real_merged_data = false`. - -use crate::blend::BlendMode; -use crate::compression::Compression; -use crate::error::{PsdError, Result}; -use crate::file::{GlobalLayerMask, LayerInfoPlacement, PsdFile}; -use crate::header::{ColorMode, Header, Version}; -use crate::image_data::ImageData; -use crate::io::encode_legacy_name; -use crate::layer::{BlendingRanges, ChannelData, LayerFlags, LayerInfo, LayerMask, LayerRecord, MaskData, Rect}; -use crate::resources::{ImageResource, ResolutionInfo, ids, version_info_resource}; -use crate::tagged::{SectionType, TaggedBlock}; - -/// Interleaved pixel data with alpha. CMYK values are *ink amounts* -/// (0 = no ink); the builder stores them inverted as Photoshop does. -#[derive(Debug, Clone, PartialEq)] -pub enum PixelData { - /// RGBA, 8-bit. - Rgba8(Vec), - /// RGBA, 16-bit. - Rgba16(Vec), - /// Gray + alpha, 8-bit. - GrayA8(Vec), - /// Gray + alpha, 16-bit. - GrayA16(Vec), - /// CMYK ink + alpha, 8-bit. - Cmyka8(Vec), - /// CMYK ink + alpha, 16-bit. - Cmyka16(Vec), -} - -impl PixelData { - fn mode_depth(&self) -> (ColorMode, u16) { - match self { - PixelData::Rgba8(_) => (ColorMode::Rgb, 8), - PixelData::Rgba16(_) => (ColorMode::Rgb, 16), - PixelData::GrayA8(_) => (ColorMode::Grayscale, 8), - PixelData::GrayA16(_) => (ColorMode::Grayscale, 16), - PixelData::Cmyka8(_) => (ColorMode::Cmyk, 8), - PixelData::Cmyka16(_) => (ColorMode::Cmyk, 16), - } - } - /// Samples per pixel including alpha. - fn spp(&self) -> usize { - match self.mode_depth().0 { - ColorMode::Rgb => 4, - ColorMode::Grayscale => 2, - _ => 5, - } - } - fn len(&self) -> usize { - match self { - PixelData::Rgba8(v) | PixelData::GrayA8(v) | PixelData::Cmyka8(v) => v.len(), - PixelData::Rgba16(v) | PixelData::GrayA16(v) | PixelData::Cmyka16(v) => v.len(), - } - } - /// Planar big-endian plane for interleaved component `c`, as stored - /// (CMYK inverted). - fn plane(&self, c: usize, n: usize) -> Vec { - let spp = self.spp(); - let invert = self.mode_depth().0 == ColorMode::Cmyk && c < 4; - match self { - PixelData::Rgba8(v) | PixelData::GrayA8(v) | PixelData::Cmyka8(v) => { - (0..n).map(|i| if invert { 255 - v[i * spp + c] } else { v[i * spp + c] }).collect() - } - PixelData::Rgba16(v) | PixelData::GrayA16(v) | PixelData::Cmyka16(v) => (0..n) - .flat_map(|i| { - let s = v[i * spp + c]; - (if invert { 65535 - s } else { s }).to_be_bytes() - }) - .collect(), - } - } - fn alpha_is_opaque(&self, n: usize) -> bool { - let spp = self.spp(); - match self { - PixelData::Rgba8(v) | PixelData::GrayA8(v) | PixelData::Cmyka8(v) => (0..n).all(|i| v[i * spp + spp - 1] == 255), - PixelData::Rgba16(v) | PixelData::GrayA16(v) | PixelData::Cmyka16(v) => (0..n).all(|i| v[i * spp + spp - 1] == 65535), - } - } - - fn composite_plane(&self, c: usize, n: usize) -> Vec { - // Photoshop stores transparent RGB composites against white; layer channels stay straight, - // and so do Gray and CMYK composites here (see `PsdBuilder::composite`). - match self { - Self::Rgba8(v) if c < 3 => v - .as_chunks::<4>() - .0 - .iter() - .take(n) - .map(|p| { - let (color, alpha) = (u32::from(p[c]), u32::from(p[3])); - if alpha == 0 { p[c] } else { ((color * alpha + 127) / 255 + 255 - alpha) as u8 } - }) - .collect(), - Self::Rgba16(v) if c < 3 => v - .as_chunks::<4>() - .0 - .iter() - .take(n) - .flat_map(|p| { - let (color, alpha) = (u32::from(p[c]), u32::from(p[3])); - let value = if alpha == 0 { p[c] } else { ((color * alpha + 32767) / 65535 + 65535 - alpha) as u16 }; - value.to_be_bytes() - }) - .collect(), - _ => self.plane(c, n), - } - } -} - -/// A layer mask given as 8-bit samples. -#[derive(Debug, Clone, PartialEq)] -pub struct MaskSpec { - /// Mask rectangle in document coordinates. - pub rect: Rect, - /// `rect.width × rect.height` samples (0 = hidden, 255 = shown). - pub data: Vec, - /// Value outside the rectangle. - pub default_color: u8, - /// Mask disabled. - pub disabled: bool, -} - -/// A raster layer. -#[derive(Debug, Clone, PartialEq)] -pub struct LayerSpec { - /// Name (written both as legacy Pascal name and `luni`). - pub name: String, - /// Left edge. - pub left: i32, - /// Top edge. - pub top: i32, - /// Width. - pub width: u32, - /// Height. - pub height: u32, - /// Pixels (must match the builder's color mode and depth). - pub pixels: PixelData, - /// Blend mode. - pub blend_mode: BlendMode, - /// Opacity 0..=255. - pub opacity: u8, - /// Fill opacity (`iOpa`), if not 255. - pub fill_opacity: Option, - /// Visible. - pub visible: bool, - /// Clipped to the layer below. - pub clipping: bool, - /// Optional user mask. - pub mask: Option, - /// Additional blocks appended verbatim. - pub extra_blocks: Vec, -} - -impl LayerSpec { - /// A visible normal layer at full opacity. - pub fn new(name: impl Into, left: i32, top: i32, width: u32, height: u32, pixels: PixelData) -> Self { - LayerSpec { - name: name.into(), - left, - top, - width, - height, - pixels, - blend_mode: BlendMode::Normal, - opacity: 255, - fill_opacity: None, - visible: true, - clipping: false, - mask: None, - extra_blocks: Vec::new(), - } - } -} - -/// A group (folder). -#[derive(Debug, Clone, PartialEq)] -pub struct GroupSpec { - /// Name. - pub name: String, - /// Blend mode (default pass-through). - pub blend_mode: BlendMode, - /// Opacity. - pub opacity: u8, - /// Visible. - pub visible: bool, - /// Open (expanded) in the layers panel. - pub open: bool, -} - -impl GroupSpec { - /// A visible, open, pass-through group. - pub fn new(name: impl Into) -> Self { - GroupSpec { name: name.into(), blend_mode: BlendMode::PassThrough, opacity: 255, visible: true, open: true } - } -} - -#[derive(Debug, Clone)] -enum Entry { - Layer(LayerSpec), - GroupStart, - GroupEnd(GroupSpec), -} - -/// Builds [`PsdFile`]s. Layers are pushed bottom-to-top. -#[derive(Debug, Clone)] -pub struct PsdBuilder { - width: u32, - height: u32, - color_mode: ColorMode, - depth: u16, - version: Version, - compression: Compression, - entries: Vec, - open_groups: Vec, - composite: Option, - resources: Vec, -} - -impl PsdBuilder { - /// An 8-bit RGB PSD using RLE compression. - pub fn new(width: u32, height: u32) -> Self { - PsdBuilder { - width, - height, - color_mode: ColorMode::Rgb, - depth: 8, - version: Version::Psd, - compression: Compression::Rle, - entries: Vec::new(), - open_groups: Vec::new(), - composite: None, - resources: Vec::new(), - } - } - /// Sets the color mode (RGB, Grayscale or CMYK). - pub fn color_mode(mut self, mode: ColorMode) -> Self { - self.color_mode = mode; - self - } - /// Sets the depth (8 or 16). - pub fn depth(mut self, depth: u16) -> Self { - self.depth = depth; - self - } - /// Sets PSD or PSB. - pub fn version(mut self, v: Version) -> Self { - self.version = v; - self - } - /// Sets the compression used for all channels and the merged image. - pub fn compression(mut self, c: Compression) -> Self { - self.compression = c; - self - } - /// Adds a resolution resource. - pub fn resolution(mut self, dpi: f64) -> Self { - self.resources.push(ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(dpi).to_bytes())); - self - } - /// Adds an ICC profile resource. - pub fn icc_profile(mut self, icc: Vec) -> Self { - self.resources.push(ImageResource::new(ids::ICC_PROFILE, icc)); - self - } - /// Adds an arbitrary image resource. - pub fn resource(mut self, r: ImageResource) -> Self { - self.resources.push(r); - self - } - /// Pushes a layer above the previous one. - pub fn push_layer(&mut self, spec: LayerSpec) -> &mut Self { - self.entries.push(Entry::Layer(spec)); - self - } - /// Opens a group; subsequent layers go inside until [`Self::end_group`]. - pub fn begin_group(&mut self, spec: GroupSpec) -> &mut Self { - self.entries.push(Entry::GroupStart); - self.open_groups.push(spec); - self - } - /// Closes the innermost open group. - pub fn end_group(&mut self) -> Result<&mut Self> { - let g = self.open_groups.pop().ok_or_else(|| PsdError::invalid("end_group without begin_group"))?; - self.entries.push(Entry::GroupEnd(g)); - Ok(self) - } - /// Supplies the merged composite (straight samples, same format as layers, full canvas). - /// Transparent RGB is stored against white, quantized at the document depth. Gray and CMYK - /// composites with alpha are stored straight (not matted against white as Photoshop would): - /// a test that reads them as a Photoshop merged image has to allow for that. - pub fn composite(&mut self, pixels: PixelData) -> &mut Self { - self.composite = Some(pixels); - self - } - - fn color_channels(&self) -> Result { - match self.color_mode { - ColorMode::Rgb => Ok(3), - ColorMode::Grayscale => Ok(1), - ColorMode::Cmyk => Ok(4), - m => Err(PsdError::Unsupported(format!("builder color mode {m:?}"))), - } - } - - fn check_pixels(&self, p: &PixelData, n: usize) -> Result<()> { - if p.mode_depth() != (self.color_mode, self.depth) { - return Err(PsdError::invalid(format!("pixel format {:?} does not match document {:?}/{}", p.mode_depth(), self.color_mode, self.depth))); - } - if p.len() != n * p.spp() { - return Err(PsdError::invalid(format!("pixel buffer has {} samples, expected {}", p.len(), n * p.spp()))); - } - Ok(()) - } - - fn channel(&self, id: i16, plane: &[u8], w: usize, h: usize) -> Result { - ChannelData::encode(id, self.compression, plane, w, h, self.depth, self.version) - } - - fn empty_channels(&self, cc: usize) -> Result> { - let mut v = vec![self.channel(-1, &[], 0, 0)?]; - for c in 0..cc { - v.push(self.channel(c as i16, &[], 0, 0)?); - } - Ok(v) - } - - fn layer_record(&self, spec: &LayerSpec, cc: usize, id: u32) -> Result { - let (w, h) = (spec.width as usize, spec.height as usize); - let n = w * h; - self.check_pixels(&spec.pixels, n)?; - let mut channels = vec![self.channel(-1, &spec.pixels.plane(cc, n), w, h)?]; - for c in 0..cc { - channels.push(self.channel(c as i16, &spec.pixels.plane(c, n), w, h)?); - } - let mut mask = MaskData::None; - if let Some(m) = &spec.mask { - let (mw, mh) = m.rect.size()?; - if m.data.len() != mw * mh { - return Err(PsdError::invalid("mask buffer size mismatch")); - } - let plane: Vec = if self.depth == 16 { m.data.iter().flat_map(|&v| (u16::from(v) * 257).to_be_bytes()).collect() } else { m.data.clone() }; - channels.push(self.channel(-2, &plane, mw, mh)?); - let flags = if m.disabled { LayerMask::FLAG_DISABLED } else { 0 }; - mask = MaskData::Mask(LayerMask::new(m.rect, m.default_color, flags)); - } - let mut flags = LayerFlags(0); - flags.set_hidden(!spec.visible); - let mut blocks = vec![TaggedBlock::unicode_name(&spec.name), TaggedBlock::layer_id(id)]; - if let Some(f) = spec.fill_opacity { - blocks.push(TaggedBlock::fill_opacity(f)); - } - blocks.extend(spec.extra_blocks.iter().cloned()); - Ok(LayerRecord { - rect: Rect::from_xywh(spec.left, spec.top, spec.width, spec.height), - channels, - blend_mode: spec.blend_mode, - opacity: spec.opacity, - clipping: u8::from(spec.clipping), - flags, - filler: 0, - mask, - blending_ranges: BlendingRanges::full(cc), - name: encode_legacy_name(&spec.name), - blocks, - extra_trailing: Vec::new(), - }) - } - - /// Builds the file model. - pub fn build(&self) -> Result { - if !self.open_groups.is_empty() { - return Err(PsdError::invalid("unclosed group")); - } - if !matches!(self.depth, 8 | 16) { - return Err(PsdError::Unsupported(format!("builder depth {}", self.depth))); - } - let cc = self.color_channels()?; - let mut layers = Vec::new(); - for (id, e) in (1u32..).zip(self.entries.iter()) { - match e { - Entry::Layer(spec) => layers.push(self.layer_record(spec, cc, id)?), - Entry::GroupStart => layers.push(LayerRecord { - channels: self.empty_channels(cc)?, - blending_ranges: BlendingRanges::full(cc), - name: b"".to_vec(), - blocks: vec![ - TaggedBlock::unicode_name(""), - TaggedBlock::layer_id(id), - TaggedBlock::section_divider(SectionType::BoundingDivider, None, None), - ], - ..Default::default() - }), - Entry::GroupEnd(g) => { - let kind = if g.open { SectionType::OpenFolder } else { SectionType::ClosedFolder }; - let mut flags = LayerFlags(0); - flags.set_hidden(!g.visible); - layers.push(LayerRecord { - channels: self.empty_channels(cc)?, - blend_mode: g.blend_mode, - opacity: g.opacity, - flags, - blending_ranges: BlendingRanges::full(cc), - name: encode_legacy_name(&g.name), - blocks: vec![ - TaggedBlock::unicode_name(&g.name), - TaggedBlock::layer_id(id), - TaggedBlock::section_divider(kind, Some(g.blend_mode), None), - ], - ..Default::default() - }); - } - } - } - - let (w, h) = (self.width as usize, self.height as usize); - let n = w * h; - let (real, planes, with_alpha) = match &self.composite { - Some(p) => { - self.check_pixels(p, n)?; - let with_alpha = !p.alpha_is_opaque(n); - let mut planes = Vec::new(); - for c in 0..cc + usize::from(with_alpha) { - planes.extend(if with_alpha { p.composite_plane(c, n) } else { p.plane(c, n) }); - } - (true, planes, with_alpha) - } - None => { - let bps = usize::from(self.depth / 8); - // White: 0xff in RGB/gray; no ink (stored inverted as 0xff) in CMYK. - (false, vec![0xff; n * bps * cc], false) - } - }; - let channels = (cc + usize::from(with_alpha)) as u16; - let header = Header::new(self.version, self.width, self.height, channels, self.depth, self.color_mode); - header.validate()?; - let image_data = ImageData::encode(self.compression, &planes, &header)?; - let mut resources = self.resources.clone(); - resources.push(version_info_resource(real)); - - let has_layers = !layers.is_empty(); - let layer_info = has_layers.then_some(LayerInfo { merged_alpha: with_alpha, layers, padding: None }); - let layer_info_placement = if has_layers && self.depth == 16 { - LayerInfoPlacement::GlobalBlock { index: 0, signature: *b"8BIM", key: *b"Lr16", padding: None } - } else { - LayerInfoPlacement::Section - }; - Ok(PsdFile { - header, - color_mode_data: Vec::new(), - resources, - layer_info, - layer_info_placement, - global_layer_mask: has_layers.then(GlobalLayerMask::default), - global_blocks: Vec::new(), - layer_mask_trailing: Vec::new(), - image_data, - write_as_psb: false, - }) - } - - /// Builds and serializes. - pub fn to_bytes(&self) -> Result> { - self.build()?.to_bytes() - } -} diff --git a/crates/psd/src/codepage.rs b/crates/psd/src/codepage.rs deleted file mode 100644 index af472ea574..0000000000 --- a/crates/psd/src/codepage.rs +++ /dev/null @@ -1,874 +0,0 @@ -//! 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, each page's punctuation, the degree sign, and ¡ opening an exclamation: "¡Hola!"). The -//! highest share wins. Two single-byte readings don't count: the letters windows-1252 alone -//! has at 0x80–0x9F (Š š Ž ž Ÿ ƒ ˆ), where Mac Roman keeps its accented lowercase (Mac -//! "Opacité" is 1252 "OpacitŽ"), unless one starts a word ("Škoda", "šuma") in a file whose -//! own Unicode text doesn't write the Mac Roman letter on that byte instead (a French "état", -//! a German "über", "öffnen"); -//! and a windows-1251 Cyrillic letter glued into an ASCII word (Mac "Höhe" is 1251 "Hшhe"), -//! unless the name's letters are mostly Cyrillic ("CMYKканал", "Копiя") or the letter is in a -//! Cyrillic word of its own ("Layer Слой", "Слой1"). -//! 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 if it is among them, otherwise the first highest-scoring candidate, -//! flagged [`Guess::uncertain`]. -//! 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. - -use encoding_rs::{ - 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}; - -/// 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 settled the highest-scoring candidates' tie; `encoding` is a fallback among them. - 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 }; - } - // The accented letters the file's own Unicode text uses: what its writer's language writes. - let hint_letters: std::collections::BTreeSet = hint.chars().filter(|c| !c.is_ascii() && c.is_alphabetic()).flat_map(char::to_lowercase).collect(); - 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, &hint_letters); - (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); - } - } - 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 }, - // A fallback must not discard the scores and choose a lower-scoring page. - None => { - let encoding = if tied.contains(&WINDOWS_1252) { WINDOWS_1252 } else { tied.first().copied().unwrap_or(WINDOWS_1252) }; - Guess { encoding, 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 } - } -} - -/// 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, &std::collections::BTreeSet::new()); - 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, 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, 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"))), - } -} - -/// 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. `hint_letters` are the accented letters the file's own Unicode -/// text writes (lowercase), which settle a word-initial letter of windows-1252's 0x80–0x9F. -fn score(enc: &'static Encoding, name: &[u8], hint_letters: &std::collections::BTreeSet) -> (u64, u64) { - if enc == WINDOWS_1252 || enc == WINDOWS_1251 || enc == MACINTOSH { - // Letters, typographic punctuation, the degree sign ("Rotation 90°") and ¡ opening an - // exclamation ("¡Hola!") are common, as the double-byte pages' punctuation rows are, with two readings - // held back: the letters windows-1252 alone has at 0x80–0x9F, where Mac Roman keeps its - // accented lowercase (Mac "Opacité" is 1252 "OpacitŽ"), unless one starts a word ("Škoda", - // "ŠKODA", "šuma") and the file's own text doesn't write the Mac Roman letter instead (a - // French "état", a German "öffnen"); and a windows-1251 Cyrillic letter glued into an ASCII - // word (Mac "Höhe" is 1251 "Hшhe"), unless the name's letters are mostly Cyrillic - // ("CMYKканал", Ukrainian "Копiя") or the letter is in a Cyrillic word of its own ("Layer - // Слой"); a lone one right after a digit (Mac "90°" alone is 1251 "90Ў") never counts. - let decoded = Name::new(&decode(name, enc)); - let chars = &decoded.chars; - let cyrillic_name = chars.iter().filter(|c| is_cyrillic(**c)).count() >= chars.iter().filter(|c| c.is_ascii_alphabetic()).count(); - let (mut common, mut high) = (0u64, 0u64); - for (i, &ch) in chars.iter().enumerate() { - if ch.is_ascii() { - continue; - } - high += 1; - let (after_ascii, letters_after) = position(&decoded, i); - let counts = if enc == WINDOWS_1252 && RARE_1252_LETTERS.contains(&ch) { - // Opening a word, capital or not ("Škoda", "šuma"), before an ASCII letter of - // either case: Mac Roman's lowercase ä before a capital ("äKODA") is no word - // either. - let word_initial = !after_ascii && letters_after >= 1; - // The same byte as Mac Roman reads it: a letter the file's text writes, where it - // never writes this one, says the writer meant that ("état", not "Žtat"). - let written = |c: char| c.to_lowercase().all(|l| hint_letters.contains(&l)); - let mac = name.get(i..=i).map(|b| decode(b, MACINTOSH)).and_then(|s| s.chars().next()); - word_initial && !(mac.is_some_and(|m| m.is_alphabetic() && written(m)) && !written(ch)) - } else if enc == WINDOWS_1251 && is_cyrillic(ch) { - (cyrillic_name && !lone_after_digit(&decoded, i)) || cyrillic_word(&decoded, i) - } else { - ch.is_alphabetic() || TYPOGRAPHIC.contains(&ch) || ch == '°' || (ch == '¡' && opens_exclamation(&decoded, i)) - }; - common += u64::from(counts); - } - return (common, high); - } - 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) -} - -/// [`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. -/// -/// windows-1251 has Cyrillic letters (І і Ј д) where windows-1252 has ² ³ £ ä, so a windows-1252 -/// name like "Fläche m²" or "Preis £5" would score higher as windows-1251 ("Flдche mІ", "Preis -/// Ј5"); [`score`] counts a Cyrillic letter only in a name whose letters are mostly Cyrillic, -/// which keeps ordinary Russian names such as "CMYKканал" or Ukrainian "Копiя" (Latin i). -fn single_byte_score(enc: &'static Encoding, name: &[u8], common: impl Fn(&Name, usize) -> bool) -> (u64, u64) { - let name = Name::new(&decode(name, enc)); - (0..name.chars.len()) - .filter(|i| name.chars.get(*i).is_some_and(|c| !c.is_ascii())) - .fold((0, 0), |(c, h), i| (c.saturating_add(u64::from(common(&name, i))), h.saturating_add(1))) -} - -/// A decoded name with what the position checks of [`score`] need, each found in one pass, so a -/// long name (a hostile file's 64 KiB of one letter) costs linear time rather than a rescan of -/// the rest of the name from every character. -struct Name { - chars: Vec, - /// `letters_from[k]`: how many letters run from `k` on (0 one past the end). - letters_from: Vec, - /// Where the last "!" is. - last_bang: Option, - /// For each Cyrillic letter, the run of Cyrillic letters around it (`start..end`); `i..i + 1` - /// for any other character. - cyrillic_runs: Vec<(usize, usize)>, -} - -impl Name { - fn new(text: &str) -> Self { - let chars: Vec = text.chars().collect(); - let n = chars.len(); - let mut letters_from = vec![0usize; n + 1]; - let mut run = 0usize; - for (slot, c) in letters_from.iter_mut().zip(&chars).rev() { - run = if c.is_alphabetic() { run.saturating_add(1) } else { 0 }; - *slot = run; - } - let last_bang = chars.iter().rposition(|c| *c == '!'); - let mut cyrillic_runs: Vec<(usize, usize)> = (0..n).map(|i| (i, i + 1)).collect(); - let mut start = 0; - while start < n { - if !chars.get(start).is_some_and(|c| is_cyrillic(*c)) { - start += 1; - continue; - } - let mut end = start + 1; - while chars.get(end).is_some_and(|c| is_cyrillic(*c)) { - end += 1; - } - for slot in cyrillic_runs.get_mut(start..end).into_iter().flatten() { - *slot = (start, end); - } - start = end; - } - Self { chars, letters_from, last_bang, cyrillic_runs } - } -} - -/// Whether the character at `i` of `chars` 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, -/// [`LATIN_SYMBOLS`], and ¡ opening an exclamation ("¡Hola!"), as in [`score`]. -fn is_latin_common(name: &Name, i: usize) -> bool { - let Some(&ch) = name.chars.get(i) else { return false }; - (ch.is_alphabetic() && !RARE_1252_LETTERS.contains(&ch) && ch != 'Œ' && ch != 'œ') - || TYPOGRAPHIC.contains(&ch) - || LATIN_SYMBOLS.contains(&ch) - || (ch == '¡' && opens_exclamation(name, i)) -} - -/// Where the character at `i` of `name` sits: right after an ASCII letter or digit (inside a word -/// or a number), and how many letters (accented ones too: "¡Ánimo!") follow it directly. -fn position(name: &Name, i: usize) -> (bool, usize) { - let after_ascii = i.checked_sub(1).and_then(|k| name.chars.get(k)).is_some_and(|c| c.is_ascii_alphanumeric()); - let letters_after = name.letters_from.get(i.saturating_add(1)).copied().unwrap_or(0); - (after_ascii, letters_after) -} - -/// Whether ¡ at `i` opens a Spanish exclamation ("¡Hola!", "Capa ¡Atención!", "¡Ánimo!"): no letter -/// or digit right before it, two letters or more after it, and the closing "!" later in the name. -/// Mac Roman's degree sign on the same byte follows a number ("Rotation 90°") or stands before a -/// unit ("20 °C", "20 °Celsius"), with no "!" to close. -fn opens_exclamation(name: &Name, i: usize) -> bool { - let (after_ascii, letters_after) = position(name, i); - !after_ascii && letters_after >= 2 && name.last_bang.is_some_and(|bang| bang > i) -} - -/// The letters windows-1252 has at 0x80–0x9F and Mac Roman doesn't: there Mac Roman keeps its -/// accented lowercase (ä é ö ü ...), so these never decide against it. Œ and œ (0x8C, 0x9C: Mac -/// å, ú) are real French letters and keep counting in [`score`]; [`is_latin_common`] leaves them -/// out as well. -const RARE_1252_LETTERS: [char; 7] = ['Š', 'š', 'Ž', 'ž', 'Ÿ', 'ƒ', 'ˆ']; - -/// A Cyrillic letter (windows-1251's 0xC0–0xFF and the letters among 0x80–0xBF). -fn is_cyrillic(ch: char) -> bool { - ('\u{0400}'..='\u{04FF}').contains(&ch) && ch.is_alphabetic() -} - -/// Whether the Cyrillic letter at `i` is in a Cyrillic word of its own: a run of two or more, -/// not glued to an ASCII letter, and not right after a digit ("Слой" beside "Layer", "Слой1"; -/// not "OpacitЋ", nor "90ЎЋ", which is Mac Roman "90°é": a digit ends a number, not a word, so -/// what follows it without a space is its unit or suffix). -fn cyrillic_word(name: &Name, i: usize) -> bool { - let (start, end) = cyrillic_run(name, i); - let glued_before = start.checked_sub(1).and_then(|k| name.chars.get(k)).is_some_and(|c| c.is_ascii_alphanumeric()); - let glued_after = name.chars.get(end).is_some_and(|c| c.is_ascii_alphabetic()); - end.saturating_sub(start) >= 2 && !glued_before && !glued_after -} - -/// The run of Cyrillic letters around the Cyrillic letter at `i` (`start..end`). -fn cyrillic_run(name: &Name, i: usize) -> (usize, usize) { - name.cyrillic_runs.get(i).copied().unwrap_or((i, i.saturating_add(1))) -} - -/// Whether the Cyrillic letter at `i` stands alone right after a digit: a unit or a symbol misread -/// (Mac Roman "90°" is windows-1251 "90Ў"), whatever the rest of the name; a run after a digit is -/// a Russian unit ("5шт") and still counts. -fn lone_after_digit(name: &Name, i: usize) -> bool { - let (start, end) = cyrillic_run(name, i); - end.saturating_sub(start) == 1 && start.checked_sub(1).and_then(|k| name.chars.get(k)).is_some_and(|c| c.is_ascii_digit()) -} - -/// Latin-1 symbols people type in names (windows-1252 0xA2–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: Ä, ô), and ¥ (0xA5, Mac Roman's -/// bullet in [`TYPOGRAPHIC`]: Mac "Ebene • Kopie"); and ¡ (0xA1), where Mac Roman has its degree -/// sign, the commoner of the two in names (Mac "Rotation 90°", "20 °C"), which counts only where -/// it opens an exclamation closed by "!" ("¡Hola!"; [`opens_exclamation`], in [`score`] and -/// [`is_latin_common`]). So a windows-1252 name whose only non-ASCII character is one of the -/// others ("Logo ®", "¿Tamaño?", "Preis ¥100") still reads as Mac Roman ("Logo Æ"). -const LATIN_SYMBOLS: [char; 10] = ['¢', '£', '©', '«', '°', '±', '²', '³', '¶', '·']; - -/// 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: GBK, 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 latin1_symbols_read_as_1252_not_mac_roman() { - // 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 mac_roman_accents_on_1252_letter_bytes_stay_mac_roman() { - // #10774: Mac Roman é ä ö ü Ä (0x8E 0x8A 0x9A 0x9F 0x80) are windows-1252 Ž Š š Ÿ € and - // windows-1251 Ћ Љ ш џ Ђ. The rare 1252 letters don't count, and a Cyrillic letter in a - // Latin word doesn't either, so Mac Roman wins with a Latin hint and without one. - let cases: [(&[&str], &str); 6] = [ - (&["Opacité 50%"], "Définir"), - (&["Opacité 50%"], "Set 1"), - (&["Sélection", "Créer un calque", "Luminosité/Contraste"], "Définir"), - (&["Höhe", "Grün", "Bär"], "Größe ändern"), - (&["Höhe"], "Set 1"), - (&["Ändern"], "Set 1"), - ]; - for (words, hint) in cases { - let g = guess_words(MACINTOSH, words, hint); - assert_eq!(g, Guess { encoding: MACINTOSH, uncertain: false }, "{words:?} with hint {hint:?}"); - let bytes = encoded(MACINTOSH, words); - for (b, w) in bytes.iter().zip(words) { - assert_eq!(decode(b, g.encoding), *w); - } - } - } - - #[test] - fn mac_roman_degree_sign_is_not_cyrillic() { - // #10774: Mac Roman ° (0xA1) is windows-1251 Ў and windows-1252 ¡; the degree sign is - // common text, a lone Cyrillic letter among Latin ones is not. - // "Layer 90°é" (review): ° and é are windows-1251 Ў and Ћ, two Cyrillic letters in a row, - // but glued to the number, so no word of their own. - let cases: [(&[&str], &str); 6] = [ - (&["Rotation 90°"], "Définir"), - (&["Rotation 90°"], "Set 1"), - (&["Rotation 90°"], "Größe ändern"), - (&["Rotation 90°", "Arrière-plan"], "Définir"), - (&["Layer 90°é"], "Set 1"), - (&["Layer 90°é"], "Définir"), - ]; - for (words, hint) in cases { - let g = guess_words(MACINTOSH, words, hint); - assert_eq!(g, Guess { encoding: MACINTOSH, uncertain: false }, "{words:?} with hint {hint:?}"); - } - } - - #[test] - fn the_same_names_in_windows_1252_stay_windows_1252() { - for words in [&["Opacité 50%"][..], &["Höhe", "Grün", "Bär"], &["Rotation 90°"], &["Ändern"], &["Fläche m²"], &["Preis £5"]] { - assert_eq!(guess_words(WINDOWS_1252, words, "Set 1").encoding, WINDOWS_1252, "{words:?}"); - assert_eq!(guess_words(WINDOWS_1252, words, "Größe ändern"), Guess { encoding: WINDOWS_1252, uncertain: false }, "{words:?}"); - } - } - - #[test] - fn cyrillic_names_in_latin_hinted_files_and_cyrillic_words_beside_latin_ones_stay_1251() { - // A Cyrillic step name in a set with a French name reads as it did; a Cyrillic word beside - // a Latin one counts as Cyrillic, and the hint settles the tie with windows-1252's letters. - assert_eq!(guess_words(WINDOWS_1251, &["Ёлка"], "Définir"), Guess { encoding: WINDOWS_1251, uncertain: false }); - assert_eq!(guess_words(WINDOWS_1251, &["Layer Слой"], "Набор 1"), Guess { encoding: WINDOWS_1251, uncertain: false }); - assert_eq!(guess_words(WINDOWS_1251, &["Layer Слой1"], "Набор 1"), Guess { encoding: WINDOWS_1251, uncertain: false }, "a digit after the word"); - assert_eq!(guess_words(WINDOWS_1251, &["Layer Слой", "Ёлка"], "Set 1"), Guess { encoding: WINDOWS_1251, uncertain: false }); - // Alone and without a hint, "Layer Слой" is as ambiguous as before (every letter is one in - // windows-1252 too): the flagged fallback. - assert_eq!(guess_words(WINDOWS_1251, &["Layer Слой"], "Set 1"), Guess { encoding: WINDOWS_1252, uncertain: true }); - } - - #[test] - fn a_rare_letter_starting_a_word_keeps_windows_1252() { - // windows-1252 Š Ž Ÿ š ž (0x8A 0x8E 0x9F 0x9A 0x9E) are Mac Roman ä é ü ö û: one starting - // a word ("Škoda", all caps "ŠKODA", lowercase "šuma") counts, an accent inside a word (Mac - // "Opacité" as "OpacitŽ") does not. - for words in [&["Škoda"][..], &["ŠKODA"], &["Žaba"], &["Šibenik", "Žaba"], &["ŽUPA", "Set"], &["šuma"], &["žaba"]] { - assert_eq!(guess_words(WINDOWS_1252, words, "Nastavení"), Guess { encoding: WINDOWS_1252, uncertain: false }, "{words:?}"); - assert_eq!(guess_words(WINDOWS_1252, words, "Set 1").encoding, WINDOWS_1252, "{words:?}"); - } - // In a file whose own text writes ä and never Š (a German Photoshop), the byte reads as - // the Mac Roman ä it would be there: the file's alphabet decides what the bytes can't. - assert_eq!(guess_words(WINDOWS_1252, &["Škoda"], "Größe ändern").encoding, MACINTOSH); - assert_eq!(guess_words(WINDOWS_1252, &["šuma"], "Größe ändern").encoding, MACINTOSH, "the file writes ö and never š"); - } - - #[test] - fn an_inverted_exclamation_opening_an_exclamation_reads_as_windows_1252() { - // windows-1252 ¡ (0xA1) is Mac Roman °: ¡ opening an exclamation, two letters or more - // after it (accented ones too) and the closing "!" later ("¡Hola!", "¡Ánimo!"), counts for - // windows-1252 (review); after a number ("90°"), before a unit ("20 °C", "20 °Celsius") or - // without a "!" the byte stays the degree sign. - for words in [&["¡Hola!"][..], &["Capa ¡Atención!"], &["¡Ánimo!"]] { - assert_eq!(guess_words(WINDOWS_1252, words, "Configuración"), Guess { encoding: WINDOWS_1252, uncertain: false }, "{words:?}"); - assert_eq!(guess_words(WINDOWS_1252, words, "Set 1").encoding, WINDOWS_1252, "{words:?}"); - } - // (With a Latin hint: without any, a lone 0xA1 before an ASCII letter is also a Big5 - // punctuation pair, a tie the fallback flags.) - for words in [&["Rotation 90°"][..], &["Temperatur 20 °C"], &["20 °Celsius"]] { - for hint in ["Configuración", "Größe ändern"] { - assert_eq!(guess_words(MACINTOSH, words, hint), Guess { encoding: MACINTOSH, uncertain: false }, "{words:?} with hint {hint:?}"); - } - } - assert_eq!(guess_words(MACINTOSH, &["Rotation 90°"], "Set 1"), Guess { encoding: MACINTOSH, uncertain: false }); - } - - #[test] - fn a_lone_cyrillic_letter_after_a_digit_is_no_cyrillic_name() { - // Mac Roman "90°" alone has no ASCII letter, so its one windows-1251 letter (Ў) would make - // the name "mostly Cyrillic" (review): a lone Cyrillic letter right after a digit never - // counts. A one-letter Cyrillic name and a Russian unit after a digit still do. - for hint in ["Set 1", "Définir"] { - assert_eq!(guess_words(MACINTOSH, &["90°"], hint), Guess { encoding: MACINTOSH, uncertain: false }, "hint {hint:?}"); - } - assert_eq!(guess_words(WINDOWS_1251, &["Я"], "Набор 1"), Guess { encoding: WINDOWS_1251, uncertain: false }); - assert_eq!(guess_words(WINDOWS_1251, &["5шт"], "Набор 1"), Guess { encoding: WINDOWS_1251, uncertain: false }); - } - - #[test] - fn word_initial_mac_roman_accents_read_as_mac_roman_when_the_file_writes_them() { - // Mac é (0x8E) and ü (0x9F) are windows-1252 Ž and Ÿ, capitals that could start a word: - // in a file whose own text has é or ü and no Ž or Ÿ, they are the Mac Roman letters. - assert_eq!(guess_words(MACINTOSH, &["état"], "Définir"), Guess { encoding: MACINTOSH, uncertain: false }); - assert_eq!(guess_words(MACINTOSH, &["über Ebene", "Höhe"], "Größe ändern"), Guess { encoding: MACINTOSH, uncertain: false }); - // Without such text the capital reading stands, as before: the bytes alone can't tell. - assert_eq!(guess_words(MACINTOSH, &["éclair"], "Set 1").encoding, WINDOWS_1252); - } - - #[test] - fn cyrillic_names_with_latin_words_still_read_as_1251() { - // Mostly Cyrillic letters count; a Latin brand name or a Latin i in Ukrainian doesn't - // turn the set into something else. - let g = guess_words(WINDOWS_1251, &["CMYKканал", "Копiя", "Слой 1"], "Набор 1"); - assert_eq!(g, Guess { encoding: WINDOWS_1251, uncertain: false }); - let bytes = encoded(WINDOWS_1251, &["CMYKканал"]); - assert_eq!(decode(&bytes[0], g.encoding), "CMYKканал"); - } - - #[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. - // 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}"); - } - } - - #[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 first highest-scoring candidate still decodes them. - let names: &[&[u8]] = &[b"\x80\xff\x80"]; - let g = guess(names, ""); - assert_eq!(g, Guess { encoding: WINDOWS_1251, uncertain: true }); - assert_eq!(decode(names[0], g.encoding), "ЂяЂ"); - assert_eq!(guess(names, "Набор").encoding, WINDOWS_1251); - } - - #[test] - fn uncertain_fallback_stays_among_the_highest_scoring_candidates() { - // Mac Roman "éäé" (0x8E 0x8A 0x8E) is windows-1251 "ЋЉЋ", three Cyrillic letters in a - // row, a word of their own: both pages score every non-ASCII byte as a letter (an odd - // count of bytes, so no double-byte page reads it). Windows-1252 reads "ŽŠŽ", no - // word-initial capital among them, so it must not win their unresolved tie. (Mac Roman - // "Ändern" no longer ties: its lone Cyrillic letter glued into a Latin word, 1251 - // "Ђndern", doesn't count, #10774.) - let names: &[&[u8]] = &[b"\x8e\x8a\x8e"]; - for hint in ["Set 1", "保存"] { - let g = guess(names, hint); - assert!([MACINTOSH, WINDOWS_1251].contains(&g.encoding), "{hint}: {g:?}"); - assert!(g.uncertain, "{hint}: {g:?}"); - assert_eq!(score(g.encoding, names[0], &Default::default()), (3, 3)); - } - assert_eq!(guess(&[b"\x80ndern"], "Set 1"), Guess { encoding: MACINTOSH, uncertain: false }, "Mac Roman \"Ändern\" is certain now"); - } - - #[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", "iso-2022-jp", "csISO2022JP"] { - 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)); - } - #[test] - fn a_name_of_one_long_letter_run_is_scored_in_linear_time() { - // 64 KiB of one letter (é in windows-1252, й in windows-1251, Mac Roman's È), of - // alternating Cyrillic letters, and of "¡ab" with no "!": every character used to rescan - // the rest of the name, which took minutes. - for unit in [&[0xe9u8][..], &[0xe9, 0xea][..], &[0xa1, b'a', b'b'][..]] { - let name = unit.repeat(GUESS_SAMPLE / unit.len()); - let started = std::time::Instant::now(); - let _ = guess(&[&name], ""); - assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?} took {:?}", unit, started.elapsed()); - } - } -} diff --git a/crates/psd/src/compression.rs b/crates/psd/src/compression.rs deleted file mode 100644 index 513dda76ba..0000000000 --- a/crates/psd/src/compression.rs +++ /dev/null @@ -1,679 +0,0 @@ -//! Channel image data codecs: Raw, RLE (PackBits), ZIP, and ZIP with prediction. -//! -//! All decoded data is *planar* bytes in the file's native big-endian sample -//! order: `planes × height × row_bytes` where `row_bytes` depends on depth -//! (depth 1 packs 8 pixels per byte, MSB first). - -use std::io::{Read, Write}; - -use crate::error::{PsdError, Result}; -use crate::header::{Version, row_bytes}; -use crate::io::Reader; - -/// Maximum number of decoded bytes a single decode call may produce: 8 GiB on -/// 64-bit targets, 2 GiB elsewhere (the same budget as `photocraft-codecs`' -/// default `Limits::max_alloc`). -/// -/// The decoders bound their output by their input on their own (RLE expands -/// at most 64x, Raw needs every byte present), so this is a backstop against -/// decompression bombs, not the main guard. It has to fit real PSBs: a -/// 30000² RGB merged image is 2.7 GB, and a 33000² 16-bit layer channel is -/// 2.2 GB, both of which a 2 GiB cap turned into empty layers (#375). -pub const MAX_DECODED_BYTES: u64 = if cfg!(target_pointer_width = "64") { 8 << 30 } else { 2 << 30 }; - -/// Compression method stored before channel / image data. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum Compression { - /// 0: uncompressed. - Raw, - /// 1: PackBits RLE with a per-row byte-count table. - Rle, - /// 2: zlib without prediction. - Zip, - /// 3: zlib with horizontal delta prediction. - ZipPrediction, - /// Unknown method; data is preserved but cannot be decoded. - Unknown(u16), -} - -impl Compression { - /// All four decodable methods. - pub const ALL: [Compression; 4] = [Compression::Raw, Compression::Rle, Compression::Zip, Compression::ZipPrediction]; - - /// From the stored value. - pub fn from_u16(v: u16) -> Self { - match v { - 0 => Compression::Raw, - 1 => Compression::Rle, - 2 => Compression::Zip, - 3 => Compression::ZipPrediction, - v => Compression::Unknown(v), - } - } - /// Stored value. - pub fn as_u16(self) -> u16 { - match self { - Compression::Raw => 0, - Compression::Rle => 1, - Compression::Zip => 2, - Compression::ZipPrediction => 3, - Compression::Unknown(v) => v, - } - } -} - -/// PackBits (Apple / TIFF) run-length coding as used by Photoshop RLE. -pub mod packbits { - use crate::error::{PsdError, Result}; - - /// Encodes one row, appending to `out`. Never emits the `-128` no-op. - pub fn encode(src: &[u8], out: &mut Vec) { - let n = src.len(); - let mut i = 0; - while i < n { - // Length of the run starting at i. - let mut run = 1; - while i + run < n && run < 128 && src[i + run] == src[i] { - run += 1; - } - // A literal never stops before a 2-byte run, so any run of >= 2 - // seen here starts a packet boundary: a run packet is never larger. - if run >= 2 { - out.push((1i16 - run as i16) as i8 as u8); - out.push(src[i]); - i += run; - continue; - } - // Literal: extend until a run of >= 3 begins or 128 bytes. - let start = i; - let mut len = 0; - while i < n && len < 128 { - if i + 2 < n && src[i] == src[i + 1] && src[i] == src[i + 2] { - break; - } - i += 1; - len += 1; - } - out.push((len - 1) as u8); - out.extend_from_slice(&src[start..start + len]); - } - } - - /// Returns the encoded form of `src`. - pub fn encode_vec(src: &[u8]) -> Vec { - let mut v = Vec::with_capacity(src.len() + src.len() / 128 + 1); - encode(src, &mut v); - v - } - - /// Decodes `src` into exactly `expected` bytes appended to `out`. - /// - /// Errors if the input is exhausted early or a packet would overflow the - /// row. Trailing input after the row is complete is ignored except for - /// `-128` no-op bytes (which are always permitted). Errors, rather than - /// overflowing, when `out.len() + expected` does not fit in `usize`. - pub(crate) fn decode_into(src: &[u8], expected: usize, out: &mut Vec) -> Result<()> { - let target = out.len().checked_add(expected).ok_or(PsdError::LimitExceeded("PackBits output length overflows usize"))?; - let mut i = 0; - while out.len() < target { - let Some(&h) = src.get(i) else { - return Err(PsdError::Decompress("PackBits row ended early".into())); - }; - i += 1; - let h = h as i8; - if h >= 0 { - let len = h as usize + 1; - let Some(lit) = src.get(i..i + len) else { - return Err(PsdError::Decompress("PackBits literal truncated".into())); - }; - if len > target - out.len() { - return Err(PsdError::Decompress("PackBits literal overflows row".into())); - } - out.extend_from_slice(lit); - i += len; - } else if h != -128 { - let len = 1 - h as isize; - let len = len as usize; - let Some(&b) = src.get(i) else { - return Err(PsdError::Decompress("PackBits run truncated".into())); - }; - i += 1; - if len > target - out.len() { - return Err(PsdError::Decompress("PackBits run overflows row".into())); - } - out.extend(std::iter::repeat_n(b, len)); - } - } - Ok(()) - } - - /// Decodes into a new vector of exactly `expected` bytes. - pub fn decode(src: &[u8], expected: usize) -> Result> { - let mut v = Vec::with_capacity(expected.min(src.len().saturating_mul(64))); - decode_into(src, expected, &mut v)?; - Ok(v) - } -} - -/// Geometry of a set of planes to encode/decode. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct PlaneLayout { - /// Number of planes (1 for a layer channel, channel count for the merged image). - pub planes: usize, - /// Pixels per row. - pub width: usize, - /// Rows per plane. - pub height: usize, - /// Bits per sample (1, 8, 16, 32). - pub depth: u16, - /// PSD vs PSB (affects RLE count width). - pub version: Version, -} - -impl PlaneLayout { - /// Bytes per row. - pub fn row_bytes(&self) -> usize { - row_bytes(self.width, self.depth) - } - /// Total rows over all planes. - pub fn rows(&self) -> Result { - self.planes.checked_mul(self.height).ok_or(PsdError::LimitExceeded("row count overflow")) - } - /// Total decoded bytes without the [`MAX_DECODED_BYTES`] cap. - pub fn total_bytes(&self) -> Result { - (self.planes as u64) - .checked_mul(self.height as u64) - .and_then(|v| v.checked_mul(self.row_bytes() as u64)) - .ok_or(PsdError::LimitExceeded("decoded size overflow")) - } - - /// Total decoded bytes, checked against [`MAX_DECODED_BYTES`]. - pub fn decoded_len(&self) -> Result { - let total = self.total_bytes()?; - if total > MAX_DECODED_BYTES { - return Err(PsdError::LimitExceeded("decoded channel data exceeds MAX_DECODED_BYTES")); - } - usize::try_from(total).map_err(|_| PsdError::LimitExceeded("decoded size exceeds address space")) - } - fn count_size(&self) -> usize { - if self.version.is_psb() { 4 } else { 2 } - } -} - -/// Decodes planar data (excluding the 2-byte compression field). -pub fn decode_planes(compression: Compression, data: &[u8], layout: &PlaneLayout) -> Result> { - let total = layout.decoded_len()?; - match compression { - Compression::Raw => { - if data.len() < total { - return Err(PsdError::UnexpectedEof { offset: data.len(), needed: total - data.len() }); - } - let mut out = Vec::new(); - out.try_reserve_exact(total).map_err(|_| PsdError::OutOfMemory("not enough memory for the decoded channel data"))?; - out.extend_from_slice(&data[..total]); - Ok(out) - } - Compression::Rle => decode_rle(data, layout, total), - Compression::Zip => inflate_checked(data, total as u64, true), - Compression::ZipPrediction => { - let mut v = inflate_checked(data, total as u64, true)?; - unpredict(&mut v, layout)?; - Ok(v) - } - Compression::Unknown(c) => Err(PsdError::Unsupported(format!("compression method {c}"))), - } -} - -/// Bytes a PSD RLE stream (two-byte row counts) of `rows` rows grows by when written as PSB -/// (four-byte row counts); an error when `data` is too short to hold the count table. -pub(crate) fn rle_widening(data: &[u8], rows: usize) -> Result { - rle_widening_len(data.len() as u64, rows) -} - -/// [`rle_widening`] from the stream's length alone, so data still in its source (or staged on -/// the scratch disk) is not read to measure it. -pub(crate) fn rle_widening_len(len: u64, rows: usize) -> Result { - let table = rows.checked_mul(2).ok_or(PsdError::LimitExceeded("row count overflow"))? as u64; - if len < table { - let offset = usize::try_from(len).unwrap_or(usize::MAX); - return Err(PsdError::UnexpectedEof { offset, needed: usize::try_from(table - len).unwrap_or(usize::MAX) }); - } - Ok(table) -} - -/// Encodes planar data (excluding the 2-byte compression field). -pub fn encode_planes(compression: Compression, decoded: &[u8], layout: &PlaneLayout) -> Result> { - let total = layout.decoded_len()?; - if decoded.len() != total { - return Err(PsdError::invalid(format!("decoded buffer has {} bytes, layout requires {}", decoded.len(), total))); - } - match compression { - Compression::Raw => Ok(decoded.to_vec()), - Compression::Rle => encode_rle(decoded, layout), - Compression::Zip => Ok(zip_compress(decoded)), - Compression::ZipPrediction => { - let mut v = decoded.to_vec(); - predict(&mut v, layout)?; - Ok(zip_compress(&v)) - } - Compression::Unknown(c) => Err(PsdError::Unsupported(format!("compression method {c}"))), - } -} - -/// Validates encoded sizes and, for ZIP, the complete stream and checksum. -/// -/// A ZIP stream whose declared size is over [`MAX_DECODED_BYTES`] is not -/// decompressed at all (#2926): [`decode_planes`] refuses that layout with -/// `LimitExceeded` anyway, so inflating it here would only be work on an -/// untrusted file before the same error. The bytes are kept verbatim, like an -/// unknown compression method, so a layered file whose merged composite is -/// too large still opens. -pub(crate) fn validate_planes(compression: Compression, data: &[u8], layout: &PlaneLayout) -> Result<()> { - let total = layout.total_bytes()?; - match compression { - Compression::Raw => { - if (data.len() as u64) < total { - return Err(PsdError::UnexpectedEof { offset: data.len(), needed: usize::try_from(total - data.len() as u64).unwrap_or(usize::MAX) }); - } - Ok(()) - } - Compression::Rle => { - let rows = layout.rows()?; - let mut r = Reader::new(data); - r.check_count(rows as u64, layout.count_size() as u64)?; - let mut sum: u64 = 0; - for _ in 0..rows { - sum += read_count(&mut r, layout.version)? as u64; - } - if sum > r.remaining() as u64 { - return Err(PsdError::UnexpectedEof { offset: data.len(), needed: usize::try_from(sum - r.remaining() as u64).unwrap_or(usize::MAX) }); - } - Ok(()) - } - Compression::Zip | Compression::ZipPrediction if total > MAX_DECODED_BYTES => Ok(()), - Compression::Zip | Compression::ZipPrediction => inflate_checked(data, total, false).map(|_| ()), - Compression::Unknown(_) => Ok(()), - } -} - -#[cfg(test)] -thread_local! { - /// ZIP streams inflated on this thread (tests count passes over the merged image). - pub(crate) static INFLATES: std::cell::Cell = const { std::cell::Cell::new(0) }; -} - -// Keep only the requested pixels, but consume the trailer to verify Adler-32. -// A bounded surplus tolerates padding without unbounded decompression work. -fn inflate_checked(data: &[u8], expected: u64, keep: bool) -> Result> { - const OOM: PsdError = PsdError::OutOfMemory("not enough memory for the decoded channel data"); - #[cfg(test)] - INFLATES.with(|n| n.set(n.get() + 1)); - let mut decoder = flate2::Decompress::new(true); - let mut out = Vec::new(); - if keep { - out.try_reserve_exact(expected.min(data.len().saturating_mul(1032) as u64) as usize).map_err(|_| OOM)?; - } - let mut buf = vec![0; expected.saturating_add(1).clamp(8192, 1 << 20) as usize]; - loop { - let before = (decoder.total_in(), decoder.total_out()); - let input = data.get(before.0 as usize..).ok_or_else(|| PsdError::Decompress("zlib input overflow".into()))?; - let status = decoder.decompress(input, &mut buf, flate2::FlushDecompress::None).map_err(|e| PsdError::Decompress(e.to_string()))?; - let got = decoder.total_out(); - if got > expected.saturating_add(1 << 20) { - return Err(PsdError::LimitExceeded("zlib output exceeds the declared size and padding allowance")); - } - if keep { - let n = (got - before.1).min(expected.saturating_sub(out.len() as u64)) as usize; - out.try_reserve(n).map_err(|_| OOM)?; - out.extend_from_slice(buf.get(..n).ok_or_else(|| PsdError::Decompress("zlib output overflow".into()))?); - } - if status == flate2::Status::StreamEnd { - if got < expected { - return Err(PsdError::Decompress(format!("zlib stream produced {got} of {expected} bytes"))); - } - return Ok(out); - } - if before == (decoder.total_in(), got) { - return Err(PsdError::Decompress("incomplete zlib stream".into())); - } - } -} - -fn read_count(r: &mut Reader<'_>, v: Version) -> Result { - Ok(if v.is_psb() { r.u32()? as usize } else { r.u16()? as usize }) -} - -fn decode_rle(data: &[u8], layout: &PlaneLayout, total: usize) -> Result> { - let rows = layout.rows()?; - let rb = layout.row_bytes(); - let mut r = Reader::new(data); - r.check_count(rows as u64, layout.count_size() as u64)?; - let mut counts = Vec::with_capacity(rows); - for _ in 0..rows { - counts.push(read_count(&mut r, layout.version)?); - } - // PackBits expands at most 64x (2 input bytes -> 128 output bytes). - if (total as u64) > (r.remaining() as u64).saturating_mul(64) { - return Err(PsdError::Decompress("RLE data too short for declared size".into())); - } - // Up to MAX_DECODED_BYTES: report a machine without that much memory instead of aborting. - let mut out = Vec::new(); - out.try_reserve_exact(total).map_err(|_| PsdError::OutOfMemory("not enough memory for the decoded channel data"))?; - for c in counts { - let row = r.bytes(c)?; - packbits::decode_into(row, rb, &mut out)?; - } - Ok(out) -} - -fn encode_rle(decoded: &[u8], layout: &PlaneLayout) -> Result> { - let rows = layout.rows()?; - let rb = layout.row_bytes(); - let cs = layout.count_size(); - if rows == 0 { - return Ok(Vec::new()); - } - // Rows are independent, so they pack in parallel chunks of rows. Two passes: the first only - // measures each packed row, so the output is allocated once at its exact size and the second - // packs every row straight into its place. Collecting packed chunks and then copying them into - // the output held the encoded image twice, with growth slack, at the save's peak (#6607). - let threads = if cfg!(target_arch = "wasm32") { 1 } else { std::thread::available_parallelism().map_or(1, |v| v.get()).clamp(1, 32) }; - let chunk_rows = rows.div_ceil(threads).max(1); - let row = |r: usize| &decoded[r * rb..(r + 1) * rb]; - let mut lens = vec![0usize; rows]; - for_each_chunk(threads, lens.chunks_mut(chunk_rows).enumerate().collect(), |(c, lens): (usize, &mut [usize])| { - let mut scratch = Vec::with_capacity(rb + rb.div_ceil(128)); - for (i, len) in lens.iter_mut().enumerate() { - scratch.clear(); - packbits::encode(row(c * chunk_rows + i), &mut scratch); - *len = scratch.len(); - } - })?; - let mut out = vec![0u8; rows * cs + lens.iter().sum::()]; - let (counts, mut packed) = out.split_at_mut(rows * cs); - for (count, &n) in counts.chunks_exact_mut(cs).zip(&lens) { - if cs == 2 { - let n = u16::try_from(n).map_err(|_| PsdError::LimitExceeded("RLE row exceeds 65535 bytes (use PSB)"))?; - count.copy_from_slice(&n.to_be_bytes()); - } else { - let n = u32::try_from(n).map_err(|_| PsdError::LimitExceeded("RLE row too large"))?; - count.copy_from_slice(&n.to_be_bytes()); - } - } - let mut parts = Vec::with_capacity(threads); - for (c, lens) in lens.chunks(chunk_rows).enumerate() { - let (part, rest) = packed.split_at_mut(lens.iter().sum()); - parts.push((c, lens, part)); - packed = rest; - } - for_each_chunk(threads, parts, |(c, lens, mut part): (usize, &[usize], &mut [u8])| { - let mut scratch = Vec::with_capacity(rb + rb.div_ceil(128)); - for (i, &n) in lens.iter().enumerate() { - scratch.clear(); - packbits::encode(row(c * chunk_rows + i), &mut scratch); - let (dst, rest) = std::mem::take(&mut part).split_at_mut(n); - dst.copy_from_slice(&scratch); - part = rest; - } - })?; - Ok(out) -} - -/// Runs `f` on every item, each on its own thread unless `threads` is 1 (wasm32). -fn for_each_chunk(threads: usize, items: Vec, f: impl Fn(T) + Sync) -> Result<()> { - if threads == 1 { - items.into_iter().for_each(f); - return Ok(()); - } - std::thread::scope(|scope| { - let handles: Vec<_> = items.into_iter().map(|item| scope.spawn(|| f(item))).collect(); - // Join every worker instead of aborting the scope with a thread panic. - let mut ok = true; - for h in handles { - ok &= h.join().is_ok(); - } - if ok { Ok(()) } else { Err(PsdError::LimitExceeded("an RLE worker panicked")) } - }) -} - -/// zlib-compresses `data` at the default level. -pub fn zip_compress(data: &[u8]) -> Vec { - let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); - // Writing into a Vec cannot fail. - let _ = e.write_all(data); - e.finish().unwrap_or_default() -} - -/// Decompresses a zlib stream, requiring at least `expected` output bytes and -/// returning exactly `expected`. -/// -/// The output is reserved fallibly and read in chunks, never past `expected` -/// bytes, so a stream declaring a huge size reports an error on a machine -/// without that much memory instead of aborting. -pub fn zip_decompress(data: &[u8], expected: usize) -> Result> { - const OOM: PsdError = PsdError::OutOfMemory("not enough memory for the decoded channel data"); - const CHUNK: usize = 1 << 20; - let mut dec = flate2::read::ZlibDecoder::new(data).take(u64::try_from(expected).unwrap_or(u64::MAX)); - let mut out = Vec::new(); - // Deflate expands at most ~1032:1, so this is the most a valid stream can need. - out.try_reserve_exact(expected.min(data.len().saturating_mul(1032))).map_err(|_| OOM)?; - let mut buf = vec![0u8; CHUNK.min(expected).max(1)]; - loop { - let n = match dec.read(&mut buf) { - Ok(0) => break, - Ok(n) => n, - Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue, - Err(e) => return Err(PsdError::Decompress(e.to_string())), - }; - let chunk = buf.get(..n).ok_or_else(|| PsdError::Decompress("zlib reader overran its buffer".into()))?; - out.try_reserve(n).map_err(|_| OOM)?; - out.extend_from_slice(chunk); - } - if out.len() < expected { - return Err(PsdError::Decompress(format!("zlib stream produced {} of {} bytes", out.len(), expected))); - } - Ok(out) -} - -/// Applies horizontal delta prediction in place (encoder side). -/// -/// * 1/8-bit: byte-wise delta per row. -/// * 16-bit: big-endian u16 sample delta per row. -/// * 32-bit: each row's samples are split into four byte planes (MSB plane -/// first) and the resulting row is byte-wise delta coded, as Photoshop does. -pub fn predict(buf: &mut [u8], layout: &PlaneLayout) -> Result<()> { - let rb = layout.row_bytes(); - if rb == 0 { - return Ok(()); - } - let w = layout.width; - let mut scratch = Vec::new(); - for row in buf.chunks_exact_mut(rb) { - match layout.depth { - 1 | 8 => { - for i in (1..row.len()).rev() { - row[i] = row[i].wrapping_sub(row[i - 1]); - } - } - 16 => { - // One forward pass: the previous *original* sample stays in a - // register, so nothing is re-read after being overwritten. - let mut prev = 0u16; - for s in row.as_chunks_mut::<2>().0 { - let cur = u16::from_be_bytes(*s); - *s = cur.wrapping_sub(prev).to_be_bytes(); - prev = cur; - } - } - 32 => { - scratch.clear(); - scratch.resize(rb, 0); - // Split into four byte planes (MSB first) and delta the whole - // plane-major row. Plane k's first delta uses the last byte of - // plane k - 1, so seed each plane's "previous" with it. - let mut prev = [0u8; 4]; - if let Some(l) = row.as_chunks::<4>().0.last() { - prev = [0, l[0], l[1], l[2]]; - } - let (p0, rest) = scratch.split_at_mut(w); - let (p1, rest) = rest.split_at_mut(w); - let (p2, p3) = rest.split_at_mut(w); - let planes = p0.iter_mut().zip(p1.iter_mut()).zip(p2.iter_mut().zip(p3.iter_mut())); - for (s, ((o0, o1), (o2, o3))) in row.as_chunks::<4>().0.iter().zip(planes) { - *o0 = s[0].wrapping_sub(prev[0]); - *o1 = s[1].wrapping_sub(prev[1]); - *o2 = s[2].wrapping_sub(prev[2]); - *o3 = s[3].wrapping_sub(prev[3]); - prev = [s[0], s[1], s[2], s[3]]; - } - row.copy_from_slice(&scratch); - } - d => return Err(PsdError::Unsupported(format!("prediction for depth {d}"))), - } - } - Ok(()) -} - -/// Reverses [`predict`] in place (decoder side). -pub fn unpredict(buf: &mut [u8], layout: &PlaneLayout) -> Result<()> { - let rb = layout.row_bytes(); - if rb == 0 { - return Ok(()); - } - let w = layout.width; - let mut scratch = Vec::new(); - for row in buf.chunks_exact_mut(rb) { - match layout.depth { - 1 | 8 => { - for i in 1..row.len() { - row[i] = row[i].wrapping_add(row[i - 1]); - } - } - 16 => { - // Running sum carried in a register; one pass over the row. - let mut acc = 0u16; - for s in row.as_chunks_mut::<2>().0 { - acc = acc.wrapping_add(u16::from_be_bytes(*s)); - *s = acc.to_be_bytes(); - } - } - 32 => { - scratch.clear(); - scratch.extend_from_slice(row); - // The byte-wise running sum runs across the four planes, so - // plane k starts at the wrapping total of planes 0..k. - let (p0, rest) = scratch.split_at(w); - let (p1, rest) = rest.split_at(w); - let (p2, p3) = rest.split_at(w); - let sum = |p: &[u8]| p.iter().fold(0u8, |a, &b| a.wrapping_add(b)); - let b1 = sum(p0); - let b2 = b1.wrapping_add(sum(p1)); - let b3 = b2.wrapping_add(sum(p2)); - let mut acc = [0u8, b1, b2, b3]; - let planes = p0.iter().zip(p1).zip(p2.iter().zip(p3)); - for (o, ((&s0, &s1), (&s2, &s3))) in row.as_chunks_mut::<4>().0.iter_mut().zip(planes) { - acc[0] = acc[0].wrapping_add(s0); - acc[1] = acc[1].wrapping_add(s1); - acc[2] = acc[2].wrapping_add(s2); - acc[3] = acc[3].wrapping_add(s3); - *o = acc; - } - } - d => return Err(PsdError::Unsupported(format!("prediction for depth {d}"))), - } - } - Ok(()) -} - -#[cfg(test)] -mod tests; - -#[cfg(test)] -mod parallel_rle_equivalence { - use super::*; - - /// The parallel row packer's output must be byte-equal to a straightforward sequential - /// encoding of the same plane, across depths, row counts around the chunking and data - /// shapes (runs, noise, all-default). - #[test] - fn parallel_rle_matches_sequential() { - let mut data: u64 = 0x9e37_79b9_7f4a_7c15; - let mut next = move || { - data ^= data << 13; - data ^= data >> 7; - data ^= data << 17; - data - }; - let layout_for = |rows: usize, rb: usize, version: Version| PlaneLayout { planes: 1, width: rb, height: rows, depth: 8, version }; - for (rows, rb, version) in [ - (0usize, 4usize, Version::Psd), - (1, 4, Version::Psd), - (7, 4, Version::Psb), - (64, 4, Version::Psd), - (65, 4, Version::Psb), // chunk boundary - (513, 4, Version::Psd), // more rows than threads on most runners - (2049, 4, Version::Psb), - (2, 4, Version::Psd), // fewer rows than threads - (33, 3000, Version::Psd), - (31, 20000, Version::Psb), - ] { - let pattern: Vec = match rows % 3 { - 0 => vec![7u8; rows * rb], // long runs - 1 => (0..rows * rb).map(|i| (i * 31 % 251) as u8).collect(), // noise-ish - _ => vec![0u8; rows * rb], // all default - }; - let pattern = if pattern.len() != rows * rb { vec![7u8; rows * rb] } else { pattern }; - let mut data = pattern.clone(); - if rows % 4 == 0 { - // sprinkle runs into the noise - for chunk in data.chunks_mut(97) { - if let Some(f) = chunk.first_mut() { - *f = 200; - } - } - } - let _ = next(); - let layout = layout_for(rows, rb, version); - let parallel = encode_rle(&data, &layout).expect("parallel encode"); - let sequential = encode_rle_sequential(&data, &layout).expect("sequential encode"); - assert_eq!(parallel, sequential, "rows {rows} rb {rb}"); - // #6607: measured first, then packed in place: one allocation, exactly the file's size. - assert_eq!(parallel.capacity(), parallel.len(), "rows {rows} rb {rb}: the output grew or was over-allocated"); - } - } - - /// A row too long for a PSD's 16-bit RLE count is the same error from the two-pass encoder. - #[test] - fn rle_rows_past_sixteen_bits_are_refused_in_psd() { - let layout_for = |rows: usize, rb: usize, version: Version| PlaneLayout { planes: 1, width: rb, height: rows, depth: 8, version }; - let rb = 70_000; - let layout = layout_for(3, rb, Version::Psd); - let noise: Vec = (0..3 * rb).map(|i| (i * 31 % 251) as u8).collect(); - assert_eq!(encode_rle(&noise, &layout), Err(PsdError::LimitExceeded("RLE row exceeds 65535 bytes (use PSB)"))); - assert_eq!(encode_rle(&noise, &layout_for(3, rb, Version::Psb)), encode_rle_sequential(&noise, &layout_for(3, rb, Version::Psb))); - } - - /// The pre-parallel encoder, kept as the oracle. - fn encode_rle_sequential(decoded: &[u8], layout: &PlaneLayout) -> Result> { - let rows = layout.rows()?; - let rb = layout.row_bytes(); - let cs = layout.count_size(); - let mut out = vec![0u8; rows * cs]; - let mut enc = Vec::new(); - for row in 0..rows { - let start = enc.len(); - packbits::encode(&decoded[row * rb..(row + 1) * rb], &mut enc); - let n = enc.len() - start; - if cs == 2 { - let n = u16::try_from(n).map_err(|_| PsdError::LimitExceeded("RLE row exceeds 65535 bytes (use PSB)"))?; - out[row * 2..row * 2 + 2].copy_from_slice(&n.to_be_bytes()); - } else { - let n = u32::try_from(n).map_err(|_| PsdError::LimitExceeded("RLE row too large"))?; - out[row * 4..row * 4 + 4].copy_from_slice(&n.to_be_bytes()); - } - } - out.extend_from_slice(&enc); - Ok(out) - } -} diff --git a/crates/psd/src/compression/tests.rs b/crates/psd/src/compression/tests.rs deleted file mode 100644 index 47d7986290..0000000000 --- a/crates/psd/src/compression/tests.rs +++ /dev/null @@ -1,465 +0,0 @@ -use super::*; - -/// The straightforward index-based versions, kept as the oracle for the -/// register-carried rewrites in [`predict`] and [`unpredict`]. -mod reference { - use super::super::*; - - pub fn predict(buf: &mut [u8], layout: &PlaneLayout) { - let rb = layout.row_bytes(); - let w = layout.width; - let mut scratch = Vec::new(); - for row in buf.chunks_exact_mut(rb) { - match layout.depth { - 8 => { - for i in (1..row.len()).rev() { - row[i] = row[i].wrapping_sub(row[i - 1]); - } - } - 16 => { - for i in (1..w).rev() { - let a = u16::from_be_bytes([row[2 * i], row[2 * i + 1]]); - let b = u16::from_be_bytes([row[2 * i - 2], row[2 * i - 1]]); - row[2 * i..2 * i + 2].copy_from_slice(&a.wrapping_sub(b).to_be_bytes()); - } - } - _ => { - scratch.clear(); - scratch.resize(rb, 0); - for i in 0..w { - for k in 0..4 { - scratch[k * w + i] = row[4 * i + k]; - } - } - for i in (1..rb).rev() { - scratch[i] = scratch[i].wrapping_sub(scratch[i - 1]); - } - row.copy_from_slice(&scratch); - } - } - } - } - - pub fn unpredict(buf: &mut [u8], layout: &PlaneLayout) { - let rb = layout.row_bytes(); - let w = layout.width; - let mut scratch = Vec::new(); - for row in buf.chunks_exact_mut(rb) { - match layout.depth { - 8 => { - for i in 1..row.len() { - row[i] = row[i].wrapping_add(row[i - 1]); - } - } - 16 => { - for i in 1..w { - let a = u16::from_be_bytes([row[2 * i], row[2 * i + 1]]); - let b = u16::from_be_bytes([row[2 * i - 2], row[2 * i - 1]]); - row[2 * i..2 * i + 2].copy_from_slice(&a.wrapping_add(b).to_be_bytes()); - } - } - _ => { - for i in 1..rb { - row[i] = row[i].wrapping_add(row[i - 1]); - } - scratch.clear(); - scratch.extend_from_slice(row); - for i in 0..w { - for k in 0..4 { - row[4 * i + k] = scratch[k * w + i]; - } - } - } - } - } - } -} - -#[test] -fn prediction_matches_reference_on_random_planes() { - let mut state = 0x9E37_79B9_7F4A_7C15u64; - let mut next = move || { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - state - }; - for depth in [8u16, 16, 32] { - for width in (1..=70).chain([255, 256, 257, 1000, 1023]) { - for height in [1usize, 2, 3] { - for fill in 0..4 { - let layout = PlaneLayout { planes: 1, width, height, depth, version: Version::Psd }; - let len = layout.row_bytes() * height; - let src: Vec = (0..len) - .map(|_| match fill { - 0 => next() as u8, - 1 => 0xFF, - 2 => [0x00, 0xFF, 0x80, 0x7F][(next() & 3) as usize], - _ => (next() as u8) | 0xF0, - }) - .collect(); - let (mut want, mut got) = (src.clone(), src.clone()); - reference::predict(&mut want, &layout); - predict(&mut got, &layout).unwrap(); - assert_eq!(got, want, "predict depth {depth} width {width} height {height} fill {fill}"); - let (mut want, mut got) = (src.clone(), src); - reference::unpredict(&mut want, &layout); - unpredict(&mut got, &layout).unwrap(); - assert_eq!(got, want, "unpredict depth {depth} width {width} height {height} fill {fill}"); - } - } - } - } -} - -#[test] -fn checked_zip_validates_trailer_size_and_padding_budget() { - let layout = PlaneLayout { planes: 1, width: 3, height: 1, depth: 8, version: Version::Psd }; - for compression in [Compression::Zip, Compression::ZipPrediction] { - let data = encode_planes(compression, &[1, 2, 3], &layout).unwrap(); - for cut in 0..data.len() { - assert!(decode_planes(compression, &data[..cut], &layout).is_err(), "cut {cut}"); - assert!(validate_planes(compression, &data[..cut], &layout).is_err()); - } - let mut corrupt = data; - *corrupt.last_mut().unwrap() ^= 1; - assert!(decode_planes(compression, &corrupt, &layout).is_err()); - assert!(validate_planes(compression, &corrupt, &layout).is_err()); - } - let padded = zip_compress(&[1, 2, 3, 0]); - assert_eq!(decode_planes(Compression::Zip, &padded, &layout).unwrap(), [1, 2, 3]); - let bomb = zip_compress(&vec![0; (1 << 20) + 4]); - assert!(decode_planes(Compression::Zip, &bomb, &layout).is_err()); - assert!(validate_planes(Compression::Zip, &bomb, &layout).is_err()); -} - -fn layout(planes: usize, width: usize, height: usize, depth: u16, version: Version) -> PlaneLayout { - PlaneLayout { planes, width, height, depth, version } -} - -fn pb_roundtrip(src: &[u8]) -> Vec { - let enc = packbits::encode_vec(src); - let dec = packbits::decode(&enc, src.len()).unwrap(); - assert_eq!(dec, src, "encoded: {enc:?}"); - enc -} - -#[test] -fn zip_absurd_declared_size_is_an_error() { - let z = zip_compress(&[7u8; 64]); - for expected in [1usize << 40, usize::MAX / 2, usize::MAX] { - assert!(zip_decompress(&z, expected).is_err(), "expected {expected}"); - } - // Through decode_planes: a tiny ZIP channel claiming a huge (but capped) plane. - let l = layout(1, 1 << 16, 1 << 15, 8, Version::Psb); - assert!(decode_planes(Compression::Zip, &z, &l).is_err()); - assert!(decode_planes(Compression::ZipPrediction, &z, &l).is_err()); - // Past MAX_DECODED_BYTES. - let l = layout(4, 1 << 20, 1 << 20, 32, Version::Psb); - assert!(decode_planes(Compression::Zip, &z, &l).is_err()); - // Garbage that is not zlib at all. - assert!(zip_decompress(&[0xff; 16], 1 << 30).is_err()); -} - -#[test] -fn zip_decompress_exact_and_truncated() { - let src: Vec = (0..3_000_000u32).map(|i| (i % 251) as u8).collect(); - let z = zip_compress(&src); - assert_eq!(zip_decompress(&z, src.len()).unwrap(), src); - // Asking for fewer bytes returns exactly that many. - assert_eq!(zip_decompress(&z, 1000).unwrap(), &src[..1000]); - assert!(zip_decompress(&z, src.len() + 1).is_err()); - assert!(zip_decompress(&z, 0).unwrap().is_empty()); -} - -#[test] -fn packbits_empty() { - assert!(pb_roundtrip(&[]).is_empty()); -} - -#[test] -fn packbits_single() { - assert_eq!(pb_roundtrip(&[7]), vec![0, 7]); -} - -#[test] -fn packbits_run_of_two() { - assert_eq!(pb_roundtrip(&[5, 5]), vec![0xff, 5]); -} - -#[test] -fn packbits_run_128() { - let src = vec![9u8; 128]; - assert_eq!(pb_roundtrip(&src), vec![0x81, 9]); -} - -#[test] -fn packbits_run_129() { - let src = vec![9u8; 129]; - assert_eq!(pb_roundtrip(&src), vec![0x81, 9, 0, 9]); -} - -#[test] -fn packbits_run_130_and_256() { - pb_roundtrip(&[1u8; 130]); - let enc = pb_roundtrip(&[1u8; 256]); - assert_eq!(enc, vec![0x81, 1, 0x81, 1]); -} - -#[test] -fn packbits_literal_128_and_129() { - let src: Vec = (0..128u32).map(|i| i as u8).collect(); - let enc = pb_roundtrip(&src); - assert_eq!(enc[0], 127); - assert_eq!(enc.len(), 129); - let src: Vec = (0..129u32).map(|i| i as u8).collect(); - let enc = pb_roundtrip(&src); - assert_eq!(enc[0], 127); - assert_eq!(enc[129], 0); - assert_eq!(enc.len(), 131); -} - -#[test] -fn packbits_literal_run_boundary() { - pb_roundtrip(&[1, 2, 3, 3, 3, 3, 4, 5]); - pb_roundtrip(&[1, 1, 2, 2, 3, 3]); - pb_roundtrip(&[1, 2, 2, 3]); - pb_roundtrip(&[0, 0, 0, 1, 0, 0, 0]); - let enc = pb_roundtrip(&[1, 2, 3, 3, 3]); - assert_eq!(enc, vec![1, 1, 2, 0xfe, 3]); -} - -#[test] -fn packbits_never_emits_noop() { - for n in 0..300usize { - let src: Vec = (0..n).map(|i| ((i / 3) % 5) as u8).collect(); - let enc = pb_roundtrip(&src); - // Walk the packets to find headers. - let mut i = 0; - while i < enc.len() { - let h = enc[i] as i8; - assert_ne!(h, -128); - i += if h >= 0 { h as usize + 2 } else { 2 }; - } - } -} - -#[test] -fn packbits_decode_noop_skipped() { - assert_eq!(packbits::decode(&[0x80, 0, 42], 1).unwrap(), vec![42]); -} - -#[test] -fn packbits_decode_errors() { - assert!(packbits::decode(&[], 1).is_err()); - assert!(packbits::decode(&[2, 1, 2], 3).is_err()); // literal truncated - assert!(packbits::decode(&[0xfe], 3).is_err()); // run truncated - assert!(packbits::decode(&[0xfd, 1], 3).is_err()); // run overflows (4 > 3) - assert!(packbits::decode(&[3, 1, 2, 3, 4], 3).is_err()); // literal overflows -} - -/// `out.len() + expected` past `usize::MAX` used to panic in debug builds and, in release, -/// wrap and return `Ok` having decoded nothing. -#[test] -fn packbits_decode_into_output_length_overflow_is_an_error() { - let mut out = vec![7u8]; - let r = packbits::decode_into(&[0x00, 0xaa], usize::MAX, &mut out); - assert!(matches!(r, Err(PsdError::LimitExceeded(_))), "{r:?}"); - assert_eq!(out, [7]); - // The largest `expected` that fits still decodes up to the input, then reports it short. - let r = packbits::decode_into(&[0x00, 0xaa], usize::MAX - 1, &mut out); - assert!(matches!(r, Err(PsdError::Decompress(_))), "{r:?}"); - assert_eq!(out, [7, 0xaa]); -} - -#[test] -fn packbits_zero_expected_ignores_input() { - assert_eq!(packbits::decode(&[0xff, 1], 0).unwrap(), Vec::::new()); -} - -#[test] -fn compression_values() { - for v in 0..6 { - assert_eq!(Compression::from_u16(v).as_u16(), v); - } - assert_eq!(Compression::from_u16(9), Compression::Unknown(9)); -} - -fn sample_data(l: &PlaneLayout) -> Vec { - let n = l.decoded_len().unwrap(); - (0..n).map(|i| ((i * 7 + i / 5) % 251) as u8).collect() -} - -#[test] -fn all_codecs_roundtrip_all_depths() { - for version in [Version::Psd, Version::Psb] { - for depth in [1u16, 8, 16, 32] { - for (w, h) in [(0, 0), (1, 1), (3, 2), (17, 5), (0, 3), (4, 0)] { - for planes in [1, 3] { - let l = layout(planes, w, h, depth, version); - let data = sample_data(&l); - for c in Compression::ALL { - let enc = encode_planes(c, &data, &l).unwrap(); - validate_planes(c, &enc, &l).unwrap(); - let dec = decode_planes(c, &enc, &l).unwrap(); - assert_eq!(dec, data, "{c:?} {depth} {w}x{h} {version:?}"); - } - } - } - } - } -} - -#[test] -fn rle_count_width_psd_vs_psb() { - let data = vec![0u8; 4]; - let psd = encode_planes(Compression::Rle, &data, &layout(1, 2, 2, 8, Version::Psd)).unwrap(); - let psb = encode_planes(Compression::Rle, &data, &layout(1, 2, 2, 8, Version::Psb)).unwrap(); - assert_eq!(psd, vec![0, 2, 0, 2, 0xff, 0, 0xff, 0]); - assert_eq!(psb, vec![0, 0, 0, 2, 0, 0, 0, 2, 0xff, 0, 0xff, 0]); - assert!(decode_planes(Compression::Rle, &psd, &layout(1, 2, 2, 8, Version::Psb)).is_err()); -} - -#[test] -fn rle_odd_width() { - let l = layout(1, 7, 3, 16, Version::Psd); - let data = sample_data(&l); - let enc = encode_planes(Compression::Rle, &data, &l).unwrap(); - assert_eq!(decode_planes(Compression::Rle, &enc, &l).unwrap(), data); -} - -#[test] -fn rle_truncated_fails() { - let l = layout(1, 10, 10, 8, Version::Psd); - let data = sample_data(&l); - let enc = encode_planes(Compression::Rle, &data, &l).unwrap(); - for cut in 0..enc.len() { - assert!(decode_planes(Compression::Rle, &enc[..cut], &l).is_err(), "cut {cut}"); - assert!(validate_planes(Compression::Rle, &enc[..cut], &l).is_err(), "cut {cut}"); - } -} - -#[test] -fn zip_truncated_fails() { - let l = layout(1, 10, 10, 8, Version::Psd); - let data = sample_data(&l); - let enc = encode_planes(Compression::Zip, &data, &l).unwrap(); - for cut in 0..enc.len() - 4 { - assert!(decode_planes(Compression::Zip, &enc[..cut], &l).is_err(), "cut {cut}"); - assert!(validate_planes(Compression::Zip, &enc[..cut], &l).is_err(), "cut {cut}"); - } -} - -/// #2926: a ZIP stream declaring more than `MAX_DECODED_BYTES` is not inflated at parse -/// time. Garbage zlib data proves it: decompressing it would fail, skipping it passes, and -/// decoding the layout still reports the size limit. -#[test] -fn zip_over_budget_is_not_decompressed_at_parse() { - let l = layout(4, 300_000, 300_000, 8, Version::Psb); - assert!(l.total_bytes().unwrap() > MAX_DECODED_BYTES); - let garbage = [0xde, 0xad, 0xbe, 0xef, 0x01, 0x02, 0x03]; - for c in [Compression::Zip, Compression::ZipPrediction] { - validate_planes(c, &garbage, &l).unwrap(); - assert!(matches!(decode_planes(c, &garbage, &l), Err(PsdError::LimitExceeded(_))), "{c:?}"); - } - // Within the budget the stream is still checked. - let small = layout(1, 4, 4, 8, Version::Psd); - assert!(validate_planes(Compression::Zip, &garbage, &small).is_err()); -} - -#[test] -fn raw_short_fails() { - let l = layout(2, 3, 3, 8, Version::Psd); - assert!(decode_planes(Compression::Raw, &[0; 17], &l).is_err()); - assert!(decode_planes(Compression::Raw, &[0; 18], &l).is_ok()); -} - -#[test] -fn unknown_compression_errors() { - let l = layout(1, 1, 1, 8, Version::Psd); - assert!(decode_planes(Compression::Unknown(7), &[0], &l).is_err()); - assert!(encode_planes(Compression::Unknown(7), &[0], &l).is_err()); -} - -#[test] -fn encode_rejects_wrong_size() { - let l = layout(1, 2, 2, 8, Version::Psd); - assert!(encode_planes(Compression::Raw, &[0; 3], &l).is_err()); -} - -#[test] -fn decoded_len_limits() { - let l = layout(56, 300_000, 300_000, 32, Version::Psb); - assert!(matches!(l.decoded_len(), Err(PsdError::LimitExceeded(_)))); - assert!(decode_planes(Compression::Rle, &[0; 16], &l).is_err()); -} - -/// Real PSBs go past 2 GiB in one decode (#375): a 30000² RGB merged image and a 33000² -/// 16-bit layer channel. Only checks the limit, so nothing is allocated. -#[test] -#[cfg(target_pointer_width = "64")] -fn decoded_len_allows_large_psb_planes() { - assert_eq!(layout(3, 30_000, 30_000, 8, Version::Psb).decoded_len().unwrap(), 2_700_000_000); - assert_eq!(layout(1, 33_000, 33_000, 16, Version::Psb).decoded_len().unwrap(), 2_178_000_000); - assert!(layout(4, 40_000, 40_000, 16, Version::Psb).decoded_len().is_err()); -} - -#[test] -fn prediction_8bit_known_vector() { - let l = layout(1, 4, 1, 8, Version::Psd); - let mut v = vec![10, 12, 11, 255]; - predict(&mut v, &l).unwrap(); - assert_eq!(v, vec![10, 2, 255, 244]); - unpredict(&mut v, &l).unwrap(); - assert_eq!(v, vec![10, 12, 11, 255]); -} - -#[test] -fn prediction_16bit_known_vector() { - let l = layout(1, 3, 1, 16, Version::Psd); - let mut v = vec![0x01, 0x00, 0x01, 0x05, 0x00, 0x00]; - predict(&mut v, &l).unwrap(); - assert_eq!(v, vec![0x01, 0x00, 0x00, 0x05, 0xfe, 0xfb]); - unpredict(&mut v, &l).unwrap(); - assert_eq!(v, vec![0x01, 0x00, 0x01, 0x05, 0x00, 0x00]); -} - -#[test] -fn prediction_32bit_plane_shuffle() { - // Two samples: AABBCCDD and 11223344 → planes [AA,11][BB,22][CC,33][DD,44] - let l = layout(1, 2, 1, 32, Version::Psd); - let orig = vec![0xAA, 0xBB, 0xCC, 0xDD, 0x11, 0x22, 0x33, 0x44]; - let mut v = orig.clone(); - predict(&mut v, &l).unwrap(); - let planes = [0xAAu8, 0x11, 0xBB, 0x22, 0xCC, 0x33, 0xDD, 0x44]; - let mut expect = planes; - for i in (1..8).rev() { - expect[i] = expect[i].wrapping_sub(expect[i - 1]); - } - assert_eq!(v, expect); - unpredict(&mut v, &l).unwrap(); - assert_eq!(v, orig); -} - -#[test] -fn prediction_32bit_floats_roundtrip() { - let l = layout(1, 5, 2, 32, Version::Psd); - let mut v = Vec::new(); - for i in 0..10 { - v.extend_from_slice(&(i as f32 * 0.37 - 1.0).to_be_bytes()); - } - let enc = encode_planes(Compression::ZipPrediction, &v, &l).unwrap(); - assert_eq!(decode_planes(Compression::ZipPrediction, &enc, &l).unwrap(), v); -} - -#[test] -fn zip_bomb_is_bounded() { - let big = zip_compress(&vec![0u8; 1 << 20]); - let out = zip_decompress(&big, 10).unwrap(); - assert_eq!(out.len(), 10); -} - -#[test] -fn zip_garbage_errors() { - assert!(zip_decompress(&[1, 2, 3, 4], 4).is_err()); -} diff --git a/crates/psd/src/csh.rs b/crates/psd/src/csh.rs deleted file mode 100644 index a024eb675d..0000000000 --- a/crates/psd/src/csh.rs +++ /dev/null @@ -1,127 +0,0 @@ -//! Photoshop custom shape sets (`.csh`, version 2). -//! -//! Container layout: Michel Mariani's public format research, -//! . -//! Geometry uses Adobe's path record format. No external implementation or shape assets copied. - -use crate::error::{PsdError, Result}; -use crate::io::Reader; -use crate::path::{PathData, RECORD_LEN}; - -/// Maximum encoded file size accepted by this reader. -pub const MAX_FILE_BYTES: usize = 64 << 20; -/// Maximum presets in a set. -pub const MAX_SHAPES: usize = 10_000; -/// Maximum path records across all presets, not per shape. -pub const MAX_RECORDS: usize = 1_000_000; -/// Maximum UTF-16 units in a preset name, including its optional trailing null. -pub const MAX_NAME_UNITS: usize = 32_768; - -/// A named shape with its reference bounds and normalized path records. -#[derive(Debug, Clone, PartialEq)] -pub struct CshShape { - /// Display name. - pub name: String, - /// Source shape identifier (usually a UUID). - pub id: String, - /// Reference rectangle: top, left, bottom, right. Coordinates may be negative. - pub bounds: [i32; 4], - /// Coordinates are fractions of the reference rectangle's width and height. - pub path: PathData, -} - -/// Read a complete set before callers modify their preset libraries. -/// Unsupported versions, truncated records and excessive aggregate sizes return errors. -pub fn parse(bytes: &[u8]) -> Result> { - if bytes.len() > MAX_FILE_BYTES { - return Err(PsdError::LimitExceeded("CSH file bytes")); - } - let mut r = Reader::new(bytes); - let signature = r.array()?; - if &signature != b"cush" { - return Err(PsdError::InvalidSignature { expected: "cush", found: signature }); - } - if r.u32()? != 2 { - return Err(PsdError::Unsupported("CSH file version (expected 2)".into())); - } - let count = r.u32()? as usize; - if count > MAX_SHAPES { - return Err(PsdError::LimitExceeded("CSH shape count")); - } - r.check_count(count as u64, 32)?; - let mut shapes = Vec::new(); - let mut remaining_records = MAX_RECORDS; - for _ in 0..count { - let units = r.u32()? as usize; - if units > MAX_NAME_UNITS { - return Err(PsdError::LimitExceeded("CSH name length")); - } - let raw = r.bytes(units * 2)?; - let mut name: Vec = raw.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).collect(); - if name.last() == Some(&0) { - name.pop(); - } - let name = String::from_utf16(&name).map_err(|_| PsdError::invalid("CSH name is not valid UTF-16"))?; - let padding = (4 - r.pos() % 4) % 4; - zero_padding(r.bytes(padding)?)?; - if r.u32()? != 1 { - return Err(PsdError::Unsupported("CSH shape version (expected 1)".into())); - } - let length = r.u32()?; - if !length.is_multiple_of(4) { - return Err(PsdError::invalid("CSH shape length must be aligned to four bytes")); - } - let mut shape = r.sub(u64::from(length))?; - let id_len = usize::from(shape.u8()?); - let id = std::str::from_utf8(shape.bytes(id_len)?).map_err(|_| PsdError::invalid("CSH identifier is not UTF-8"))?.to_owned(); - let bounds = [shape.i32()?, shape.i32()?, shape.i32()?, shape.i32()?]; - if bounds[2] <= bounds[0] || bounds[3] <= bounds[1] { - return Err(PsdError::invalid("CSH reference bounds are empty or reversed")); - } - let records = shape.remaining() / RECORD_LEN; - remaining_records = remaining_records.checked_sub(records).ok_or(PsdError::LimitExceeded("CSH aggregate path records"))?; - let path = PathData::from_bytes(shape.bytes(records * RECORD_LEN)?)?; - if shape.remaining() > 3 { - return Err(PsdError::invalid("CSH incomplete path record")); - } - zero_padding(shape.peek_rest())?; - validate_path(&path)?; - shapes.push(CshShape { name, id, bounds, path }); - } - if !r.is_empty() { - return Err(PsdError::invalid("CSH trailing data")); - } - Ok(shapes) -} - -/// Refuse nonzero alignment bytes rather than silently discarding extra payload data as padding. -fn zero_padding(bytes: &[u8]) -> Result<()> { - if bytes.iter().any(|&b| b != 0) { - return Err(PsdError::invalid("CSH nonzero padding")); - } - Ok(()) -} - -/// Enforce subpath structure more strictly than the generic PSD path reader. -/// Each length record must be followed by exactly its declared number of knots, with matching -/// open/closed selectors. Fill and clipboard records are accepted only between subpaths. -/// Rejecting inconsistent records prevents a damaged preset from silently changing geometry. -fn validate_path(path: &PathData) -> Result<()> { - let mut pending = 0u16; - let mut closed = false; - for record in &path.records { - match record.selector { - 0 | 3 if pending == 0 => { - pending = u16::from_be_bytes([record.data[0], record.data[1]]); - closed = record.selector == 0; - } - 1 | 2 | 4 | 5 if pending > 0 && closed == (record.selector <= 2) => pending -= 1, - 6..=8 if pending == 0 => {} - _ => return Err(PsdError::invalid("CSH path selectors or knot counts are inconsistent")), - } - } - if pending != 0 { - return Err(PsdError::invalid("CSH subpath is missing knots")); - } - Ok(()) -} diff --git a/crates/psd/src/descriptor.rs b/crates/psd/src/descriptor.rs deleted file mode 100644 index 8bb5f6bb35..0000000000 --- a/crates/psd/src/descriptor.rs +++ /dev/null @@ -1,867 +0,0 @@ -//! Photoshop ActionDescriptor structures (OSType-tagged key/value trees). -//! -//! These appear inside many tagged blocks (`lfx2`, `SoCo`, `GdFl`, `TySh`, -//! `PlLd`, …), usually wrapped in a [`VersionedDescriptor`] (version 16). -//! Parsing and writing are exact: `write(parse(b)) == b` for well-formed input. - -use crate::error::{PsdError, Result}; -use crate::io::{Reader, WriteExt, read_unicode_units, write_unicode_units}; - -/// Maximum nesting depth accepted when parsing (fuzz safety). -pub const MAX_DEPTH: usize = 64; - -/// A Photoshop Unicode string: UTF-16 code units, preserved exactly -/// (including any trailing NUL and unpaired surrogates). -#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct UnicodeString(pub Vec); - -impl UnicodeString { - /// Encodes `s` as UTF-16 without a trailing NUL. - pub fn new(s: &str) -> Self { - UnicodeString(s.encode_utf16().collect()) - } - /// Encodes `s` as UTF-16 followed by a NUL terminator (as Photoshop - /// commonly writes in descriptors). - pub fn new_nul(s: &str) -> Self { - let mut v: Vec = s.encode_utf16().collect(); - v.push(0); - UnicodeString(v) - } - /// Lossy conversion, stripping trailing NULs. - pub fn to_string_lossy(&self) -> String { - let mut end = self.0.len(); - while end > 0 && self.0[end - 1] == 0 { - end -= 1; - } - String::from_utf16_lossy(&self.0[..end]) - } - pub(crate) fn read(r: &mut Reader<'_>) -> Result { - Ok(UnicodeString(read_unicode_units(r)?)) - } - pub(crate) fn write(&self, out: &mut Vec) { - write_unicode_units(out, &self.0); - } -} - -/// Four-character class and key ids Photoshop writes as length-4 strings, never as codes -/// (`00000004 'warp'`, not `00000000 'warp'`). -pub const STRING_IDS: [&str; 3] = ["warp", "list", "time"]; - -/// A class / key / type identifier: a length-prefixed string, where a stored -/// length of 0 means a 4-character code follows. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum Id { - /// Stored as length 0 + 4 bytes. - Code([u8; 4]), - /// Stored as explicit length + bytes (e.g. `"artboardRect"`). - Str(Vec), -} - -impl Id { - /// Convenience constructor: 4-byte strings become [`Id::Code`], others - /// [`Id::Str`]. The four-character names Photoshop stores as length-4 strings - /// ([`STRING_IDS`]: `warp`, `list`, `time`) are [`Id::Str`] too: Photoshop treats the - /// string and the code as different keys and doesn't recognise the code form. - pub fn new(s: &str) -> Self { - let b = s.as_bytes(); - match b { - [a, b, c, d] if !STRING_IDS.contains(&s) => Id::Code([*a, *b, *c, *d]), - _ => Id::Str(b.to_vec()), - } - } - /// The identifier's bytes. - pub fn as_bytes(&self) -> &[u8] { - match self { - Id::Code(c) => c, - Id::Str(s) => s, - } - } - /// `true` if the identifier's bytes equal `s`. - pub fn is(&self, s: &str) -> bool { - self.as_bytes() == s.as_bytes() - } - pub(crate) fn read(r: &mut Reader<'_>) -> Result { - let n = r.u32()?; - if n == 0 { Ok(Id::Code(r.array()?)) } else { Ok(Id::Str(r.bytes_u64(u64::from(n))?.to_vec())) } - } - pub(crate) fn write(&self, out: &mut Vec) { - match self { - Id::Code(c) => { - out.put_u32(0); - out.put(c); - } - Id::Str(s) => { - out.put_u32(s.len() as u32); - out.put(s); - } - } - } -} - -/// A class reference: display name + class id. -#[derive(Debug, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct Class { - /// Display name. - pub name: UnicodeString, - /// Class identifier. - pub class_id: Id, -} - -impl Class { - fn read(r: &mut Reader<'_>) -> Result { - Ok(Class { name: UnicodeString::read(r)?, class_id: Id::read(r)? }) - } - fn write(&self, out: &mut Vec) { - self.name.write(out); - self.class_id.write(out); - } -} - -/// One element of an `'obj '` reference. -#[derive(Debug, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum ReferenceItem { - /// `prop` - Property { - /// Class. - class: Class, - /// Property key. - key: Id, - }, - /// `Clss` - Class(Class), - /// `Enmr` - Enumerated { - /// Class. - class: Class, - /// Enum type. - type_id: Id, - /// Enum value. - value: Id, - }, - /// `rele` - Offset { - /// Class. - class: Class, - /// Offset. - offset: i32, - }, - /// `Idnt`: a class plus an identifier (Photoshop's layer ids in action references). - Identifier { - /// Class. - class: Class, - /// Identifier. - id: u32, - }, - /// `indx`: a class plus a zero-based index. - Index { - /// Class. - class: Class, - /// Index. - index: u32, - }, - /// `name` - Name { - /// Class. - class: Class, - /// Name. - name: UnicodeString, - }, -} - -/// A descriptor value, tagged by its OSType. -#[derive(Debug, Clone, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum Value { - /// `obj ` - Reference(Vec), - /// `Objc` - Descriptor(Descriptor), - /// `GlbO` - GlobalObject(Descriptor), - /// `VlLs` - List(Vec), - /// `doub` - Double(f64), - /// `UntF`: unit (`#Ang`, `#Rsl`, `#Rlt`, `#Nne`, `#Prc`, `#Pxl`, …) + value. - UnitFloat { - /// Unit code. - unit: [u8; 4], - /// Value. - value: f64, - }, - /// `UnFl`: unit + array of doubles (used in `ObAr`). - UnitFloats { - /// Unit code. - unit: [u8; 4], - /// Values. - values: Vec, - }, - /// `TEXT` - Text(UnicodeString), - /// `enum` - Enumerated { - /// Enum type. - type_id: Id, - /// Enum value. - value: Id, - }, - /// `long` - Integer(i32), - /// `comp` - LargeInteger(i64), - /// `bool` - Boolean(bool), - /// `type` - Class(Class), - /// `GlbC` - GlobalClass(Class), - /// `alis`: raw alias data. - Alias(Vec), - /// `Pth `: raw file path data (length-prefixed). - Path(Vec), - /// `tdta`: raw data. - RawData(Vec), - /// `ObAr`: object array (best effort; see [`ObjectArray`]). - ObjectArray(ObjectArray), -} - -/// `ObAr` object array. Undocumented in the Adobe spec; the layout follows -/// ag-psd (MIT): a u32 (observed as the element count / version 16) followed -/// by a descriptor-shaped body whose values are usually `UnFl`. -#[derive(Debug, Clone, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ObjectArray { - /// Leading u32, preserved. - pub prefix: u32, - /// Body. - pub body: Descriptor, -} - -/// An ActionDescriptor: class plus ordered key/value items. -#[derive(Debug, Clone, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct Descriptor { - /// Display name of the class (often empty). - pub name: UnicodeString, - /// Class id. - pub class_id: Id, - /// Items in stored order. - pub items: Vec<(Id, Value)>, -} - -impl Default for Descriptor { - fn default() -> Self { - Descriptor::new("null") - } -} - -impl Descriptor { - /// Creates an empty descriptor of the given class. - pub fn new(class_id: &str) -> Self { - Descriptor { name: UnicodeString::default(), class_id: Id::new(class_id), items: Vec::new() } - } - - /// Builder-style item append. - pub fn with(mut self, key: &str, value: Value) -> Self { - self.items.push((Id::new(key), value)); - self - } - - /// Looks up the first item with key `key`. - pub fn get(&self, key: &str) -> Option<&Value> { - self.items.iter().find(|(k, _)| k.is(key)).map(|(_, v)| v) - } - - /// Parses a descriptor from `data`, which must be consumed entirely. - pub fn from_bytes(data: &[u8]) -> Result { - let mut r = Reader::new(data); - let d = Self::read(&mut r)?; - if !r.is_empty() { - return Err(PsdError::invalid("trailing bytes after descriptor")); - } - Ok(d) - } - - /// Serializes the descriptor. - pub fn to_bytes(&self) -> Vec { - let mut v = Vec::new(); - self.write(&mut v); - v - } - - pub(crate) fn read(r: &mut Reader<'_>) -> Result { - read_descriptor(r, 0) - } - - pub(crate) fn write(&self, out: &mut Vec) { - self.name.write(out); - self.class_id.write(out); - out.put_u32(self.items.len() as u32); - for (k, v) in &self.items { - k.write(out); - write_value(v, out); - } - } -} - -/// A descriptor prefixed by a u32 version (16 in all current Photoshop files). -#[derive(Debug, Clone, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct VersionedDescriptor { - /// Descriptor version (16). - pub version: u32, - /// The descriptor. - pub descriptor: Descriptor, -} - -impl VersionedDescriptor { - /// Wraps a descriptor with version 16. - pub fn new(descriptor: Descriptor) -> Self { - VersionedDescriptor { version: 16, descriptor } - } - /// Parses from bytes (must be fully consumed). - pub fn from_bytes(data: &[u8]) -> Result { - let mut r = Reader::new(data); - let v = Self::read(&mut r)?; - if !r.is_empty() { - return Err(PsdError::invalid("trailing bytes after versioned descriptor")); - } - Ok(v) - } - /// Parses a versioned descriptor at the start of `data`, returning it and - /// the number of bytes consumed (trailing data is allowed, e.g. the warp - /// descriptor after the text descriptor in `TySh`). - pub fn parse_prefix(data: &[u8]) -> Result<(Self, usize)> { - let mut r = Reader::new(data); - let v = Self::read(&mut r)?; - Ok((v, r.pos())) - } - /// Serializes. - pub fn to_bytes(&self) -> Vec { - let mut v = Vec::new(); - self.write(&mut v); - v - } - pub(crate) fn read(r: &mut Reader<'_>) -> Result { - let version = r.u32()?; - if version != 16 { - return Err(PsdError::invalid(format!("descriptor version {version}, expected 16"))); - } - Ok(VersionedDescriptor { version, descriptor: Descriptor::read(r)? }) - } - pub(crate) fn write(&self, out: &mut Vec) { - out.put_u32(self.version); - self.descriptor.write(out); - } -} - -/// Most items preallocated for a file-declared count. `check_count` only -/// guarantees a few bytes per item while parsed items are far larger, so the -/// count must not drive the up-front reservation (or abort on allocation). -const MAX_PREALLOC: usize = 4096; - -pub(crate) fn vec_for_count(n: u32) -> Vec { - Vec::with_capacity((n as usize).min(MAX_PREALLOC)) -} - -fn read_descriptor(r: &mut Reader<'_>, depth: usize) -> Result { - if depth > MAX_DEPTH { - return Err(PsdError::LimitExceeded("descriptor nesting too deep")); - } - let name = UnicodeString::read(r)?; - let class_id = Id::read(r)?; - let n = r.u32()?; - // Each item needs at least 5 (1-byte string key) + 4 (type) + 1 (bool). - r.check_count(u64::from(n), 10)?; - let mut items = vec_for_count(n); - for _ in 0..n { - let key = Id::read(r)?; - let v = read_value(r, depth + 1)?; - items.push((key, v)); - } - Ok(Descriptor { name, class_id, items }) -} - -fn read_value(r: &mut Reader<'_>, depth: usize) -> Result { - if depth > MAX_DEPTH { - return Err(PsdError::LimitExceeded("descriptor nesting too deep")); - } - let ty = r.array::<4>()?; - read_typed_value(r, &ty, depth) -} - -fn read_typed_value(r: &mut Reader<'_>, ty: &[u8; 4], depth: usize) -> Result { - Ok(match ty { - b"obj " => { - let n = r.u32()?; - r.check_count(u64::from(n), 8)?; - let mut items = vec_for_count(n); - for _ in 0..n { - items.push(read_reference_item(r)?); - } - Value::Reference(items) - } - b"Objc" => Value::Descriptor(read_descriptor(r, depth + 1)?), - b"GlbO" => Value::GlobalObject(read_descriptor(r, depth + 1)?), - b"VlLs" => { - let n = r.u32()?; - r.check_count(u64::from(n), 4)?; - let mut items = vec_for_count(n); - for _ in 0..n { - items.push(read_value(r, depth + 1)?); - } - Value::List(items) - } - b"doub" => Value::Double(r.f64()?), - b"UntF" => Value::UnitFloat { unit: r.array()?, value: r.f64()? }, - b"UnFl" => { - let unit = r.array()?; - let n = r.u32()?; - r.check_count(u64::from(n), 8)?; - let mut values = vec_for_count(n); - for _ in 0..n { - values.push(r.f64()?); - } - Value::UnitFloats { unit, values } - } - b"TEXT" => Value::Text(UnicodeString::read(r)?), - b"enum" => Value::Enumerated { type_id: Id::read(r)?, value: Id::read(r)? }, - b"long" => Value::Integer(r.i32()?), - b"comp" => Value::LargeInteger(r.i64()?), - b"bool" => Value::Boolean(r.u8()? != 0), - b"type" => Value::Class(Class::read(r)?), - b"GlbC" => Value::GlobalClass(Class::read(r)?), - b"alis" => { - let n = r.u32()?; - Value::Alias(r.bytes_u64(u64::from(n))?.to_vec()) - } - b"Pth " => { - let n = r.u32()?; - Value::Path(r.bytes_u64(u64::from(n))?.to_vec()) - } - b"tdta" => { - let n = r.u32()?; - Value::RawData(r.bytes_u64(u64::from(n))?.to_vec()) - } - b"ObAr" => { - let prefix = r.u32()?; - Value::ObjectArray(ObjectArray { prefix, body: read_descriptor(r, depth + 1)? }) - } - other => { - return Err(PsdError::Unsupported(format!("descriptor OSType {:?}", String::from_utf8_lossy(other)))); - } - }) -} - -fn read_reference_item(r: &mut Reader<'_>) -> Result { - let ty = r.array::<4>()?; - Ok(match &ty { - b"prop" => ReferenceItem::Property { class: Class::read(r)?, key: Id::read(r)? }, - b"Clss" => ReferenceItem::Class(Class::read(r)?), - b"Enmr" => ReferenceItem::Enumerated { class: Class::read(r)?, type_id: Id::read(r)?, value: Id::read(r)? }, - b"rele" => ReferenceItem::Offset { class: Class::read(r)?, offset: r.i32()? }, - b"Idnt" => ReferenceItem::Identifier { class: Class::read(r)?, id: r.u32()? }, - b"indx" => ReferenceItem::Index { class: Class::read(r)?, index: r.u32()? }, - b"name" => ReferenceItem::Name { class: Class::read(r)?, name: UnicodeString::read(r)? }, - other => { - return Err(PsdError::Unsupported(format!("reference item type {:?}", String::from_utf8_lossy(other)))); - } - }) -} - -fn value_type(v: &Value) -> &'static [u8; 4] { - match v { - Value::Reference(_) => b"obj ", - Value::Descriptor(_) => b"Objc", - Value::GlobalObject(_) => b"GlbO", - Value::List(_) => b"VlLs", - Value::Double(_) => b"doub", - Value::UnitFloat { .. } => b"UntF", - Value::UnitFloats { .. } => b"UnFl", - Value::Text(_) => b"TEXT", - Value::Enumerated { .. } => b"enum", - Value::Integer(_) => b"long", - Value::LargeInteger(_) => b"comp", - Value::Boolean(_) => b"bool", - Value::Class(_) => b"type", - Value::GlobalClass(_) => b"GlbC", - Value::Alias(_) => b"alis", - Value::Path(_) => b"Pth ", - Value::RawData(_) => b"tdta", - Value::ObjectArray(_) => b"ObAr", - } -} - -fn write_value(v: &Value, out: &mut Vec) { - out.put(value_type(v)); - match v { - Value::Reference(items) => { - out.put_u32(items.len() as u32); - for it in items { - write_reference_item(it, out); - } - } - Value::Descriptor(d) | Value::GlobalObject(d) => d.write(out), - Value::List(items) => { - out.put_u32(items.len() as u32); - for it in items { - write_value(it, out); - } - } - Value::Double(d) => out.put_f64(*d), - Value::UnitFloat { unit, value } => { - out.put(unit); - out.put_f64(*value); - } - Value::UnitFloats { unit, values } => { - out.put(unit); - out.put_u32(values.len() as u32); - for v in values { - out.put_f64(*v); - } - } - Value::Text(s) => s.write(out), - Value::Enumerated { type_id, value } => { - type_id.write(out); - value.write(out); - } - Value::Integer(i) => out.put_i32(*i), - Value::LargeInteger(i) => out.put_i64(*i), - Value::Boolean(b) => out.put_u8(u8::from(*b)), - Value::Class(c) | Value::GlobalClass(c) => c.write(out), - Value::Alias(b) | Value::Path(b) | Value::RawData(b) => { - out.put_u32(b.len() as u32); - out.put(b); - } - Value::ObjectArray(o) => { - out.put_u32(o.prefix); - o.body.write(out); - } - } -} - -fn write_reference_item(it: &ReferenceItem, out: &mut Vec) { - match it { - ReferenceItem::Property { class, key } => { - out.put(b"prop"); - class.write(out); - key.write(out); - } - ReferenceItem::Class(c) => { - out.put(b"Clss"); - c.write(out); - } - ReferenceItem::Enumerated { class, type_id, value } => { - out.put(b"Enmr"); - class.write(out); - type_id.write(out); - value.write(out); - } - ReferenceItem::Offset { class, offset } => { - out.put(b"rele"); - class.write(out); - out.put_i32(*offset); - } - ReferenceItem::Identifier { class, id } => { - out.put(b"Idnt"); - class.write(out); - out.put_u32(*id); - } - ReferenceItem::Index { class, index } => { - out.put(b"indx"); - class.write(out); - out.put_u32(*index); - } - ReferenceItem::Name { class, name } => { - out.put(b"name"); - class.write(out); - name.write(out); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn class(name: &str, id: &str) -> Class { - Class { name: UnicodeString::new(name), class_id: Id::new(id) } - } - - #[test] - fn declared_counts_do_not_drive_preallocation() { - assert!(vec_for_count::(u32::MAX).capacity() <= MAX_PREALLOC); - // A 1M-item list of booleans parses (items grow the vector as needed). - let n = 1_000_000u32; - let mut data = n.to_be_bytes().to_vec(); - for _ in 0..n { - data.extend_from_slice(b"bool\x01"); - } - let mut r = Reader::new(&data); - match read_typed_value(&mut r, b"VlLs", 0).unwrap() { - Value::List(v) => assert_eq!(v.len(), n as usize), - other => panic!("expected list, got {other:?}"), - } - } - - pub(crate) fn sample() -> Descriptor { - Descriptor::new("null") - .with("Nm ", Value::Text(UnicodeString::new_nul("Hello \u{1F600}"))) - .with("Opct", Value::UnitFloat { unit: *b"#Prc", value: 75.5 }) - .with("enab", Value::Boolean(true)) - .with("long", Value::Integer(-5)) - .with("comp", Value::LargeInteger(1 << 40)) - .with("doub", Value::Double(0.25)) - .with("Md ", Value::Enumerated { type_id: Id::new("BlnM"), value: Id::new("Mltp") }) - .with("artboardRect", Value::Descriptor(Descriptor::new("classFloatRect").with("Top ", Value::Double(1.0)))) - .with("list", Value::List(vec![Value::Integer(1), Value::Text(UnicodeString::new("x"))])) - .with( - "null", - 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: -1 }, - ReferenceItem::Identifier { class: class("", "Lyr "), id: 7 }, - ReferenceItem::Index { class: class("\0", "Lyr "), index: 2 }, - ReferenceItem::Name { class: class("", "Lyr "), name: UnicodeString::new("Bg") }, - ]), - ) - .with("type", Value::Class(class("c", "Clr "))) - .with("glbc", Value::GlobalClass(class("c", "RGBC"))) - .with("glbo", Value::GlobalObject(Descriptor::default())) - .with("alis", Value::Alias(vec![1, 2, 3])) - .with("tdta", Value::RawData(vec![0xde, 0xad])) - .with("pth ", Value::Path(vec![9, 9])) - .with( - "ObAr", - Value::ObjectArray(ObjectArray { - prefix: 16, - body: Descriptor::new("rationalPoint").with("Hrzn", Value::UnitFloats { unit: *b"#Pxl", values: vec![1.0, 2.0] }), - }), - ) - } - - #[test] - fn roundtrip_all_types() { - let d = sample(); - let b = d.to_bytes(); - let p = Descriptor::from_bytes(&b).unwrap(); - assert_eq!(p, d); - assert_eq!(p.to_bytes(), b); - } - - /// `warp`, `list` and `time` are written as length-4 strings, as Photoshop writes them, both - /// as keys and as class ids; other four-character names stay codes. Reading accepts both - /// forms, and a code read from a file is written back as a code. - #[test] - fn photoshop_string_ids_are_written_as_strings() { - let str_id = |s: &str| [&[0, 0, 0, 4][..], s.as_bytes()].concat(); - let code_id = |s: &str| [&[0, 0, 0, 0][..], s.as_bytes()].concat(); - for name in STRING_IDS { - assert_eq!(Id::new(name), Id::Str(name.as_bytes().to_vec())); - let d = Descriptor::new(name).with(name, Value::Integer(1)); - let b = d.to_bytes(); - // Name (empty unicode string), then the class id; then the item count and the key. - assert_eq!(&b[4..12], &str_id(name)[..], "class {name}"); - assert_eq!(&b[16..24], &str_id(name)[..], "key {name}"); - let back = Descriptor::from_bytes(&b).unwrap(); - assert_eq!(back, d); - assert!(back.class_id.is(name) && back.get(name).is_some()); - // A file that wrote the code form keeps it, and lookups still find the key. - let mut coded = b.clone(); - coded.splice(16..24, code_id(name)); - let back = Descriptor::from_bytes(&coded).unwrap(); - assert_eq!(back.get(name), Some(&Value::Integer(1))); - assert_eq!(back.to_bytes(), coded); - } - assert_eq!(Id::new("view"), Id::Code(*b"view")); - assert_eq!(Id::new("Txt "), Id::Code(*b"Txt ")); - } - - #[test] - fn versioned_roundtrip() { - let v = VersionedDescriptor::new(sample()); - let b = v.to_bytes(); - assert_eq!(&b[..4], &[0, 0, 0, 16]); - assert_eq!(VersionedDescriptor::from_bytes(&b).unwrap(), v); - } - - #[test] - fn versioned_parse_prefix() { - let v = VersionedDescriptor::new(sample()); - let mut b = v.to_bytes(); - let n = b.len(); - b.extend_from_slice(&[1, 2, 3]); - let (p, used) = VersionedDescriptor::parse_prefix(&b).unwrap(); - assert_eq!(p, v); - assert_eq!(used, n); - } - - #[test] - fn versioned_rejects_other_version() { - let mut b = VersionedDescriptor::new(Descriptor::new("null")).to_bytes(); - b[3] = 15; - assert!(VersionedDescriptor::from_bytes(&b).is_err()); - } - - #[test] - fn id_encoding() { - let mut v = Vec::new(); - Id::new("Nm ").write(&mut v); - assert_eq!(v, [0, 0, 0, 0, b'N', b'm', b' ', b' ']); - let mut v = Vec::new(); - Id::new("abc").write(&mut v); - assert_eq!(v, [0, 0, 0, 3, b'a', b'b', b'c']); - // A 4-byte explicit-length id stays explicit. - let data = [0, 0, 0, 4, b'a', b'b', b'c', b'd']; - let id = Id::read(&mut Reader::new(&data)).unwrap(); - assert_eq!(id, Id::Str(b"abcd".to_vec())); - let mut v = Vec::new(); - id.write(&mut v); - assert_eq!(v, data); - } - - #[test] - fn get_and_lookup() { - let d = sample(); - assert_eq!(d.get("long"), Some(&Value::Integer(-5))); - assert!(d.get("nope").is_none()); - } - - #[test] - fn unicode_lossy() { - assert_eq!(UnicodeString::new_nul("ab").to_string_lossy(), "ab"); - assert_eq!(UnicodeString(vec![0xd800, 0x41]).to_string_lossy(), "\u{fffd}A"); - } - - #[test] - fn truncations_error() { - let b = sample().to_bytes(); - for cut in 0..b.len() { - assert!(Descriptor::from_bytes(&b[..cut]).is_err(), "cut {cut}"); - } - } - - #[test] - fn trailing_bytes_error() { - let mut b = sample().to_bytes(); - b.push(0); - assert!(Descriptor::from_bytes(&b).is_err()); - } - - #[test] - fn unknown_ostype_errors() { - let mut b = Descriptor::new("null").to_bytes(); - let n = b.len(); - b[n - 1] = 1; // one item - b.extend_from_slice(&[0, 0, 0, 0, b'k', b'e', b'y', b' ']); - b.extend_from_slice(b"????"); - assert!(matches!(Descriptor::from_bytes(&b), Err(PsdError::Unsupported(_)))); - } - - #[test] - fn deep_nesting_is_limited() { - let mut d = Descriptor::new("null"); - for _ in 0..(MAX_DEPTH + 5) { - d = Descriptor::new("null").with("in ", Value::Descriptor(d)); - } - let b = d.to_bytes(); - assert!(matches!(Descriptor::from_bytes(&b), Err(PsdError::LimitExceeded(_)))); - } - - #[test] - fn huge_counts_rejected_without_alloc() { - let mut b = Vec::new(); - b.put_u32(0); - b.put_u32(0); - b.put(b"null"); - b.put_u32(u32::MAX); - assert!(Descriptor::from_bytes(&b).is_err()); - } -} - -#[cfg(test)] -pub(crate) mod proptests { - use super::*; - use proptest::prelude::*; - - fn arb_id() -> impl Strategy { - prop_oneof![any::<[u8; 4]>().prop_map(Id::Code), proptest::collection::vec(any::(), 1..12).prop_map(Id::Str),] - } - fn arb_ustr() -> impl Strategy { - proptest::collection::vec(any::(), 0..8).prop_map(UnicodeString) - } - fn arb_class() -> impl Strategy { - (arb_ustr(), arb_id()).prop_map(|(name, class_id)| Class { name, class_id }) - } - fn arb_ref() -> impl Strategy { - prop_oneof![ - (arb_class(), arb_id()).prop_map(|(class, key)| ReferenceItem::Property { class, key }), - arb_class().prop_map(ReferenceItem::Class), - (arb_class(), arb_id(), arb_id()).prop_map(|(class, type_id, value)| ReferenceItem::Enumerated { class, type_id, value }), - (arb_class(), any::()).prop_map(|(class, offset)| ReferenceItem::Offset { class, offset }), - (arb_class(), any::()).prop_map(|(class, id)| ReferenceItem::Identifier { class, id }), - (arb_class(), any::()).prop_map(|(class, index)| ReferenceItem::Index { class, index }), - (arb_class(), arb_ustr()).prop_map(|(class, name)| ReferenceItem::Name { class, name }), - ] - } - fn finite() -> impl Strategy { - -1e12f64..1e12 - } - fn arb_leaf() -> impl Strategy { - prop_oneof![ - finite().prop_map(Value::Double), - (any::<[u8; 4]>(), finite()).prop_map(|(unit, value)| Value::UnitFloat { unit, value }), - (any::<[u8; 4]>(), proptest::collection::vec(finite(), 0..4)).prop_map(|(unit, values)| Value::UnitFloats { unit, values }), - arb_ustr().prop_map(Value::Text), - (arb_id(), arb_id()).prop_map(|(type_id, value)| Value::Enumerated { type_id, value }), - any::().prop_map(Value::Integer), - any::().prop_map(Value::LargeInteger), - any::().prop_map(Value::Boolean), - arb_class().prop_map(Value::Class), - arb_class().prop_map(Value::GlobalClass), - proptest::collection::vec(any::(), 0..8).prop_map(Value::Alias), - proptest::collection::vec(any::(), 0..8).prop_map(Value::RawData), - proptest::collection::vec(any::(), 0..8).prop_map(Value::Path), - proptest::collection::vec(arb_ref(), 0..3).prop_map(Value::Reference), - ] - } - pub(crate) fn arb_descriptor() -> impl Strategy { - let leaf = arb_leaf(); - let value = leaf.prop_recursive(3, 24, 4, |inner| { - prop_oneof![ - proptest::collection::vec(inner.clone(), 0..4).prop_map(Value::List), - (arb_ustr(), arb_id(), proptest::collection::vec((arb_id(), inner.clone()), 0..4)) - .prop_map(|(name, id, items)| Value::Descriptor(Descriptor { name, class_id: id, items })), - (arb_ustr(), arb_id(), proptest::collection::vec((arb_id(), inner.clone()), 0..3)) - .prop_map(|(name, id, items)| Value::GlobalObject(Descriptor { name, class_id: id, items })), - (any::(), arb_id(), proptest::collection::vec((arb_id(), inner), 0..3)).prop_map(|(prefix, id, items)| Value::ObjectArray(ObjectArray { - prefix, - body: Descriptor { name: UnicodeString::default(), class_id: id, items } - })), - ] - }); - (arb_ustr(), arb_id(), proptest::collection::vec((arb_id(), value), 0..6)).prop_map(|(name, id, items)| Descriptor { name, class_id: id, items }) - } - - proptest! { - #[test] - fn descriptor_roundtrip(d in arb_descriptor()) { - let b = d.to_bytes(); - let p = Descriptor::from_bytes(&b).unwrap(); - prop_assert_eq!(&p, &d); - prop_assert_eq!(p.to_bytes(), b); - } - - #[test] - fn descriptor_parse_never_panics(data in proptest::collection::vec(any::(), 0..256)) { - let _ = Descriptor::from_bytes(&data); - let _ = VersionedDescriptor::from_bytes(&data); - } - } -} diff --git a/crates/psd/src/error.rs b/crates/psd/src/error.rs deleted file mode 100644 index 2e4f87d849..0000000000 --- a/crates/psd/src/error.rs +++ /dev/null @@ -1,76 +0,0 @@ -//! Error type for every fallible operation in this crate. - -use thiserror::Error; - -/// Errors produced while parsing, decoding, encoding or writing PSD/PSB data. -/// -/// Parsers never panic on malformed input; every failure is reported through -/// this type. -#[derive(Debug, Error, Clone, PartialEq, Eq)] -#[non_exhaustive] -pub enum PsdError { - /// The input ended before a structure was complete. - #[error("unexpected end of data at offset {offset} (needed {needed} more bytes)")] - UnexpectedEof { - /// Offset (relative to the current section) where the read started. - offset: usize, - /// Number of bytes that were requested but not available. - needed: usize, - }, - /// A four-byte signature did not match. - #[error("invalid signature {found:?}, expected {expected}")] - InvalidSignature { - /// Human-readable description of the expected signature(s). - expected: &'static str, - /// The bytes that were found. - found: [u8; 4], - }, - /// Header version is neither 1 (PSD) nor 2 (PSB). - #[error("unsupported file version {0}")] - UnsupportedVersion(u16), - /// A dimension, count or allocation exceeded the configured safety limits. - #[error("limit exceeded: {0}")] - LimitExceeded(&'static str), - /// A buffer could not be allocated: the system has no memory for it. Unlike - /// [`PsdError::LimitExceeded`] the data may be valid, so the caller can retry smaller. - #[error("out of memory: {0}")] - OutOfMemory(&'static str), - /// Structurally invalid data. - #[error("invalid data: {0}")] - Invalid(String), - /// A compressed stream could not be decoded. - #[error("decompression failed: {0}")] - Decompress(String), - /// Reading from a [`crate::source::ReadAt`] source failed. - #[error("read failed: {0}")] - Read(String), - /// An operation is not supported for this data (e.g. unknown compression). - #[error("unsupported: {0}")] - Unsupported(String), -} - -impl PsdError { - pub(crate) fn invalid(msg: impl Into) -> Self { - PsdError::Invalid(msg.into()) - } - - /// The error a streaming write ([`crate::PsdFile::write_to`]) failed with: the serializer's - /// own error when it was one, otherwise the I/O error's text. - pub(crate) fn from_io(e: std::io::Error) -> Self { - let text = e.to_string(); - match e.into_inner().map(|inner| inner.downcast::()) { - Some(Ok(e)) => *e, - _ => PsdError::Invalid(format!("write failed: {text}")), - } - } -} - -/// A serializer error inside a streaming write ([`crate::PsdFile::write_to`]), as `InvalidData`. -impl From for std::io::Error { - fn from(e: PsdError) -> Self { - std::io::Error::new(std::io::ErrorKind::InvalidData, e) - } -} - -/// Convenience alias. -pub type Result = std::result::Result; diff --git a/crates/psd/src/file.rs b/crates/psd/src/file.rs deleted file mode 100644 index 40e8ef5db3..0000000000 --- a/crates/psd/src/file.rs +++ /dev/null @@ -1,1174 +0,0 @@ -//! The top-level [`PsdFile`] model, parser and writer. - -use std::io::{Seek, Write}; - -use crate::compression::{Compression, MAX_DECODED_BYTES, decode_planes, rle_widening_len, validate_planes}; -use crate::error::{PsdError, Result}; -use crate::header::{ColorMode, Header, Version}; -use crate::image_data::ImageData; -use crate::io::{Reader, Sink, WriteExt}; -use crate::layer::{LayerInfo, LayerRecord}; -use crate::resources::{self, ImageResource, ResourceData, ids}; -use crate::tagged::{TaggedBlock, read_blocks_with, uses_long_length, write_blocks_to}; - -/// The name the reference editor gives the merged transparency among the alpha channel names. -const TRANSPARENCY_NAME: &str = "Transparency"; - -/// Where the layer info was stored in the file. -#[derive(Debug, Clone, PartialEq, Eq, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum LayerInfoPlacement { - /// In the layer info field of the layer and mask section (8-bit files). - #[default] - Section, - /// In a global `Lr16` / `Lr32` / `Layr` tagged block (16/32-bit files). - /// The block is re-inserted at `index` among `global_blocks` on write. - GlobalBlock { - /// Position among the global blocks. - index: usize, - /// Block signature (`8BIM` / `8B64`). - signature: [u8; 4], - /// Block key. - key: [u8; 4], - /// Padding after the block (see [`TaggedBlock::padding`]). - padding: Option>, - }, -} - -/// Global layer mask info, stored raw with typed accessors. -#[derive(Debug, Clone, PartialEq, Eq, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct GlobalLayerMask { - /// Raw bytes (without the length field). - pub data: Vec, -} - -impl GlobalLayerMask { - /// The mask Photoshop writes for a layered file that has no global mask of its own: - /// an RGB red overlay at 50% opacity, kind 128 (use the per-layer setting), plus the - /// filler byte. A zero-length `LMsk` block in a TIFF makes Photoshop give up on the - /// layer data (it reads this 14-byte record from the block). - pub fn photoshop_default() -> Self { - GlobalLayerMask { data: vec![0, 0, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 50, 128, 0] } - } - - fn be16(&self, at: usize) -> Option { - self.data.get(at..at + 2).map(|b| u16::from_be_bytes([b[0], b[1]])) - } - /// Overlay color space. - pub fn overlay_color_space(&self) -> Option { - self.be16(0) - } - /// Four color components. - pub fn color_components(&self) -> Option<[u16; 4]> { - Some([self.be16(2)?, self.be16(4)?, self.be16(6)?, self.be16(8)?]) - } - /// Opacity 0..=100. - pub fn opacity(&self) -> Option { - self.be16(10) - } - /// Kind: 0 color selected, 1 color protected, 128 per layer. - pub fn kind(&self) -> Option { - self.data.get(12).copied() - } -} - -/// A complete PSD/PSB file. -/// -/// `PsdFile::from_bytes(b)?.to_bytes()? == b` for unmodified well-formed -/// files, and `from_bytes(to_bytes(f)) == f` for any model `f` not marked -/// [`Self::write_as_psb`] (a marked one reads back as the PSB it was written as). -#[derive(Debug, Clone, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct PsdFile { - /// Header. - pub header: Header, - /// Color mode data (palette for indexed, duotone spec, …). - pub color_mode_data: Vec, - /// Image resources in stored order. - pub resources: Vec, - /// Layer info (`None` when the layer info length is 0 and no - /// `Lr16`/`Lr32` block holds layers). - pub layer_info: Option, - /// Where [`Self::layer_info`] is stored. - pub layer_info_placement: LayerInfoPlacement, - /// Global layer mask (`None` when the field is absent entirely). - pub global_layer_mask: Option, - /// Global additional layer information blocks. - pub global_blocks: Vec, - /// Bytes at the end of the layer and mask section that do not form a block. - pub layer_mask_trailing: Vec, - /// Merged image data. - pub image_data: ImageData, - /// Write this PSD model as PSB (set by [`Self::promote_to_psb`]). The model itself stays a - /// consistent PSD: its channel data keeps two-byte RLE row counts, so everything that reads - /// it with `header.version` decodes it as before. Only [`Self::to_bytes`] and - /// [`Self::encoded_len`] write version 2, long length fields and four-byte row counts. - #[cfg_attr(feature = "serde", serde(default))] - pub write_as_psb: bool, -} - -impl PsdFile { - /// Parses a PSD or PSB file. - pub fn from_bytes(data: &[u8]) -> Result { - Self::from_bytes_and_merged(data, |_| false).map(|(file, _)| file) - } - - /// Parses like [`Self::from_bytes`] and, when `want` asks for it, decodes the merged image - /// (as [`Self::decode_merged`] would) in the same pass. `want` sees the file with everything - /// but the merged image parsed (its `image_data` is still empty). A ZIP merged image is then - /// inflated once for both the parse's check of the stream and the decode, not twice. - /// - /// Errors are those of [`Self::from_bytes`]; a merged image that passes the parse's check but - /// cannot be decoded is the inner `Err`, as [`Self::decode_merged`] would return it. - pub fn from_bytes_and_merged(data: &[u8], want: impl FnOnce(&PsdFile) -> bool) -> Result<(Self, Option>>)> { - Self::from_bytes_and_merged_recovering(data, want, |_| false) - } - - /// Parses like [`Self::from_bytes_and_merged`], but lets `recover` accept damage confined to - /// the merged image after all layer records and channel data have been read successfully. - /// Callers should opt in only when they can reconstruct the document from its layers. - /// - /// The original encoded image bytes are preserved and its parse error is returned as - /// `Some(Err(..))`, even when `want` did not request a decode. The caller must report that - /// error rather than silently discarding the merged image (which may hold extra channels). - /// Header/layer errors, missing compression fields and parse safety-limit errors stay fatal. - pub fn from_bytes_and_merged_recovering( - data: &[u8], - want: impl FnOnce(&PsdFile) -> bool, - recover: impl FnOnce(&PsdFile) -> bool, - ) -> Result<(Self, Option>>)> { - Self::from_bytes_and_merged_preflight(data, |file| Ok(want(file)), recover) - } - - /// Parses with a fallible pixel preflight after layer records are available and before - /// the merged image is read, validated or decoded. A preflight error is always fatal; - /// `recover` only handles damage encountered after an accepted preflight. - pub fn from_bytes_and_merged_preflight( - data: &[u8], - want: impl FnOnce(&PsdFile) -> Result, - recover: impl FnOnce(&PsdFile) -> bool, - ) -> Result<(Self, Option>>)> { - let mut r = Reader::new(data); - let header = Header::read(&mut r)?; - let psb = header.version.is_psb(); - let cmd_len = r.u32()?; - let color_mode_data = r.bytes_u64(u64::from(cmd_len))?.to_vec(); - let resources = resources::read_section(&mut r)?; - - let lm_len = r.len_field(psb)?; - let mut s = r.sub(lm_len)?; - let mut layer_info = None; - let mut global_layer_mask = None; - let mut global_blocks = Vec::new(); - let mut layer_mask_trailing = Vec::new(); - let mut layer_info_placement = LayerInfoPlacement::Section; - if !s.is_empty() { - let li_len = s.len_field(psb)?; - if li_len > 0 { - layer_info = Some(LayerInfo::read_body(s.bytes_u64(li_len)?, header.version)?); - } - if s.remaining() >= 4 { - let n = s.u32()?; - global_layer_mask = Some(GlobalLayerMask { data: s.bytes_u64(u64::from(n))?.to_vec() }); - let target_key = match header.depth { - 16 => Some(b"Lr16"), - 32 => Some(b"Lr32"), - _ => None, - }; - let mut candidate_seen = match target_key { - Some(_) => false, - None => layer_info.as_ref().is_some_and(|i| !i.layers.is_empty()), - }; - let (blocks, trailing) = read_blocks_with(&mut s, header.version, 4, |index, signature, key, data, padding| { - let is_candidate = match target_key { - Some(k) => &key == k, - None => matches!(&key, b"Layr" | b"Lr16" | b"Lr32"), - }; - if candidate_seen || !is_candidate { - return false; - } - candidate_seen = true; - let Ok(info) = LayerInfo::read_body(data, header.version) else { - if target_key.is_some() { - layer_info = None; - } - return false; - }; - layer_info = Some(info); - layer_info_placement = LayerInfoPlacement::GlobalBlock { index, signature, key, padding: padding.clone() }; - true - })?; - global_blocks = blocks; - layer_mask_trailing = trailing; - } else { - layer_mask_trailing = s.peek_rest().to_vec(); - } - } - let image_data = ImageData::new(Compression::Raw, Vec::new()); - let mut file = PsdFile { - header, - color_mode_data, - resources, - layer_info, - layer_info_placement, - global_layer_mask, - global_blocks, - layer_mask_trailing, - image_data, - write_as_psb: false, - }; - let want = want(&file)?; - let merged = file.read_merged_section(&mut r, want, recover)?; - Ok((file, merged)) - } - - /// Reads the merged image section from `rest` (the bytes after the layer and mask section) as - /// [`Self::from_bytes_and_merged_recovering`] does, decoding it. - pub(crate) fn read_merged_recovering(&mut self, rest: &[u8], recover: impl FnOnce(&PsdFile) -> bool) -> Result>>> { - self.read_merged_section(&mut Reader::new(rest), true, recover) - } - - fn read_merged_section(&mut self, r: &mut Reader<'_>, want: bool, recover: impl FnOnce(&PsdFile) -> bool) -> Result>>> { - let file = self; - let mut encoded = r.clone(); - let merged = if want { - file.read_merged_decoded(r).map(Some) - } else { - ImageData::read(r, &file.header).map(|image| { - file.image_data = image; - None - }) - }; - let merged = match merged { - Ok(merged) => merged, - Err(error) => { - if matches!(error, PsdError::LimitExceeded(_) | PsdError::OutOfMemory(_)) || !recover(file) { - return Err(error); - } - let compression = Compression::from_u16(encoded.u16()?); - let source = encoded.peek_rest(); - let mut data = Vec::new(); - data.try_reserve_exact(source.len()).map_err(|_| PsdError::OutOfMemory("not enough memory to retain the damaged merged image"))?; - data.extend_from_slice(source); - file.image_data = ImageData::new(compression, data); - Some(Err(error)) - } - }; - Ok(merged) - } - - /// Reads the merged image into `self.image_data` and decodes it. A ZIP stream within the - /// decode limit is inflated once: by the decode, whose stream check is the one - /// [`ImageData::read`] makes. Only when the decode fails is that check run on its own, to - /// tell a file the parse rejects (the outer `Err`) from one it accepts (the inner `Err`). - fn read_merged_decoded(&mut self, r: &mut Reader<'_>) -> Result>> { - let layout = ImageData::layout(&self.header); - let compression = Compression::from_u16(r.clone().u16()?); - let zip = matches!(compression, Compression::Zip | Compression::ZipPrediction); - if !zip || layout.total_bytes()? > MAX_DECODED_BYTES { - // Nothing is inflated twice here: the parse's check reads sizes only (or skips an - // over-limit stream, which the decode then refuses). - self.image_data = ImageData::read(r, &self.header)?; - return Ok(self.decode_merged()); - } - r.u16()?; - let data = r.peek_rest(); - let decoded = decode_planes(compression, data, &layout); - // An allocation failure is the open's, before the encoded image is copied under the same - // memory pressure. - if matches!(decoded, Err(PsdError::OutOfMemory(_))) { - return decoded.map(Ok); - } - if decoded.is_err() { - validate_planes(compression, data, &layout)?; - } - let mut copy = Vec::new(); - copy.try_reserve_exact(data.len()).map_err(|_| PsdError::OutOfMemory("not enough memory to retain the merged image"))?; - copy.extend_from_slice(data); - self.image_data = ImageData::new(compression, copy); - r.skip(data.len())?; - Ok(decoded) - } - - /// Serializes the file. - pub fn to_bytes(&self) -> Result> { - // Reserve the whole file up front, at its exact length: appending to an empty Vec - // reallocates and copies repeatedly, and a reserve that is a few bytes short makes the - // last append double the buffer, copying the whole file once more (#6607). - let len = usize::try_from(self.encoded_len()?).map_err(|_| PsdError::OutOfMemory("not enough memory to serialize the file"))?; - let mut out = Vec::new(); - out.try_reserve_exact(len).map_err(|_| PsdError::OutOfMemory("not enough memory to serialize the file"))?; - self.write_to(&mut std::io::Cursor::new(&mut out)).map_err(PsdError::from_io)?; - Ok(out) - } - - /// Serializes the file into `w` as it goes, starting at its current position: the bytes of - /// [`Self::to_bytes`] without ever holding them all (#6607). Length fields are back-patched - /// by seeking. A serializer error (a section too large for PSD, too many layers) comes back - /// as `InvalidData` carrying the [`PsdError`]; `w` then holds a partial file. - pub fn write_to(&self, w: &mut W) -> std::io::Result<()> { - let mut out = Sink::new(w)?; - self.write_staging(&mut out)?; - out.finish() - } - - /// [`Self::write_to`] writing out every `stage` staged bytes (tests: tiny stages make every - /// length field a back-patch through the stream). - #[cfg(test)] - pub(crate) fn write_to_staging(&self, w: &mut W, stage: usize) -> std::io::Result<()> { - let mut out = Sink::staging(w, stage)?; - self.write_staging(&mut out)?; - out.finish() - } - - fn write_staging(&self, out: &mut Sink<'_, W>) -> std::io::Result<()> { - let (v, widen) = self.write_form(); - let psb = v.is_psb(); - out.small(|o| { - if widen { - Header { version: v, ..self.header.clone() }.write(o); - } else { - self.header.write(o); - } - o.put_len(self.color_mode_data.len() as u64, false) - })?; - out.put(&self.color_mode_data)?; - out.small(|o| resources::write_section(o, &self.resources))?; - - let in_block = matches!(self.layer_info_placement, LayerInfoPlacement::GlobalBlock { .. }); - // An entirely empty section is written as a zero length. (A section - // containing only a zero layer-info length cannot be distinguished in - // the model and is normalized to this form.) - let section_empty = - self.layer_info.is_none() && self.global_layer_mask.is_none() && self.global_blocks.is_empty() && self.layer_mask_trailing.is_empty(); - let at = out.begin_len(psb)?; - if !section_empty { - let li = out.begin_len(psb)?; - if let (Some(info), false) = (&self.layer_info, in_block) { - info.write_body_to(out, v, widen)?; - } - out.end_len(li, psb)?; - let need_mask_field = self.global_layer_mask.is_some() || !self.global_blocks.is_empty() || (in_block && self.layer_info.is_some()); - if need_mask_field { - let gm = self.global_layer_mask.as_ref().map_or(&[][..], |g| &g.data[..]); - out.small(|o| o.put_len(gm.len() as u64, false))?; - out.put(gm)?; - } - match (&self.layer_info, &self.layer_info_placement) { - (Some(info), LayerInfoPlacement::GlobalBlock { index, signature, key, padding }) => { - let (before, after) = self.global_blocks.split_at((*index).min(self.global_blocks.len())); - write_blocks_to(out, before, v, 4)?; - // Written in place: a temporary LayerInfo payload and a clone of all - // neighboring opaque blocks otherwise double the save's memory. - out.put(signature)?; - out.put(key)?; - let long = uses_long_length(v, key); - let at = out.begin_len(long)?; - let start = out.pos(); - info.write_body_to(out, v, widen)?; - let len = out.pos() - start; - out.end_len(at, long)?; - match padding { - Some(bytes) => out.put(bytes)?, - None => out.zeros(((4 - len % 4) % 4) as usize)?, - } - write_blocks_to(out, after, v, 4)?; - } - _ => write_blocks_to(out, &self.global_blocks, v, 4)?, - } - out.put(&self.layer_mask_trailing)?; - } - out.end_len(at, psb)?; - - out.small(|o| { - o.put_u16(self.image_data.compression.as_u16()); - Ok(()) - })?; - match self.merged_widened_rows(widen)? { - 0 => out.put_encoded(&self.image_data.data, self.image_data.stored.as_ref()), - rows => out.put_widened_encoded(&self.image_data.data, self.image_data.stored.as_ref(), rows), - } - } - - /// The version the file is written as, and whether its RLE count tables widen on the way - /// (a PSD model marked [`Self::write_as_psb`]). - fn write_form(&self) -> (Version, bool) { - let widen = self.write_as_psb && !self.header.version.is_psb(); - (if widen { Version::Psb } else { self.header.version }, widen) - } - - /// The version [`Self::to_bytes`] writes: PSB for a PSD model marked [`Self::write_as_psb`], - /// else `header.version`. - pub fn written_version(&self) -> Version { - self.write_form().0 - } - - /// Rows of the merged image's RLE count table that widen on write (0 when nothing widens). - fn merged_widened_rows(&self, widen: bool) -> Result { - if widen && self.image_data.compression == Compression::Rle { ImageData::layout(&self.header).rows() } else { Ok(0) } - } - - /// Bytes every RLE count table of this PSD model grows by when written as PSB; an error - /// when a table is too short for its rows. - fn rle_widening(&self) -> Result { - let mut n = 0u64; - for layer in self.layers() { - for c in &layer.channels { - match layer.widened_rows(c, true)? { - 0 => {} - rows => n = n.saturating_add(rle_widening_len(c.encoded_len(), rows)?), - } - } - } - match self.merged_widened_rows(true)? { - 0 => Ok(n), - rows => Ok(n.saturating_add(rle_widening_len(self.image_data.encoded_len(), rows)?)), - } - } - - /// The number of bytes [`Self::to_bytes`] writes, computed without serializing the channel - /// data (only the layer records, which are small, are serialized to measure them). Lets a - /// writer check a file against the 2 GB PSD limit before choosing the version. - pub fn encoded_len(&self) -> Result { - let (v, widen) = self.write_form(); - let psb = v.is_psb(); - let len_field = |long: bool| if long { 8u64 } else { 4 }; - let blocks_len = |blocks: &[TaggedBlock]| blocks.iter().fold(0u64, |n, b| n.saturating_add(b.encoded_len_aligned(v, 4) as u64)); - let body_len = |info: &LayerInfo| -> Result { - let unpadded = info.unpadded_len_as(v, widen)?; - let padding = info.padding.as_ref().map_or(unpadded % 2, |p| p.len() as u64); - Ok(unpadded.saturating_add(padding)) - }; - // Header, colour mode data, resources. - let mut n = 26u64.saturating_add(4).saturating_add(self.color_mode_data.len() as u64).saturating_add(resources::section_len(&self.resources)); - - let in_block = matches!(self.layer_info_placement, LayerInfoPlacement::GlobalBlock { .. }); - let section_empty = - self.layer_info.is_none() && self.global_layer_mask.is_none() && self.global_blocks.is_empty() && self.layer_mask_trailing.is_empty(); - n = n.saturating_add(len_field(psb)); - if !section_empty { - n = n.saturating_add(len_field(psb)); - if let (Some(info), false) = (&self.layer_info, in_block) { - n = n.saturating_add(body_len(info)?); - } - let need_mask_field = self.global_layer_mask.is_some() || !self.global_blocks.is_empty() || (in_block && self.layer_info.is_some()); - if need_mask_field { - n = n.saturating_add(4).saturating_add(self.global_layer_mask.as_ref().map_or(0, |g| g.data.len() as u64)); - } - n = n.saturating_add(blocks_len(&self.global_blocks)); - if let (Some(info), LayerInfoPlacement::GlobalBlock { key, padding, .. }) = (&self.layer_info, &self.layer_info_placement) { - let body = body_len(info)?; - let pad = padding.as_ref().map_or((4 - body % 4) % 4, |p| p.len() as u64); - n = n.saturating_add(8).saturating_add(len_field(uses_long_length(v, key))).saturating_add(body).saturating_add(pad); - } - n = n.saturating_add(self.layer_mask_trailing.len() as u64); - } - let merged = match self.merged_widened_rows(widen)? { - 0 => 0, - rows => rle_widening_len(self.image_data.encoded_len(), rows)?, - }; - Ok(n.saturating_add(2).saturating_add(self.image_data.encoded_len()).saturating_add(merged)) - } - - /// Marks a PSD model to be written as the equivalent PSB ([`Self::write_as_psb`]) without - /// touching or re-encoding any pixels: the packed RLE rows are the same in both versions, so - /// [`Self::to_bytes`] only widens the row-count tables of the layer channels and the merged - /// image (two to four bytes per row) and the length fields while it copies them out. Raw and - /// ZIP channel data is the same in both. A PSB model is left as is. - /// - /// Every RLE count table is checked first: an error leaves the model unmarked, and the write - /// cannot fail on a table later. The layer info padding is kept; a writer that pads to an - /// alignment re-pads with [`Self::pad_layer_info_to`]. - pub fn promote_to_psb(&mut self) -> Result<()> { - if self.header.version.is_psb() || self.write_as_psb { - return Ok(()); - } - self.rle_widening()?; - self.write_as_psb = true; - Ok(()) - } - - /// Pads the layer info body to a multiple of `align` bytes as it will be written (see - /// [`LayerInfo::pad_to`]), RLE count tables widened when [`Self::write_as_psb`] is set. - pub fn pad_layer_info_to(&mut self, align: u64) -> Result<()> { - let (v, widen) = self.write_form(); - if let Some(info) = &mut self.layer_info { - info.padding = Some(vec![0; info.pad_len_as(v, widen, align)?]); - } - Ok(()) - } - - /// Layer records in file order (bottom-most first); empty if none. - pub fn layers(&self) -> &[LayerRecord] { - self.layer_info.as_ref().map_or(&[], |i| &i.layers) - } - - /// Mutable layer records (creates an empty layer info if absent). - pub fn layers_mut(&mut self) -> &mut Vec { - &mut self.layer_info.get_or_insert_with(LayerInfo::default).layers - } - - /// First resource with the given id. - pub fn resource(&self, id: u16) -> Option<&ImageResource> { - self.resources.iter().find(|r| r.id == id) - } - - /// The global `Lr16` / `Lr32` / `Layr` block that should have held the layers but could not - /// be parsed, with the parse error. [`Self::from_bytes`] keeps such a block verbatim in - /// [`Self::global_blocks`] and leaves [`Self::layer_info`] `None`, so the file reads as - /// flattened; this tells a reader that its layers were lost rather than absent. - pub fn unreadable_layer_block(&self) -> Option<(&TaggedBlock, PsdError)> { - if self.layer_info.is_some() { - return None; - } - let block = self.global_blocks.iter().find(|b| matches!(&b.key, b"Lr16" | b"Lr32" | b"Layr"))?; - LayerInfo::read_body(&block.data, self.header.version).err().map(|e| (block, e)) - } - - /// First global block with the given key. - pub fn global_block(&self, key: &[u8; 4]) -> Option<&TaggedBlock> { - self.global_blocks.iter().find(|b| &b.key == key) - } - - /// ICC profile bytes (resource 1039). - pub fn icc_profile(&self) -> Option<&[u8]> { - self.resource(ids::ICC_PROFILE).map(|r| &r.data[..]) - } - - /// Resolution info (resource 1005). - pub fn resolution(&self) -> Option { - match self.resource(ids::RESOLUTION_INFO)?.parsed()? { - Ok(ResourceData::ResolutionInfo(r)) => Some(r), - _ => None, - } - } - - /// The "has real merged data" flag of resource 1057, if present. - pub fn has_real_merged_data(&self) -> Option { - match self.resource(ids::VERSION_INFO)?.parsed()? { - Ok(ResourceData::VersionInfo(v)) => Some(v.has_real_merged_data), - _ => None, - } - } - - /// Decodes the merged image into planar big-endian samples. - pub fn decode_merged(&self) -> Result> { - self.image_data.decode(&self.header) - } - - /// `true` if the merged image carries a transparency channel: its first extra channel, when - /// the layer count was stored negative or a "Saving Merged Transparency" global block (see - /// [`TaggedBlock::is_merged_transparency_marker`]) is present. Photoshop marks 32-bit documents - /// with `Mt32` and a positive layer count (psd-tools transparentbg.psd). Photoshop also names - /// the merged transparency "Transparency" and lists it first among the alpha channel names, - /// and some of its 16-bit PSBs carry no other mark (#4654): when the layers sit in a global - /// `Lr16`/`Lr32` block, that name with one name per extra channel marks it too. - /// - /// A file without layer records has one when it is marked, or unless its alpha channel names - /// account for every extra channel without "Transparency" among them: a flat file from the - /// reference editor lists only its alpha and spot channels there (psd-tools - /// cmyk-alpha-spot.psd), while writers of plain RGBA files name nothing. - pub fn merged_has_alpha(&self) -> bool { - let Some(color) = self.header.color_mode.color_channels() else { - return false; - }; - if self.header.channels <= color { - return false; - } - let marked = self.global_blocks.iter().any(TaggedBlock::is_merged_transparency_marker); - match &self.layer_info { - Some(li) => { - let in_block = matches!(self.layer_info_placement, LayerInfoPlacement::GlobalBlock { .. }); - li.merged_alpha || marked || (in_block && self.names_merged_transparency(self.header.channels - color)) - } - None => { - let names = self.alpha_channel_names(); - marked || names.len() != usize::from(self.header.channels - color) || names.first().is_some_and(|n| n == TRANSPARENCY_NAME) - } - } - } - - /// `true` when the alpha channel names hold exactly `extra` names and the first is - /// "Transparency", the reference editor's name for the merged transparency. - fn names_merged_transparency(&self, extra: u16) -> bool { - let names = self.alpha_channel_names(); - names.len() == usize::from(extra) && names.first().is_some_and(|n| n == TRANSPARENCY_NAME) - } - - /// The alpha channel names: the Unicode names (resource 1045), else the Pascal names (1006) - /// older writers and psd-tools store alone, decoded as MacRoman. Empty when the file names no channel. - pub fn alpha_channel_names(&self) -> Vec { - let mut names = Vec::new(); - if let Some(r) = self.resource(1045) { - let mut at = 0usize; - while let Some(len) = r.data.get(at..at.saturating_add(4)).and_then(|b| b.try_into().ok()).map(u32::from_be_bytes) { - at = at.saturating_add(4); - let end = (len as usize).checked_mul(2).and_then(|n| at.checked_add(n)); - let Some(units) = end.and_then(|end| r.data.get(at..end)) else { break }; - let units: Vec = units.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).collect(); - names.push(String::from_utf16_lossy(&units).trim_end_matches('\0').to_string()); - at = at.saturating_add(units.len() * 2); - } - } else if let Some(r) = self.resource(1006) { - let mut at = 0usize; - while let Some(&len) = r.data.get(at) { - let Some(name) = r.data.get(at + 1..at + 1 + usize::from(len)) else { break }; - names.push(crate::codepage::decode(name, encoding_rs::MACINTOSH)); - at += 1 + usize::from(len); - } - } - names - } - - /// Checks structural invariants that the writer relies on. - pub fn validate(&self) -> Result<()> { - self.header.validate()?; - if self.header.version == Version::Psd && (self.header.width > 30_000 || self.header.height > 30_000) { - return Err(PsdError::LimitExceeded("PSD dimensions exceed 30000; use PSB")); - } - if self.header.color_mode == ColorMode::Indexed && self.color_mode_data.len() != 768 { - return Err(PsdError::invalid("indexed color mode requires a 768-byte palette")); - } - Ok(()) - } - - /// Reads a file from disk (native targets only). - #[cfg(not(target_arch = "wasm32"))] - pub fn open(path: impl AsRef) -> std::io::Result> { - Ok(Self::from_bytes(&std::fs::read(path)?)) - } - - /// Writes the file to disk (native targets only). - #[cfg(not(target_arch = "wasm32"))] - pub fn save(&self, path: impl AsRef) -> std::io::Result<()> { - let b = self.to_bytes().map_err(std::io::Error::other)?; - std::fs::write(path, b) - } -} - -#[cfg(test)] -mod write_tests { - use super::*; - use crate::{Compression, testgen}; - use std::io::{Seek, Write}; - - /// #6607: the output is allocated once, at its exact length. A reserve a few bytes short of - /// the file made the last append double the buffer, copying the whole file once more. - #[test] - fn serializing_allocates_the_output_once() { - for case in testgen::all_cases() { - let bytes = case.file.to_bytes().unwrap(); - assert_eq!(bytes.capacity(), bytes.len(), "{}: the buffer grew past its first allocation", case.name); - } - } - - /// A stream that records the length of every write it gets. - struct Recorder { - inner: std::io::Cursor>, - writes: Vec, - } - - impl Write for Recorder { - fn write(&mut self, b: &[u8]) -> std::io::Result { - self.writes.push(b.len()); - self.inner.write(b) - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } - } - - impl Seek for Recorder { - fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result { - self.inner.seek(to) - } - } - - /// The bytes `file` streams with `stage`-byte staging, after a 3-byte prefix that must stay. - fn streamed(file: &PsdFile, stage: usize) -> Vec { - let mut w = std::io::Cursor::new(b"pre".to_vec()); - w.set_position(3); - file.write_to_staging(&mut w, stage).unwrap(); - let end = w.position(); - let mut bytes = w.into_inner(); - assert_eq!(&bytes[..3], b"pre"); - assert_eq!(end, bytes.len() as u64, "the stream must end at the file's end"); - bytes.drain(..3); - bytes - } - - /// #6607: streaming into a file writes exactly the bytes of `to_bytes`, wherever the stream - /// starts and however little is staged, so every length field is back-patched through the - /// stream (both placements of the layer info, PSD and PSB, every mode and depth). - #[test] - fn streaming_writes_the_same_bytes_with_lengths_patched_by_seeking() { - for case in testgen::all_cases() { - let want = case.file.to_bytes().unwrap(); - for stage in [0, 1, 7, 4096] { - assert!(streamed(&case.file, stage) == want, "{} stage {stage}: streamed bytes differ", case.name); - } - let mut w = std::io::Cursor::new(Vec::new()); - case.file.write_to(&mut w).unwrap(); - assert!(w.into_inner() == want, "{}: write_to differs from to_bytes", case.name); - } - } - - /// A PSD model written as PSB (its RLE count tables widened on the way out) and a model read - /// lazily from a source (its pixel data not in memory) stream the bytes `to_bytes` writes. - #[test] - fn promoted_and_source_backed_files_stream_the_same_bytes() { - for case in testgen::all_cases() { - let mut promoted = case.file.clone(); - if promoted.header.version == Version::Psd { - promoted.promote_to_psb().unwrap(); - let want = promoted.to_bytes().unwrap(); - for stage in [0, 1, 7, 4096] { - assert!(streamed(&promoted, stage) == want, "{} promoted, stage {stage}", case.name); - } - } - let bytes = case.file.to_bytes().unwrap(); - let lazy = PsdFile::from_source(crate::Source::new(bytes.clone())).unwrap(); - for stage in [0, 1, 4096] { - assert!(streamed(&lazy, stage) == bytes, "{} source-backed, stage {stage}", case.name); - } - } - } - - /// Channel data and a merged image still in their source (an imported file's, or what an - /// exporter spilled to scratch) are copied through in short reads, never read whole. - #[test] - fn source_backed_data_is_copied_in_short_reads() { - struct Reads(Vec, std::sync::Mutex); - impl crate::source::ReadAt for Reads { - fn len(&self) -> u64 { - self.0.len() as u64 - } - fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()> { - let mut most = self.1.lock().unwrap(); - *most = (*most).max(buf.len()); - self.0.as_slice().read_at(offset, buf) - } - } - let mut file = testgen::small(Version::Psd, Compression::Raw); - file.image_data = ImageData::new(Compression::Raw, vec![5; 300]); - let info = file.layer_info.as_mut().unwrap(); - info.layers[0].channels[0] = crate::layer::ChannelData::new(0, Some(Compression::Raw), vec![6; 301]); - let bytes = file.to_bytes().unwrap(); - let source = std::sync::Arc::new(Reads(bytes.clone(), std::sync::Mutex::new(0))); - let lazy = PsdFile::from_source(crate::Source::from_arc(source.clone())).unwrap(); - *source.1.lock().unwrap() = 0; - let mut w = std::io::Cursor::new(Vec::new()); - lazy.write_to(&mut w).unwrap(); - assert!(w.into_inner() == bytes); - assert!(*source.1.lock().unwrap() <= 7, "read {} bytes at once", source.1.lock().unwrap()); - } - - /// #5333: RLE data still in its source widens to PSB in short reads too, the count table and - /// then the packed rows, one consecutive pass, never the whole merged image or channel at once. - #[test] - fn source_backed_rle_widens_in_short_reads() { - struct Reads(Vec, std::sync::Mutex<(usize, Vec<(u64, usize)>)>); - impl crate::source::ReadAt for Reads { - fn len(&self) -> u64 { - self.0.len() as u64 - } - fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()> { - let mut seen = self.1.lock().unwrap(); - seen.0 = seen.0.max(buf.len()); - seen.1.push((offset, buf.len())); - self.0.as_slice().read_at(offset, buf) - } - } - let file = testgen::small(Version::Psd, Compression::Rle); - assert_eq!(file.image_data.compression, Compression::Rle); - let bytes = file.to_bytes().unwrap(); - let mut promoted = file.clone(); - promoted.promote_to_psb().unwrap(); - let want = promoted.to_bytes().unwrap(); - let source = std::sync::Arc::new(Reads(bytes, std::sync::Mutex::new((0, Vec::new())))); - let mut lazy = PsdFile::from_source(crate::Source::from_arc(source.clone())).unwrap(); - assert!(lazy.image_data.stored.is_some(), "the merged image stays in the source"); - lazy.promote_to_psb().unwrap(); - *source.1.lock().unwrap() = (0, Vec::new()); - let mut w = std::io::Cursor::new(Vec::new()); - lazy.write_to(&mut w).unwrap(); - assert!(w.into_inner() == want); - let seen = source.1.lock().unwrap(); - assert!(seen.0 <= 7, "read {} bytes at once", seen.0); - let merged = lazy.image_data.stored.as_ref().unwrap(); - let reads: Vec<_> = seen.1.iter().filter(|(at, _)| (merged.offset..merged.offset + merged.len).contains(at)).collect(); - let mut next = merged.offset; - for &&(at, n) in &reads { - assert_eq!(at, next, "the merged image is read in one consecutive pass"); - next += n as u64; - } - assert_eq!(next, merged.offset + merged.len); - } - - /// #6607: pixel data goes to the stream as it is, never through a staging copy, so a save - /// holds the model and a short buffer, not a second copy of the file. - #[test] - fn streaming_passes_channel_and_merged_data_straight_through() { - let mut file = testgen::small(Version::Psd, Compression::Raw); - let big = 3 * crate::io::STAGE_FOR_TESTS; - file.image_data = ImageData::new(Compression::Raw, vec![5; big]); - let info = file.layer_info.as_mut().unwrap(); - info.layers[0].channels[0] = crate::layer::ChannelData::new(0, Some(Compression::Raw), vec![6; big + 1]); - let mut w = Recorder { inner: std::io::Cursor::new(Vec::new()), writes: Vec::new() }; - file.write_to(&mut w).unwrap(); - assert!(w.writes.contains(&big), "merged image data was staged: {:?}", w.writes); - assert!(w.writes.contains(&(big + 1)), "channel data was staged: {:?}", w.writes); - assert!(w.writes.iter().filter(|&&n| n != big && n != big + 1).all(|&n| n < crate::io::STAGE_FOR_TESTS * 2), "{:?}", w.writes); - let bytes = w.inner.into_inner(); - assert_eq!(PsdFile::from_bytes(&bytes).unwrap(), file); - assert!(bytes == file.to_bytes().unwrap()); - } - - /// A serializer error in the middle of a stream comes back as the same `PsdError` `to_bytes` - /// reports, inside an `InvalidData` I/O error. - #[test] - fn streaming_reports_serializer_errors() { - let mut file = testgen::small(Version::Psd, Compression::Raw); - let info = file.layer_info.as_mut().unwrap(); - let layer = info.layers[0].clone(); - info.layers = vec![layer; 32768]; - let want = file.to_bytes().unwrap_err(); - let e = file.write_to(&mut std::io::Cursor::new(Vec::new())).unwrap_err(); - assert_eq!(e.kind(), std::io::ErrorKind::InvalidData); - assert_eq!(PsdError::from_io(e), want); - // A damaged count table of a promoted file fails the stream as it fails `to_bytes`. - let mut file = testgen::small(Version::Psd, Compression::Rle); - file.promote_to_psb().unwrap(); - file.image_data.data.truncate(3); - let want = file.to_bytes().unwrap_err(); - let e = file.write_to(&mut std::io::Cursor::new(Vec::new())).unwrap_err(); - assert_eq!(PsdError::from_io(e), want); - } - - /// `encoded_len` is exactly what `to_bytes` writes, for every generated file and both layer - /// info placements, with and without padding (#5285). - #[test] - fn encoded_len_matches_the_written_length() { - for case in testgen::all_cases() { - assert_eq!(case.file.encoded_len().unwrap(), case.file.to_bytes().unwrap().len() as u64, "{}", case.name); - } - for version in [Version::Psd, Version::Psb] { - for key in [*b"Lr16", *b"Layr"] { - for padding in [None, Some(vec![]), Some(vec![1, 2, 3])] { - for body_padding in [None, Some(vec![]), Some(vec![9])] { - let mut file = testgen::small(version, Compression::Rle); - file.global_blocks = vec![TaggedBlock::new(*b"zz01", vec![11]), TaggedBlock::new(*b"lnk2", vec![1; 5])]; - file.layer_info_placement = LayerInfoPlacement::GlobalBlock { index: 1, signature: *b"8BIM", key, padding: padding.clone() }; - file.layer_info.as_mut().unwrap().padding = body_padding; - file.layer_mask_trailing = vec![0; 3]; - file.resources.push(ImageResource { name: b"odd".to_vec(), ..ImageResource::new(4000, vec![1, 2, 3]) }); - assert_eq!(file.encoded_len().unwrap(), file.to_bytes().unwrap().len() as u64, "{version:?} {key:?}"); - } - } - } - } - let mut empty = testgen::small(Version::Psd, Compression::Raw); - empty.layer_info = None; - empty.global_layer_mask = None; - empty.global_blocks.clear(); - assert_eq!(empty.encoded_len().unwrap(), empty.to_bytes().unwrap().len() as u64); - } - - /// A promoted PSD writes exactly the PSB written directly from the same pixels, and reads - /// back as that PSB; the model itself stays a PSD that every reader decodes as before (#5285). - #[test] - fn promote_to_psb_writes_the_psb_written_directly() { - let cases = testgen::all_cases(); - let (psd, psb) = cases.split_at(cases.len() / 2); - for (psd, psb) in psd.iter().zip(psb) { - assert_eq!(psd.file.header.version, Version::Psd, "{}", psd.name); - let mut promoted = psd.file.clone(); - promoted.promote_to_psb().unwrap(); - assert!(promoted.write_as_psb); - assert_eq!(promoted.written_version(), Version::Psb); - let bytes = promoted.to_bytes().unwrap(); - assert!(bytes == psb.file.to_bytes().unwrap(), "{}", psd.name); - assert_eq!(promoted.encoded_len().unwrap(), bytes.len() as u64, "{}", psd.name); - assert_eq!(PsdFile::from_bytes(&bytes).unwrap(), psb.file, "{}", psd.name); - // Unchanged as a model: same header, same (two-byte) channel data. - assert_eq!(PsdFile { write_as_psb: false, ..promoted.clone() }, psd.file, "{}", psd.name); - assert_eq!(promoted.decode_merged().ok(), psd.file.decode_merged().ok(), "{}", psd.name); - } - } - - /// Re-padding a promoted model pads what is written, as `pad_to` does for a PSB. - #[test] - fn pad_layer_info_to_pads_the_written_body() { - let mut promoted = testgen::layered(Version::Psd, ColorMode::Rgb, 8, Compression::Rle); - promoted.promote_to_psb().unwrap(); - promoted.pad_layer_info_to(4).unwrap(); - let mut direct = testgen::layered(Version::Psb, ColorMode::Rgb, 8, Compression::Rle); - direct.layer_info.as_mut().unwrap().pad_to(Version::Psb, 4).unwrap(); - assert!(promoted.to_bytes().unwrap() == direct.to_bytes().unwrap()); - } - - /// A damaged RLE table is refused before anything changes: the file stays a valid PSD. - #[test] - fn promote_to_psb_is_atomic() { - let mut file = testgen::small(Version::Psd, Compression::Rle); - // The last layer with pixels ("b", two rows): its red channel loses its row-count table. - let layers = &mut file.layer_info.as_mut().unwrap().layers; - let red = layers[2].channels.iter_mut().find(|c| c.id == 0).unwrap(); - assert_eq!(red.compression, Some(Compression::Rle)); - red.data.truncate(1); - let before = file.clone(); - assert!(file.promote_to_psb().is_err()); - assert_eq!(file, before); - assert!(!file.write_as_psb); - // A table damaged after promotion fails the write instead of panicking. - let mut file = testgen::small(Version::Psd, Compression::Rle); - file.promote_to_psb().unwrap(); - file.image_data.data.truncate(3); - assert!(file.to_bytes().is_err()); - assert!(file.encoded_len().is_err()); - } - - #[test] - fn global_blocks_default_to_four_byte_padding() { - for version in [Version::Psd, Version::Psb] { - for len in 1usize..8 { - let mut file = testgen::small(version, Compression::Raw); - file.global_blocks = vec![TaggedBlock::new(*b"TEST", vec![7; len]), TaggedBlock::new(*b"NEXT", vec![8; 4])]; - let bytes = file.to_bytes().unwrap(); - let start = bytes.windows(8).position(|b| b == b"8BIMTEST").unwrap() + 12; - let next = bytes.windows(8).position(|b| b == b"8BIMNEXT").unwrap(); - assert_eq!(next - start, len.next_multiple_of(4)); - let mut expected = vec![7; len]; - expected.resize(len.next_multiple_of(4), 0); - assert_eq!(&bytes[start..start + expected.len()], expected); - assert_eq!(PsdFile::from_bytes(&bytes).unwrap(), file); - } - } - } - - #[test] - fn streamed_layer_info_equals_a_materialized_tagged_block() { - for version in [Version::Psd, Version::Psb] { - for key in [*b"Lr16", *b"Lr32", *b"Layr"] { - for index in [0, 1, 2, usize::MAX] { - for padding in [None, Some(vec![]), Some(vec![42]), Some(vec![1, 2, 3])] { - let mut file = testgen::small(version, Compression::Raw); - file.global_blocks = vec![TaggedBlock::new(*b"zz01", vec![11]), TaggedBlock::new(*b"zz02", vec![12, 13])]; - file.layer_info_placement = LayerInfoPlacement::GlobalBlock { index, signature: *b"8B64", key, padding: padding.clone() }; - // An odd body catches padding calculated against the final file offset. - file.layer_info.as_mut().unwrap().padding = Some(vec![77]); - let actual = file.to_bytes().unwrap(); - let mut materialized = file.clone(); - let mut data = Vec::new(); - materialized.layer_info.take().unwrap().write_body(&mut data, version).unwrap(); - materialized.global_blocks.insert(index.min(materialized.global_blocks.len()), TaggedBlock { signature: *b"8B64", key, data, padding }); - materialized.layer_info_placement = LayerInfoPlacement::Section; - assert_eq!(actual, materialized.to_bytes().unwrap(), "{version:?} {key:?} {index}"); - } - } - } - } - } - - /// #2926: a PSB whose ZIP merged image declares more than `MAX_DECODED_BYTES` opens without - /// inflating that stream (its layers are still usable); decoding the composite reports the limit. - #[test] - fn over_budget_zip_merged_image_opens_without_inflating() { - let mut bytes = testgen::small(Version::Psb, Compression::Zip).to_bytes().unwrap(); - // Header: height at 14, width at 18 (big-endian u32). - bytes[14..18].copy_from_slice(&300_000u32.to_be_bytes()); - bytes[18..22].copy_from_slice(&300_000u32.to_be_bytes()); - let file = PsdFile::from_bytes(&bytes).unwrap(); - assert!(!file.layers().is_empty()); - assert!(matches!(file.decode_merged(), Err(PsdError::LimitExceeded(_)))); - let (same, merged) = PsdFile::from_bytes_and_merged(&bytes, |_| true).unwrap(); - assert_eq!(same, file); - assert!(matches!(merged, Some(Err(PsdError::LimitExceeded(_))))); - } - - /// Parsing and decoding a ZIP merged image together inflates it once (the parse's stream - /// check is the decode's), with the same model, pixels and errors as the two steps apart. - #[test] - fn merged_zip_image_is_inflated_once_when_decoded_with_the_parse() { - use crate::compression::INFLATES; - let inflates = |f: &dyn Fn()| { - let before = INFLATES.with(std::cell::Cell::get); - f(); - INFLATES.with(std::cell::Cell::get) - before - }; - for compression in [Compression::Zip, Compression::ZipPrediction] { - let bytes = testgen::small(Version::Psd, compression).to_bytes().unwrap(); - let file = PsdFile::from_bytes(&bytes).unwrap(); - let pixels = file.decode_merged().unwrap(); - let apart = inflates(&|| drop(PsdFile::from_bytes(&bytes).unwrap().decode_merged().unwrap())); - let together = inflates(&|| { - let (parsed, merged) = PsdFile::from_bytes_and_merged(&bytes, |f| f.image_data.data.is_empty()).unwrap(); - assert_eq!(parsed, file); - assert_eq!(merged.unwrap().unwrap(), pixels); - }); - assert_eq!(together + 1, apart, "{compression:?}"); - let (parsed, merged) = PsdFile::from_bytes_and_merged(&bytes, |_| false).unwrap(); - assert_eq!((parsed, merged), (file, None)); - // A broken stream (its checksum) is still the parse's error. - let mut broken = bytes.clone(); - *broken.last_mut().unwrap() ^= 0xff; - let alone = PsdFile::from_bytes(&broken).unwrap_err().to_string(); - assert_eq!(PsdFile::from_bytes_and_merged(&broken, |_| true).unwrap_err().to_string(), alone); - } - } - - #[test] - fn global_layer_info_serialization_propagates_layer_limit_errors() { - let mut file = testgen::small(Version::Psd, Compression::Raw); - file.layer_info = Some(LayerInfo { layers: vec![LayerRecord::default(); 32768], ..Default::default() }); - file.layer_info_placement = LayerInfoPlacement::GlobalBlock { index: usize::MAX, signature: *b"8BIM", key: *b"Lr16", padding: None }; - assert!(matches!(file.to_bytes(), Err(PsdError::LimitExceeded(_)))); - } - - #[test] - fn global_layers_preserve_order_padding_and_first_candidate() { - for version in [Version::Psd, Version::Psb] { - for depth in [16, 32] { - let mut file = testgen::layered(version, ColorMode::Rgb, depth, Compression::Raw); - let key = if depth == 16 { *b"Lr16" } else { *b"Lr32" }; - file.global_blocks = vec![TaggedBlock::new(*b"BEFR", vec![1]), TaggedBlock::new(*b"AFTR", vec![2, 3])]; - file.layer_info_placement = LayerInfoPlacement::GlobalBlock { index: 1, signature: *b"8B64", key, padding: Some(vec![7, 8]) }; - file.layer_mask_trailing = vec![9; 4]; - let bytes = file.to_bytes().unwrap(); - let parsed = PsdFile::from_bytes(&bytes).unwrap(); - assert_eq!(parsed, file); - assert_eq!(parsed.to_bytes().unwrap(), bytes); - let mut duplicate = Vec::new(); - file.layer_info.as_ref().unwrap().write_body(&mut duplicate, version).unwrap(); - file.global_blocks.push(TaggedBlock::new(key, duplicate)); - assert_eq!(PsdFile::from_bytes(&file.to_bytes().unwrap()).unwrap(), file); - file.global_blocks.insert(0, TaggedBlock::new(key, vec![255])); - let bytes = file.to_bytes().unwrap(); - let parsed = PsdFile::from_bytes(&bytes).unwrap(); - assert!(parsed.layer_info.is_none()); - assert_eq!(parsed.global_blocks.len(), 5); - assert_eq!(parsed.to_bytes().unwrap(), bytes); - } - } - } - - #[test] - fn global_layers_prioritized_over_compatibility_section() { - for version in [Version::Psd, Version::Psb] { - for depth in [16, 32] { - let file = testgen::layered(version, ColorMode::Rgb, depth, Compression::Raw); - let key = if depth == 16 { *b"Lr16" } else { *b"Lr32" }; - let mut lr_data = Vec::new(); - file.layer_info.as_ref().unwrap().write_body(&mut lr_data, version).unwrap(); - - // Photoshop writes an empty (or 8-bit compatibility) Layer Info section - // alongside the global Lr16/Lr32 block (#4928). - let mut compat_file = file.clone(); - compat_file.layer_info = - Some(LayerInfo { layers: vec![LayerRecord { name: b"CompatibilityLayer".to_vec(), ..Default::default() }], ..Default::default() }); - compat_file.layer_info_placement = LayerInfoPlacement::Section; - compat_file.global_blocks.insert(0, TaggedBlock::new(key, lr_data)); - - let bytes = compat_file.to_bytes().unwrap(); - let parsed = PsdFile::from_bytes(&bytes).unwrap(); - - assert_eq!(parsed.layers().len(), file.layers().len()); - assert_ne!(parsed.layers()[0].name(), "CompatibilityLayer"); - assert_eq!(parsed.layers()[0].name(), file.layers()[0].name()); - assert!(matches!(parsed.layer_info_placement, LayerInfoPlacement::GlobalBlock { key: k, .. } if k == key)); - } - } - } - - /// Without layer records, the extra channels hold a merged transparency unless the alpha - /// channel names (1045, else 1006) name each of them and none first as "Transparency". - #[test] - fn a_flat_file_names_its_extra_channels() { - let mut file = testgen::small(Version::Psd, Compression::Raw); - file.layer_info = None; - file.header.channels = 5; - file.resources.retain(|r| r.id != 1045 && r.id != 1006); - assert!(file.merged_has_alpha(), "nothing named: a plain RGBA file"); - let pascal = |names: &[&str]| names.iter().flat_map(|n| std::iter::once(n.len() as u8).chain(n.bytes())).collect::>(); - let unicode = |names: &[&str]| { - names - .iter() - .flat_map(|n| (n.encode_utf16().count() as u32).to_be_bytes().into_iter().chain(n.encode_utf16().flat_map(u16::to_be_bytes))) - .collect::>() - }; - for (names, transparency) in - [(&["Spot", "Alpha 1"][..], false), (&["Transparency", "Alpha 1"][..], true), (&["Alpha 1"][..], true), (&["A", "B", "C"][..], true)] - { - let mut p = file.clone(); - p.resources.push(ImageResource::new(1006, pascal(names))); - assert_eq!(p.merged_has_alpha(), transparency, "1006 {names:?}"); - assert_eq!(p.alpha_channel_names(), names, "1006"); - let mut u = file.clone(); - u.resources.push(ImageResource::new(1045, unicode(names))); - assert_eq!(u.merged_has_alpha(), transparency, "1045 {names:?}"); - assert_eq!(u.alpha_channel_names(), names, "1045"); - } - // A merged-transparency marker wins over a complete list of names. - let mut marked = file.clone(); - marked.resources.push(ImageResource::new(1006, pascal(&["Spot", "Alpha 1"]))); - marked.global_blocks.push(TaggedBlock::new(*b"Mt32", Vec::new())); - assert!(marked.merged_has_alpha()); - // Truncated names stop at the damage. - let mut cut = file.clone(); - cut.resources.push(ImageResource::new(1006, vec![9, b'a'])); - assert!(cut.alpha_channel_names().is_empty()); - assert!(cut.merged_has_alpha()); - } - - #[test] - fn pascal_channel_names_use_mac_roman_and_unicode_takes_precedence() { - let mut file = testgen::small(Version::Psd, Compression::Raw); - file.resources.retain(|r| !matches!(r.id, 1006 | 1045)); - file.resources.push(ImageResource::new(1006, b"\x04caf\x8e\x03x".to_vec())); - assert_eq!(file.alpha_channel_names(), ["café"]); - file.resources.push(ImageResource::new(1045, vec![0, 0, 0, 1, 0, b'Z'])); - assert_eq!(file.alpha_channel_names(), ["Z"]); - } - - /// A positive layer count plus a merged-transparency marker still makes the first extra - /// channel the transparency, for the specification's keys and for the `MTrn` Photoshop - /// writes in a layered TIFF. - #[test] - fn merged_transparency_markers_mark_the_first_extra_channel() { - let mut file = testgen::small(Version::Psd, Compression::Raw); - if let Some(li) = &mut file.layer_info { - li.merged_alpha = false; - } - assert!(!file.merged_has_alpha()); - for key in [*b"Mtrn", *b"MTrn", *b"Mt16", *b"Mt32"] { - let mut marked = file.clone(); - marked.global_blocks.push(TaggedBlock::new(key, Vec::new())); - assert!(marked.merged_has_alpha(), "{}", String::from_utf8_lossy(&key)); - } - // Other keys, and the marker's letters in another case, do not. - for key in [*b"MTRN", *b"mtrn", *b"Lr16"] { - let mut other = file.clone(); - other.global_blocks.push(TaggedBlock::new(key, Vec::new())); - assert!(!other.merged_has_alpha(), "{}", String::from_utf8_lossy(&key)); - } - } - #[test] - fn preflight_refusal_precedes_merged_validation_and_cannot_be_recovered() { - let file = testgen::small(Version::Psd, Compression::Zip); - let mut bytes = file.to_bytes().unwrap(); - bytes.truncate(bytes.len() - file.image_data.data.len() - 2); - let recover_called = std::cell::Cell::new(false); - let preflight = |_: &PsdFile| Err(PsdError::LimitExceeded("test import budget")); - let recover = |_: &PsdFile| { - recover_called.set(true); - true - }; - assert!(matches!(PsdFile::from_bytes_and_merged_preflight(&bytes, preflight, recover), Err(PsdError::LimitExceeded("test import budget")))); - assert!(matches!( - PsdFile::from_source_and_merged_preflight(crate::Source::new(bytes), preflight, recover), - Err(PsdError::LimitExceeded("test import budget")) - )); - assert!(!recover_called.get()); - } -} diff --git a/crates/psd/src/filter_effects.rs b/crates/psd/src/filter_effects.rs deleted file mode 100644 index cadb3ac8d0..0000000000 --- a/crates/psd/src/filter_effects.rs +++ /dev/null @@ -1,344 +0,0 @@ -//! Smart-filter caches: the global `FEid` / `FXid` ("Filter Effects") block. -//! -//! Layout (Adobe PSD spec, "Filter Effects", checked against Photoshop-authored files): -//! -//! ```text -//! u32 version (1..=3), then one section per smart object, each padded with zeros to a multiple -//! of 4 bytes (the padding is not counted in its length): -//! u64 length, then until that length is used up: -//! Pascal identifier (the smart object's `placed` id in its `SoLd` descriptor, unpadded) -//! u32 item version (1), u64 item length, then inside the item: -//! rect (top, left, bottom, right), u32 depth, u32 max channels, -//! max channels + 2 slots: u32 written flag; if set u64 length, u16 compression, data -//! after the item: u8 flag; if set rect, u64 length, u16 compression, data -//! ``` -//! -//! Photoshop puts one item in each section. Files written by earlier PhotoCraft versions put -//! every item in one section; both read. -//! -//! The slots hold the unfiltered placed pixels (colour channels from slot 0, transparency in the -//! last slot) and the trailing image is the filter mask, in document coordinates. RLE row counts -//! are four bytes wide (PSB style) in every file version. - -use crate::compression::{Compression, PlaneLayout, decode_planes, encode_planes}; -use crate::error::{PsdError, Result}; -use crate::header::Version; -use crate::io::{Reader, WriteExt, read_pascal, write_pascal}; -use crate::layer::Rect; - -/// Most slots an item may declare (Photoshop writes 24 channels + 2). -pub(crate) const MAX_SLOTS: u32 = 64; - -/// One compressed plane of a filter-effects item. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct EffectsPlane { - /// Compression of `data`. - pub compression: Compression, - /// Encoded data (without the compression field). - pub data: Vec, -} - -impl EffectsPlane { - /// Encodes one plane of `w × h` big-endian samples of `depth` bits (RLE uses four-byte counts). - pub fn encode(compression: Compression, decoded: &[u8], w: usize, h: usize, depth: u16) -> Result { - let layout = PlaneLayout { planes: 1, width: w, height: h, depth, version: Version::Psb }; - Ok(EffectsPlane { compression, data: encode_planes(compression, decoded, &layout)? }) - } - - /// Decodes into `w × h` big-endian samples of `depth` bits. A size the encoded data can't - /// possibly hold (PackBits expands at most 64×, zlib about 1032×) is refused before any - /// allocation, so a tiny corrupt block can't ask for gigabytes. - pub fn decode(&self, w: usize, h: usize, depth: u16) -> Result> { - let layout = PlaneLayout { planes: 1, width: w, height: h, depth, version: Version::Psb }; - let n = self.data.len() as u64; - let most = match self.compression { - Compression::Raw => n, - Compression::Rle => n.saturating_mul(64), - _ => n.saturating_mul(1032).saturating_add(64), - }; - if layout.total_bytes()? > most { - return Err(PsdError::invalid("filter effects: plane larger than its data can hold")); - } - decode_planes(self.compression, &self.data, &layout) - } -} - -/// The cache of one smart object's filters. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct FilterEffectsItem { - /// The smart object's `placed` id. - pub id: String, - /// Item version (1). - pub version: u32, - /// Bounds of the cached planes. - pub rect: Rect, - /// Bits per sample. - pub depth: u32, - /// Declared channel count; there are `max_channels + 2` slots. - pub max_channels: u32, - /// The slots (`None` = not written). - pub slots: Vec>, - /// The filter mask: bounds and plane. - pub mask: Option<(Rect, EffectsPlane)>, -} - -impl FilterEffectsItem { - /// The decoded filter mask (8/16/32-bit big-endian samples) with its bounds. - pub fn decoded_mask(&self) -> Option<(Rect, Vec)> { - let (r, p) = self.mask.as_ref()?; - let (w, h) = r.size().ok()?; - let depth = u16::try_from(self.depth).ok()?; - Some((*r, p.decode(w, h, depth).ok()?)) - } -} - -/// A parsed `FEid`/`FXid` block. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct FilterEffects { - /// Block version (1..=3). - pub version: u32, - /// One item per smart object with filters. - pub items: Vec, -} - -fn read_rect(r: &mut Reader<'_>) -> Result { - Ok(Rect { top: r.i32()?, left: r.i32()?, bottom: r.i32()?, right: r.i32()? }) -} - -fn write_rect(out: &mut Vec, r: &Rect) { - out.put_i32(r.top); - out.put_i32(r.left); - out.put_i32(r.bottom); - out.put_i32(r.right); -} - -fn read_plane(r: &mut Reader<'_>) -> Result { - let len = r.u64()?; - if len < 2 { - return Err(PsdError::invalid("filter effects: plane shorter than its compression field")); - } - let mut sub = r.sub(len)?; - let compression = Compression::from_u16(sub.u16()?); - Ok(EffectsPlane { compression, data: sub.peek_rest().to_vec() }) -} - -/// One item: identifier, the cached planes and the filter mask after them. -fn read_item(body: &mut Reader<'_>) -> Result { - let id = String::from_utf8_lossy(&read_pascal(body, 1)?).into_owned(); - let version = body.u32()?; - let item_len = body.u64()?; - let mut it = body.sub(item_len)?; - let rect = read_rect(&mut it)?; - let depth = it.u32()?; - let max_channels = it.u32()?; - if max_channels > MAX_SLOTS { - return Err(PsdError::LimitExceeded("filter effects: too many channels")); - } - let mut slots = Vec::with_capacity(max_channels as usize + 2); - for _ in 0..max_channels + 2 { - slots.push(if it.u32()? != 0 { Some(read_plane(&mut it)?) } else { None }); - } - if !it.is_empty() { - return Err(PsdError::invalid(format!("filter effects item {id}: {} unexpected bytes", it.remaining()))); - } - let mask = if body.is_empty() || body.u8()? == 0 { None } else { Some((read_rect(body)?, read_plane(body)?)) }; - Ok(FilterEffectsItem { id, version, rect, depth, max_channels, slots, mask }) -} - -fn write_plane(out: &mut Vec, p: &EffectsPlane) { - out.put_u64(p.data.len() as u64 + 2); - out.put_u16(p.compression.as_u16()); - out.put(&p.data); -} - -impl FilterEffects { - /// Parses block data. Trailing zero padding is allowed. - pub fn parse(data: &[u8]) -> Result { - let mut r = Reader::new(data); - let version = r.u32()?; - if !(1..=3).contains(&version) { - return Err(PsdError::invalid(format!("filter effects version {version}"))); - } - let mut items = Vec::new(); - loop { - let len = r.u64()?; - let mut body = r.sub(len)?; - while !body.is_empty() { - items.push(read_item(&mut body)?); - } - // Sections are padded to 4 bytes; the last one's padding may be cut short. - let pad = ((4 - len % 4) % 4).min(r.remaining() as u64); - r.skip(pad as usize)?; - let rest = r.peek_rest(); - // Padding is at most three bytes. Check the length before scanning the suffix for - // zeros: otherwise each iteration scans the whole remaining buffer, which is - // quadratic when a block contains many empty sections. - if rest.len() <= 3 && rest.iter().all(|&b| b == 0) { - break; - } - if rest.len() < 8 { - return Err(PsdError::invalid(format!("filter effects: {} unexpected bytes after the data", rest.len()))); - } - } - Ok(FilterEffects { version, items }) - } - - /// Serializes block data as Photoshop writes it: one section per item, each padded to 4 bytes. - pub fn to_bytes(&self) -> Vec { - let mut out = Vec::new(); - out.put_u32(self.version); - for it in &self.items { - let mut body = Vec::new(); - write_pascal(&mut body, it.id.as_bytes(), 1); - body.put_u32(it.version); - let at = body.begin_len(true); - write_rect(&mut body, &it.rect); - body.put_u32(it.depth); - body.put_u32(it.max_channels); - for i in 0..it.max_channels as usize + 2 { - match it.slots.get(i).and_then(Option::as_ref) { - Some(p) => { - body.put_u32(1); - write_plane(&mut body, p); - } - None => body.put_u32(0), - } - } - // A 64-bit length never overflows. - let _ = body.end_len(at, true); - match &it.mask { - Some((r, p)) => { - body.put_u8(1); - write_rect(&mut body, r); - write_plane(&mut body, p); - } - None => body.put_u8(0), - } - out.put_u64(body.len() as u64); - out.put(&body); - out.resize(out.len().next_multiple_of(4), 0); - } - if self.items.is_empty() { - // One empty section, so the block still parses. - out.put_u64(0); - } - out - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn item(id: &str, mask: bool) -> FilterEffectsItem { - let rect = Rect { top: 1, left: 2, bottom: 5, right: 6 }; - let plane = |v: u8| EffectsPlane::encode(Compression::Rle, &[v; 16], 4, 4, 8).unwrap(); - let mut slots = vec![None; 26]; - slots[0] = Some(plane(10)); - slots[25] = Some(plane(255)); - FilterEffectsItem { id: id.into(), version: 1, rect, depth: 8, max_channels: 24, slots, mask: mask.then(|| (rect, plane(128))) } - } - - /// The unpadded body of `it`'s section. - fn section(it: &FilterEffectsItem) -> Vec { - let b = FilterEffects { version: 3, items: vec![it.clone()] }.to_bytes(); - let len = u64::from_be_bytes(b[4..12].try_into().unwrap()) as usize; - b[12..12 + len].to_vec() - } - - #[test] - fn round_trips() { - let fx = FilterEffects { version: 3, items: vec![item("a-1", true), item("b-2", false)] }; - let bytes = fx.to_bytes(); - let back = FilterEffects::parse(&bytes).unwrap(); - assert_eq!(back, fx); - assert_eq!(back.items[0].decoded_mask().unwrap().1, vec![128; 16]); - assert_eq!(back.items[0].slots[0].as_ref().unwrap().decode(4, 4, 8).unwrap(), vec![10; 16]); - // No items still writes a section, so the block reads back. - let empty = FilterEffects { version: 3, items: Vec::new() }; - assert_eq!(FilterEffects::parse(&empty.to_bytes()).unwrap(), empty); - // Padding is allowed, garbage is not. - let mut padded = bytes.clone(); - padded.extend([0, 0]); - assert!(FilterEffects::parse(&padded).is_ok()); - padded.push(7); - assert!(FilterEffects::parse(&padded).is_err()); - } - - /// Photoshop writes one length-prefixed section per smart object, each padded to 4 bytes - /// outside its length. A document with two filtered smart objects has two sections. - #[test] - fn reads_one_section_per_item() { - let (a, b) = (item("a-1", true), item("b-2", false)); - let (sa, sb) = (section(&a), section(&b)); - assert_ne!(sa.len() % 4, 0, "the first section must need padding"); - let mut bytes = 3u32.to_be_bytes().to_vec(); - for s in [&sa, &sb] { - bytes.extend((s.len() as u64).to_be_bytes()); - bytes.extend(s.iter()); - bytes.resize(bytes.len().next_multiple_of(4), 0); - } - let fx = FilterEffects::parse(&bytes).unwrap(); - assert_eq!(fx.items, vec![a, b]); - // Written back the same way, byte for byte. - assert_eq!(fx.to_bytes(), bytes); - } - - /// Older PhotoCraft files hold every item in one section; they still read. - #[test] - fn reads_several_items_in_one_section() { - let items = vec![item("a-1", true), item("b-2", false)]; - let mut body = Vec::new(); - for it in &items { - body.extend(section(it)); - } - let mut bytes = 3u32.to_be_bytes().to_vec(); - bytes.extend((body.len() as u64).to_be_bytes()); - bytes.extend(&body); - assert_eq!(FilterEffects::parse(&bytes).unwrap().items, items); - } - - #[test] - fn mutations_never_panic() { - let bytes = FilterEffects { version: 3, items: vec![item("x", true), item("y", false)] }.to_bytes(); - let mut state = 0x9E37_79B9_7F4A_7C15u64; - let mut next = || { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - state - }; - for _ in 0..2000 { - let mut b = bytes.clone(); - for _ in 0..1 + next() % 4 { - let i = (next() as usize) % b.len(); - b[i] = next() as u8; - } - if let Ok(fx) = FilterEffects::parse(&b) { - for it in &fx.items { - let _ = it.decoded_mask(); - for p in it.slots.iter().flatten() { - let _ = p.decode(4, 4, 8); - } - } - let _ = fx.to_bytes(); - } - } - } - - #[test] - fn malformed_data_is_an_error() { - let bytes = FilterEffects { version: 3, items: vec![item("x", true)] }.to_bytes(); - // Cut anywhere before the end of the section (only its padding may be missing). - for n in 0..12 + section(&item("x", true)).len() { - assert!(FilterEffects::parse(&bytes[..n]).is_err(), "truncated at {n}"); - } - let mut bad = bytes.clone(); - bad[3] = 9; // version - assert!(FilterEffects::parse(&bad).is_err()); - let mut huge = bytes; - let at = 4 + 8 + 2 + 4 + 8 + 16 + 4; // max channels - huge[at..at + 4].copy_from_slice(&u32::MAX.to_be_bytes()); - assert!(FilterEffects::parse(&huge).is_err()); - } -} diff --git a/crates/psd/src/fixtures.rs b/crates/psd/src/fixtures.rs deleted file mode 100644 index a8bd3d43c9..0000000000 --- a/crates/psd/src/fixtures.rs +++ /dev/null @@ -1,566 +0,0 @@ -//! Large-file stress fixtures (#216, #375, #5107), generated at test time and never committed. -//! -//! Two kinds: -//! -//! * [`Streamed`]: multi-gigabyte PSD/PSB files written straight from the Adobe PSD spec, row by -//! row, independent of [`PsdBuilder`] (so they don't inherit its limits, and the generator needs -//! a few megabytes of memory however large the file). One full-canvas layer (or none) plus the -//! merged image; every sample follows [`sample`], so a reader can check any pixel without the -//! file. [`PSD_2GB`] is the largest file Photoshop saves as PSD; [`PSB_CASES`] are 2.5–5 GB. -//! * [`Grid`]: layered documents built with [`PsdBuilder`]: a background and a grid of layers in -//! groups, with masks, a hidden layer, a closed group and drop shadows. [`LAYERED_20MP`] is the -//! 20 MP photo-sized document, [`LAYOUT_150`] the 150-layer A4 layout. [`Grid::expected`] is -//! the merged colour at any point away from the shadows ([`Grid::sample_points`] lists some). -//! -//! Photoshop's limits, which the presets respect: a PSD is at most 30,000 px a side and 2 GB; a -//! PSB at most 300,000 px a side. - -use std::io::{self, Write}; - -use crate::builder::{GroupSpec, LayerSpec, MaskSpec, PixelData, PsdBuilder}; -use crate::descriptor::{Descriptor, Id, Value, VersionedDescriptor}; -use crate::error::Result; -use crate::file::PsdFile; -use crate::header::Version; -use crate::layer::Rect; -use crate::tagged::TaggedBlock; - -/// Photoshop's PSD size cap: files of 2 GB or more must be PSB. -pub const PSD_MAX_FILE_BYTES: u64 = 2 * 1024 * 1024 * 1024; -/// Photoshop's PSD side cap (px). -pub const PSD_MAX_SIDE: u32 = 30_000; - -/// The 8-bit sample of channel `c` (0..3 colour, 3 = alpha) at (`x`, `y`) in a [`Streamed`] file. -/// RLE files ignore `x` (constant rows compress to almost nothing). 16-bit files store `v * 257`. -pub fn sample(x: u32, y: u32, c: u32, rle: bool) -> u8 { - if c == 3 { - return 255; - } - let x = if rle { 0 } else { x }; - (x.wrapping_mul(7).wrapping_add(y.wrapping_mul(13)).wrapping_add(c.wrapping_mul(101)) & 0xff) as u8 -} - -/// A large RGB file written row by row. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Streamed { - /// File stem, e.g. `layer8-25k-raw`. - pub name: &'static str, - /// PSD (v1) or PSB (v2). - pub version: Version, - /// Width (px). - pub width: u32, - /// Height (px). - pub height: u32, - /// 8 or 16. - pub depth: u16, - /// RLE (PackBits) or raw. - pub rle: bool, - /// One full-canvas RGBA layer, or a flattened file (merged image only). - pub layered: bool, -} - -const fn psb(name: &'static str, side: u32, depth: u16, rle: bool, layered: bool) -> Streamed { - Streamed { name, version: Version::Psb, width: side, height: side, depth, rle, layered } -} - -/// A 2.02 GB layered PSD just under Photoshop's 2 GB cap: 17,000² px, one raw full-canvas layer -/// (289 MB per channel) and the raw merged image. -pub const PSD_2GB: Streamed = - Streamed { name: "psd-layer8-17k-raw", version: Version::Psd, width: 17_000, height: 17_000, depth: 8, rle: false, layered: true }; - -/// The 4–5 GB PSB generated for #375 and #216. -pub const PSB_CASES: [Streamed; 5] = [ - // Composite of 2.52 GB in one decode. - psb("flat8-29k-rle", 29_000, 8, true, false), - // A 4.8 GB file: offsets past 4 GiB, composite of 4.8 GB. - psb("flat8-40k-raw", 40_000, 8, false, false), - // 4.38 GB file: layer channels of 625 MB, composite of 1.9 GB, data past 4 GiB. - PSB_4GB, - // Layer channels of 900 MB, composite of 2.7 GB. - psb("layer8-30k-rle", 30_000, 8, true, true), - // Layer channels of 2.18 GB each. - psb("layer16-33k-rle", 33_000, 16, true, true), -]; - -/// The layered 4.38 GB PSB (25,000² px, raw): layer data and the merged image past 4 GiB. -pub const PSB_4GB: Streamed = psb("layer8-25k-raw", 25_000, 8, false, true); - -/// PackBits for a row of `n` equal bytes: runs of 128, then the remainder. -fn rle_row(n: u64, b: u8) -> Vec { - let mut v = Vec::new(); - let mut left = n; - while left > 0 { - let run = left.min(128); - // `run` is 1..=128, so 257 - run is 129..=256 and only 256 (run 1) needs the literal form. - if run == 1 { - v.extend_from_slice(&[0, b]); - } else { - v.extend_from_slice(&[(257 - run) as u8, b]); - } - left -= run; - } - v -} - -fn too_big(what: &str) -> io::Error { - io::Error::new(io::ErrorKind::InvalidInput, format!("{what} does not fit a PSD (v1) length field")) -} - -impl Streamed { - /// File name with the right extension. - pub fn file_name(&self) -> String { - format!("{}.{}", self.name, if self.version == Version::Psb { "psb" } else { "psd" }) - } - - fn psb(&self) -> bool { - self.version == Version::Psb - } - - fn row_bytes(&self) -> u64 { - u64::from(self.width) * u64::from(self.depth / 8) - } - - /// Bytes of one RLE row (all rows have the same length). - fn rle_len(&self) -> u64 { - rle_row(self.row_bytes(), 0).len() as u64 - } - - /// Size of a channel block (compression word, RLE counts, rows) of `planes` planes. - fn channel_len(&self, planes: u64) -> u64 { - let rows = planes * u64::from(self.height); - let count = if self.psb() { 4 } else { 2 }; - if self.rle { 2 + rows * count + rows * self.rle_len() } else { 2 + rows * self.row_bytes() } - } - - /// Writes a length field: 8 bytes in PSB, 4 in PSD. - fn put_len(&self, out: &mut Vec, v: u64, what: &str) -> io::Result<()> { - if self.psb() { - out.extend_from_slice(&v.to_be_bytes()); - } else { - out.extend_from_slice(&u32::try_from(v).map_err(|_| too_big(what))?.to_be_bytes()); - } - Ok(()) - } - - /// The layer record of the one layer: transparency (-1), then R, G, B. - fn layer_record(&self) -> io::Result> { - let ch_len = self.channel_len(1); - let name = b"Layer 1"; - let mut rec = Vec::new(); - for v in [0, 0, self.height, self.width] { - rec.extend_from_slice(&v.to_be_bytes()); - } - rec.extend_from_slice(&4u16.to_be_bytes()); - for id in [-1i16, 0, 1, 2] { - rec.extend_from_slice(&id.to_be_bytes()); - self.put_len(&mut rec, ch_len, "a layer channel")?; - } - rec.extend_from_slice(b"8BIMnorm"); - rec.extend_from_slice(&[255, 0, 0, 0]); - // Extra data: no mask, no blending ranges, the Pascal name padded to 4. - let mut extra = Vec::new(); - extra.extend_from_slice(&0u32.to_be_bytes()); - extra.extend_from_slice(&0u32.to_be_bytes()); - extra.push(name.len() as u8); - extra.extend_from_slice(name); - while extra.len() % 4 != 0 { - extra.push(0); - } - rec.extend_from_slice(&(extra.len() as u32).to_be_bytes()); - rec.extend_from_slice(&extra); - Ok(rec) - } - - /// The header, the empty colour-mode and resource sections and the layer section's head - /// (everything before the first channel's data), plus the padding after the layer channels. - fn head(&self) -> io::Result<(Vec, u64)> { - let mut h = Vec::new(); - h.extend_from_slice(b"8BPS"); - h.extend_from_slice(&(if self.psb() { 2u16 } else { 1 }).to_be_bytes()); - h.extend_from_slice(&[0; 6]); - h.extend_from_slice(&3u16.to_be_bytes()); - h.extend_from_slice(&self.height.to_be_bytes()); - h.extend_from_slice(&self.width.to_be_bytes()); - h.extend_from_slice(&self.depth.to_be_bytes()); - h.extend_from_slice(&3u16.to_be_bytes()); - // Colour mode data and image resources: empty. - h.extend_from_slice(&0u32.to_be_bytes()); - h.extend_from_slice(&0u32.to_be_bytes()); - if !self.layered { - self.put_len(&mut h, 0, "the layer section")?; - return Ok((h, 0)); - } - let rec = self.layer_record()?; - let mut layer_info = 2 + rec.len() as u64 + 4 * self.channel_len(1); - let pad = layer_info % 2; - layer_info += pad; - let len_field = if self.psb() { 8 } else { 4 }; - // Layer and mask information: layer info (with its length) + empty global mask (4 bytes). - self.put_len(&mut h, len_field + layer_info + 4, "the layer section")?; - self.put_len(&mut h, layer_info, "the layer info")?; - h.extend_from_slice(&1i16.to_be_bytes()); - h.extend_from_slice(&rec); - Ok((h, pad)) - } - - /// The exact size of the file [`write_to`](Self::write_to) writes, without writing it. - pub fn file_len(&self) -> io::Result { - let (head, pad) = self.head()?; - let layers = if self.layered { 4 * self.channel_len(1) + pad + 4 } else { 0 }; - Ok(head.len() as u64 + layers + self.channel_len(3)) - } - - /// The bytes of one row of channel `ch`. - fn row(&self, y: u32, ch: u32, buf: &mut Vec) { - buf.clear(); - if self.rle { - buf.extend(rle_row(self.row_bytes(), sample(0, y, ch, true))); - return; - } - for x in 0..self.width { - let s = sample(x, y, ch, false); - buf.push(s); - if self.depth == 16 { - buf.push(s); - } - } - } - - /// Writes the compression word, the counts and the rows of `chans`. - fn write_planes(&self, w: &mut impl Write, chans: &[u32]) -> io::Result<()> { - w.write_all(&u16::from(self.rle).to_be_bytes())?; - if self.rle { - let n = self.rle_len(); - let one = if self.psb() { - u32::try_from(n).map_err(|_| too_big("an RLE row"))?.to_be_bytes().to_vec() - } else { - u16::try_from(n).map_err(|_| too_big("an RLE row"))?.to_be_bytes().to_vec() - }; - for _ in 0..chans.len() as u64 * u64::from(self.height) { - w.write_all(&one)?; - } - } - let mut buf = Vec::new(); - for &ch in chans { - for y in 0..self.height { - self.row(y, ch, &mut buf); - w.write_all(&buf)?; - } - } - Ok(()) - } - - /// Streams the file into `w` (buffer it). Returns the bytes written. A PSD whose lengths - /// don't fit its 32-bit fields is refused before anything is written. - pub fn write_to(&self, w: &mut impl Write) -> io::Result { - let len = self.file_len()?; - let (head, pad) = self.head()?; - w.write_all(&head)?; - if self.layered { - // Transparency, then R, G, B. - for ch in [3, 0, 1, 2] { - self.write_planes(w, &[ch])?; - } - w.write_all(&vec![0; pad as usize])?; - w.write_all(&0u32.to_be_bytes())?; - } - self.write_planes(w, &[0, 1, 2])?; - w.flush()?; - Ok(len) - } - - /// Writes the file to `path` (created or truncated). Returns its size. - #[cfg(not(target_arch = "wasm32"))] - pub fn write_file(&self, path: &std::path::Path) -> io::Result { - let mut w = io::BufWriter::with_capacity(8 << 20, std::fs::File::create(path)?); - self.write_to(&mut w) - } - - /// The 8-bit value of channel `c` (3 = alpha) at (`x`, `y`): the layer's and the merged - /// image's (they are the same). - pub fn sample(&self, x: u32, y: u32, c: u32) -> u8 { - sample(x, y, c, self.rle) - } -} - -/// A layered document: a background and a grid of layers, one group per grid row. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Grid { - /// Canvas width (px). - pub width: u32, - /// Canvas height (px). - pub height: u32, - /// Layers in the grid (the background is extra). - pub layers: u32, - /// Grid columns; a group per row of `cols` layers. - pub cols: u32, -} - -/// A 20 MP (5472 × 3648) layered photo: background, 5 layers in 2 groups (one closed), a -/// mask and a drop shadow. -pub const LAYERED_20MP: Grid = Grid { width: 5472, height: 3648, layers: 5, cols: 3 }; - -/// A 150-layer A4 layout at 300 ppi (2480 × 3508): background + 149 layers in 15 groups, with -/// masks, hidden layers, closed groups and drop shadows. -pub const LAYOUT_150: Grid = Grid { width: 2480, height: 3508, layers: 149, cols: 10 }; - -/// What a grid layer carries. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct GridLayer { - /// Bounds in document coordinates. - pub rect: Rect, - /// Base colour; the layer adds its local x to it (a horizontal ramp). - pub base: [u8; 3], - /// Has a mask showing only the left half. - pub masked: bool, - /// Hidden. - pub hidden: bool, - /// Has a drop shadow (`lfx2`). - pub shadow: bool, -} - -/// The `lfx2` descriptor of a drop shadow: multiply, black, 75 %, 120°, distance 5, size 5. -fn drop_shadow() -> Vec { - let px = |v: f64| Value::UnitFloat { unit: *b"#Pxl", value: v }; - let color = Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)).with("Grn ", Value::Double(0.0)).with("Bl ", Value::Double(0.0)); - let shadow = Descriptor::new("DrSh") - .with("enab", Value::Boolean(true)) - .with("Md ", Value::Enumerated { type_id: Id::new("BlnM"), value: Id::new("Mltp") }) - .with("Clr ", Value::Descriptor(color)) - .with("Opct", Value::UnitFloat { unit: *b"#Prc", value: 75.0 }) - .with("uglg", Value::Boolean(false)) - .with("lagl", Value::UnitFloat { unit: *b"#Ang", value: 120.0 }) - .with("Dstn", px(5.0)) - .with("Ckmt", px(0.0)) - .with("blur", px(5.0)); - let root = Descriptor::new("null") - .with("Scl ", Value::UnitFloat { unit: *b"#Prc", value: 100.0 }) - .with("masterFXSwitch", Value::Boolean(true)) - .with("DrSh", Value::Descriptor(shadow)); - let mut data = 0u32.to_be_bytes().to_vec(); - data.extend(VersionedDescriptor::new(root).to_bytes()); - data -} - -impl Grid { - /// Grid rows (= groups). - pub fn rows(&self) -> u32 { - self.layers.div_ceil(self.cols.max(1)) - } - - fn cell(&self) -> (u32, u32) { - (self.width / self.cols.max(1), self.height / self.rows().max(1)) - } - - /// Gap between a layer and its cell's edge (larger than any shadow's reach). - fn inset(&self) -> u32 { - let (cw, ch) = self.cell(); - (cw.min(ch) / 8).max(1) - } - - /// Layer `i` of the grid (0-based, bottom to top), or `None` past the end. - pub fn layer(&self, i: u32) -> Option { - if i >= self.layers { - return None; - } - let (cw, ch) = self.cell(); - let inset = self.inset(); - let (col, row) = (i % self.cols.max(1), i / self.cols.max(1)); - let rect = - Rect::from_xywh((col * cw + inset) as i32, (row * ch + inset) as i32, cw.saturating_sub(2 * inset).max(1), ch.saturating_sub(2 * inset).max(1)); - let masked = i % 5 == 1; - let hidden = i % 13 == 12; - Some(GridLayer { - rect, - base: [(i * 37 + 20) as u8, (i * 91 + 50) as u8, (i * 53 + 90) as u8], - masked, - hidden, - shadow: i % 7 == 3 && !masked && !hidden, - }) - } - - /// Name of grid layer `i`. - pub fn layer_name(i: u32) -> String { - format!("Layer {}", i + 1) - } - - /// Name of the group of grid row `r`. - pub fn group_name(r: u32) -> String { - format!("Row {}", r + 1) - } - - /// Groups of rows `r % 4 == 3` are closed in the layers panel. - pub fn group_open(r: u32) -> bool { - r % 4 != 3 - } - - /// The background's colour at (`x`, `y`): [`sample`] in runs of 16 px (RLE has runs to find). - pub fn background(x: u32, y: u32) -> [u8; 3] { - [0, 1, 2].map(|c| sample(x / 16, y, c, false)) - } - - /// Grid layer `i`'s pixel colour at document (`x`, `y`), ignoring visibility and mask. - fn layer_color(l: &GridLayer, x: u32) -> [u8; 3] { - let lx = x.wrapping_sub(l.rect.left as u32); - l.base.map(|b| (u32::from(b) + lx) as u8) - } - - /// The merged colour at (`x`, `y`). Exact except within a few pixels of a shadowed layer's - /// edges (the merged image this generator stores leaves shadows out). - pub fn expected(&self, x: u32, y: u32) -> [u8; 3] { - let (cw, ch) = self.cell(); - let (col, row) = (x / cw.max(1), y / ch.max(1)); - if col < self.cols - && let Some(l) = self.layer(row * self.cols + col) - { - let (xi, yi) = (x as i32, y as i32); - let inside = xi >= l.rect.left && xi < l.rect.right && yi >= l.rect.top && yi < l.rect.bottom; - let shown = !l.masked || i64::from(xi) < i64::from(l.rect.left) + l.rect.width() / 2; - if inside && shown && !l.hidden { - return Self::layer_color(&l, x); - } - } - Self::background(x, y) - } - - /// Points to check, away from every shadow: in each of a few layers, its shown half, its - /// masked-out half, and the gap at its cell's corner. - pub fn sample_points(&self) -> Vec<(u32, u32)> { - let step = (self.layers / 12).max(1); - let mut v = vec![(0, 0), (self.width - 1, self.height - 1)]; - for i in (0..self.layers).step_by(step as usize) { - let Some(l) = self.layer(i) else { continue }; - let (w, h) = (l.rect.width() as u32, l.rect.height() as u32); - let (x0, y0) = (l.rect.left as u32, l.rect.top as u32); - v.push((x0 + w / 4, y0 + h / 2)); - v.push((x0 + w * 3 / 4, y0 + h / 2)); - v.push((x0 - self.inset() / 2, y0 - self.inset() / 2)); - } - v - } - - /// Builds the file (8-bit RGB, RLE): layers bottom to top, the merged image from - /// [`expected`](Self::expected). - pub fn build(&self, version: Version) -> Result { - let (w, h) = (self.width, self.height); - let mut b = PsdBuilder::new(w, h).version(version); - let mut bg = Vec::with_capacity(w as usize * h as usize * 4); - for y in 0..h { - for x in 0..w { - bg.extend(Self::background(x, y)); - bg.push(255); - } - } - b.push_layer(LayerSpec::new("Background", 0, 0, w, h, PixelData::Rgba8(bg))); - for row in 0..self.rows() { - b.begin_group(GroupSpec { open: Self::group_open(row), ..GroupSpec::new(Self::group_name(row)) }); - for i in row * self.cols..((row + 1) * self.cols).min(self.layers) { - let Some(l) = self.layer(i) else { continue }; - let (lw, lh) = (l.rect.width() as u32, l.rect.height() as u32); - let mut px = Vec::with_capacity(lw as usize * lh as usize * 4); - for _ in 0..lh { - for lx in 0..lw { - px.extend(Self::layer_color(&l, l.rect.left as u32 + lx)); - px.push(255); - } - } - let mut spec = LayerSpec::new(Self::layer_name(i), l.rect.left, l.rect.top, lw, lh, PixelData::Rgba8(px)); - spec.visible = !l.hidden; - if l.masked { - let data = (0..lh).flat_map(|_| (0..lw).map(move |x| if x < lw / 2 { 255 } else { 0 })).collect(); - spec.mask = Some(MaskSpec { rect: l.rect, data, default_color: 0, disabled: false }); - } - if l.shadow { - spec.extra_blocks.push(TaggedBlock::new(*b"lfx2", drop_shadow())); - } - b.push_layer(spec); - } - b.end_group()?; - } - let mut merged = Vec::with_capacity(w as usize * h as usize * 4); - for y in 0..h { - for x in 0..w { - merged.extend(self.expected(x, y)); - merged.push(255); - } - } - b.composite(PixelData::Rgba8(merged)); - b.build() - } -} - -#[cfg(test)] -#[allow(clippy::unwrap_used, clippy::indexing_slicing)] -mod tests { - use super::*; - - #[test] - fn presets_respect_photoshop_limits() { - let psd = PSD_2GB.file_len().unwrap(); - assert!(psd < PSD_MAX_FILE_BYTES && psd > 2_000_000_000, "{psd}"); - const { assert!(PSD_2GB.width <= PSD_MAX_SIDE && PSD_2GB.height <= PSD_MAX_SIDE) }; - for c in PSB_CASES { - assert!(c.file_len().is_ok() && c.width <= 300_000, "{}", c.name); - } - assert!(PSB_4GB.file_len().unwrap() > 4 << 30); - // A PSD too big for its 32-bit lengths is refused, not wrapped. - let huge = Streamed { width: 33_000, height: 33_000, ..PSD_2GB }; - assert!(huge.file_len().is_err()); - assert!(huge.write_to(&mut io::sink()).is_err()); - } - - /// Small streamed files parse, and their pixels are [`sample`]'s. - #[test] - fn small_streamed_files_parse() { - for version in [Version::Psd, Version::Psb] { - for (rle, layered, depth) in [(false, true, 8), (true, true, 8), (true, false, 16), (false, false, 8)] { - let c = Streamed { name: "t", version, width: 300, height: 7, depth, rle, layered }; - let mut out = Vec::new(); - let n = c.write_to(&mut out).unwrap(); - assert_eq!(n, out.len() as u64, "{c:?}"); - let file = PsdFile::from_bytes(&out).unwrap(); - let merged = file.image_data.decode(&file.header).unwrap(); - let bps = usize::from(depth / 8); - let plane = 300 * 7 * bps; - for (x, y, ch) in [(0u32, 0u32, 0u32), (299, 6, 2), (150, 3, 1)] { - let i = ch as usize * plane + (y as usize * 300 + x as usize) * bps; - assert_eq!(merged[i], c.sample(x, y, ch), "{c:?} ({x}, {y}) {ch}"); - } - assert_eq!(file.layers().len(), usize::from(layered), "{c:?}"); - } - } - } - - #[test] - fn grid_layout_is_consistent() { - for g in [LAYERED_20MP, LAYOUT_150] { - let last = g.layer(g.layers - 1).unwrap(); - assert!(last.rect.right <= g.width as i32 && last.rect.bottom <= g.height as i32); - assert!(g.layer(g.layers).is_none()); - let all: Vec<_> = (0..g.layers).filter_map(|i| g.layer(i)).collect(); - assert!(all.iter().any(|l| l.masked) && all.iter().any(|l| l.shadow)); - for (x, y) in g.sample_points() { - assert!(x < g.width && y < g.height); - } - } - assert!((0..LAYOUT_150.layers).filter_map(|i| LAYOUT_150.layer(i)).any(|l| l.hidden)); - } - - /// A small grid builds, parses, and its merged image is [`Grid::expected`]. - #[test] - fn small_grid_builds() { - let g = Grid { width: 120, height: 90, layers: 14, cols: 4 }; - let file = g.build(Version::Psd).unwrap(); - let bytes = file.to_bytes().unwrap(); - let file = PsdFile::from_bytes(&bytes).unwrap(); - // Background + 14 layers + 4 groups (two records each). - assert_eq!(file.layers().len(), 1 + 14 + 8); - let merged = file.image_data.decode(&file.header).unwrap(); - for (x, y) in g.sample_points() { - let want = g.expected(x, y); - for c in 0..3 { - assert_eq!(merged[c * 120 * 90 + (y * 120 + x) as usize], want[c], "({x}, {y}) {c}"); - } - } - } -} diff --git a/crates/psd/src/grd.rs b/crates/psd/src/grd.rs deleted file mode 100644 index bfa2cd91c7..0000000000 --- a/crates/psd/src/grd.rs +++ /dev/null @@ -1,299 +0,0 @@ -//! Photoshop gradient files (`.grd`, version 5: Photoshop 6 and later). -//! -//! Layout from public descriptions of the format: `8BGR`, version u16 (5), then a versioned -//! ActionDescriptor whose `GrdL` list holds `Grdn` objects, each with a `Grad` object: -//! `Nm ` name, `GrdF` form (`CstS` custom stops or `ClNs` noise), `Clrs` colour stops -//! (`Clr ` colour, `Type` user/foreground/background, `Lctn` 0..4096, `Mdpn` midpoint %) and -//! `Trns` transparency stops (`Opct` %, `Lctn`, `Mdpn`). Older (version 3) files are rejected. -//! Colours are returned in the model they were stored in; converting them is the caller's job. - -use crate::descriptor::{Descriptor, Value, VersionedDescriptor}; -use crate::error::{PsdError, Result}; - -/// Most gradients read from one file. -pub const MAX_GRADIENTS: usize = 10_000; -/// Most stops read per gradient. -pub const MAX_STOPS: usize = 1_000; - -/// A stop colour as stored. -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum GrdColor { - /// 0..1 RGB (from 0..255 components). - Rgb([f32; 3]), - /// Hue degrees, saturation and brightness 0..1. - Hsb([f32; 3]), - /// 0..1 C, M, Y, K ink. - Cmyk([f32; 4]), - /// L 0..100, a, b. - Lab([f32; 3]), - /// 0..1 ink (0 = white). - Gray(f32), - /// The live foreground colour. - Foreground, - /// The live background colour. - Background, -} - -/// One colour stop. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct GrdStop { - /// 0..1. - pub location: f32, - /// 0..1 (0.5 = centred). - pub midpoint: f32, - /// Colour. - pub color: GrdColor, -} - -/// One gradient. -#[derive(Debug, Clone, PartialEq, Default)] -pub struct GrdGradient { - /// Name. - pub name: String, - /// Noise gradient (`ClNs`): stops are absent; callers usually skip or approximate it. - pub noise: bool, - /// Colour stops, in file order. - pub stops: Vec, - /// Transparency stops: (location 0..1, opacity 0..1, midpoint 0..1). - pub opacity: Vec<(f32, f32, f32)>, -} - -/// The raw number behind a key. It is deliberately *not* filtered: every caller passes the result -/// through `finite`, so filtering here as well would give two guards with two different answers to -/// the same input, and mutation testing showed the second one was unreachable. -fn num(d: &Descriptor, k: &str) -> Option { - match d.get(k)? { - Value::Double(v) => Some(*v), - Value::UnitFloat { value, .. } => Some(*value), - Value::Integer(v) => Some(f64::from(*v)), - Value::LargeInteger(v) => Some(*v as f64), - _ => None, - } -} -/// The single guard every number passes through on its way to an `f32`. Only a NaN is truly -/// without a value, so only a NaN returns `None`; the caller then falls back to the default its -/// own field documents (opacity opaque, a midpoint centred, a channel zero). -/// -/// Everything else — including `±inf` and a value finite as `f64` but larger than `f32::MAX` -/// (`1e300`, which would otherwise overflow the cast to an infinity) — is *saturated* to the -/// representable range before the cast. That keeps the mapping monotonic: a bigger input never -/// yields a smaller output, so "too large" lands at the top of the range rather than snapping to a -/// field default and inverting the result. -fn finite(v: f64) -> Option { - if v.is_nan() { - return None; - } - Some(v.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32) -} -fn f(d: &Descriptor, k: &str) -> f32 { - finite(num(d, k).unwrap_or(0.0)).unwrap_or(0.0) -} -fn clamp01(v: f32) -> f32 { - v.clamp(0.0, 1.0) -} -/// A hue in degrees. An in-range value (0..=360, including exactly 360) is kept verbatim; only an -/// out-of-range value wraps with `rem_euclid`, so 370 -> 10 and -10 -> 350. Wrapping every value -/// would alter a legal 360 to 0 (and f32 round-off on a tiny negative can itself land on 360), -/// changing the colour at the boundary. The input is already finite, so the result stays finite. -fn hue(h: f32) -> f32 { - if (0.0..=360.0).contains(&h) { h } else { h.rem_euclid(360.0) } -} - -fn obj<'a>(d: &'a Descriptor, k: &str) -> Option<&'a Descriptor> { - match d.get(k)? { - Value::Descriptor(o) | Value::GlobalObject(o) => Some(o), - _ => None, - } -} -fn list<'a>(d: &'a Descriptor, k: &str) -> &'a [Value] { - match d.get(k) { - Some(Value::List(v)) => v, - _ => &[], - } -} -fn enum_is(d: &Descriptor, k: &str, v: &str) -> bool { - matches!(d.get(k), Some(Value::Enumerated { value, .. }) if value.is(v)) -} - -fn color(c: &Descriptor) -> Option { - let id = c.class_id.as_bytes(); - Some(match id { - // Every component documented as 0..=1 is clamped here, like every other range in this - // module: a hostile file can store any integer at all, and dividing by 100 or 255 does not - // bring it back into range on its own. - b"RGBC" => GrdColor::Rgb([f(c, "Rd ") / 255.0, f(c, "Grn ") / 255.0, f(c, "Bl ") / 255.0].map(clamp01)), - // Hue is a circular degree value in 0..=360; see `hue`. An in-range value (including - // exactly 360) is kept, only an out-of-range one wraps, so a hostile hue cannot become a - // different, wrong colour at the boundary. - b"HSBC" => GrdColor::Hsb([hue(f(c, "H ")), (f(c, "Strt") / 100.0).clamp(0.0, 1.0), (f(c, "Brgh") / 100.0).clamp(0.0, 1.0)]), - b"CMYC" => GrdColor::Cmyk([f(c, "Cyn ") / 100.0, f(c, "Mgnt") / 100.0, f(c, "Ylw ") / 100.0, f(c, "Blck") / 100.0].map(clamp01)), - // L* is 0..=100; a*/b* are signed and bounded to the CIELAB gamut (-128..=127) so a hostile - // value cannot hand a downstream colour converter an out-of-gamut number to overflow on. - b"LbCl" => GrdColor::Lab([f(c, "Lmnc").clamp(0.0, 100.0), f(c, "A ").clamp(-128.0, 127.0), f(c, "B ").clamp(-128.0, 127.0)]), - b"Grsc" => GrdColor::Gray(clamp01(f(c, "Gry ") / 100.0)), - _ => return None, - }) -} - -fn location(d: &Descriptor) -> f32 { - (f(d, "Lctn") / 4096.0).clamp(0.0, 1.0) -} -fn midpoint(d: &Descriptor) -> f32 { - finite(num(d, "Mdpn").unwrap_or(50.0) / 100.0).unwrap_or(0.5).clamp(0.0, 1.0) -} - -fn gradient(g: &Descriptor) -> GrdGradient { - let name = match g.get("Nm ") { - Some(Value::Text(t)) => t.to_string_lossy(), - _ => String::new(), - }; - let mut out = GrdGradient { name, noise: enum_is(g, "GrdF", "ClNs"), ..Default::default() }; - for v in list(g, "Clrs").iter().take(MAX_STOPS) { - let Value::Descriptor(s) = v else { continue }; - let c = if enum_is(s, "Type", "FrgC") { - Some(GrdColor::Foreground) - } else if enum_is(s, "Type", "BckC") { - Some(GrdColor::Background) - } else { - obj(s, "Clr ").and_then(color) - }; - if let Some(color) = c { - out.stops.push(GrdStop { location: location(s), midpoint: midpoint(s), color }); - } - } - for v in list(g, "Trns").iter().take(MAX_STOPS) { - let Value::Descriptor(s) = v else { continue }; - out.opacity.push((location(s), finite(num(s, "Opct").unwrap_or(100.0) / 100.0).unwrap_or(1.0).clamp(0.0, 1.0), midpoint(s))); - } - out -} - -/// Parses a `.grd` file. -pub fn parse(data: &[u8]) -> Result> { - let sig = data.get(0..4).ok_or(PsdError::UnexpectedEof { offset: 0, needed: 4 })?; - if sig != b"8BGR" { - let mut found = [0u8; 4]; - found.copy_from_slice(sig); - return Err(PsdError::InvalidSignature { expected: "8BGR", found }); - } - let version = data.get(4..6).map(|b| u16::from_be_bytes([b[0], b[1]])).ok_or(PsdError::UnexpectedEof { offset: 4, needed: 2 })?; - if version != 5 { - return Err(PsdError::Unsupported(format!("gradient file version {version} (only version 5, Photoshop 6 and later)"))); - } - let (vd, _) = VersionedDescriptor::parse_prefix(data.get(6..).unwrap_or_default())?; - let out: Vec = list(&vd.descriptor, "GrdL") - .iter() - .take(MAX_GRADIENTS) - .filter_map(|v| match v { - Value::Descriptor(d) => obj(d, "Grad").map(gradient), - _ => None, - }) - .collect(); - if out.is_empty() { - return Err(PsdError::invalid("the gradient file holds no gradients")); - } - Ok(out) -} - -/// Writes a version 5 `.grd` file (RGB / foreground / background stops; used by tests). -pub fn write(gradients: &[GrdGradient]) -> Vec { - use crate::descriptor::{Id, UnicodeString}; - let en = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) }; - let items = gradients - .iter() - .map(|g| { - let stops = g - .stops - .iter() - .map(|s| { - let (ty, c) = match s.color { - GrdColor::Foreground => ("FrgC", None), - GrdColor::Background => ("BckC", None), - GrdColor::Rgb([r, gg, b]) => ("UsrS", Some((r, gg, b))), - _ => ("UsrS", Some((0.0, 0.0, 0.0))), - }; - let mut d = Descriptor::new("Clrt"); - if let Some((r, gg, b)) = c { - let rgb = Descriptor::new("RGBC") - .with("Rd ", Value::Double(f64::from(r) * 255.0)) - .with("Grn ", Value::Double(f64::from(gg) * 255.0)) - .with("Bl ", Value::Double(f64::from(b) * 255.0)); - d = d.with("Clr ", Value::Descriptor(rgb)); - } - Value::Descriptor( - d.with("Type", en("Clry", ty)) - .with("Lctn", Value::Integer((s.location * 4096.0).round() as i32)) - .with("Mdpn", Value::Integer((s.midpoint * 100.0).round() as i32)), - ) - }) - .collect(); - let trns = g - .opacity - .iter() - .map(|&(l, o, m)| { - Value::Descriptor( - Descriptor::new("TrnS") - .with("Opct", Value::UnitFloat { unit: *b"#Prc", value: f64::from(o) * 100.0 }) - .with("Lctn", Value::Integer((l * 4096.0).round() as i32)) - .with("Mdpn", Value::Integer((m * 100.0).round() as i32)), - ) - }) - .collect(); - let grad = Descriptor::new("Grdn") - .with("Nm ", Value::Text(UnicodeString::new_nul(&g.name))) - .with("GrdF", en("GrdF", if g.noise { "ClNs" } else { "CstS" })) - .with("Intr", Value::Double(4096.0)) - .with("Clrs", Value::List(stops)) - .with("Trns", Value::List(trns)); - Value::Descriptor(Descriptor::new("Grdn").with("Grad", Value::Descriptor(grad))) - }) - .collect(); - let mut out = b"8BGR".to_vec(); - out.extend_from_slice(&5u16.to_be_bytes()); - out.extend_from_slice(&VersionedDescriptor::new(Descriptor::new("null").with("GrdL", Value::List(items))).to_bytes()); - out -} - -#[cfg(test)] -mod tests { - use super::*; - - fn sample() -> Vec { - vec![ - GrdGradient { - name: "Sunset ✓".into(), - noise: false, - stops: vec![ - GrdStop { location: 0.0, midpoint: 0.5, color: GrdColor::Foreground }, - GrdStop { location: 0.25, midpoint: 0.3, color: GrdColor::Rgb([1.0, 0.5, 0.0]) }, - GrdStop { location: 1.0, midpoint: 0.5, color: GrdColor::Background }, - ], - opacity: vec![(0.0, 1.0, 0.5), (1.0, 0.25, 0.5)], - }, - GrdGradient { name: "Noise".into(), noise: true, ..Default::default() }, - ] - } - - #[test] - fn round_trip() { - let b = write(&sample()); - assert_eq!(parse(&b).unwrap(), sample()); - } - - #[test] - fn hostile_input_errors() { - assert!(parse(b"").is_err()); - assert!(parse(b"8BGR\0\x03").is_err()); - assert!(parse(b"8BPS\0\x05").is_err()); - let b = write(&sample()); - for cut in 0..b.len() { - let _ = parse(&b[..cut]); - } - for i in 0..b.len() { - let mut c = b.clone(); - c[i] ^= 0x5a; - let _ = parse(&c); - } - assert!(parse(&write(&[])).is_err()); - } -} diff --git a/crates/psd/src/hdr.rs b/crates/psd/src/hdr.rs deleted file mode 100644 index 2b576c2ba4..0000000000 --- a/crates/psd/src/hdr.rs +++ /dev/null @@ -1,93 +0,0 @@ -//! HDR toning settings: the Color Mode Data of 32-bit-per-channel documents. -//! -//! Adobe's specification only documents the Color Mode Data section for -//! indexed and duotone images, but every 32-bit file Photoshop saves carries -//! an `hdrt` record there (the defaults of Image › Mode › 8/16 Bits/Channel › -//! HDR Toning), and current versions append an `hdra` record. Photoshop 2026 -//! refuses to open a 32-bit file whose Color Mode Data is empty or not in this -//! form ("the open options are incorrect", #291), so writers must emit it. -//! -//! The layout below was established by observing Photoshop-saved files (the -//! `photocraft-corpus` oracles); fields whose meaning is not known are written -//! with the values Photoshop writes for a new document. - -use crate::io::WriteExt; - -/// Key of the HDR toning record. -pub const TONING_KEY: &[u8; 4] = b"hdrt"; -/// Key of the record current Photoshop versions append after the toning record. -pub const EXTRA_KEY: &[u8; 4] = b"hdra"; - -/// `true` if `data` (a file's Color Mode Data) starts with an HDR toning record. -pub fn is_toning_data(data: &[u8]) -> bool { - data.starts_with(TONING_KEY) -} - -/// The Color Mode Data Photoshop writes for a new 32-bit document: a version 3 -/// `hdrt` record (method 2, preset "Linear", an identity toning curve) followed -/// by a version 6 `hdra` record. 110 bytes. -pub fn default_toning_data() -> Vec { - let mut out = Vec::with_capacity(110); - // `hdrt`, version 3. - out.put(TONING_KEY); - out.put_u32(3); - out.put(&0.23f32.to_be_bytes()); - out.put_u32(2); // toning method - // Preset name: Unicode string (UTF-16 code units including the terminator). - let name: Vec = "Linear".encode_utf16().chain(std::iter::once(0)).collect(); - out.put_u32(name.len() as u32); - for u in name { - out.put_u16(u); - } - // Toning curve: two points, (0, 0) and (255, 255), both corners. - out.put_u16(2); - out.put_u16(2); - for (input, output) in [(0u16, 0u16), (255, 255)] { - out.put_u16(output); - out.put_u16(input); - } - out.put(&[1, 1]); - out.put(&[0; 8]); - out.put(&16.0f32.to_be_bytes()); - out.put_u32(1); - out.put_u32(0); - out.put(&1.0f32.to_be_bytes()); - // `hdra`, version 6. - out.put(EXTRA_KEY); - out.put_u32(6); - out.put_u32(0); - out.put(&20.0f32.to_be_bytes()); - out.put(&30.0f32.to_be_bytes()); - out.put_u32(0); - out.put_u32(0); - out.put(&1.0f32.to_be_bytes()); - out.put(&[0; 6]); - out -} - -/// The Color Mode Data a writer should emit for a file of `depth` bits per -/// channel when it has nothing of its own to keep: the default HDR toning -/// records for 32-bit files, nothing otherwise (indexed and duotone data come -/// from the document). -pub fn color_mode_data_for_depth(depth: u16) -> Vec { - if depth == 32 { default_toning_data() } else { Vec::new() } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn default_record_layout() { - let d = default_toning_data(); - assert_eq!(d.len(), 110); - assert!(is_toning_data(&d)); - assert_eq!(&d[72..76], EXTRA_KEY); - // Version fields. - assert_eq!(&d[4..8], &3u32.to_be_bytes()); - assert_eq!(&d[76..80], &6u32.to_be_bytes()); - assert!(color_mode_data_for_depth(8).is_empty()); - assert!(color_mode_data_for_depth(16).is_empty()); - assert_eq!(color_mode_data_for_depth(32), d); - } -} diff --git a/crates/psd/src/header.rs b/crates/psd/src/header.rs deleted file mode 100644 index d99555be2b..0000000000 --- a/crates/psd/src/header.rs +++ /dev/null @@ -1,254 +0,0 @@ -//! File header: signature, version, channels, dimensions, depth and color mode. - -use crate::error::{PsdError, Result}; -use crate::io::{Reader, WriteExt}; - -/// Maximum width/height accepted by the parser (PSB limit). -pub const MAX_DIMENSION: u32 = 300_000; -/// Maximum number of channels accepted (spec: 1..=56). -pub const MAX_CHANNELS: u16 = 56; - -/// File format version. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum Version { - /// Version 1: Photoshop Document (32-bit section lengths). - Psd, - /// Version 2: Large Document Format (64-bit lengths for some sections). - Psb, -} - -impl Version { - /// `true` for PSB. - pub fn is_psb(self) -> bool { - matches!(self, Version::Psb) - } - /// Numeric version as stored in the header. - pub fn as_u16(self) -> u16 { - match self { - Version::Psd => 1, - Version::Psb => 2, - } - } -} - -/// Document color mode. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum ColorMode { - /// 0 - Bitmap, - /// 1 - Grayscale, - /// 2 - Indexed, - /// 3 - Rgb, - /// 4 - Cmyk, - /// 7 - Multichannel, - /// 8 - Duotone, - /// 9 - Lab, - /// Any other value, preserved. - Unknown(u16), -} - -impl ColorMode { - /// Converts from the stored numeric value. - pub fn from_u16(v: u16) -> Self { - match v { - 0 => ColorMode::Bitmap, - 1 => ColorMode::Grayscale, - 2 => ColorMode::Indexed, - 3 => ColorMode::Rgb, - 4 => ColorMode::Cmyk, - 7 => ColorMode::Multichannel, - 8 => ColorMode::Duotone, - 9 => ColorMode::Lab, - other => ColorMode::Unknown(other), - } - } - /// Numeric value as stored. - pub fn as_u16(self) -> u16 { - match self { - ColorMode::Bitmap => 0, - ColorMode::Grayscale => 1, - ColorMode::Indexed => 2, - ColorMode::Rgb => 3, - ColorMode::Cmyk => 4, - ColorMode::Multichannel => 7, - ColorMode::Duotone => 8, - ColorMode::Lab => 9, - ColorMode::Unknown(v) => v, - } - } - /// Number of color (non-alpha) channels for the mode, when fixed. - pub fn color_channels(self) -> Option { - match self { - ColorMode::Bitmap | ColorMode::Grayscale | ColorMode::Indexed | ColorMode::Duotone => Some(1), - ColorMode::Rgb | ColorMode::Lab => Some(3), - ColorMode::Cmyk => Some(4), - ColorMode::Multichannel | ColorMode::Unknown(_) => None, - } - } -} - -/// The 26-byte file header. -#[derive(Debug, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct Header { - /// PSD or PSB. - pub version: Version, - /// Reserved bytes (spec: must be zero). Preserved for exact round-trip. - pub reserved: [u8; 6], - /// Number of channels in the merged image, including alpha channels (1..=56). - pub channels: u16, - /// Height in pixels. - pub height: u32, - /// Width in pixels. - pub width: u32, - /// Bits per channel: 1, 8, 16 or 32. - pub depth: u16, - /// Color mode. - pub color_mode: ColorMode, -} - -impl Header { - /// Creates a header with zeroed reserved bytes. - pub fn new(version: Version, width: u32, height: u32, channels: u16, depth: u16, color_mode: ColorMode) -> Self { - Header { version, reserved: [0; 6], channels, height, width, depth, color_mode } - } - - /// Bytes per row of one channel plane. - pub fn row_bytes(&self) -> usize { - row_bytes(self.width as usize, self.depth) - } - - pub(crate) fn read(r: &mut Reader<'_>) -> Result { - let sig = r.array::<4>()?; - if &sig != b"8BPS" { - return Err(PsdError::InvalidSignature { expected: "8BPS", found: sig }); - } - let version = match r.u16()? { - 1 => Version::Psd, - 2 => Version::Psb, - v => return Err(PsdError::UnsupportedVersion(v)), - }; - let reserved = r.array::<6>()?; - let channels = r.u16()?; - let height = r.u32()?; - let width = r.u32()?; - let depth = r.u16()?; - let color_mode = ColorMode::from_u16(r.u16()?); - let h = Header { version, reserved, channels, height, width, depth, color_mode }; - h.validate()?; - Ok(h) - } - - /// Checks the header against spec constraints and safety limits. - pub fn validate(&self) -> Result<()> { - if self.channels == 0 || self.channels > MAX_CHANNELS { - return Err(PsdError::invalid(format!("channel count {} out of range 1..=56", self.channels))); - } - if self.width == 0 || self.height == 0 { - return Err(PsdError::invalid(format!("image dimensions {}x{} must be at least 1x1", self.width, self.height))); - } - if self.width > MAX_DIMENSION || self.height > MAX_DIMENSION { - return Err(PsdError::LimitExceeded("image dimensions exceed 300000")); - } - if !matches!(self.depth, 1 | 8 | 16 | 32) { - return Err(PsdError::invalid(format!("unsupported bit depth {}", self.depth))); - } - Ok(()) - } - - pub(crate) fn write(&self, out: &mut Vec) { - out.put(b"8BPS"); - out.put_u16(self.version.as_u16()); - out.put(&self.reserved); - out.put_u16(self.channels); - out.put_u32(self.height); - out.put_u32(self.width); - out.put_u16(self.depth); - out.put_u16(self.color_mode.as_u16()); - } -} - -/// Bytes per row for `width` samples at `depth` bits. -pub fn row_bytes(width: usize, depth: u16) -> usize { - match depth { - 1 => width.div_ceil(8), - d => width.saturating_mul(usize::from(d / 8).max(1)), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn bytes(h: &Header) -> Vec { - let mut v = Vec::new(); - h.write(&mut v); - v - } - - #[test] - fn header_roundtrip() { - let h = Header::new(Version::Psb, 1000, 20, 4, 16, ColorMode::Cmyk); - let b = bytes(&h); - assert_eq!(b.len(), 26); - assert_eq!(Header::read(&mut Reader::new(&b)).unwrap(), h); - } - - #[test] - fn bad_signature() { - let mut b = bytes(&Header::new(Version::Psd, 1, 1, 1, 8, ColorMode::Grayscale)); - b[0] = b'X'; - assert!(matches!(Header::read(&mut Reader::new(&b)), Err(PsdError::InvalidSignature { .. }))); - } - - #[test] - fn bad_version() { - let mut b = bytes(&Header::new(Version::Psd, 1, 1, 1, 8, ColorMode::Grayscale)); - b[5] = 3; - assert_eq!(Header::read(&mut Reader::new(&b)), Err(PsdError::UnsupportedVersion(3))); - } - - #[test] - fn limits() { - for h in [ - Header::new(Version::Psd, 300_001, 1, 1, 8, ColorMode::Rgb), - Header::new(Version::Psd, 0, 1, 1, 8, ColorMode::Rgb), - Header::new(Version::Psd, 1, 0, 1, 8, ColorMode::Rgb), - Header::new(Version::Psb, 0, 0, 1, 8, ColorMode::Rgb), - Header::new(Version::Psd, 1, 1, 0, 8, ColorMode::Rgb), - Header::new(Version::Psd, 1, 1, 57, 8, ColorMode::Rgb), - Header::new(Version::Psd, 1, 1, 3, 12, ColorMode::Rgb), - ] { - let b = bytes(&h); - assert!(Header::read(&mut Reader::new(&b)).is_err(), "{h:?}"); - } - } - - #[test] - fn color_modes_roundtrip() { - for v in 0..20u16 { - assert_eq!(ColorMode::from_u16(v).as_u16(), v); - } - assert_eq!(ColorMode::from_u16(5), ColorMode::Unknown(5)); - assert_eq!(ColorMode::Rgb.color_channels(), Some(3)); - } - - #[test] - fn row_bytes_values() { - assert_eq!(row_bytes(9, 1), 2); - assert_eq!(row_bytes(8, 1), 1); - assert_eq!(row_bytes(0, 1), 0); - assert_eq!(row_bytes(3, 8), 3); - assert_eq!(row_bytes(3, 16), 6); - assert_eq!(row_bytes(3, 32), 12); - } -} diff --git a/crates/psd/src/image_data.rs b/crates/psd/src/image_data.rs deleted file mode 100644 index 9e27af2917..0000000000 --- a/crates/psd/src/image_data.rs +++ /dev/null @@ -1,98 +0,0 @@ -//! Merged (composite) image data section. - -use std::borrow::Cow; - -use crate::compression::{Compression, PlaneLayout, decode_planes, encode_planes, validate_planes}; -use crate::error::Result; -use crate::header::Header; -use crate::io::Reader; -use crate::source::Stored; - -/// The merged image: compression plus the encoded bytes of all channels -/// (to the end of the file), kept verbatim. -/// -/// As with [`crate::ChannelData`], a file parsed by -/// [`PsdFile::from_source`](crate::PsdFile::from_source) may leave the bytes in the source -/// (`stored`, with `data` empty); equality compares the bytes wherever they are. -#[derive(Debug, Clone)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ImageData { - /// Compression method for the whole image. - pub compression: Compression, - /// Encoded data. For RLE: the byte-count table for every row of every - /// channel followed by the rows. - pub data: Vec, - /// Where the encoded bytes are when they were left in the source. (Not serialized.) - #[cfg_attr(feature = "serde", serde(skip))] - pub stored: Option, -} - -impl PartialEq for ImageData { - fn eq(&self, other: &Self) -> bool { - if self.compression != other.compression || self.encoded_len() != other.encoded_len() { - return false; - } - match (self.encoded(), other.encoded()) { - (Ok(a), Ok(b)) => a == b, - _ => false, - } - } -} - -impl Eq for ImageData {} - -impl ImageData { - /// A merged image whose encoded bytes are in memory. - pub fn new(compression: Compression, data: Vec) -> Self { - ImageData { compression, data, stored: None } - } - - /// The encoded bytes: borrowed from `data`, or read from the source. - pub fn encoded(&self) -> Result> { - crate::source::encoded(&self.data, self.stored.as_ref()) - } - - /// Number of encoded bytes, wherever they are. - pub fn encoded_len(&self) -> u64 { - self.stored.as_ref().map_or(self.data.len() as u64, |s| s.len) - } - - /// Reads bytes left in the source into `data`. - pub fn load(&mut self) -> Result<()> { - if let Some(s) = &self.stored { - self.data = s.read()?; - self.stored = None; - } - Ok(()) - } - - /// Plane layout for the merged image described by `header`. - pub fn layout(header: &Header) -> PlaneLayout { - PlaneLayout { - planes: usize::from(header.channels), - width: header.width as usize, - height: header.height as usize, - depth: header.depth, - version: header.version, - } - } - - /// Encodes planar data (`channels × height × row_bytes`). - pub fn encode(compression: Compression, decoded: &[u8], header: &Header) -> Result { - Ok(ImageData::new(compression, encode_planes(compression, decoded, &Self::layout(header))?)) - } - - /// Decodes all channels into planar big-endian samples. - pub fn decode(&self, header: &Header) -> Result> { - decode_planes(self.compression, &self.encoded()?, &Self::layout(header)) - } - - pub(crate) fn read(r: &mut Reader<'_>, header: &Header) -> Result { - let compression = Compression::from_u16(r.u16()?); - let data = r.peek_rest(); - validate_planes(compression, data, &Self::layout(header))?; - let data = data.to_vec(); - r.skip(data.len())?; - Ok(ImageData::new(compression, data)) - } -} diff --git a/crates/psd/src/io.rs b/crates/psd/src/io.rs deleted file mode 100644 index 8537b74649..0000000000 --- a/crates/psd/src/io.rs +++ /dev/null @@ -1,518 +0,0 @@ -//! Bounds-checked big-endian reader and writer helpers. - -use std::io::{Seek, SeekFrom, Write}; - -use crate::error::{PsdError, Result}; - -/// A name as UTF-16 code units, capped at `max` **without ever splitting a surrogate pair**. -/// `encode_utf16().take(max)` would cut between the high and low half of a pair above U+FFFF and -/// write ill-formed UTF-16 to disk, so whole scalar values are added until one would not fit. -/// Both the `.aco` and `.ase` writers share this; keeping it in one place is deliberate, so the -/// surrogate fix cannot drift between the two formats. -pub(crate) fn utf16_units(name: &str, max: usize) -> Vec { - let mut units = Vec::new(); - for c in name.chars() { - if units.len() + c.len_utf16() > max { - break; - } - let mut buf = [0u16; 2]; - units.extend_from_slice(c.encode_utf16(&mut buf)); - } - units -} - -/// A cursor over a byte slice. Every read is bounds checked. Integers are big-endian (the PSD -/// byte order) unless the reader was made with [`Reader::new_little`], which only the TIFF -/// byte-order transcoder uses ([`crate::tiff`]). -#[derive(Debug, Clone)] -pub(crate) struct Reader<'a> { - data: &'a [u8], - pos: usize, - little: bool, -} - -impl<'a> Reader<'a> { - pub(crate) fn new(data: &'a [u8]) -> Self { - Reader { data, pos: 0, little: false } - } - - /// A reader of little-endian integers (Photoshop data inside an Intel-order TIFF). - pub(crate) fn new_little(data: &'a [u8]) -> Self { - Reader { data, pos: 0, little: true } - } - - pub(crate) fn pos(&self) -> usize { - self.pos - } - - pub(crate) fn remaining(&self) -> usize { - self.data.len() - self.pos - } - - pub(crate) fn is_empty(&self) -> bool { - self.remaining() == 0 - } - - /// Bytes from the current position without consuming. - pub(crate) fn peek_rest(&self) -> &'a [u8] { - &self.data[self.pos..] - } - - pub(crate) fn bytes(&mut self, n: usize) -> Result<&'a [u8]> { - if n > self.remaining() { - return Err(PsdError::UnexpectedEof { offset: self.pos, needed: n - self.remaining() }); - } - let s = &self.data[self.pos..self.pos + n]; - self.pos += n; - Ok(s) - } - - /// Reads `n` bytes where `n` comes from a (possibly 64-bit) length field. - pub(crate) fn bytes_u64(&mut self, n: u64) -> Result<&'a [u8]> { - let n = usize::try_from(n).map_err(|_| PsdError::LimitExceeded("length exceeds address space"))?; - self.bytes(n) - } - - pub(crate) fn sub(&mut self, n: u64) -> Result> { - let little = self.little; - Ok(Reader { data: self.bytes_u64(n)?, pos: 0, little }) - } - - pub(crate) fn skip(&mut self, n: usize) -> Result<()> { - self.bytes(n).map(|_| ()) - } - - pub(crate) fn array(&mut self) -> Result<[u8; N]> { - let s = self.bytes(N)?; - let mut out = [0u8; N]; - out.copy_from_slice(s); - Ok(out) - } - - pub(crate) fn u8(&mut self) -> Result { - Ok(self.array::<1>()?[0]) - } - pub(crate) fn u16(&mut self) -> Result { - let b = self.array()?; - Ok(if self.little { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) }) - } - pub(crate) fn i16(&mut self) -> Result { - let b = self.array()?; - Ok(if self.little { i16::from_le_bytes(b) } else { i16::from_be_bytes(b) }) - } - pub(crate) fn u32(&mut self) -> Result { - let b = self.array()?; - Ok(if self.little { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }) - } - pub(crate) fn i32(&mut self) -> Result { - let b = self.array()?; - Ok(if self.little { i32::from_le_bytes(b) } else { i32::from_be_bytes(b) }) - } - pub(crate) fn u64(&mut self) -> Result { - let b = self.array()?; - Ok(if self.little { u64::from_le_bytes(b) } else { u64::from_be_bytes(b) }) - } - pub(crate) fn i64(&mut self) -> Result { - let b = self.array()?; - Ok(if self.little { i64::from_le_bytes(b) } else { i64::from_be_bytes(b) }) - } - pub(crate) fn f64(&mut self) -> Result { - let b = self.array()?; - Ok(if self.little { f64::from_le_bytes(b) } else { f64::from_be_bytes(b) }) - } - - /// Reads a length field that is 4 bytes, or 8 bytes when `long`. - pub(crate) fn len_field(&mut self, long: bool) -> Result { - if long { self.u64() } else { Ok(u64::from(self.u32()?)) } - } - - /// Returns `Err` unless `count * min_item_size` bytes remain. Used to - /// validate element counts before allocating. - pub(crate) fn check_count(&self, count: u64, min_item_size: u64) -> Result<()> { - let need = count.saturating_mul(min_item_size); - if need > self.remaining() as u64 { - return Err(PsdError::UnexpectedEof { offset: self.pos, needed: usize::try_from(need - self.remaining() as u64).unwrap_or(usize::MAX) }); - } - Ok(()) - } -} - -/// Big-endian writing helpers on `Vec`. -pub(crate) trait WriteExt { - fn put_u8(&mut self, v: u8); - fn put_u16(&mut self, v: u16); - fn put_i16(&mut self, v: i16); - fn put_u32(&mut self, v: u32); - fn put_i32(&mut self, v: i32); - fn put_u64(&mut self, v: u64); - fn put_i64(&mut self, v: i64); - fn put_f64(&mut self, v: f64); - fn put(&mut self, b: &[u8]); - /// Writes a length field (4 or 8 bytes). - fn put_len(&mut self, v: u64, long: bool) -> Result<()>; - /// Reserves a length placeholder, returning its position. - fn begin_len(&mut self, long: bool) -> usize; - /// Back-patches a placeholder with the number of bytes written since. - fn end_len(&mut self, at: usize, long: bool) -> Result<()>; -} - -impl WriteExt for Vec { - fn put_u8(&mut self, v: u8) { - self.push(v); - } - fn put_u16(&mut self, v: u16) { - self.extend_from_slice(&v.to_be_bytes()); - } - fn put_i16(&mut self, v: i16) { - self.extend_from_slice(&v.to_be_bytes()); - } - fn put_u32(&mut self, v: u32) { - self.extend_from_slice(&v.to_be_bytes()); - } - fn put_i32(&mut self, v: i32) { - self.extend_from_slice(&v.to_be_bytes()); - } - fn put_u64(&mut self, v: u64) { - self.extend_from_slice(&v.to_be_bytes()); - } - fn put_i64(&mut self, v: i64) { - self.extend_from_slice(&v.to_be_bytes()); - } - fn put_f64(&mut self, v: f64) { - self.extend_from_slice(&v.to_be_bytes()); - } - fn put(&mut self, b: &[u8]) { - self.extend_from_slice(b); - } - fn put_len(&mut self, v: u64, long: bool) -> Result<()> { - if long { - self.put_u64(v); - } else { - let v = u32::try_from(v).map_err(|_| PsdError::LimitExceeded("section too large for 32-bit length (use PSB)"))?; - self.put_u32(v); - } - Ok(()) - } - fn begin_len(&mut self, long: bool) -> usize { - let at = self.len(); - self.extend_from_slice(if long { &[0u8; 8] } else { &[0u8; 4] }); - at - } - fn end_len(&mut self, at: usize, long: bool) -> Result<()> { - let hdr = if long { 8 } else { 4 }; - let n = (self.len() - at - hdr) as u64; - if long { - self[at..at + 8].copy_from_slice(&n.to_be_bytes()); - } else { - let v = u32::try_from(n).map_err(|_| PsdError::LimitExceeded("section too large for 32-bit length (use PSB)"))?; - self[at..at + 4].copy_from_slice(&v.to_be_bytes()); - } - Ok(()) - } -} - -/// Staged bytes [`Sink`] collects before writing them out in one call. -const STAGE: usize = 64 << 10; -/// Bytes of stored channel data read per piece by [`Sink::put_encoded`]. -const COPY_CHUNK: u64 = if cfg!(test) { 7 } else { 8 << 20 }; -#[cfg(test)] -pub(crate) const STAGE_FOR_TESTS: usize = STAGE; - -/// Writes the file to a seekable stream as it is serialized (#6607): the small parts (headers, -/// records, lengths) are staged in a short buffer, while pixel data and other long slices go -/// straight to the stream, so the whole file never sits in memory. A length placeholder -/// ([`Sink::begin_len`]) that was already written out is back-patched by seeking. The bytes are -/// exactly the ones the `Vec` writers ([`WriteExt`]) produce. -pub(crate) struct Sink<'w, W: Write + Seek + ?Sized> { - w: &'w mut W, - /// Bytes not yet written; they start at stream position `base`. - buf: Vec, - base: u64, - /// Staged bytes that trigger a write ([`STAGE`]; tests use less). - stage: usize, -} - -impl<'w, W: Write + Seek + ?Sized> Sink<'w, W> { - /// A sink writing at `w`'s current position. - pub(crate) fn new(w: &'w mut W) -> std::io::Result { - Self::staging(w, STAGE) - } - - /// [`Self::new`] writing out once `stage` bytes are staged. - pub(crate) fn staging(w: &'w mut W, stage: usize) -> std::io::Result { - let base = w.stream_position()?; - Ok(Sink { w, buf: Vec::new(), base, stage }) - } - - /// The stream position of the next byte. - pub(crate) fn pos(&self) -> u64 { - self.base + self.buf.len() as u64 - } - - /// Appends a small part built by `f` with the `Vec` writers. Lengths `f` back-patches stay - /// inside what it appends. - pub(crate) fn small(&mut self, f: impl FnOnce(&mut Vec) -> Result<()>) -> std::io::Result<()> { - f(&mut self.buf)?; - if self.buf.len() >= self.stage { self.flush() } else { Ok(()) } - } - - /// Appends `b`, straight to the stream when it is long. - pub(crate) fn put(&mut self, b: &[u8]) -> std::io::Result<()> { - if self.buf.len() + b.len() < self.stage { - self.buf.extend_from_slice(b); - return Ok(()); - } - self.flush()?; - self.w.write_all(b)?; - self.base += b.len() as u64; - Ok(()) - } - - /// Appends RLE channel data whose 2-byte row-count table widens to 4 bytes (a PSD model - /// written as PSB): the table is widened in staged pieces, the packed rows go straight - /// through: each two-byte count becomes `00 00` and the count, the packed rows are unchanged. - pub(crate) fn put_widened_rle(&mut self, data: &[u8], rows: usize) -> std::io::Result<()> { - let table_len = usize::try_from(crate::compression::rle_widening(data, rows)?).map_err(|_| PsdError::LimitExceeded("row count overflow"))?; - let (table, packed) = data.split_at_checked(table_len).ok_or_else(|| PsdError::invalid("RLE row-count table out of range"))?; - for part in table.chunks(STAGE / 2) { - self.widen_counts(part)?; - } - self.put(packed) - } - - /// [`Self::put_widened_rle`] for data held in memory (`data`) or, when `stored`, still in its - /// source: the count table and then the packed rows are read in [`COPY_CHUNK`]-sized parts - /// (#5333), so a staged merged image or channel is never read back whole to widen it. - pub(crate) fn put_widened_encoded(&mut self, data: &[u8], stored: Option<&crate::source::Stored>, rows: usize) -> std::io::Result<()> { - let Some(s) = stored else { return self.put_widened_rle(data, rows) }; - let table_len = crate::compression::rle_widening_len(s.len, rows)?; - // Whole counts per part; the parts follow each other, so a staged range is read in one pass. - let table_part = (COPY_CHUNK / 2).max(1) * 2; - let mut at = 0u64; - while at < s.len { - let n = if at < table_len { (table_len - at).min(table_part) } else { (s.len - at).min(COPY_CHUNK) }; - let part = s.read_part(at, n)?; - if at < table_len { - self.widen_counts(&part)? - } else { - self.put(&part)? - } - at += n; - } - Ok(()) - } - - /// Two-byte RLE row counts as four-byte ones (`00 00` and the count), staged. - fn widen_counts(&mut self, counts: &[u8]) -> std::io::Result<()> { - self.small(|o| { - for count in counts.as_chunks::<2>().0 { - o.extend_from_slice(&[0, 0, count[0], count[1]]); - } - Ok(()) - }) - } - - /// Appends encoded bytes held in memory (`data`) or, when `stored`, still in their source: - /// those are copied through in [`COPY_CHUNK`] pieces, so a channel or merged image kept on - /// disk (an imported file's, or one an exporter spilled to scratch) is never read whole. - pub(crate) fn put_encoded(&mut self, data: &[u8], stored: Option<&crate::source::Stored>) -> std::io::Result<()> { - let Some(s) = stored else { return self.put(data) }; - let mut at = 0u64; - while at < s.len { - let n = (s.len - at).min(COPY_CHUNK); - let part = s.read_part(at, n)?; - self.put(&part)?; - at += n; - } - Ok(()) - } - - /// `n` zero bytes (padding, at most a few). - pub(crate) fn zeros(&mut self, n: usize) -> std::io::Result<()> { - self.small(|b| { - b.extend(std::iter::repeat_n(0u8, n)); - Ok(()) - }) - } - - /// Reserves a length placeholder (4 or 8 bytes), returning its stream position. - pub(crate) fn begin_len(&mut self, long: bool) -> std::io::Result { - let at = self.pos(); - self.zeros(if long { 8 } else { 4 })?; - Ok(at) - } - - /// Back-patches the placeholder at `at` with the number of bytes written since. - pub(crate) fn end_len(&mut self, at: u64, long: bool) -> std::io::Result<()> { - let hdr = if long { 8 } else { 4 }; - let n = self.pos() - at - hdr; - let bytes = if long { - n.to_be_bytes().to_vec() - } else { - u32::try_from(n).map_err(|_| PsdError::LimitExceeded("section too large for 32-bit length (use PSB)"))?.to_be_bytes().to_vec() - }; - if at >= self.base { - let i = (at - self.base) as usize; - self.buf[i..i + bytes.len()].copy_from_slice(&bytes); - return Ok(()); - } - self.flush()?; - self.w.seek(SeekFrom::Start(at))?; - self.w.write_all(&bytes)?; - self.w.seek(SeekFrom::Start(self.base))?; - Ok(()) - } - - fn flush(&mut self) -> std::io::Result<()> { - self.w.write_all(&self.buf)?; - self.base += self.buf.len() as u64; - self.buf.clear(); - Ok(()) - } - - /// Writes out what is still staged. Dropping a sink without it loses those bytes. - pub(crate) fn finish(mut self) -> std::io::Result<()> { - self.flush()?; - self.w.flush() - } -} - -/// Runs a streaming writer on the end of `out`, the `Vec` writers' way of sharing it. -pub(crate) fn append_with(out: &mut Vec, f: impl FnOnce(&mut Sink<'_, std::io::Cursor<&mut Vec>>) -> std::io::Result<()>) -> Result<()> { - let at = out.len() as u64; - let mut c = std::io::Cursor::new(out); - c.set_position(at); - let mut s = Sink::new(&mut c).map_err(PsdError::from_io)?; - f(&mut s).map_err(PsdError::from_io)?; - s.finish().map_err(PsdError::from_io) -} - -/// Reads a Pascal string (length byte + bytes) whose total size is padded to -/// a multiple of `align`. Returns the raw name bytes. -pub(crate) fn read_pascal(r: &mut Reader<'_>, align: usize) -> Result> { - let n = r.u8()? as usize; - let name = r.bytes(n)?.to_vec(); - let total = 1 + n; - let pad = (align - total % align) % align; - r.skip(pad)?; - Ok(name) -} - -pub(crate) fn write_pascal(out: &mut Vec, name: &[u8], align: usize) { - let n = name.len().min(255); - out.put_u8(n as u8); - out.put(&name[..n]); - let total = 1 + n; - let pad = (align - total % align) % align; - out.extend(std::iter::repeat_n(0u8, pad)); -} - -/// Decodes legacy (Pascal) names: UTF-8 when valid, otherwise Latin-1. -pub(crate) fn decode_legacy_name(b: &[u8]) -> String { - match std::str::from_utf8(b) { - Ok(s) => s.to_owned(), - Err(_) => b.iter().map(|&c| c as char).collect(), - } -} - -/// Encodes a name for a legacy Pascal field: non-ASCII chars become `?`. -pub(crate) fn encode_legacy_name(s: &str) -> Vec { - s.chars().map(|c| if c.is_ascii() && !c.is_ascii_control() { c as u8 } else { b'?' }).take(255).collect() -} - -/// Reads a Photoshop Unicode string: u32 code-unit count + UTF-16BE units. -pub(crate) fn read_unicode_units(r: &mut Reader<'_>) -> Result> { - let n = r.u32()? as u64; - r.check_count(n, 2)?; - let mut v = Vec::with_capacity(n as usize); - for _ in 0..n { - v.push(r.u16()?); - } - Ok(v) -} - -pub(crate) fn write_unicode_units(out: &mut Vec, units: &[u16]) { - out.put_u32(units.len() as u32); - for &u in units { - out.put_u16(u); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reader_reads_big_endian() { - let data = [0x00, 0x01, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x02]; - let mut r = Reader::new(&data); - assert_eq!(r.u16().unwrap(), 1); - assert_eq!(r.i16().unwrap(), -2); - assert_eq!(r.u32().unwrap(), 2); - assert!(r.is_empty()); - assert!(matches!(r.u8(), Err(PsdError::UnexpectedEof { .. }))); - } - - #[test] - fn reader_eof_reports_needed() { - let mut r = Reader::new(&[1, 2]); - match r.u32() { - Err(PsdError::UnexpectedEof { offset, needed }) => { - assert_eq!(offset, 0); - assert_eq!(needed, 2); - } - other => panic!("{other:?}"), - } - } - - #[test] - fn check_count_rejects_huge() { - let r = Reader::new(&[0; 8]); - assert!(r.check_count(u64::MAX, 4).is_err()); - assert!(r.check_count(2, 4).is_ok()); - assert!(r.check_count(3, 4).is_err()); - } - - #[test] - fn len_patch_roundtrip() { - let mut v = Vec::new(); - let at = v.begin_len(false); - v.put(&[1, 2, 3]); - v.end_len(at, false).unwrap(); - assert_eq!(v, [0, 0, 0, 3, 1, 2, 3]); - let mut v = Vec::new(); - let at = v.begin_len(true); - v.put(&[9]); - v.end_len(at, true).unwrap(); - assert_eq!(v, [0, 0, 0, 0, 0, 0, 0, 1, 9]); - } - - #[test] - fn pascal_padding() { - for (name, align, total) in [(&b""[..], 2, 2), (&b"a"[..], 2, 2), (&b"ab"[..], 2, 4), (&b""[..], 4, 4), (&b"abc"[..], 4, 4), (&b"abcd"[..], 4, 8)] { - let mut v = Vec::new(); - write_pascal(&mut v, name, align); - assert_eq!(v.len(), total, "{name:?} align {align}"); - let mut r = Reader::new(&v); - assert_eq!(read_pascal(&mut r, align).unwrap(), name); - assert!(r.is_empty()); - } - } - - #[test] - fn legacy_names() { - assert_eq!(decode_legacy_name(b"Layer 1"), "Layer 1"); - assert_eq!(decode_legacy_name(&[0x41, 0xe9]), "A\u{e9}"); - assert_eq!(encode_legacy_name("h\u{e9}llo"), b"h?llo"); - } - - #[test] - fn unicode_units_roundtrip() { - let mut v = Vec::new(); - write_unicode_units(&mut v, &[0x48, 0x69, 0]); - let mut r = Reader::new(&v); - assert_eq!(read_unicode_units(&mut r).unwrap(), vec![0x48, 0x69, 0]); - let mut r = Reader::new(&[0xff, 0xff, 0xff, 0xff]); - assert!(read_unicode_units(&mut r).is_err()); - } -} diff --git a/crates/psd/src/layer.rs b/crates/psd/src/layer.rs deleted file mode 100644 index 90f6550863..0000000000 --- a/crates/psd/src/layer.rs +++ /dev/null @@ -1,889 +0,0 @@ -//! Layer records, layer masks, blending ranges and per-layer channel data. - -use std::borrow::Cow; - -use crate::blend::BlendMode; -use crate::compression::{Compression, PlaneLayout, decode_planes, encode_planes, rle_widening_len}; -use crate::error::{PsdError, Result}; -use crate::header::{MAX_DIMENSION, Version}; -use crate::io::{Reader, Sink, WriteExt, append_with, decode_legacy_name, read_pascal, write_pascal}; -use crate::source::Stored; -use crate::tagged::{BlockData, SectionDivider, SectionType, TaggedBlock, read_blocks, uses_long_length, write_blocks}; - -/// Channel id of the transparency mask. -pub const CHANNEL_TRANSPARENCY: i16 = -1; -/// Channel id of the user-supplied layer mask. -pub const CHANNEL_USER_MASK: i16 = -2; -/// Channel id of the real user-supplied layer mask (when both a user mask and -/// a vector mask are present). -pub const CHANNEL_REAL_USER_MASK: i16 = -3; - -/// Maximum number of channels per layer accepted by the parser. -pub const MAX_LAYER_CHANNELS: u16 = 64; - -/// A rectangle as stored in PSD files (top, left, bottom, right). -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct Rect { - /// Top edge (inclusive). - pub top: i32, - /// Left edge (inclusive). - pub left: i32, - /// Bottom edge (exclusive). - pub bottom: i32, - /// Right edge (exclusive). - pub right: i32, -} - -impl Rect { - /// Rectangle from origin and size. - pub fn from_xywh(left: i32, top: i32, width: u32, height: u32) -> Self { - Rect { top, left, bottom: top.saturating_add(height.min(i32::MAX as u32) as i32), right: left.saturating_add(width.min(i32::MAX as u32) as i32) } - } - /// Width (may be negative for malformed data). - pub fn width(&self) -> i64 { - i64::from(self.right) - i64::from(self.left) - } - /// Height (may be negative for malformed data). - pub fn height(&self) -> i64 { - i64::from(self.bottom) - i64::from(self.top) - } - /// `true` when width or height is zero or negative. - pub fn is_empty(&self) -> bool { - self.width() <= 0 || self.height() <= 0 - } - /// Validated `(width, height)` as `usize`. - pub fn size(&self) -> Result<(usize, usize)> { - let (w, h) = (self.width(), self.height()); - if w < 0 || h < 0 { - return Err(PsdError::invalid("rectangle has negative size")); - } - if w > i64::from(MAX_DIMENSION) || h > i64::from(MAX_DIMENSION) { - return Err(PsdError::LimitExceeded("layer dimensions exceed 300000")); - } - Ok((w as usize, h as usize)) - } - fn read(r: &mut Reader<'_>) -> Result { - Ok(Rect { top: r.i32()?, left: r.i32()?, bottom: r.i32()?, right: r.i32()? }) - } - fn write(&self, out: &mut Vec) { - out.put_i32(self.top); - out.put_i32(self.left); - out.put_i32(self.bottom); - out.put_i32(self.right); - } -} - -/// Layer record flag byte. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct LayerFlags(pub u8); - -impl LayerFlags { - /// Bit 0. - pub const TRANSPARENCY_PROTECTED: u8 = 1 << 0; - /// Bit 1 (set = hidden). - pub const HIDDEN: u8 = 1 << 1; - /// Bit 2 (obsolete). - pub const OBSOLETE: u8 = 1 << 2; - /// Bit 3: bit 4 carries useful information. - pub const BIT4_USEFUL: u8 = 1 << 3; - /// Bit 4: pixel data irrelevant to the appearance of the document. - pub const PIXEL_DATA_IRRELEVANT: u8 = 1 << 4; - - fn bit(self, b: u8) -> bool { - self.0 & b != 0 - } - fn set(&mut self, b: u8, on: bool) { - if on { - self.0 |= b; - } else { - self.0 &= !b; - } - } - /// Transparency protected. - pub fn transparency_protected(self) -> bool { - self.bit(Self::TRANSPARENCY_PROTECTED) - } - /// Hidden. - pub fn hidden(self) -> bool { - self.bit(Self::HIDDEN) - } - /// Bit 4 is meaningful. - pub fn bit4_useful(self) -> bool { - self.bit(Self::BIT4_USEFUL) - } - /// Pixel data irrelevant (only meaningful when `bit4_useful`). - pub fn pixel_data_irrelevant(self) -> bool { - self.bit(Self::PIXEL_DATA_IRRELEVANT) - } - /// Sets hidden. - pub fn set_hidden(&mut self, v: bool) { - self.set(Self::HIDDEN, v); - } - /// Sets transparency protection. - pub fn set_transparency_protected(&mut self, v: bool) { - self.set(Self::TRANSPARENCY_PROTECTED, v); - } - /// Sets pixel-data-irrelevant (also sets bit 3). - pub fn set_pixel_data_irrelevant(&mut self, v: bool) { - self.set(Self::BIT4_USEFUL, true); - self.set(Self::PIXEL_DATA_IRRELEVANT, v); - } -} - -/// Optional mask parameters (present when mask flag bit 4 is set). -#[derive(Debug, Clone, Copy, PartialEq, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct MaskParameters { - /// Parameter flags byte (bit 0 user density, 1 user feather, 2 vector - /// density, 3 vector feather). - pub flags: u8, - /// User mask density. - pub user_density: Option, - /// User mask feather. - pub user_feather: Option, - /// Vector mask density. - pub vector_density: Option, - /// Vector mask feather. - pub vector_feather: Option, -} - -/// "Real" user mask fields (present in 36+-byte mask records). -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct RealMask { - /// Real flags. - pub flags: u8, - /// Real user mask background (0 or 255). - pub background: u8, - /// Real mask rectangle. - pub rect: Rect, -} - -/// Layer mask / adjustment layer data. -#[derive(Debug, Clone, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct LayerMask { - /// Mask rectangle. - pub rect: Rect, - /// Default color outside the rectangle (0 or 255). - pub default_color: u8, - /// Flags: bit 0 position relative to layer, 1 disabled, 2 invert - /// (obsolete), 3 user mask came from rendering other data, 4 parameters - /// applied. - pub flags: u8, - /// Mask parameters (when flag bit 4 is set). - pub parameters: Option, - /// Real user mask fields. - pub real: Option, - /// Remaining bytes (the 2 padding bytes of the 20-byte form, etc.). - pub trailing: Vec, - /// When both are present, the real-mask fields come before the mask parameters. Photoshop - /// writes this order (the published spec lists the parameters first); `false` keeps a file - /// that uses the spec's order byte-stable. - #[cfg_attr(feature = "serde", serde(default = "default_true"))] - pub real_first: bool, -} - -#[cfg(feature = "serde")] -fn default_true() -> bool { - true -} - -/// Byte length of the mask parameter values announced by the parameter flags byte `pf`. -pub(crate) fn mask_parameter_bytes(pf: u8) -> usize { - usize::from(pf & 1 != 0) + 8 * usize::from(pf & 2 != 0) + usize::from(pf & 4 != 0) + 8 * usize::from(pf & 8 != 0) -} - -impl LayerMask { - /// Mask flag: position relative to layer. - pub const FLAG_RELATIVE: u8 = 1 << 0; - /// Mask flag: disabled. - pub const FLAG_DISABLED: u8 = 1 << 1; - /// Mask flag: invert when blending (obsolete). - pub const FLAG_INVERT: u8 = 1 << 2; - /// Mask flag: parameters present. - pub const FLAG_PARAMETERS: u8 = 1 << 4; - - /// The simple 20-byte form. - pub fn new(rect: Rect, default_color: u8, flags: u8) -> Self { - LayerMask { rect, default_color, flags: flags & !Self::FLAG_PARAMETERS, parameters: None, real: None, trailing: vec![0, 0], real_first: true } - } - /// `true` if the disabled flag is set. - pub fn disabled(&self) -> bool { - self.flags & Self::FLAG_DISABLED != 0 - } - - /// Whether `d` (a whole mask record with mask parameters) stores the real-mask fields before - /// the parameters, as Photoshop does. The spec's order wins when it reads as parameters - /// followed by padding alone (no real mask), the one layout the two orders can share. When - /// both orders fit the record's length, Photoshop's is taken unless its reading is - /// implausible (a real-mask background that is neither 0 nor 255, or parameter flag bits - /// the spec does not define) while the spec's reading with a real mask is sound. - pub(crate) fn real_before_parameters(d: &[u8]) -> bool { - // Parameters at `pf_at`, then 0..=3 bytes of padding, and nothing else. - let fits = - |pf_at: usize| d.get(pf_at).is_some_and(|&pf| (pf_at + 1 + mask_parameter_bytes(pf)..=pf_at + 4 + mask_parameter_bytes(pf)).contains(&d.len())); - if fits(18) { - return false; - } - let photoshop = fits(36); - if !photoshop { - return false; - } - let known_flags = |pf: u8| pf & 0xF0 == 0; - let real_background_ok = |at: usize| d.get(at + 1).is_some_and(|&bg| bg == 0 || bg == 255); - // Photoshop's reading: real-mask fields at 18, parameters at 36. - let photoshop_plausible = real_background_ok(18) && d.get(36).is_some_and(|&pf| known_flags(pf)); - // The spec's reading: parameters at 18, then the 18 real-mask bytes, then padding. - let spec_plausible = d.get(18).is_some_and(|&pf| { - let real_at = 19 + mask_parameter_bytes(pf); - known_flags(pf) && (real_at + 18..=real_at + 21).contains(&d.len()) && real_background_ok(real_at) - }); - photoshop_plausible || !spec_plausible - } - - fn parse(d: &[u8]) -> Result { - let mut r = Reader::new(d); - let rect = Rect::read(&mut r)?; - let default_color = r.u8()?; - let flags = r.u8()?; - let read_real = |r: &mut Reader<'_>| -> Result> { - Ok(if r.remaining() >= 18 { Some(RealMask { flags: r.u8()?, background: r.u8()?, rect: Rect::read(r)? }) } else { None }) - }; - let has_parameters = flags & Self::FLAG_PARAMETERS != 0; - let real_first = has_parameters && Self::real_before_parameters(d); - let mut real = if real_first { read_real(&mut r)? } else { None }; - let parameters = if has_parameters { - let pf = r.u8()?; - Some(MaskParameters { - flags: pf, - user_density: if pf & 1 != 0 { Some(r.u8()?) } else { None }, - user_feather: if pf & 2 != 0 { Some(r.f64()?) } else { None }, - vector_density: if pf & 4 != 0 { Some(r.u8()?) } else { None }, - vector_feather: if pf & 8 != 0 { Some(r.f64()?) } else { None }, - }) - } else { - None - }; - if !real_first { - real = read_real(&mut r)?; - } - // The order only matters when both are present; otherwise default to Photoshop's. - let real_first = real_first || real.is_none() || parameters.is_none(); - Ok(LayerMask { rect, default_color, flags, parameters, real, trailing: r.peek_rest().to_vec(), real_first }) - } - - /// Bytes [`Self::write`] produces. - fn encoded_len(&self) -> u64 { - let real = if self.real.is_some() { 18 } else { 0 }; - let parameters = self.parameters.as_ref().map_or(0, |p| { - 1 + u64::from(p.user_density.is_some()) - + 8 * u64::from(p.user_feather.is_some()) - + u64::from(p.vector_density.is_some()) - + 8 * u64::from(p.vector_feather.is_some()) - }); - 18 + real + parameters + self.trailing.len() as u64 - } - - fn write(&self, out: &mut Vec) { - self.rect.write(out); - out.put_u8(self.default_color); - out.put_u8(self.flags); - let write_real = |out: &mut Vec| { - if let Some(real) = &self.real { - out.put_u8(real.flags); - out.put_u8(real.background); - real.rect.write(out); - } - }; - if self.real_first { - write_real(out); - } - if let Some(p) = &self.parameters { - out.put_u8(p.flags); - if let Some(v) = p.user_density { - out.put_u8(v); - } - if let Some(v) = p.user_feather { - out.put_f64(v); - } - if let Some(v) = p.vector_density { - out.put_u8(v); - } - if let Some(v) = p.vector_feather { - out.put_f64(v); - } - } - if !self.real_first { - write_real(out); - } - out.put(&self.trailing); - } -} - -/// The layer mask data field of a layer record. -#[derive(Debug, Clone, PartialEq, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum MaskData { - /// Length 0. - #[default] - None, - /// Parsed mask. - Mask(LayerMask), - /// Unparseable mask data, preserved. - Raw(Vec), -} - -/// Layer blending ranges ("Blend If"), stored raw. The data is a sequence of -/// 8-byte entries: composite gray first, then one per channel; each entry is -/// source (black lo, black hi, white lo, white hi) then destination. -#[derive(Debug, Clone, PartialEq, Eq, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct BlendingRanges { - /// Raw bytes. - pub data: Vec, -} - -/// One blending range entry. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct BlendRange { - /// Source range: black low, black high, white low, white high. - pub source: [u8; 4], - /// Destination range. - pub dest: [u8; 4], -} - -impl BlendingRanges { - /// Default "full" ranges for composite + `channels` channels. - pub fn full(channels: usize) -> Self { - let mut data = Vec::with_capacity((channels + 1) * 8); - for _ in 0..=channels { - data.extend_from_slice(&[0, 0, 255, 255, 0, 0, 255, 255]); - } - BlendingRanges { data } - } - /// Parsed entries (incomplete trailing bytes are ignored). - pub fn ranges(&self) -> Vec { - self.data.as_chunks::<8>().0.iter().map(|c| BlendRange { source: [c[0], c[1], c[2], c[3]], dest: [c[4], c[5], c[6], c[7]] }).collect() - } -} - -/// Encoded image data for one layer channel. -/// -/// The encoded bytes are in `data`, or, for a file parsed by -/// [`PsdFile::from_source`](crate::PsdFile::from_source), still in the source at `stored` (and -/// `data` is empty). Every method here reads them from wherever they are; two channels are equal -/// when their bytes are, wherever each one keeps them. -#[derive(Debug, Clone)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ChannelData { - /// Channel id: 0.. color channels, -1 transparency, -2 user mask, - /// -3 real user mask. - pub id: i16, - /// Compression; `None` when the stored length was 0 (no compression - /// field at all). - pub compression: Option, - /// Encoded bytes following the compression field, kept verbatim (empty while `stored`). - pub data: Vec, - /// Where the encoded bytes are when they were left in the source: see [`Self::load`]. - /// (Not serialized: load the channel first.) - #[cfg_attr(feature = "serde", serde(skip))] - pub stored: Option, -} - -impl PartialEq for ChannelData { - fn eq(&self, other: &Self) -> bool { - if self.id != other.id || self.compression != other.compression || self.encoded_len() != other.encoded_len() { - return false; - } - match (self.encoded(), other.encoded()) { - (Ok(a), Ok(b)) => a == b, - _ => false, - } - } -} - -impl Eq for ChannelData {} - -impl ChannelData { - /// Encodes planar samples (`height × row_bytes`). - pub fn encode(id: i16, compression: Compression, decoded: &[u8], width: usize, height: usize, depth: u16, version: Version) -> Result { - let layout = PlaneLayout { planes: 1, width, height, depth, version }; - Ok(ChannelData::new(id, Some(compression), encode_planes(compression, decoded, &layout)?)) - } - - /// A channel whose encoded bytes are in memory. - pub fn new(id: i16, compression: Option, data: Vec) -> Self { - ChannelData { id, compression, data, stored: None } - } - - /// The encoded bytes (after the compression field): borrowed from `data`, or read from the - /// source when they were left there. - pub fn encoded(&self) -> Result> { - crate::source::encoded(&self.data, self.stored.as_ref()) - } - - /// Number of encoded bytes, wherever they are. - pub fn encoded_len(&self) -> u64 { - self.stored.as_ref().map_or(self.data.len() as u64, |s| s.len) - } - - /// Reads bytes left in the source into `data`, so the channel no longer needs its source. - pub fn load(&mut self) -> Result<()> { - if let Some(s) = &self.stored { - self.data = s.read()?; - self.stored = None; - } - Ok(()) - } - - /// Decodes into planar big-endian samples. - pub fn decode(&self, width: usize, height: usize, depth: u16, version: Version) -> Result> { - let layout = PlaneLayout { planes: 1, width, height, depth, version }; - match self.compression { - Some(c) => decode_planes(c, &self.encoded()?, &layout), - None => { - if layout.decoded_len()? == 0 { - Ok(Vec::new()) - } else { - Err(PsdError::invalid("channel has no data")) - } - } - } - } - - /// Replaces the channel contents, re-encoding with `compression`. - #[allow(clippy::too_many_arguments)] - pub fn set_decoded(&mut self, compression: Compression, decoded: &[u8], width: usize, height: usize, depth: u16, version: Version) -> Result<()> { - *self = Self::encode(self.id, compression, decoded, width, height, depth, version)?; - Ok(()) - } - - fn stored_len(&self) -> u64 { - match self.compression { - Some(_) => 2 + self.encoded_len(), - None => 0, - } - } -} - -/// A layer record together with its channel image data. -#[derive(Debug, Clone, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct LayerRecord { - /// Layer bounds. - pub rect: Rect, - /// Channels in stored order, including encoded image data. - pub channels: Vec, - /// Blend mode. - pub blend_mode: BlendMode, - /// Opacity 0..=255. - pub opacity: u8, - /// Clipping: 0 base, 1 non-base (clipped to layer below). - pub clipping: u8, - /// Flags. - pub flags: LayerFlags, - /// Filler byte (zero), preserved. - pub filler: u8, - /// Layer mask data. - pub mask: MaskData, - /// Blending ranges. - pub blending_ranges: BlendingRanges, - /// Legacy Pascal name bytes (padded to 4 in the file). - pub name: Vec, - /// Additional layer information blocks. - pub blocks: Vec, - /// Bytes at the end of the extra-data field that do not form a block. - pub extra_trailing: Vec, -} - -impl Default for LayerRecord { - fn default() -> Self { - LayerRecord { - rect: Rect::default(), - channels: Vec::new(), - blend_mode: BlendMode::Normal, - opacity: 255, - clipping: 0, - flags: LayerFlags(0), - filler: 0, - mask: MaskData::None, - blending_ranges: BlendingRanges::default(), - name: Vec::new(), - blocks: Vec::new(), - extra_trailing: Vec::new(), - } - } -} - -impl LayerRecord { - /// Layer name, preferring the Unicode `luni` block over the legacy name. - pub fn name(&self) -> String { - for b in &self.blocks { - if &b.key == b"luni" - && let Some(Ok(BlockData::UnicodeName(n))) = b.parsed() - { - return n; - } - } - decode_legacy_name(&self.name) - } - - /// First block with the given key. - pub fn block(&self, key: &[u8; 4]) -> Option<&TaggedBlock> { - self.blocks.iter().find(|b| &b.key == key) - } - - /// Mutable access to the first block with the given key. - pub fn block_mut(&mut self, key: &[u8; 4]) -> Option<&mut TaggedBlock> { - self.blocks.iter_mut().find(|b| &b.key == key) - } - - /// Section divider (`lsct`, falling back to `lsdk`), if present and valid. - pub fn section_divider(&self) -> Option { - for key in [b"lsct", b"lsdk"] { - if let Some(Ok(BlockData::SectionDivider(s))) = self.block(key).and_then(TaggedBlock::parsed) { - return Some(s); - } - } - None - } - - /// Section type (Other if no divider). - pub fn section_type(&self) -> SectionType { - self.section_divider().map_or(SectionType::Other, |s| s.kind) - } - - /// `true` unless the hidden flag is set. - pub fn is_visible(&self) -> bool { - !self.flags.hidden() - } - - /// Layer id from `lyid`. - pub fn layer_id(&self) -> Option { - match self.block(b"lyid")?.parsed()? { - Ok(BlockData::LayerId(v)) => Some(v), - _ => None, - } - } - - /// Fill opacity from `iOpa` (255 if absent). - pub fn fill_opacity(&self) -> u8 { - match self.block(b"iOpa").and_then(TaggedBlock::parsed) { - Some(Ok(BlockData::FillOpacity(v))) => v, - _ => 255, - } - } - - /// Parsed layer mask, if any. - pub fn layer_mask(&self) -> Option<&LayerMask> { - match &self.mask { - MaskData::Mask(m) => Some(m), - _ => None, - } - } - - /// Channel with the given id. - pub fn channel(&self, id: i16) -> Option<&ChannelData> { - self.channels.iter().find(|c| c.id == id) - } - - /// Rectangle that a channel's pixels cover: the layer rect for color and - /// transparency channels, the mask rect for -2, the real mask rect for -3. - pub fn channel_rect(&self, id: i16) -> Rect { - match (id, &self.mask) { - (CHANNEL_USER_MASK, MaskData::Mask(m)) => m.rect, - (CHANNEL_REAL_USER_MASK, MaskData::Mask(m)) => m.real.map_or(m.rect, |r| r.rect), - _ => self.rect, - } - } - - /// Decodes a channel's samples (planar, big-endian). - pub fn decode_channel(&self, id: i16, depth: u16, version: Version) -> Result> { - let ch = self.channel(id).ok_or_else(|| PsdError::invalid(format!("layer has no channel {id}")))?; - let (w, h) = self.channel_rect(id).size()?; - ch.decode(w, h, depth, version) - } - - pub(crate) fn read(r: &mut Reader<'_>, version: Version) -> Result<(Self, Vec)> { - let rect = Rect::read(r)?; - let nch = r.u16()?; - if nch > MAX_LAYER_CHANNELS { - return Err(PsdError::LimitExceeded("too many channels in layer")); - } - let mut channels = Vec::with_capacity(usize::from(nch)); - let mut lens = Vec::with_capacity(usize::from(nch)); - for _ in 0..nch { - let id = r.i16()?; - let len = r.len_field(version.is_psb())?; - channels.push(ChannelData::new(id, None, Vec::new())); - lens.push(len); - } - let sig = r.array::<4>()?; - if &sig != b"8BIM" { - return Err(PsdError::InvalidSignature { expected: "8BIM (layer blend mode)", found: sig }); - } - let blend_mode = BlendMode::from_key(r.array()?); - let opacity = r.u8()?; - let clipping = r.u8()?; - let flags = LayerFlags(r.u8()?); - let filler = r.u8()?; - let extra_len = r.u32()?; - let mut x = r.sub(u64::from(extra_len))?; - let mask_len = x.u32()?; - let mask_bytes = x.bytes_u64(u64::from(mask_len))?; - let mask = if mask_bytes.is_empty() { - MaskData::None - } else { - match LayerMask::parse(mask_bytes) { - Ok(m) => MaskData::Mask(m), - Err(_) => MaskData::Raw(mask_bytes.to_vec()), - } - }; - let br_len = x.u32()?; - let blending_ranges = BlendingRanges { data: x.bytes_u64(u64::from(br_len))?.to_vec() }; - let name = read_pascal(&mut x, 4)?; - let (blocks, extra_trailing) = read_blocks(&mut x, version)?; - Ok((LayerRecord { rect, channels, blend_mode, opacity, clipping, flags, filler, mask, blending_ranges, name, blocks, extra_trailing }, lens)) - } - - /// Rows of a channel's RLE count table that grow when a PSD model is written as PSB - /// (`widen`, see [`crate::PsdFile::promote_to_psb`]); 0 for other channels. - pub(crate) fn widened_rows(&self, c: &ChannelData, widen: bool) -> Result { - if widen && c.compression == Some(Compression::Rle) { Ok(self.channel_rect(c.id).size()?.1) } else { Ok(0) } - } - - /// Bytes [`Self::write`] produces, computed without serializing. Errors where `write` would. - fn encoded_len(&self, version: Version) -> Result { - let too_big = || PsdError::LimitExceeded("section too large for 32-bit length (use PSB)"); - u16::try_from(self.channels.len()).map_err(|_| PsdError::LimitExceeded("too many channels"))?; - let channel_len: u64 = if version.is_psb() { 8 } else { 4 }; - if !version.is_psb() && self.channels.iter().any(|c| u32::try_from(c.stored_len()).is_err()) { - return Err(too_big()); - } - let mask = match &self.mask { - MaskData::None => 0, - MaskData::Mask(mask) => mask.encoded_len(), - MaskData::Raw(b) => b.len() as u64, - }; - u32::try_from(mask).map_err(|_| too_big())?; - let ranges = self.blending_ranges.data.len() as u64; - u32::try_from(ranges).map_err(|_| too_big())?; - let name = 1 + self.name.len().min(255) as u64; - let name = name.next_multiple_of(4); - let mut extra = (4 + mask).saturating_add(4 + ranges).saturating_add(name).saturating_add(self.extra_trailing.len() as u64); - for b in &self.blocks { - if !uses_long_length(version, &b.key) && u32::try_from(b.data.len()).is_err() { - return Err(too_big()); - } - extra = extra.saturating_add(b.encoded_len(version) as u64); - } - u32::try_from(extra).map_err(|_| too_big())?; - // rect, channel count, channel entries, signature + blend key, four flag bytes, extra length. - Ok((16 + 2 + self.channels.len() as u64 * (2 + channel_len) + 8 + 4 + 4).saturating_add(extra)) - } - - fn write(&self, out: &mut Vec, version: Version, widen: bool) -> Result<()> { - self.rect.write(out); - let nch = u16::try_from(self.channels.len()).map_err(|_| PsdError::LimitExceeded("too many channels"))?; - out.put_u16(nch); - for c in &self.channels { - out.put_i16(c.id); - let rows = self.widened_rows(c, widen)?; - let grown = if rows == 0 { 0 } else { rle_widening_len(c.encoded_len(), rows)? }; - out.put_len(c.stored_len().saturating_add(grown), version.is_psb())?; - } - out.put(b"8BIM"); - out.put(&self.blend_mode.key()); - out.put_u8(self.opacity); - out.put_u8(self.clipping); - out.put_u8(self.flags.0); - out.put_u8(self.filler); - let at = out.begin_len(false); - let m = out.begin_len(false); - match &self.mask { - MaskData::None => {} - MaskData::Mask(mask) => mask.write(out), - MaskData::Raw(b) => out.put(b), - } - out.end_len(m, false)?; - out.put_len(self.blending_ranges.data.len() as u64, false)?; - out.put(&self.blending_ranges.data); - write_pascal(out, &self.name, 4); - write_blocks(out, &self.blocks, version, 2)?; - out.put(&self.extra_trailing); - out.end_len(at, false) - } -} - -/// Layer info: layer records plus their channel image data. -#[derive(Debug, Clone, PartialEq, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct LayerInfo { - /// The layer count was stored negative: the first alpha channel of the - /// merged image contains the transparency of the merged result. - pub merged_alpha: bool, - /// Layer records, bottom-most first (file order). - pub layers: Vec, - /// Bytes after the channel data. `None` = default (zero pad to even). - pub padding: Option>, -} - -impl LayerInfo { - /// Parses a layer info body (the bytes covered by its length field). - pub(crate) fn read_body(data: &[u8], version: Version) -> Result { - let mut r = Reader::new(data); - let count = r.i16()?; - let merged_alpha = count < 0; - let n = count.unsigned_abs(); - // Minimum record size: 16 rect + 2 + 4 sig + 4 key + 4 + 4 extra len. - r.check_count(u64::from(n), 34)?; - let mut layers = Vec::with_capacity(usize::from(n)); - let mut all_lens = Vec::with_capacity(usize::from(n)); - for _ in 0..n { - let (rec, lens) = LayerRecord::read(&mut r, version)?; - layers.push(rec); - all_lens.push(lens); - } - for (rec, lens) in layers.iter_mut().zip(all_lens) { - for (ch, len) in rec.channels.iter_mut().zip(lens) { - if len == 0 { - continue; - } - if len == 1 { - return Err(PsdError::invalid("channel data length 1")); - } - ch.compression = Some(Compression::from_u16(r.u16()?)); - ch.data = r.bytes_u64(len - 2)?.to_vec(); - } - } - let body_len = r.pos(); - let rest = r.peek_rest(); - let padding = if rest.len() == body_len % 2 && rest.iter().all(|&b| b == 0) { None } else { Some(rest.to_vec()) }; - Ok(LayerInfo { merged_alpha, layers, padding }) - } - - /// Length of the body (layer count, records and channel data) without - /// its trailing padding. - pub fn unpadded_len(&self, version: Version) -> Result { - self.unpadded_len_as(version, false) - } - - /// [`Self::unpadded_len`] of the body written with its RLE count tables widened (`widen`). - pub(crate) fn unpadded_len_as(&self, version: Version, widen: bool) -> Result { - // Computed from the field sizes: serializing the records just to measure them would copy - // every tagged block. Widening changes channel data only: the record's length fields keep - // their width. - let mut n = 2u64; - for l in &self.layers { - n = n.saturating_add(l.encoded_len(version)?); - } - for l in &self.layers { - for c in l.channels.iter().filter(|c| c.compression.is_some()) { - let rows = l.widened_rows(c, widen)?; - let grown = if rows == 0 { 0 } else { rle_widening_len(c.encoded_len(), rows)? }; - n = n.saturating_add(2).saturating_add(c.encoded_len()).saturating_add(grown); - } - } - Ok(n) - } - - /// Sets the padding so the body length is a multiple of `align`, as - /// Photoshop writes it (4). Readers that step over a global `Lr16`/`Lr32` - /// block in 4-byte units (psd-tools) misread the blocks after a body that - /// is only padded to even. - pub fn pad_to(&mut self, version: Version, align: u64) -> Result<()> { - self.padding = Some(vec![0; self.pad_len(version, align)?]); - Ok(()) - } - - /// Number of zero bytes [`Self::pad_to`] would set, without touching `self`. - pub(crate) fn pad_len(&self, version: Version, align: u64) -> Result { - self.pad_len_as(version, false, align) - } - - /// [`Self::pad_len`] for the body written with its RLE count tables widened (`widen`). - pub(crate) fn pad_len_as(&self, version: Version, widen: bool, align: u64) -> Result { - let align = align.max(1); - let len = self.unpadded_len_as(version, widen)?; - Ok(((align - len % align) % align) as usize) - } - - /// Bytes of channel data and their compression fields: the part of the body worth reserving up - /// front (the records are small next to the pixels). Saturates instead of overflowing. - /// (Saves reserve their exact length now, #6607; the tests still check it as a lower bound.) - #[cfg(test)] - pub(crate) fn channel_data_len(&self) -> usize { - self.layers - .iter() - .flat_map(|l| &l.channels) - .filter(|c| c.compression.is_some()) - .fold(0usize, |n, c| n.saturating_add(2).saturating_add(usize::try_from(c.encoded_len()).unwrap_or(usize::MAX))) - } - - /// Serializes the body without any trailing padding (the padding field is ignored). - pub(crate) fn write_unpadded(&self, out: &mut Vec, version: Version) -> Result<()> { - append_with(out, |s| self.write_unpadded_to(s, version, false)) - } - - /// Serializes the body (without a length field). - #[cfg(test)] - pub(crate) fn write_body(&self, out: &mut Vec, version: Version) -> Result<()> { - append_with(out, |s| self.write_body_to(s, version, false)) - } - - /// [`Self::write_unpadded`] to a streaming [`Sink`], widening the RLE count tables of a PSD - /// model written as PSB (`widen`) on the way out: the records are staged, the channel data - /// goes straight through (#6607). - pub(crate) fn write_unpadded_to( - &self, - out: &mut Sink<'_, W>, - version: Version, - widen: bool, - ) -> std::io::Result<()> { - let n = i16::try_from(self.layers.len()).map_err(|_| PsdError::LimitExceeded("more than 32767 layers"))?; - out.small(|o| { - o.put_i16(if self.merged_alpha { -n } else { n }); - Ok(()) - })?; - for l in &self.layers { - out.small(|o| l.write(o, version, widen))?; - } - for l in &self.layers { - for c in &l.channels { - if let Some(comp) = c.compression { - out.small(|o| { - o.put_u16(comp.as_u16()); - Ok(()) - })?; - match l.widened_rows(c, widen)? { - 0 => out.put_encoded(&c.data, c.stored.as_ref())?, - rows => out.put_widened_encoded(&c.data, c.stored.as_ref(), rows)?, - } - } - } - } - Ok(()) - } - - /// The body (without a length field) to a streaming [`Sink`], widening RLE count tables when - /// `widen` (see [`Self::write_unpadded_to`]). - pub(crate) fn write_body_to( - &self, - out: &mut Sink<'_, W>, - version: Version, - widen: bool, - ) -> std::io::Result<()> { - let start = out.pos(); - self.write_unpadded_to(out, version, widen)?; - match &self.padding { - Some(p) => out.put(p), - None => out.zeros(((out.pos() - start) % 2) as usize), - } - } -} - -#[cfg(test)] -mod tests; diff --git a/crates/psd/src/layer/tests.rs b/crates/psd/src/layer/tests.rs deleted file mode 100644 index c831b1c6d2..0000000000 --- a/crates/psd/src/layer/tests.rs +++ /dev/null @@ -1,374 +0,0 @@ -use super::*; - -fn sample_record(version: Version) -> LayerRecord { - let rect = Rect::from_xywh(-3, 2, 5, 4); - let px: Vec = (0..20).collect(); - let mut channels = Vec::new(); - for (id, comp) in [(-1, Compression::Rle), (0, Compression::Raw), (1, Compression::Zip), (2, Compression::ZipPrediction)] { - channels.push(ChannelData::encode(id, comp, &px, 5, 4, 8, version).unwrap()); - } - let mask = LayerMask::new(Rect::from_xywh(0, 0, 2, 2), 255, LayerMask::FLAG_RELATIVE); - channels.push(ChannelData::encode(-2, Compression::Rle, &[1, 2, 3, 4], 2, 2, 8, version).unwrap()); - LayerRecord { - rect, - channels, - blend_mode: BlendMode::Screen, - opacity: 200, - clipping: 1, - flags: LayerFlags(LayerFlags::HIDDEN), - mask: MaskData::Mask(mask), - blending_ranges: BlendingRanges::full(3), - name: b"abc".to_vec(), - blocks: vec![TaggedBlock::unicode_name("\u{e4}bc"), TaggedBlock::layer_id(5)], - ..Default::default() - } -} - -fn rt(info: &LayerInfo, version: Version) -> Vec { - let mut out = Vec::new(); - info.write_body(&mut out, version).unwrap(); - let back = LayerInfo::read_body(&out, version).unwrap(); - assert_eq!(&back, info); - let mut again = Vec::new(); - back.write_body(&mut again, version).unwrap(); - assert_eq!(again, out); - out -} - -#[test] -fn empty_layer_info() { - let out = rt(&LayerInfo::default(), Version::Psd); - assert_eq!(out, vec![0, 0]); -} - -#[test] -fn record_roundtrip_psd_psb() { - for v in [Version::Psd, Version::Psb] { - let info = LayerInfo { merged_alpha: true, layers: vec![sample_record(v), LayerRecord::default()], padding: None }; - let out = rt(&info, v); - assert_eq!(out.len() % 2, 0); - assert_eq!(&out[..2], &(-2i16).to_be_bytes()); - } -} - -#[test] -fn psb_channel_lengths_are_8_bytes() { - let mut rec = LayerRecord::default(); - rec.channels.push(ChannelData::new(0, Some(Compression::Raw), vec![])); - let info = LayerInfo { layers: vec![rec], ..Default::default() }; - let psd = rt(&info, Version::Psd); - let psb = rt(&info, Version::Psb); - assert_eq!(psb.len(), psd.len() + 4); -} - -#[test] -fn channel_decode_via_record() { - let rec = sample_record(Version::Psd); - let px: Vec = (0..20).collect(); - for id in [-1, 0, 1, 2] { - assert_eq!(rec.decode_channel(id, 8, Version::Psd).unwrap(), px); - } - assert_eq!(rec.decode_channel(-2, 8, Version::Psd).unwrap(), vec![1, 2, 3, 4]); - assert!(rec.decode_channel(7, 8, Version::Psd).is_err()); -} - -#[test] -fn record_accessors() { - let rec = sample_record(Version::Psd); - assert_eq!(rec.name(), "\u{e4}bc"); - assert!(!rec.is_visible()); - assert_eq!(rec.layer_id(), Some(5)); - assert_eq!(rec.fill_opacity(), 255); - assert_eq!(rec.section_type(), SectionType::Other); - assert!(rec.layer_mask().is_some()); - assert_eq!(rec.channel_rect(-2), Rect::from_xywh(0, 0, 2, 2)); - assert_eq!(rec.channel_rect(0), rec.rect); - let mut plain = LayerRecord { name: b"legacy".to_vec(), ..Default::default() }; - assert_eq!(plain.name(), "legacy"); - plain.blocks.push(TaggedBlock::fill_opacity(10)); - assert_eq!(plain.fill_opacity(), 10); - plain.block_mut(b"iOpa").unwrap().data[0] = 11; - assert_eq!(plain.fill_opacity(), 11); -} - -#[test] -fn mask_variants_roundtrip() { - let base = LayerMask::new(Rect::from_xywh(1, 2, 3, 4), 0, 0); - let with_real = LayerMask { real: Some(RealMask { flags: 1, background: 255, rect: Rect::from_xywh(0, 0, 9, 9) }), trailing: vec![], ..base.clone() }; - let with_params = LayerMask { - flags: LayerMask::FLAG_PARAMETERS, - parameters: Some(MaskParameters { - flags: 0b1111, - user_density: Some(128), - user_feather: Some(2.5), - vector_density: Some(64), - vector_feather: Some(0.5), - }), - real: Some(RealMask::default()), - trailing: vec![0, 0], - ..base.clone() - }; - let partial_params = LayerMask { - flags: LayerMask::FLAG_PARAMETERS, - parameters: Some(MaskParameters { flags: 0b0010, user_feather: Some(1.0), ..Default::default() }), - trailing: vec![], - ..base.clone() - }; - for m in [base, with_real, with_params, partial_params] { - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(LayerMask::parse(&out).unwrap(), m); - } -} - -/// Photoshop stores the real-mask fields before the mask parameters (psd-tools -/// mask-density-layervectormask.psd): user + vector mask with both densities set. -#[test] -fn real_mask_before_parameters_photoshop_layout() { - let mut d = Vec::new(); - Rect::from_xywh(15, -1, 18, 10).write(&mut d); - d.extend([0, LayerMask::FLAG_PARAMETERS | 8]); - d.extend([0, 255]); - Rect::from_xywh(0, 0, 32, 8).write(&mut d); - d.extend([0b0101, 64, 64, 0]); - let m = LayerMask::parse(&d).unwrap(); - assert_eq!(m.real.map(|r| r.rect), Some(Rect::from_xywh(0, 0, 32, 8))); - assert_eq!(m.real.map(|r| r.background), Some(255)); - let p = m.parameters.unwrap(); - assert_eq!((p.user_density, p.vector_density), (Some(64), Some(64))); - assert_eq!(m.trailing, vec![0]); - assert!(m.real_first); - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(out, d); -} - -/// A density-only record in the spec's order (#949): the parameter flags byte at 18 says one -/// value byte, so the spec's reading excludes the 38-byte length only if the real mask is -/// ignored, while byte 36 (inside the real rectangle's `right`) is 0 and makes Photoshop's -/// reading fit too. Photoshop's reading puts the density (64) where a 0-or-255 background -/// belongs, so the spec's order wins and the density survives. -#[test] -fn density_only_spec_layout_is_not_read_as_photoshop_order() { - for (density, right) in [(64u8, 1u32), (200, 1), (64, 300), (1, 7)] { - let mut d = Vec::new(); - Rect::from_xywh(0, 0, 1, 1).write(&mut d); - d.extend([255, LayerMask::FLAG_PARAMETERS]); - d.extend([0b0001, density]); - d.extend([0, 0]); - Rect::from_xywh(0, 0, right, 1).write(&mut d); - let m = LayerMask::parse(&d).unwrap(); - assert!(!m.real_first, "density {density}, right {right}: {m:?}"); - assert_eq!(m.parameters.unwrap().user_density, Some(density)); - assert_eq!(m.real, Some(RealMask { flags: 0, background: 0, rect: Rect::from_xywh(0, 0, right, 1) })); - assert!(m.trailing.is_empty()); - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(out, d); - } - // Photoshop's order with the same lengths still reads as Photoshop's order. - let mut d = Vec::new(); - Rect::from_xywh(0, 0, 1, 1).write(&mut d); - d.extend([255, LayerMask::FLAG_PARAMETERS]); - d.extend([0, 255]); - Rect::from_xywh(0, 0, 1, 1).write(&mut d); - d.extend([0b0001, 64]); - let m = LayerMask::parse(&d).unwrap(); - assert!(m.real_first, "{m:?}"); - assert_eq!(m.parameters.unwrap().user_density, Some(64)); - assert_eq!(m.real.map(|r| r.background), Some(255)); - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(out, d); -} - -/// The spec's order (parameters, then real fields) still parses and stays byte-stable. -#[test] -fn real_mask_after_parameters_spec_layout() { - let mut d = Vec::new(); - Rect::from_xywh(1, 2, 3, 4).write(&mut d); - d.extend([255, LayerMask::FLAG_PARAMETERS]); - d.extend([0b0011, 200]); - d.extend(1.5f64.to_be_bytes()); - d.extend([0, 255]); - Rect::from_xywh(0, 0, 3, 3).write(&mut d); - let m = LayerMask::parse(&d).unwrap(); - assert!(!m.real_first); - assert_eq!(m.real.map(|r| r.rect), Some(Rect::from_xywh(0, 0, 3, 3))); - assert_eq!(m.parameters.unwrap().user_feather, Some(1.5)); - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(out, d); - // Parameters alone (no real mask) keep reading in the spec's order. - let mut d = Vec::new(); - Rect::from_xywh(1, 2, 3, 4).write(&mut d); - d.extend([255, LayerMask::FLAG_PARAMETERS, 0b1010]); - d.extend(1.0f64.to_be_bytes()); - d.extend(2.0f64.to_be_bytes()); - d.extend([0, 0]); - let m = LayerMask::parse(&d).unwrap(); - assert_eq!(m.real, None); - assert_eq!(m.parameters.map(|p| (p.user_feather, p.vector_feather)), Some((Some(1.0), Some(2.0)))); -} - -#[test] -fn mask_sizes() { - let mut out = Vec::new(); - LayerMask::new(Rect::default(), 0, 0).write(&mut out); - assert_eq!(out.len(), 20); - let m = LayerMask { real: Some(RealMask::default()), trailing: vec![], ..LayerMask::new(Rect::default(), 0, 0) }; - let mut out = Vec::new(); - m.write(&mut out); - assert_eq!(out.len(), 36); -} - -#[test] -fn short_mask_kept_raw() { - let mut rec = LayerRecord { mask: MaskData::Raw(vec![1, 2, 3]), ..Default::default() }; - rec.channels.clear(); - let info = LayerInfo { layers: vec![rec], ..Default::default() }; - rt(&info, Version::Psd); -} - -#[test] -fn flags_helpers() { - let mut f = LayerFlags::default(); - f.set_hidden(true); - f.set_transparency_protected(true); - assert!(f.hidden() && f.transparency_protected()); - f.set_pixel_data_irrelevant(true); - assert!(f.bit4_useful() && f.pixel_data_irrelevant()); - f.set_hidden(false); - assert!(!f.hidden()); -} - -#[test] -fn blending_ranges_parse() { - let br = BlendingRanges::full(3); - assert_eq!(br.data.len(), 32); - let r = br.ranges(); - assert_eq!(r.len(), 4); - assert_eq!(r[0].source, [0, 0, 255, 255]); -} - -#[test] -fn rect_helpers() { - let r = Rect::from_xywh(-5, -6, 10, 3); - assert_eq!((r.width(), r.height()), (10, 3)); - assert_eq!(r.size().unwrap(), (10, 3)); - assert!(!r.is_empty()); - let bad = Rect { top: 5, left: 0, bottom: 0, right: 1 }; - assert!(bad.size().is_err()); - assert!(bad.is_empty()); - let huge = Rect { top: 0, left: i32::MIN, bottom: 1, right: i32::MAX }; - assert!(huge.size().is_err()); -} - -#[test] -fn truncation_errors() { - let info = LayerInfo { layers: vec![sample_record(Version::Psd)], ..Default::default() }; - let mut out = Vec::new(); - info.write_body(&mut out, Version::Psd).unwrap(); - // The final byte may be the (optional) even padding; stop before it. - for cut in 0..out.len() - 1 { - assert!(LayerInfo::read_body(&out[..cut], Version::Psd).is_err(), "cut {cut}"); - } -} - -#[test] -fn bad_blend_signature() { - let info = LayerInfo { layers: vec![LayerRecord::default()], ..Default::default() }; - let mut out = Vec::new(); - info.write_body(&mut out, Version::Psd).unwrap(); - // count(2) + rect(16) + nch(2) = 20 → signature - out[20] = b'X'; - assert!(matches!(LayerInfo::read_body(&out, Version::Psd), Err(PsdError::InvalidSignature { .. }))); -} - -#[test] -fn too_many_layers_rejected() { - let out = 1000i16.to_be_bytes(); - assert!(LayerInfo::read_body(&out, Version::Psd).is_err()); -} - -#[test] -fn zero_length_channel() { - let mut rec = LayerRecord::default(); - rec.channels.push(ChannelData::new(0, None, vec![])); - let info = LayerInfo { layers: vec![rec], ..Default::default() }; - rt(&info, Version::Psd); - assert_eq!(info.layers[0].decode_channel(0, 8, Version::Psd).unwrap(), Vec::::new()); -} - -/// The computed length matches the bytes written for every mask form, long names, custom block -/// padding, long-length blocks and trailing bytes. -#[test] -fn unpadded_len_matches_the_written_body() { - for version in [Version::Psd, Version::Psb] { - let mut layers = vec![sample_record(version), LayerRecord::default()]; - for (params, real, real_first) in [(true, true, true), (true, true, false), (true, false, true), (false, true, true)] { - let mut mask = LayerMask::new(Rect::from_xywh(1, 2, 3, 4), 0, LayerMask::FLAG_PARAMETERS); - mask.parameters = - params.then_some(MaskParameters { flags: 0x0f, user_density: Some(1), user_feather: Some(2.5), vector_density: Some(3), vector_feather: None }); - mask.real = real.then_some(RealMask { flags: 0, background: 255, rect: Rect::from_xywh(0, 0, 1, 1) }); - mask.real_first = real_first; - mask.trailing = vec![0; 3]; - let mut rec = sample_record(version); - rec.mask = MaskData::Mask(mask); - rec.name = vec![b'n'; 300]; - rec.blocks.push(TaggedBlock { signature: *b"8BIM", key: *b"lsct", data: vec![1; 5], padding: Some(vec![0; 3]) }); - rec.blocks.push(TaggedBlock { signature: *b"8BIM", key: *b"Lr16", data: vec![2; 7], padding: None }); - rec.extra_trailing = vec![9; 2]; - layers.push(rec); - } - layers.push(LayerRecord { mask: MaskData::Raw(vec![5; 11]), name: b"ab".to_vec(), ..Default::default() }); - let info = LayerInfo { layers, ..Default::default() }; - let mut out = Vec::new(); - info.write_unpadded(&mut out, version).unwrap(); - assert_eq!(info.unpadded_len(version).unwrap(), out.len() as u64, "{version:?}"); - } -} - -/// Padding without cloning the layers writes the same bytes as `pad_to` on a clone, and the -/// channel data length hint is exact. -#[test] -fn unpadded_write_matches_pad_to_on_a_clone() { - use crate::{ColorMode, Compression, testgen}; - for version in [Version::Psd, Version::Psb] { - for depth in [8u16, 16, 32] { - for compression in [Compression::Raw, Compression::Rle] { - let file = testgen::layered(version, ColorMode::Rgb, depth, compression); - let mut info = file.layer_info.clone().unwrap(); - for align in [1u64, 2, 4, 8] { - let mut cloned = info.clone(); - cloned.pad_to(version, align).unwrap(); - let mut want = Vec::new(); - cloned.write_body(&mut want, version).unwrap(); - let pad = info.pad_len(version, align).unwrap(); - let mut got = Vec::new(); - info.write_unpadded(&mut got, version).unwrap(); - assert!(got.len() >= info.channel_data_len()); - got.resize(got.len() + pad, 0); - assert_eq!(got, want, "{version:?} {depth} {compression:?} align {align}"); - } - info.padding = Some(vec![7, 7]); - let mut with_padding = Vec::new(); - info.write_body(&mut with_padding, version).unwrap(); - assert!(with_padding.ends_with(&[7, 7])); - } - } - } -} - -#[test] -fn nondefault_padding_kept() { - let info = LayerInfo { padding: Some(vec![0, 0]), ..Default::default() }; - let out = rt(&info, Version::Psd); - assert_eq!(out.len(), 4); -} - -#[test] -fn unknown_blend_and_blocks_passthrough() { - let rec = LayerRecord { blend_mode: BlendMode::Unknown(*b"wxyz"), blocks: vec![TaggedBlock::new(*b"Zzzz", vec![1, 2, 3, 4, 5])], ..Default::default() }; - rt(&LayerInfo { layers: vec![rec], ..Default::default() }, Version::Psd); -} diff --git a/crates/psd/src/lazy.rs b/crates/psd/src/lazy.rs deleted file mode 100644 index f78fa90068..0000000000 --- a/crates/psd/src/lazy.rs +++ /dev/null @@ -1,448 +0,0 @@ -//! Parsing from a [`Source`] without reading the whole file: [`PsdFile::from_source`]. -//! -//! The structure (header, resources, layer records, global blocks) is read into memory as -//! [`PsdFile::from_bytes`] would hold it. The bulk of a layered file is left in the source: every -//! channel's encoded bytes and the merged image become [`Stored`] ranges, read when they are -//! decoded. Apart from those ranges, the model is the one `from_bytes` builds from the same bytes -//! (the parse tests hold the two to that), with one difference: a merged image the caller does -//! not ask for is not read, so it is not checked either. - -use crate::compression::Compression; -use crate::error::{PsdError, Result}; -use crate::file::{GlobalLayerMask, LayerInfoPlacement, PsdFile}; -use crate::header::{Header, Version}; -use crate::image_data::ImageData; -use crate::io::Reader; -use crate::layer::{LayerInfo, LayerRecord}; -use crate::resources::ImageResource; -use crate::source::{Source, Stored}; -use crate::tagged::{TaggedBlock, is_sig, uses_long_length}; - -/// Bytes read per attempt at the layer records; doubled until they all fit. (Small in tests, so -/// they grow it.) -const RECORDS_CHUNK: u64 = if cfg!(test) { 64 } else { 1 << 20 }; - -/// A bounds-checked cursor over `start..end` of a source. -struct Cursor<'a> { - src: &'a Source, - pos: u64, - end: u64, -} - -impl<'a> Cursor<'a> { - fn new(src: &'a Source) -> Self { - Cursor { src, pos: 0, end: src.get().len() } - } - - fn remaining(&self) -> u64 { - self.end.saturating_sub(self.pos) - } - - fn is_empty(&self) -> bool { - self.remaining() == 0 - } - - fn eof(&self, needed: u64) -> PsdError { - PsdError::UnexpectedEof { - offset: usize::try_from(self.pos).unwrap_or(usize::MAX), - needed: usize::try_from(needed.saturating_sub(self.remaining())).unwrap_or(usize::MAX), - } - } - - fn need(&self, n: u64) -> Result<()> { - if n > self.remaining() { Err(self.eof(n)) } else { Ok(()) } - } - - /// Reads `n` bytes. - fn bytes(&mut self, n: u64) -> Result> { - self.need(n)?; - let v = self.src.read_vec(self.pos, n)?; - self.pos += n; - Ok(v) - } - - /// Up to `n` bytes from the current position, without consuming. - fn peek(&self, n: u64) -> Result> { - self.src.read_vec(self.pos, n.min(self.remaining())) - } - - fn array(&mut self) -> Result<[u8; N]> { - self.need(N as u64)?; - let mut b = [0u8; N]; - self.src.get().read_at(self.pos, &mut b)?; - self.pos += N as u64; - Ok(b) - } - - fn u16(&mut self) -> Result { - self.array().map(u16::from_be_bytes) - } - - fn i16(&mut self) -> Result { - self.array().map(i16::from_be_bytes) - } - - fn u32(&mut self) -> Result { - self.array().map(u32::from_be_bytes) - } - - fn len_field(&mut self, long: bool) -> Result { - if long { self.array().map(u64::from_be_bytes) } else { self.u32().map(u64::from) } - } - - /// The next `n` bytes as a cursor of their own; this one moves past them. - fn sub(&mut self, n: u64) -> Result> { - self.need(n)?; - let sub = Cursor { src: self.src, pos: self.pos, end: self.pos + n }; - self.pos += n; - Ok(sub) - } - - fn skip(&mut self, n: u64) -> Result<()> { - self.need(n)?; - self.pos += n; - Ok(()) - } - - fn rest(&mut self) -> Result> { - self.bytes(self.remaining()) - } - - /// The rest as a stored range; the cursor moves to the end. - fn stored_rest(&mut self) -> Stored { - let s = Stored { source: self.src.clone(), offset: self.pos, len: self.remaining() }; - self.pos = self.end; - s - } -} - -impl PsdFile { - /// Parses a file from `source`, leaving channel data and the merged image in it: see - /// [`crate::source`]. Decoding a channel then reads its bytes from the source, which must - /// stay unchanged while the model is in use. - pub fn from_source(source: Source) -> Result { - Self::from_source_and_merged_recovering(source, |_| false, |_| false).map(|(file, _)| file) - } - - /// [`Self::from_bytes_and_merged_recovering`] for a [`Source`]: the merged image is read only - /// when `want` asks for it (and is then decoded as there, with the same recovery); otherwise - /// it stays in the source, unread and unchecked. - pub fn from_source_and_merged_recovering( - source: Source, - want: impl FnOnce(&PsdFile) -> bool, - recover: impl FnOnce(&PsdFile) -> bool, - ) -> Result<(Self, Option>>)> { - Self::from_source_and_merged_preflight(source, |file| Ok(want(file)), recover) - } - - /// Parses with a fallible pixel preflight after layer records are available and before - /// the merged image is read, validated or decoded. A preflight error is always fatal; - /// `recover` only handles damage encountered after an accepted preflight. - pub fn from_source_and_merged_preflight( - source: Source, - want: impl FnOnce(&PsdFile) -> Result, - recover: impl FnOnce(&PsdFile) -> bool, - ) -> Result<(Self, Option>>)> { - let mut c = Cursor::new(&source); - let header = Header::read(&mut Reader::new(&c.bytes(26)?))?; - let version = header.version; - let psb = version.is_psb(); - let cmd_len = c.u32()?; - let color_mode_data = c.bytes(u64::from(cmd_len))?; - let res_len = c.u32()?; - let res = c.bytes(u64::from(res_len))?; - let mut rr = Reader::new(&res); - let mut resources = Vec::new(); - while !rr.is_empty() { - resources.push(ImageResource::read(&mut rr)?); - } - - let lm_len = c.len_field(psb)?; - let mut s = c.sub(lm_len)?; - let mut layer_info = None; - let mut global_layer_mask = None; - let mut global_blocks = Vec::new(); - let mut layer_mask_trailing = Vec::new(); - let mut layer_info_placement = LayerInfoPlacement::Section; - if !s.is_empty() { - let li_len = s.len_field(psb)?; - if li_len > 0 { - layer_info = Some(read_layer_info(s.sub(li_len)?, version)?); - } - if s.remaining() >= 4 { - let n = s.u32()?; - global_layer_mask = Some(GlobalLayerMask { data: s.bytes(u64::from(n))? }); - let target_key = match header.depth { - 16 => Some(b"Lr16"), - 32 => Some(b"Lr32"), - _ => None, - }; - let mut candidate_seen = match target_key { - Some(_) => false, - None => layer_info.as_ref().is_some_and(|i: &LayerInfo| !i.layers.is_empty()), - }; - let trailing = read_blocks( - &mut s, - version, - |index, signature, key, data, padding| { - let is_candidate = match target_key { - Some(k) => &key == k, - None => matches!(&key, b"Layr" | b"Lr16" | b"Lr32"), - }; - if candidate_seen || !is_candidate { - return Ok(None); - } - candidate_seen = true; - let info = match read_layer_info(data, version) { - Ok(info) => info, - // A failed read of the source is not damage: fail the parse, as - // reading the whole file would. - Err(e @ PsdError::Read(_)) => return Err(e), - Err(_) => { - if target_key.is_some() { - layer_info = None; - } - return Ok(None); - } - }; - layer_info = Some(info); - layer_info_placement = LayerInfoPlacement::GlobalBlock { index, signature, key, padding: padding.clone() }; - Ok(Some(())) - }, - &mut global_blocks, - )?; - layer_mask_trailing = trailing; - } else { - layer_mask_trailing = s.rest()?; - } - } - let mut file = PsdFile { - header, - color_mode_data, - resources, - layer_info, - layer_info_placement, - global_layer_mask, - global_blocks, - layer_mask_trailing, - image_data: ImageData::new(Compression::Raw, Vec::new()), - write_as_psb: false, - }; - if !want(&file)? { - let compression = Compression::from_u16(c.u16()?); - file.image_data = ImageData { compression, data: Vec::new(), stored: Some(c.stored_rest()) }; - return Ok((file, None)); - } - // The merged image is wanted: read it and decode it as `from_bytes` does. - let rest = c.rest()?; - let merged = file.read_merged_recovering(&rest, recover)?; - Ok((file, merged)) - } -} - -/// Reads tagged blocks as [`crate::tagged::read_blocks_with`] does, from a cursor: `consume` -/// sees each block's data as a cursor and returns `Some` when it took the block; the others are -/// read into memory and pushed to `blocks`. Returns the trailing bytes. -fn read_blocks<'a>( - r: &mut Cursor<'a>, - version: Version, - mut consume: impl FnMut(usize, [u8; 4], [u8; 4], Cursor<'a>, &Option>) -> Result>, - blocks: &mut Vec, -) -> Result> { - const ALIGNMENT: usize = 4; - loop { - let head = r.peek(12)?; - if head.len() < 12 || !is_sig(&head) { - return r.rest(); - } - let signature = r.array::<4>()?; - let key = r.array::<4>()?; - let len = r.len_field(uses_long_length(version, &key))?; - let data = r.sub(len)?; - // Padding as `read_blocks_with` detects it: the smallest k in 0..=3 such that the next - // signature (or the end of the region) follows k bytes later. - let rest = r.peek(7)?; - let mut pad = None; - for k in 0..=3usize { - if k == rest.len() || rest.get(k..).is_some_and(is_sig) { - pad = Some(k); - break; - } - } - let default = TaggedBlock::default_padding((len % ALIGNMENT as u64) as usize, ALIGNMENT); - let pad = pad.unwrap_or_else(|| if rest.get(..default).is_some_and(|p| p.iter().all(|&b| b == 0)) { default } else { 0 }); - let pad_bytes = rest.get(..pad).map(<[u8]>::to_vec).unwrap_or_default(); - r.skip(pad as u64)?; - let padding = if pad_bytes.len() == default && pad_bytes.iter().all(|&b| b == 0) { None } else { Some(pad_bytes) }; - let (start, end) = (data.pos, data.end); - if consume(blocks.len(), signature, key, data, &padding)?.is_none() { - let data = Cursor { src: r.src, pos: start, end }.rest()?; - blocks.push(TaggedBlock { signature, key, data, padding }); - } - } -} - -/// [`LayerInfo::read_body`] from a cursor over the body: the records are read into memory, and -/// each channel's encoded bytes become a [`Stored`] range after its compression field. -fn read_layer_info(mut r: Cursor<'_>, version: Version) -> Result { - let body_start = r.pos; - let count = r.i16()?; - let merged_alpha = count < 0; - let n = count.unsigned_abs(); - // Minimum record size, as `read_body` checks it. - if u64::from(n) * 34 > r.remaining() { - return Err(r.eof(u64::from(n) * 34)); - } - // The records' total size is only known once they are parsed: read a chunk and grow it until - // they all fit (or the body is exhausted, when their error is the body's). - let mut chunk = RECORDS_CHUNK.min(r.remaining()); - let (layers, all_lens, used) = loop { - let buf = r.peek(chunk)?; - let mut rr = Reader::new(&buf); - let mut layers = Vec::with_capacity(usize::from(n)); - let mut all_lens = Vec::with_capacity(usize::from(n)); - let parsed = (0..n).try_for_each(|_| { - let (rec, lens) = LayerRecord::read(&mut rr, version)?; - layers.push(rec); - all_lens.push(lens); - Ok::<_, PsdError>(()) - }); - match parsed { - Ok(()) => break (layers, all_lens, rr.pos() as u64), - Err(PsdError::UnexpectedEof { .. }) if chunk < r.remaining() => chunk = chunk.saturating_mul(2).min(r.remaining()), - Err(e) => return Err(e), - } - }; - r.skip(used)?; - let mut layers = layers; - for (rec, lens) in layers.iter_mut().zip(all_lens) { - for (ch, len) in rec.channels.iter_mut().zip(lens) { - if len == 0 { - continue; - } - if len == 1 { - return Err(PsdError::invalid("channel data length 1")); - } - ch.compression = Some(Compression::from_u16(r.u16()?)); - let data = r.sub(len - 2)?; - ch.stored = Some(Stored { source: data.src.clone(), offset: data.pos, len: data.remaining() }); - } - } - let body_len = r.pos - body_start; - let rest = r.rest()?; - let padding = if rest.len() as u64 == body_len % 2 && rest.iter().all(|&b| b == 0) { None } else { Some(rest) }; - Ok(LayerInfo { merged_alpha, layers, padding }) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::testgen; - - /// Every generated file, plus the layered 16/32-bit ones with their layers in a global block. - fn samples() -> Vec> { - let mut v = Vec::new(); - for case in testgen::all_cases() { - let mut file = case.file; - v.push(file.to_bytes().unwrap()); - let key = match file.header.depth { - 16 => *b"Lr16", - 32 => *b"Lr32", - _ => continue, - }; - if file.layer_info.as_ref().is_some_and(|i| !i.layers.is_empty()) { - file.global_layer_mask.get_or_insert_with(GlobalLayerMask::default); - file.layer_info_placement = LayerInfoPlacement::GlobalBlock { index: 0, signature: *b"8BIM", key, padding: None }; - v.push(file.to_bytes().unwrap()); - } - } - v - } - - fn same(bytes: Vec) { - let eager = PsdFile::from_bytes(&bytes).unwrap(); - let lazy = PsdFile::from_source(Source::new(bytes.clone())).unwrap(); - assert_eq!(lazy, eager); - assert_eq!(lazy.to_bytes().unwrap(), bytes); - assert!(lazy.layers().iter().flat_map(|l| &l.channels).all(|c| c.data.is_empty())); - assert!(lazy.image_data.data.is_empty() && lazy.image_data.stored.is_some()); - } - - #[test] - fn lazy_parse_matches_the_eager_one() { - for bytes in samples() { - same(bytes); - } - } - - /// A PSD read lazily and written as PSB widens the RLE count tables of channels still in the - /// source, byte for byte as an eager read does (main's PSB promotion, #5285, on #6583's reader). - #[test] - fn a_lazy_psd_promotes_to_the_same_psb_as_an_eager_one() { - let bytes = testgen::layered(Version::Psd, crate::ColorMode::Rgb, 8, Compression::Rle).to_bytes().unwrap(); - let mut eager = PsdFile::from_bytes(&bytes).unwrap(); - let mut lazy = PsdFile::from_source(Source::new(bytes)).unwrap(); - eager.promote_to_psb().unwrap(); - lazy.promote_to_psb().unwrap(); - let written = eager.to_bytes().unwrap(); - assert_eq!(lazy.encoded_len().unwrap(), written.len() as u64); - assert!(lazy.to_bytes().unwrap() == written, "the lazily read PSD writes another PSB"); - } - - #[test] - fn lazy_parse_fails_where_the_eager_one_does() { - for bytes in samples() { - for cut in [1, 2, 7, 26, 40, bytes.len() / 3, bytes.len() / 2, bytes.len() - 3] { - let Some(b) = bytes.get(..cut) else { continue }; - let eager = PsdFile::from_bytes(b); - let lazy = PsdFile::from_source(Source::new(b.to_vec())); - // A truncated merged image is only noticed when it is read. - match eager { - Ok(eager) => assert_eq!(lazy.unwrap(), eager, "cut at {cut}"), - Err(e) => { - let records_ok = PsdFile::from_bytes_and_merged_recovering(b, |_| false, |_| true).is_ok(); - assert!(lazy.is_err() || records_ok, "cut at {cut}: eager {e:?}"); - } - } - } - } - } - - /// A source whose `fail_at`-th read fails once. - struct FailOnce { - bytes: Vec, - fail_at: usize, - reads: std::sync::atomic::AtomicUsize, - } - - impl crate::source::ReadAt for FailOnce { - fn len(&self) -> u64 { - self.bytes.len() as u64 - } - - fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()> { - if self.reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == self.fail_at { - return Err(PsdError::Read("injected".into())); - } - self.bytes.read_at(offset, buf) - } - } - - #[test] - fn a_failed_read_fails_the_parse_instead_of_dropping_the_layers() { - for bytes in samples() { - let eager = PsdFile::from_bytes(&bytes).unwrap(); - let clean = std::sync::Arc::new(FailOnce { bytes: bytes.clone(), fail_at: usize::MAX, reads: 0.into() }); - PsdFile::from_source(Source::from_arc(clean.clone())).unwrap(); - let reads = clean.reads.load(std::sync::atomic::Ordering::SeqCst); - for fail_at in 0..reads { - let src = FailOnce { bytes: bytes.clone(), fail_at, reads: 0.into() }; - match PsdFile::from_source(Source::new(src)) { - Err(PsdError::Read(_)) => {} - Ok(lazy) => assert_eq!(lazy, eager, "read {fail_at} failed silently"), - Err(e) => panic!("read {fail_at}: {e:?}"), - } - } - } - } -} diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs deleted file mode 100644 index 5d0422f13a..0000000000 --- a/crates/psd/src/lib.rs +++ /dev/null @@ -1,101 +0,0 @@ -//! # photocraft-psd -//! -//! Faithful, lossless reader and writer for Adobe Photoshop PSD (version 1) -//! and PSB (version 2, "large document format") files. -//! -//! * [`PsdFile::from_bytes`] parses a file into a format-level model; -//! [`PsdFile::to_bytes`] writes it back. Unmodified files round-trip byte -//! for byte: channel data is kept in its original encoding, unknown tagged -//! blocks and resources are kept raw, and padding is preserved. -//! * Channel data is decoded lazily ([`ChannelData::decode`], -//! [`ImageData::decode`]) with all four compression methods supported for -//! both decoding and encoding. -//! * [`PsdBuilder`] constructs new files from RGBA/gray/CMYK buffers; the -//! caller supplies the merged composite (this crate never composites). -//! * [`descriptor`] parses and writes ActionDescriptors. -//! -//! Implemented clean-room from Adobe's public "Photoshop File Formats -//! Specification". Undocumented details that follow MIT-licensed psd-tools -//! or ag-psd behavior are noted in comments. -//! -//! The parser never panics on malformed input and enforces limits -//! (dimensions ≤ 300000, bounded allocations, bounded descriptor nesting). -//! -//! ``` -//! use photocraft_psd::{LayerSpec, PixelData, PsdBuilder, PsdFile}; -//! -//! let mut b = PsdBuilder::new(2, 1); -//! b.push_layer(LayerSpec::new("Red", 0, 0, 2, 1, PixelData::Rgba8(vec![255, 0, 0, 255, 255, 0, 0, 128]))); -//! b.composite(PixelData::Rgba8(vec![255, 0, 0, 255, 255, 0, 0, 128])); -//! let bytes = b.to_bytes()?; -//! -//! let file = PsdFile::from_bytes(&bytes)?; -//! assert_eq!(file.to_bytes()?, bytes); // byte-stable -//! let layer = file.layer(0).unwrap(); -//! assert_eq!(layer.name(), "Red"); -//! assert_eq!(layer.rgba8()?.data[7], 128); -//! # Ok::<(), photocraft_psd::PsdError>(()) -//! ``` -#![forbid(unsafe_code)] -#![warn(missing_docs)] -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] - -pub mod abr; -pub mod aco; -pub mod act; -pub mod animation; -pub mod ase; -pub mod asl; -pub mod atn; -pub mod blend; -pub mod builder; -mod codepage; -pub mod compression; -pub mod csh; -pub mod descriptor; -pub mod error; -pub mod file; -pub mod filter_effects; -#[cfg(any(test, feature = "testgen"))] -pub mod fixtures; -pub mod grd; -pub mod hdr; -pub mod header; -pub mod image_data; -mod io; -pub mod layer; -mod lazy; -pub mod metadata; -pub mod path; -pub mod patterns; -pub mod pixels; -pub mod resources; -pub mod rows; -pub mod shc; -pub mod slices; -pub mod source; -pub mod tagged; -#[cfg(any(test, feature = "testgen"))] -// Test-data generator (tests and fuzz seeds only): failing loudly is the point. -#[allow(clippy::expect_used)] -pub mod testgen; -pub mod tiff; -pub mod tree; - -pub use blend::BlendMode; -pub use builder::{GroupSpec, LayerSpec, MaskSpec, PixelData, PsdBuilder}; -pub use compression::{Compression, PlaneLayout}; -pub use descriptor::{Descriptor, VersionedDescriptor}; -pub use error::{PsdError, Result}; -pub use file::{GlobalLayerMask, LayerInfoPlacement, PsdFile}; -pub use header::{ColorMode, Header, Version}; -pub use image_data::ImageData; -pub use layer::{BlendingRanges, ChannelData, LayerFlags, LayerInfo, LayerMask, LayerRecord, MaskData, MaskParameters, RealMask, Rect}; -pub use pixels::{GrayImage, Layer, RgbaImage}; -pub use resources::{ImageResource, ResolutionInfo, ResourceData}; -pub use rows::RowDecoder; -#[cfg(any(unix, windows))] -pub use source::FileSource; -pub use source::{ReadAt, Source, Stored}; -pub use tagged::{BlockData, SectionDivider, SectionType, TaggedBlock}; -pub use tree::LayerNode; diff --git a/crates/psd/src/metadata.rs b/crates/psd/src/metadata.rs deleted file mode 100644 index 8e4565fe3f..0000000000 --- a/crates/psd/src/metadata.rs +++ /dev/null @@ -1,266 +0,0 @@ -//! `shmd` (metadata setting) layer block: a list of keyed sub-blocks, such as `cmls` (layer comp -//! state, a versioned descriptor), `cust` (the layer's modify time and XMP packet) and `mlst`. -//! -//! Layout (Adobe PSD spec, "Metadata setting"): u32 count, then per item the signature `8BIM`, -//! a 4-byte key, a copy-on-sheet-duplication byte, 3 padding bytes, a u32 length and the data. -//! Photoshop pads item data to an even length (the padding is part of the stored length), so -//! parsing and writing are exact: `write(parse(b)) == b`. - -use crate::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; -use crate::error::{PsdError, Result}; -use crate::io::{Reader, WriteExt}; - -/// One `shmd` item. -#[derive(Debug, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct MetadataItem { - /// Usually `8BIM`. - pub signature: [u8; 4], - /// Item key, e.g. `cmls`. - pub key: [u8; 4], - /// Copy on sheet duplication. - pub copy: bool, - /// The 3 bytes after the copy flag (zero in Photoshop files), kept for exactness. - pub reserved: [u8; 3], - /// Data including any padding counted in the stored length. - pub data: Vec, -} - -impl MetadataItem { - /// Typed animation descriptor for `mlst` (sparse layer frame states) or `tmln` - /// (layer timeline tracks). Other metadata, including `cust` / XMP, is not interpreted. - /// The original item stays unchanged; inheritance and track evaluation belong to the importer. - pub fn animation_descriptor(&self) -> Option> { - matches!(&self.key, b"mlst" | b"tmln").then(|| { - if self.signature != *b"8BIM" { - return Err(PsdError::InvalidSignature { expected: "8BIM animation metadata", found: self.signature }); - } - crate::animation::parse_descriptor(&self.data) - }) - } - - /// A new item; `data` is zero-padded to an even length as Photoshop writes it. - pub fn new(key: [u8; 4], mut data: Vec) -> Self { - if data.len() % 2 == 1 { - data.push(0); - } - MetadataItem { signature: *b"8BIM", key, copy: false, reserved: [0; 3], data } - } -} - -/// Parses `shmd` block data. -pub fn parse_shmd(data: &[u8]) -> Result> { - let mut r = Reader::new(data); - let count = r.u32()?; - r.check_count(u64::from(count), 16)?; - let mut out = crate::descriptor::vec_for_count(count); - for _ in 0..count { - let signature = r.array()?; - let key = r.array()?; - let copy = r.u8()? != 0; - let reserved = r.array()?; - let len = r.u32()?; - let data = r.bytes_u64(u64::from(len))?.to_vec(); - out.push(MetadataItem { signature, key, copy, reserved, data }); - } - if !r.is_empty() { - return Err(PsdError::invalid("trailing bytes after metadata items")); - } - Ok(out) -} - -/// Serializes `shmd` block data. -pub fn write_shmd(items: &[MetadataItem]) -> Vec { - let mut out = Vec::new(); - out.put_u32(items.len() as u32); - for it in items { - out.put(&it.signature); - out.put(&it.key); - out.push(u8::from(it.copy)); - out.put(&it.reserved); - out.put_u32(it.data.len() as u32); - out.put(&it.data); - } - out -} - -/// The `shmd` item that holds a layer's own metadata (its modify time and XMP). -const CUST: [u8; 4] = *b"cust"; -/// Key of a layer's XMP packet in the `cust` descriptor. -const LAYER_XMP: &str = "layerXMP"; - -// A layer's XMP packet (Photoshop's `layer.xmpMetadata.rawData`), as observed in files Photoshop -// 2026 saves: a `TEXT` item `layerXMP` (UTF-16 with a terminating NUL) in the `metadata` -// descriptor (version 16, class name a lone NUL) of the `shmd` item `cust`, after the -// `layerTime` double that every Photoshop layer has. A layer without XMP has no `layerXMP` item. - -fn pad_even(mut v: Vec) -> Vec { - if v.len() % 2 == 1 { - v.push(0); - } - v -} - -/// The `cust` descriptor of `item`, or `None` when it isn't one. -fn cust_descriptor(item: &MetadataItem) -> Option { - (item.key == CUST).then(|| VersionedDescriptor::parse_prefix(&item.data).ok().map(|(d, _)| d)).flatten() -} - -/// The XMP packet stored on a layer whose `shmd` block data is `shmd`, or `None` when it has -/// none (or the block can't be read). -pub fn layer_xmp(shmd: &[u8]) -> Option { - let items = parse_shmd(shmd).ok()?; - items.iter().filter_map(cust_descriptor).find_map(|d| match d.descriptor.get(LAYER_XMP) { - Some(Value::Text(t)) => Some(t.to_string_lossy()), - _ => None, - }) -} - -/// Splits a layer's XMP packet out of its `shmd` block data: the packet, and the block without -/// it (`None` when nothing is left). `None` when the block holds no packet, so the caller keeps -/// the original bytes. A `cust` item left empty is dropped, the other items are kept as stored. -pub fn take_layer_xmp(shmd: &[u8]) -> Option<(String, Option>)> { - let mut items = parse_shmd(shmd).ok()?; - let (i, mut vd) = items.iter().enumerate().find_map(|(i, it)| cust_descriptor(it).filter(|d| d.descriptor.get(LAYER_XMP).is_some()).map(|d| (i, d)))?; - let at = vd.descriptor.items.iter().position(|(k, _)| k.is(LAYER_XMP))?; - let xmp = match vd.descriptor.items.remove(at).1 { - Value::Text(t) => t.to_string_lossy(), - _ => return None, - }; - if vd.descriptor.items.is_empty() { - items.remove(i); - } else { - items[i].data = pad_even(vd.to_bytes()); - } - Some((xmp, (!items.is_empty()).then(|| write_shmd(&items)))) -} - -/// `shmd` block data (`shmd`, or a new block when `None`) with `xmp` as the layer's XMP packet, -/// written as Photoshop writes it: it replaces an existing packet in place, or is appended to -/// the `cust` descriptor (a new `cust` item when there is none). An unreadable block is an -/// error, so the caller never replaces data it couldn't read. -pub fn put_layer_xmp(shmd: Option<&[u8]>, xmp: &str) -> Result> { - let mut items = match shmd { - Some(b) => parse_shmd(b)?, - None => Vec::new(), - }; - let value = Value::Text(UnicodeString::new_nul(xmp)); - match items.iter().position(|it| it.key == CUST) { - Some(i) => { - let (mut vd, _) = VersionedDescriptor::parse_prefix(&items[i].data)?; - match vd.descriptor.items.iter_mut().find(|(k, _)| k.is(LAYER_XMP)) { - Some(entry) => entry.1 = value, - None => vd.descriptor.items.push((Id::new(LAYER_XMP), value)), - } - items[i].data = pad_even(vd.to_bytes()); - } - None => { - let d = Descriptor { name: UnicodeString::new_nul(""), class_id: Id::new("metadata"), items: vec![(Id::new(LAYER_XMP), value)] }; - items.push(MetadataItem::new(CUST, VersionedDescriptor::new(d).to_bytes())); - } - } - Ok(write_shmd(&items)) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn unhex(lines: &[&str]) -> Vec { - let h: String = lines.concat(); - (0..h.len()).step_by(2).map(|i| u8::from_str_radix(&h[i..i + 2], 16).unwrap()).collect() - } - - /// `shmd` of a layer saved by Photoshop 2026 after a script set its XMP to [`PS_PACKET`]. - const PS_WITH_XMP: &[&str] = &[ - "000000013842494d63757374000000000000024800000010000000010000000000086d65746164617461000000020000", - "00096c6179657254696d65646f756241dab643ffd54363000000086c61796572584d505445585400000100003c007800", - "3a0078006d0070006d00650074006100200078006d006c006e0073003a0078003d002200610064006f00620065003a00", - "6e0073003a006d006500740061002f0022003e003c007200640066003a00520044004600200078006d006c006e007300", - "3a007200640066003d00220068007400740070003a002f002f007700770077002e00770033002e006f00720067002f00", - "31003900390039002f00300032002f00320032002d007200640066002d00730079006e007400610078002d006e007300", - "230022003e003c007200640066003a004400650073006300720069007000740069006f006e0020007200640066003a00", - "610062006f00750074003d0022002200200078006d006c006e0073003a00730061006d0070006c0065003d0022006800", - "7400740070003a002f002f006500780061006d0070006c0065002e0063006f006d002f00730061006d0070006c006500", - "2f0031002e0030002f0022003e003c00730061006d0070006c0065003a00760061006c00750065003e0061006c007000", - "680061002d003100320033003c002f00730061006d0070006c0065003a00760061006c00750065003e003c002f007200", - "640066003a004400650073006300720069007000740069006f006e003e003c002f007200640066003a00520044004600", - "3e003c002f0078003a0078006d0070006d006500740061003e000000", - ]; - /// `shmd` of a layer without XMP in the same file (its own `layerTime` only). - const PS_WITHOUT_XMP: &[&str] = - &["000000013842494d63757374000000000000003400000010000000010000000000086d6574616461746100000001000000096c6179657254696d65646f756241dab643ffd86bec00"]; - const PS_PACKET: &str = concat!( - r#""#, - r#"alpha-123"#, - r#""# - ); - - #[test] - fn reads_photoshop_layer_xmp() { - assert_eq!(layer_xmp(&unhex(PS_WITH_XMP)).as_deref(), Some(PS_PACKET)); - assert_eq!(layer_xmp(&unhex(PS_WITHOUT_XMP)), None); - assert!(take_layer_xmp(&unhex(PS_WITHOUT_XMP)).is_none()); - } - - #[test] - fn take_then_put_is_exact() { - let ps = unhex(PS_WITH_XMP); - let (xmp, rest) = take_layer_xmp(&ps).unwrap(); - assert_eq!(xmp, PS_PACKET); - let rest = rest.unwrap(); - // What's left is a layer without XMP, shaped as Photoshop writes one. - assert_eq!(rest.len(), unhex(PS_WITHOUT_XMP).len()); - assert_eq!(layer_xmp(&rest), None); - assert_eq!(put_layer_xmp(Some(&rest), &xmp).unwrap(), ps); - } - - #[test] - fn put_replaces_in_place_and_creates_a_block() { - let ps = unhex(PS_WITH_XMP); - let edited = put_layer_xmp(Some(&ps), "").unwrap(); - assert_eq!(layer_xmp(&edited).as_deref(), Some("")); - // `layerTime` is kept, still first. - let items = parse_shmd(&edited).unwrap(); - let d = cust_descriptor(&items[0]).unwrap().descriptor; - assert!(d.items[0].0.is("layerTime") && d.items[1].0.is(LAYER_XMP) && d.items.len() == 2); - - let fresh = put_layer_xmp(None, PS_PACKET).unwrap(); - assert_eq!(layer_xmp(&fresh).as_deref(), Some(PS_PACKET)); - assert_eq!(take_layer_xmp(&fresh), Some((PS_PACKET.to_string(), None))); - // Other items (here a layer comp state) stay as they were. - let comps = write_shmd(&[MetadataItem::new(*b"cmls", vec![1, 2])]); - let both = put_layer_xmp(Some(&comps), PS_PACKET).unwrap(); - assert_eq!(parse_shmd(&both).unwrap()[0], parse_shmd(&comps).unwrap()[0]); - assert_eq!(take_layer_xmp(&both).unwrap().1.unwrap(), comps); - } - - #[test] - fn put_refuses_an_unreadable_block() { - assert!(put_layer_xmp(Some(&[0, 0, 0, 9]), PS_PACKET).is_err()); - let bad_cust = write_shmd(&[MetadataItem::new(CUST, vec![0, 0, 0, 16, 1])]); - assert!(put_layer_xmp(Some(&bad_cust), PS_PACKET).is_err()); - assert_eq!(layer_xmp(&bad_cust), None); - assert!(take_layer_xmp(&bad_cust).is_none()); - } - - #[test] - fn roundtrip_exact() { - let items = vec![MetadataItem::new(*b"cmls", vec![1, 2, 3]), MetadataItem { copy: true, ..MetadataItem::new(*b"cust", vec![9; 4]) }]; - assert_eq!(items[0].data.len(), 4); - let bytes = write_shmd(&items); - assert_eq!(parse_shmd(&bytes).unwrap(), items); - assert_eq!(write_shmd(&parse_shmd(&bytes).unwrap()), bytes); - } - - #[test] - fn malformed_is_an_error() { - assert!(parse_shmd(&[]).is_err()); - assert!(parse_shmd(&[0, 0, 0, 9]).is_err()); - let mut b = write_shmd(&[MetadataItem::new(*b"cmls", vec![0; 2])]); - b.push(0); - assert!(parse_shmd(&b).is_err()); - b.truncate(b.len() - 3); - assert!(parse_shmd(&b).is_err()); - } -} diff --git a/crates/psd/src/path.rs b/crates/psd/src/path.rs deleted file mode 100644 index 79f055cb0b..0000000000 --- a/crates/psd/src/path.rs +++ /dev/null @@ -1,312 +0,0 @@ -//! Path records: saved paths (image resources 2000–2997), the work path -//! (resource 1025) and vector masks (`vmsk` / `vsms` layer blocks). -//! -//! Implemented from the public Adobe "Photoshop File Formats Specification", -//! section "Path resource format": a path is a list of 26-byte records, each a -//! 2-byte selector followed by 24 bytes of data. Knot coordinates are signed -//! 8.24 fixed-point fractions of the document height (vertical) and width -//! (horizontal), stored vertical first. -//! -//! Undocumented detail (as documented by the MIT-licensed psd-tools): bytes -//! 2–3 of a subpath length record's data (after the knot count) hold the -//! *path operation* of the subpath (`-1` or `1` combine/or, `2` subtract, -//! `3` intersect, `0` exclude/xor). Everything else is kept raw, so parsing -//! and writing a record list is byte-exact. - -use crate::error::{PsdError, Result}; - -/// Length of one path record in bytes (selector + data). -pub const RECORD_LEN: usize = 26; - -/// Record selectors (spec table "Path data record types"). -pub mod selector { - /// Closed subpath length record. - pub const CLOSED_LENGTH: u16 = 0; - /// Closed subpath Bézier knot, linked. - pub const CLOSED_KNOT_LINKED: u16 = 1; - /// Closed subpath Bézier knot, unlinked. - pub const CLOSED_KNOT_UNLINKED: u16 = 2; - /// Open subpath length record. - pub const OPEN_LENGTH: u16 = 3; - /// Open subpath Bézier knot, linked. - pub const OPEN_KNOT_LINKED: u16 = 4; - /// Open subpath Bézier knot, unlinked. - pub const OPEN_KNOT_UNLINKED: u16 = 5; - /// Path fill rule record. - pub const FILL_RULE: u16 = 6; - /// Clipboard record. - pub const CLIPBOARD: u16 = 7; - /// Initial fill rule record. - pub const INITIAL_FILL: u16 = 8; -} - -/// One 26-byte path record, kept raw. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PathRecord { - /// Record type (see [`selector`]). - pub selector: u16, - /// The 24 data bytes. - pub data: [u8; 24], -} - -impl PathRecord { - fn u16_at(&self, at: usize) -> u16 { - u16::from_be_bytes([self.data[at], self.data[at + 1]]) - } - fn i32_at(&self, at: usize) -> i32 { - i32::from_be_bytes([self.data[at], self.data[at + 1], self.data[at + 2], self.data[at + 3]]) - } - /// Whether this is a (closed or open) subpath length record. - pub fn is_length(&self) -> bool { - matches!(self.selector, selector::CLOSED_LENGTH | selector::OPEN_LENGTH) - } - /// Whether this is a Bézier knot record. - pub fn is_knot(&self) -> bool { - matches!(self.selector, 1 | 2 | 4 | 5) - } -} - -/// A Bézier knot as fractions of the document size: `(x, y)` pairs. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct PsdKnot { - /// Linked (smooth) knot: the control points move together. - pub linked: bool, - /// Control point preceding the anchor (`(x, y)` fractions). - pub pre: (f64, f64), - /// Anchor point. - pub anchor: (f64, f64), - /// Control point leaving the anchor. - pub post: (f64, f64), -} - -/// A subpath: its knots, closed flag and path operation. -#[derive(Clone, Debug, PartialEq)] -pub struct PsdSubpath { - /// Closed subpath. - pub closed: bool, - /// Path operation (bytes 2–3 of the length record data): `-1`/`1` - /// combine, `2` subtract, `3` intersect, `0` exclude. - pub operation: i16, - /// Knots in order. - pub knots: Vec, -} - -/// Fixed 8.24 → fraction. -pub fn fixed_to_f64(v: i32) -> f64 { - f64::from(v) / 16_777_216.0 -} - -/// Fraction → fixed 8.24 (rounded, saturating). -pub fn f64_to_fixed(v: f64) -> i32 { - (v * 16_777_216.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32 -} - -/// A parsed path record list. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct PathData { - /// Records in file order. - pub records: Vec, -} - -impl PathData { - /// Parses path records. Trailing bytes shorter than a record are ignored. - pub fn from_bytes(data: &[u8]) -> Result { - if data.len() / RECORD_LEN > 4_000_000 { - return Err(PsdError::LimitExceeded("path records")); - } - let records = data - .as_chunks::() - .0 - .iter() - .map(|c| { - let mut d = [0u8; 24]; - d.copy_from_slice(&c[2..]); - PathRecord { selector: u16::from_be_bytes([c[0], c[1]]), data: d } - }) - .collect(); - Ok(PathData { records }) - } - - /// Serializes the records. - pub fn to_bytes(&self) -> Vec { - let mut out = Vec::with_capacity(self.records.len() * RECORD_LEN); - for r in &self.records { - out.extend_from_slice(&r.selector.to_be_bytes()); - out.extend_from_slice(&r.data); - } - out - } - - /// Initial fill rule: `true` when the path starts with all pixels filled - /// (inverted path). - pub fn initial_fill(&self) -> bool { - self.records.iter().find(|r| r.selector == selector::INITIAL_FILL).is_some_and(|r| r.u16_at(0) != 0) - } - - /// Subpaths with their knots. Knot records not preceded by a length - /// record, or beyond a length record's count, start/extend a subpath - /// leniently instead of failing. - pub fn subpaths(&self) -> Vec { - let mut out: Vec = Vec::new(); - let mut remaining = 0usize; - for r in &self.records { - if r.is_length() { - remaining = usize::from(r.u16_at(0)); - out.push(PsdSubpath { - closed: r.selector == selector::CLOSED_LENGTH, - operation: r.u16_at(2) as i16, - // No preallocation: the count is untrusted (u16) and PsdKnot is 56 bytes. - knots: Vec::new(), - }); - } else if r.is_knot() { - let closed = r.selector <= 2; - if remaining == 0 && out.last().is_none_or(|s| s.closed != closed) { - out.push(PsdSubpath { closed, operation: -1, knots: Vec::new() }); - } - remaining = remaining.saturating_sub(1); - let pt = |i: usize| (fixed_to_f64(r.i32_at(i * 8 + 4)), fixed_to_f64(r.i32_at(i * 8))); - if let Some(s) = out.last_mut() { - s.knots.push(PsdKnot { linked: matches!(r.selector, 1 | 4), pre: pt(0), anchor: pt(1), post: pt(2) }); - } - } - } - out - } - - /// Builds a record list: a fill rule record, an initial fill record, - /// then each subpath's length record and knots. - pub fn from_subpaths(subpaths: &[PsdSubpath], initial_fill: bool) -> Self { - let mut records = vec![PathRecord { selector: selector::FILL_RULE, data: [0; 24] }, PathRecord { selector: selector::INITIAL_FILL, data: [0; 24] }]; - records[1].data[..2].copy_from_slice(&u16::from(initial_fill).to_be_bytes()); - for s in subpaths { - let mut data = [0u8; 24]; - data[..2].copy_from_slice(&(s.knots.len().min(u16::MAX as usize) as u16).to_be_bytes()); - data[2..4].copy_from_slice(&s.operation.to_be_bytes()); - // Photoshop writes 1 here (psd-tools default); meaning unknown. - data[4..6].copy_from_slice(&1u16.to_be_bytes()); - records.push(PathRecord { selector: if s.closed { selector::CLOSED_LENGTH } else { selector::OPEN_LENGTH }, data }); - for k in s.knots.iter().take(u16::MAX as usize) { - let sel = match (s.closed, k.linked) { - (true, true) => selector::CLOSED_KNOT_LINKED, - (true, false) => selector::CLOSED_KNOT_UNLINKED, - (false, true) => selector::OPEN_KNOT_LINKED, - (false, false) => selector::OPEN_KNOT_UNLINKED, - }; - let mut d = [0u8; 24]; - for (i, p) in [k.pre, k.anchor, k.post].iter().enumerate() { - d[i * 8..i * 8 + 4].copy_from_slice(&f64_to_fixed(p.1).to_be_bytes()); - d[i * 8 + 4..i * 8 + 8].copy_from_slice(&f64_to_fixed(p.0).to_be_bytes()); - } - records.push(PathRecord { selector: sel, data: d }); - } - } - PathData { records } - } -} - -/// A vector mask block (`vmsk` / `vsms`): version, flags and path records. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct VectorMaskBlock { - /// Version (3). - pub version: u32, - /// Flags: bit 0 invert, bit 1 not linked, bit 2 disabled. - pub flags: u32, - /// The path. - pub path: PathData, -} - -impl VectorMaskBlock { - /// Invert flag. - pub const FLAG_INVERT: u32 = 1; - /// Not-linked flag. - pub const FLAG_NOT_LINKED: u32 = 2; - /// Disabled flag. - pub const FLAG_DISABLED: u32 = 4; - - /// Parses the block data. - pub fn from_bytes(data: &[u8]) -> Result { - if data.len() < 8 { - return Err(PsdError::UnexpectedEof { offset: 0, needed: 8 - data.len() }); - } - let version = u32::from_be_bytes([data[0], data[1], data[2], data[3]]); - let flags = u32::from_be_bytes([data[4], data[5], data[6], data[7]]); - Ok(VectorMaskBlock { version, flags, path: PathData::from_bytes(&data[8..])? }) - } - - /// Serializes the block data. - pub fn to_bytes(&self) -> Vec { - let mut out = Vec::with_capacity(8 + self.path.records.len() * RECORD_LEN); - out.extend_from_slice(&self.version.to_be_bytes()); - out.extend_from_slice(&self.flags.to_be_bytes()); - out.extend_from_slice(&self.path.to_bytes()); - out - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn sample() -> Vec { - vec![ - PsdSubpath { - closed: true, - operation: 1, - knots: vec![ - PsdKnot { linked: false, pre: (0.25, 0.25), anchor: (0.25, 0.25), post: (0.25, 0.25) }, - PsdKnot { linked: true, pre: (0.625, 0.125), anchor: (0.75, 0.25), post: (0.875, 0.375) }, - PsdKnot { linked: false, pre: (0.5, 0.75), anchor: (0.5, 0.75), post: (0.5, 0.75) }, - ], - }, - PsdSubpath { closed: false, operation: 2, knots: vec![PsdKnot { linked: false, pre: (-0.5, 1.5), anchor: (0.0, 1.0), post: (0.0625, 0.9375) }] }, - ] - } - - #[test] - fn subpaths_does_not_preallocate_from_untrusted_counts() { - let mut bytes = Vec::new(); - for _ in 0..100_000 { - bytes.extend_from_slice(&selector::CLOSED_LENGTH.to_be_bytes()); - bytes.extend_from_slice(&0xFFFFu16.to_be_bytes()); - bytes.extend_from_slice(&[0u8; 22]); - } - let subs = PathData::from_bytes(&bytes).unwrap().subpaths(); - assert_eq!(subs.len(), 100_000); - assert!(subs.iter().all(|s| s.knots.capacity() == 0)); - } - - #[test] - fn subpaths_roundtrip_and_bytes_are_stable() { - let p = PathData::from_subpaths(&sample(), true); - let bytes = p.to_bytes(); - assert_eq!(bytes.len(), (2 + 2 + 4) * RECORD_LEN); - let q = PathData::from_bytes(&bytes).unwrap(); - assert_eq!(q.to_bytes(), bytes); - assert_eq!(q.subpaths(), sample()); - assert!(q.initial_fill()); - } - - #[test] - fn vector_mask_block_roundtrip() { - let b = VectorMaskBlock { version: 3, flags: VectorMaskBlock::FLAG_INVERT, path: PathData::from_subpaths(&sample(), false) }; - let bytes = b.to_bytes(); - assert_eq!(VectorMaskBlock::from_bytes(&bytes).unwrap(), b); - assert!(VectorMaskBlock::from_bytes(&[0; 4]).is_err()); - } - - #[test] - fn fixed_point_conversion() { - assert_eq!(f64_to_fixed(1.0), 1 << 24); - assert_eq!(fixed_to_f64(-(1 << 23)), -0.5); - assert_eq!(f64_to_fixed(1e12), i32::MAX); - } - - #[test] - fn lenient_knots_without_length_record() { - let mut p = PathData::from_subpaths(&sample(), false); - p.records.retain(|r| !r.is_length()); - let s = p.subpaths(); - assert_eq!(s.len(), 2); - assert_eq!(s[0].knots.len(), 3); - } -} diff --git a/crates/psd/src/patterns.rs b/crates/psd/src/patterns.rs deleted file mode 100644 index fb604f0c02..0000000000 --- a/crates/psd/src/patterns.rs +++ /dev/null @@ -1,631 +0,0 @@ -//! Patterns: the global `Patt` / `Pat2` / `Pat3` tagged blocks (8 / 16 / 32-bit documents) and -//! standalone `.pat` files. -//! -//! Layout per the public Photoshop File Formats Specification ("Patterns" and "Virtual Memory -//! Array List"): -//! -//! ```text -//! pattern := version u32 (1), image mode u32, height i16, width i16, -//! name (Unicode string), unique id (Pascal string, unpadded), -//! [indexed: 256 × RGB palette], virtual memory array list -//! VMA list := version u32 (3), length u32, rect (top, left, bottom, right i32), -//! channel count u32, then count + 2 arrays (user mask, sheet mask) -//! array := written u32 (0 = absent), length u32 (0 = absent), depth u32, rect, -//! depth u16, compression u8 (0 raw, 1 PackBits RLE), data -//! ``` -//! -//! In the tagged blocks each pattern is prefixed by its u32 length and padded to 4 bytes; a -//! `.pat` file is `8BPT`, version u16 (1), count u32, then the patterns without length prefixes. -//! Photoshop writes the channel count as 24 and only marks the real channels as written; like -//! ag-psd (MIT) we take the first written arrays as the colour channels and the next one as -//! transparency. Photoshop stores a pattern's transparency in the last (sheet mask) array and -//! leaves the user mask unwritten (psd-tools multichannel-pattern-fill.psd, Photoshop CC 2019); a -//! file with transparency in the user mask array is refused by Photoshop (#8054). - -use crate::compression::{Compression, MAX_DECODED_BYTES, PlaneLayout, decode_planes, encode_planes}; -use crate::error::{PsdError, Result}; -use crate::header::Version; - -/// Largest pattern edge accepted (Photoshop's own limit is far lower). -const MAX_EDGE: u32 = 30_000; -/// Budget for zero-padded channel planes summed over every pattern of one parse (a block, a `.pat` -/// file, an `.abr`). Photoshop writes every channel at the pattern rectangle, so a smaller channel -/// rectangle is only padding; without this cap a few hundred bytes (1x1 channels, a huge pattern -/// rectangle) would allocate up to `MAX_DECODED_BYTES` of zeros. -const MAX_PADDED_PATTERN_BYTES: u64 = 512 << 20; -// A PackBits run packet emits at most 128 bytes from a 2-byte packet. -const MAX_RLE_EXPANSION: u64 = 64; - -/// Decoded bytes left for the patterns of one parse. Shared by every pattern read in one call, so -/// many patterns can't each claim the whole per-pattern allowance. -#[derive(Debug, Clone)] -pub struct PatternBudget { - decoded_left: u64, - padded_left: u64, -} - -impl Default for PatternBudget { - fn default() -> Self { - PatternBudget { decoded_left: MAX_DECODED_BYTES, padded_left: MAX_PADDED_PATTERN_BYTES } - } -} - -impl PatternBudget { - /// A budget of at most `decoded` decoded bytes (zero padding included), and never more than - /// the default limits. - pub fn with_decoded_limit(decoded: u64) -> Self { - let d = Self::default(); - PatternBudget { decoded_left: d.decoded_left.min(decoded), padded_left: d.padded_left.min(decoded) } - } - - /// Cap both decoded and padded bytes to the amount still available to a containing file. - pub fn cap_decoded_to(&mut self, decoded: u64) { - self.decoded_left = self.decoded_left.min(decoded); - self.padded_left = self.padded_left.min(decoded); - } - - /// Decoded bytes still available. - pub fn decoded_left(&self) -> u64 { - self.decoded_left - } -} - -/// One pattern tile with planar, big-endian samples. -#[derive(Debug, Clone, PartialEq)] -pub struct PsdPattern { - /// PSD colour mode number (1 gray, 2 indexed, 3 RGB, 4 CMYK, 7 multichannel, 8 duotone, 9 Lab). - pub mode: u32, - /// Tile width in pixels. - pub width: u32, - /// Tile height in pixels. - pub height: u32, - /// Name without the trailing NUL (built-ins look like `$$$/Patterns/…=Water`). - pub name: String, - /// Unique id (usually a UUID). - pub id: String, - /// Indexed-colour palette (768 bytes, RGB triplets). - pub palette: Option>, - /// Bits per sample: 1, 8, 16 or 32. - pub depth: u16, - /// Decoded colour planes (`width × height` samples each). - pub channels: Vec>, - /// Decoded transparency plane, if any. - pub alpha: Option>, -} - -/// Colour channels implied by a PSD colour mode. -pub fn mode_channels(mode: u32) -> usize { - match mode { - 3 | 9 => 3, - 4 => 4, - _ => 1, - } -} - -struct Rd<'a> { - b: &'a [u8], - p: usize, -} - -struct PatternChannel<'a> { - data: &'a [u8], - compression: Compression, - source: PlaneLayout, - destination: PlaneLayout, - x: usize, - y: usize, -} - -impl<'a> Rd<'a> { - fn take(&mut self, n: usize) -> Result<&'a [u8]> { - let end = self.p.checked_add(n).ok_or(PsdError::LimitExceeded("pattern length overflow"))?; - if end > self.b.len() { - return Err(PsdError::UnexpectedEof { offset: self.p, needed: end - self.b.len() }); - } - let s = &self.b[self.p..end]; - self.p = end; - Ok(s) - } - fn u8(&mut self) -> Result { - Ok(self.take(1)?[0]) - } - fn u16(&mut self) -> Result { - let s = self.take(2)?; - Ok(u16::from_be_bytes([s[0], s[1]])) - } - fn u32(&mut self) -> Result { - let s = self.take(4)?; - Ok(u32::from_be_bytes([s[0], s[1], s[2], s[3]])) - } - fn i32(&mut self) -> Result { - Ok(self.u32()? as i32) - } - fn rect(&mut self) -> Result<[i32; 4]> { - Ok([self.i32()?, self.i32()?, self.i32()?, self.i32()?]) - } -} - -/// A pattern's mode, name, id and palette, up to its virtual memory array list. -struct PatternHeader { - mode: u32, - name: String, - id: String, - palette: Option>, -} - -fn read_header(r: &mut Rd) -> Result { - let version = r.u32()?; - if version != 1 { - return Err(PsdError::invalid(format!("pattern version {version}"))); - } - let mode = r.u32()?; - let _h = r.u16()?; - let _w = r.u16()?; - let n = r.u32()? as usize; - if n > 65_536 { - return Err(PsdError::LimitExceeded("pattern name length")); - } - let units: Vec = r.take(n * 2)?.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect(); - let name = String::from_utf16_lossy(&units).trim_end_matches('\0').to_string(); - let idl = r.u8()? as usize; - let id = String::from_utf8_lossy(r.take(idl)?).to_string(); - let palette = if mode == 2 { - let p = r.take(768)?.to_vec(); - // Some writers follow the palette with 4 extra bytes (ag-psd skips them). - if r.b.get(r.p..r.p + 4).is_some_and(|v| v != [0, 0, 0, 3]) { - r.take(4)?; - } - Some(p) - } else { - None - }; - Ok(PatternHeader { mode, name, id, palette }) -} - -/// The body of a pattern's virtual memory array list (after its version and length). -fn read_vma_body<'a>(r: &mut Rd<'a>) -> Result<&'a [u8]> { - let vver = r.u32()?; - if vver != 3 { - return Err(PsdError::invalid(format!("virtual memory array list version {vver}"))); - } - let len = r.u32()? as usize; - 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 }; - let [top, left, bottom, right] = v.rect()?; - let w = right.checked_sub(left).ok_or(PsdError::LimitExceeded("pattern width overflow"))?; - let h = bottom.checked_sub(top).ok_or(PsdError::LimitExceeded("pattern height overflow"))?; - if w <= 0 || h <= 0 || w as u32 > MAX_EDGE || h as u32 > MAX_EDGE { - return Err(PsdError::LimitExceeded("pattern size")); - } - let (w, h) = (w as u32, h as u32); - let count = v.u32()?; - if count > 64 { - return Err(PsdError::LimitExceeded("pattern channel count")); - } - // Validate every channel and the total padded size before decoding any plane. - // Otherwise a later channel can exceed the existing pattern budget only after - // earlier channels have already allocated several gigabytes of zero padding. - // `budget` is shared by every pattern of the parse, so many patterns can't each pad up to the - // per-parse cap. - let mut channels = Vec::new(); - let mut first_depth: Option = None; - for _ in 0..count + 2 { - if v.p >= body.len() { - break; - } - if v.u32()? == 0 { - continue; - } - let alen = v.u32()? as usize; - if alen == 0 { - continue; - } - if alen < 23 { - return Err(PsdError::invalid("short virtual memory array")); - } - let d32 = v.u32()?; - let [ct, cl, cb, cr] = v.rect()?; - let d16 = v.u16()?; - let comp = v.u8()?; - let data = v.take(alen - 23)?; - let d = if matches!(d16, 1 | 8 | 16 | 32) { d16 } else { d32 as u16 }; - if !matches!(d, 1 | 8 | 16 | 32) { - return Err(PsdError::invalid(format!("pattern depth {d}"))); - } - // Every plane is sized by one depth; a channel at another depth can't be written back. - if *first_depth.get_or_insert(d) != d { - return Err(PsdError::invalid("pattern channels have different depths")); - } - if ct < top || cl < left || cb > bottom || cr > right || cb < ct || cr < cl { - return Err(PsdError::invalid("pattern channel rectangle falls outside pattern rectangle")); - } - let cw = usize::try_from(cr.checked_sub(cl).ok_or(PsdError::LimitExceeded("pattern channel width overflow"))?) - .map_err(|_| PsdError::invalid("negative pattern channel width"))?; - let ch = usize::try_from(cb.checked_sub(ct).ok_or(PsdError::LimitExceeded("pattern channel height overflow"))?) - .map_err(|_| PsdError::invalid("negative pattern channel height"))?; - let channel_layout = PlaneLayout { planes: 1, width: cw, height: ch, depth: d, version: Version::Psd }; - let channel_bytes = channel_layout.total_bytes()?; - let layout = PlaneLayout { planes: 1, width: w as usize, height: h as usize, depth: d, version: Version::Psd }; - let plane_bytes = layout.total_bytes()?; - budget.decoded_left = budget.decoded_left.checked_sub(plane_bytes).ok_or(PsdError::LimitExceeded("pattern data exceeds MAX_DECODED_BYTES"))?; - if cw != w as usize || ch != h as usize { - budget.padded_left = - budget.padded_left.checked_sub(plane_bytes).ok_or(PsdError::LimitExceeded("padded pattern channels exceed MAX_PADDED_PATTERN_BYTES"))?; - } - let _ = layout.decoded_len()?; - let compression = if comp == 1 { - Compression::Rle - } else if comp == 0 { - Compression::Raw - } else { - Compression::Unknown(u16::from(comp)) - }; - let max_expansion = match compression { - Compression::Raw => Some(1), - Compression::Rle => Some(MAX_RLE_EXPANSION), - Compression::Zip | Compression::ZipPrediction | Compression::Unknown(_) => None, - }; - if let Some(max_expansion) = max_expansion { - let expansion_limit = u64::try_from(data.len()) - .map_err(|_| PsdError::LimitExceeded("pattern channel input exceeds address space"))? - .checked_mul(max_expansion) - .ok_or(PsdError::LimitExceeded("pattern channel input size overflow"))?; - if channel_bytes > expansion_limit { - return Err(PsdError::LimitExceeded("pattern channel exceeds its input-derived size limit")); - } - } - let x = usize::try_from(cl.checked_sub(left).ok_or(PsdError::LimitExceeded("pattern channel x offset overflow"))?) - .map_err(|_| PsdError::invalid("negative pattern channel x offset"))?; - let y = usize::try_from(ct.checked_sub(top).ok_or(PsdError::LimitExceeded("pattern channel y offset overflow"))?) - .map_err(|_| PsdError::invalid("negative pattern channel y offset"))?; - channels.push(PatternChannel { data, compression, source: channel_layout, destination: layout, x, y }); - } - let nc = mode_channels(mode); - 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.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)?); - } - let alpha = (planes.len() > nc).then(|| planes.remove(nc)); - planes.truncate(nc); - let depth = first_depth.unwrap_or(8); - Ok(PsdPattern { mode, width: w, height: h, name, id, palette, depth, channels: planes, alpha }) -} - -fn place_channel_plane(mut plane: Vec, source: &PlaneLayout, x: usize, y: usize, destination: &PlaneLayout) -> Result> { - if source.planes != 1 || destination.planes != 1 || source.depth != destination.depth { - return Err(PsdError::invalid("incompatible pattern channel layouts")); - } - let x_end = x.checked_add(source.width).ok_or(PsdError::LimitExceeded("pattern channel x offset overflow"))?; - let y_end = y.checked_add(source.height).ok_or(PsdError::LimitExceeded("pattern channel y offset overflow"))?; - if x_end > destination.width || y_end > destination.height { - return Err(PsdError::invalid("pattern channel rectangle falls outside pattern rectangle")); - } - let source_len = source.decoded_len()?; - if plane.len() != source_len { - return Err(PsdError::invalid("pattern channel payload does not match its rectangle")); - } - let destination_len = destination.decoded_len()?; - if x == 0 && y == 0 && source.width == destination.width && source.height == destination.height { - // Preserve the old placement's zeroed unused bits without copying a full - // bitmap plane. Only the last byte of each non-byte-aligned row changes. - if source.depth == 1 && !source.width.is_multiple_of(8) { - let mask = u8::MAX << (8 - source.width % 8); - for row in plane.chunks_exact_mut(source.row_bytes()) { - if let Some(last) = row.last_mut() { - *last &= mask; - } - } - } - return Ok(plane); - } - let mut out = zeroed_pattern_plane(destination_len)?; - if source.depth == 1 { - let source_row_bytes = source.row_bytes(); - let destination_row_bytes = destination.row_bytes(); - for row in 0..source.height { - for col in 0..source.width { - let source_pos = row - .checked_mul(source_row_bytes) - .and_then(|v| v.checked_add(col / 8)) - .ok_or(PsdError::LimitExceeded("pattern channel source offset overflow"))?; - let destination_col = x.checked_add(col).ok_or(PsdError::LimitExceeded("pattern channel destination offset overflow"))?; - let destination_pos = y - .checked_add(row) - .and_then(|v| v.checked_mul(destination_row_bytes)) - .and_then(|v| v.checked_add(destination_col / 8)) - .ok_or(PsdError::LimitExceeded("pattern channel destination offset overflow"))?; - let source_bit = 7 - col % 8; - let destination_bit = 7 - destination_col % 8; - let source_byte = plane.get(source_pos).ok_or(PsdError::invalid("pattern channel payload does not match its rectangle"))?; - let value = (*source_byte >> source_bit) & 1; - let dst = out.get_mut(destination_pos).ok_or(PsdError::invalid("pattern channel placement exceeds its output plane"))?; - *dst |= value << destination_bit; - } - } - } else { - let bytes_per_sample = usize::from(source.depth / 8); - let source_row_bytes = source.row_bytes(); - let destination_row_bytes = destination.row_bytes(); - let row_bytes = source.width.checked_mul(bytes_per_sample).ok_or(PsdError::LimitExceeded("pattern channel row size overflow"))?; - let x_bytes = x.checked_mul(bytes_per_sample).ok_or(PsdError::LimitExceeded("pattern channel x offset overflow"))?; - for row in 0..source.height { - let source_start = row.checked_mul(source_row_bytes).ok_or(PsdError::LimitExceeded("pattern channel source offset overflow"))?; - let destination_start = y - .checked_add(row) - .and_then(|v| v.checked_mul(destination_row_bytes)) - .and_then(|v| v.checked_add(x_bytes)) - .ok_or(PsdError::LimitExceeded("pattern channel destination offset overflow"))?; - let source_end = source_start.checked_add(row_bytes).ok_or(PsdError::LimitExceeded("pattern channel source offset overflow"))?; - let destination_end = destination_start.checked_add(row_bytes).ok_or(PsdError::LimitExceeded("pattern channel destination offset overflow"))?; - let source_row = plane.get(source_start..source_end).ok_or(PsdError::invalid("pattern channel payload does not match its rectangle"))?; - let destination_row = - out.get_mut(destination_start..destination_end).ok_or(PsdError::invalid("pattern channel placement exceeds its output plane"))?; - destination_row.copy_from_slice(source_row); - } - } - Ok(out) -} - -fn zeroed_pattern_plane(len: usize) -> Result> { - let mut out = Vec::new(); - out.try_reserve_exact(len).map_err(|_| PsdError::OutOfMemory("not enough memory for the padded pattern channel"))?; - out.resize(len, 0); - Ok(out) -} - -fn write_pattern(p: &PsdPattern, out: &mut Vec) -> Result<()> { - if p.width > MAX_EDGE || p.height > MAX_EDGE || p.width > i16::MAX as u32 || p.height > i16::MAX as u32 { - return Err(PsdError::LimitExceeded("pattern size")); - } - out.extend_from_slice(&1u32.to_be_bytes()); - out.extend_from_slice(&p.mode.to_be_bytes()); - out.extend_from_slice(&(p.height as u16).to_be_bytes()); - out.extend_from_slice(&(p.width as u16).to_be_bytes()); - let units: Vec = p.name.encode_utf16().chain(std::iter::once(0)).collect(); - // The reader refuses longer names (see `read_pattern`). - if units.len() > 65_536 { - return Err(PsdError::LimitExceeded("pattern name length")); - } - out.extend_from_slice(&(units.len() as u32).to_be_bytes()); - for u in units { - out.extend_from_slice(&u.to_be_bytes()); - } - let id = p.id.as_bytes(); - let idl = id.len().min(255); - out.push(idl as u8); - out.extend_from_slice(&id[..idl]); - if p.mode == 2 { - let mut pal = p.palette.clone().unwrap_or_default(); - pal.resize(768, 0); - out.extend_from_slice(&pal); - } - let rect = [0i32, 0, p.height as i32, p.width as i32]; - let mut body = Vec::new(); - for v in rect { - body.extend_from_slice(&v.to_be_bytes()); - } - const SLOTS: u32 = 24; - body.extend_from_slice(&SLOTS.to_be_bytes()); - let layout = PlaneLayout { planes: 1, width: p.width as usize, height: p.height as usize, depth: p.depth, version: Version::Psd }; - let array = |plane: &[u8], body: &mut Vec| -> Result<()> { - let (comp, data) = - if p.depth == 8 { (1u8, encode_planes(Compression::Rle, plane, &layout)?) } else { (0u8, encode_planes(Compression::Raw, plane, &layout)?) }; - body.extend_from_slice(&1u32.to_be_bytes()); - body.extend_from_slice(&((23 + data.len()) as u32).to_be_bytes()); - body.extend_from_slice(&u32::from(p.depth).to_be_bytes()); - for v in rect { - body.extend_from_slice(&v.to_be_bytes()); - } - body.extend_from_slice(&p.depth.to_be_bytes()); - body.push(comp); - body.extend_from_slice(&data); - Ok(()) - }; - let nc = p.channels.len().min(SLOTS as usize); - for c in &p.channels[..nc] { - array(c, &mut body)?; - } - for _ in nc..SLOTS as usize { - body.extend_from_slice(&0u32.to_be_bytes()); - } - // User mask slot: unused; sheet mask slot: transparency, where Photoshop keeps it (#8054). - body.extend_from_slice(&0u32.to_be_bytes()); - match &p.alpha { - Some(a) => array(a, &mut body)?, - None => body.extend_from_slice(&0u32.to_be_bytes()), - } - out.extend_from_slice(&3u32.to_be_bytes()); - out.extend_from_slice(&(body.len() as u32).to_be_bytes()); - out.extend_from_slice(&body); - Ok(()) -} - -/// Parses the data of a `Patt` / `Pat2` / `Pat3` global block. -pub fn parse_pattern_block(data: &[u8]) -> Result> { - parse_pattern_block_with(data, &mut PatternBudget::default()) -} - -/// [`parse_pattern_block`] charging `budget`, so several blocks of one document share one limit. -/// Charges are monotonic even when a later record in the block fails. -pub fn parse_pattern_block_with(data: &[u8], budget: &mut PatternBudget) -> Result> { - let mut r = Rd { b: data, p: 0 }; - let mut out = Vec::new(); - while r.p + 4 <= data.len() { - let len = r.u32()? as usize; - if len == 0 { - break; - } - let body = r.take(len)?; - out.push(read_pattern(&mut Rd { b: body, p: 0 }, budget)?); - let pad = (4 - len % 4) % 4; - r.p = (r.p + pad).min(data.len()); - } - 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`. -pub fn block_has_user_mask(data: &[u8]) -> bool { - let mut r = Rd { b: data, p: 0 }; - while r.p + 4 <= data.len() { - let Ok(len) = r.u32() else { return false }; - if len == 0 { - break; - } - let Ok(body) = r.take(len as usize) else { return false }; - if pattern_has_user_mask(&mut Rd { b: body, p: 0 }).unwrap_or(false) { - return true; - } - let pad = (4 - len as usize % 4) % 4; - r.p = (r.p + pad).min(data.len()); - } - false -} - -fn pattern_has_user_mask(r: &mut Rd) -> Result { - read_header(r)?; - let mut v = Rd { b: read_vma_body(r)?, p: 0 }; - v.rect()?; - let count = v.u32()?; - // Every array takes at least 4 bytes, so the body bounds this loop whatever `count` says. - for i in 0..count.saturating_add(2) { - if v.p >= v.b.len() { - break; - } - if v.u32()? == 0 { - continue; - } - let alen = v.u32()? as usize; - if i == count && alen != 0 { - return Ok(true); - } - v.take(alen)?; - } - Ok(false) -} - -/// Serializes patterns as `Patt` / `Pat2` / `Pat3` block data. -pub fn write_pattern_block(patterns: &[PsdPattern]) -> Result> { - let mut out = Vec::new(); - for p in patterns { - let mut one = Vec::new(); - write_pattern(p, &mut one)?; - out.extend_from_slice(&(one.len() as u32).to_be_bytes()); - let pad = (4 - one.len() % 4) % 4; - out.extend_from_slice(&one); - out.extend(std::iter::repeat_n(0u8, pad)); - } - Ok(out) -} - -/// Tagged-block key for patterns of a document at `depth` bits. -pub fn block_key(depth: u16) -> [u8; 4] { - match depth { - 16 => *b"Pat2", - 32 => *b"Pat3", - _ => *b"Patt", - } -} - -/// The most patterns a `.pat` file may hold: more are refused on read and on write. -pub const MAX_PAT_PATTERNS: usize = 100_000; - -/// Parses a `.pat` pattern file. -pub fn parse_pat_file(data: &[u8]) -> Result> { - let mut r = Rd { b: data, p: 0 }; - let sig = r.take(4)?; - if sig != b"8BPT" { - return Err(PsdError::InvalidSignature { expected: "8BPT", found: [sig[0], sig[1], sig[2], sig[3]] }); - } - let _version = r.u16()?; - let count = r.u32()? as usize; - if count > MAX_PAT_PATTERNS { - return Err(PsdError::LimitExceeded("pattern count")); - } - let mut out = Vec::new(); - let mut budget = PatternBudget::default(); - for _ in 0..count { - out.push(read_pattern(&mut r, &mut budget)?); - } - Ok(out) -} - -/// Writes a `.pat` pattern file. -pub fn write_pat_file(patterns: &[PsdPattern]) -> Result> { - if patterns.len() > MAX_PAT_PATTERNS { - return Err(PsdError::LimitExceeded("pattern count")); - } - let mut out = b"8BPT".to_vec(); - out.extend_from_slice(&1u16.to_be_bytes()); - out.extend_from_slice(&(patterns.len() as u32).to_be_bytes()); - for p in patterns { - write_pattern(p, &mut out)?; - } - Ok(out) -} - -#[cfg(test)] -mod tests; diff --git a/crates/psd/src/patterns/tests.rs b/crates/psd/src/patterns/tests.rs deleted file mode 100644 index e66d583738..0000000000 --- a/crates/psd/src/patterns/tests.rs +++ /dev/null @@ -1,352 +0,0 @@ -use super::*; - -fn pat(depth: u16, alpha: bool) -> PsdPattern { - let (w, h) = (5u32, 3u32); - let bpp = usize::from(depth / 8); - let plane = |s: u8| (0..w as usize * h as usize * bpp).map(|i| (i as u8).wrapping_mul(7).wrapping_add(s)).collect::>(); - PsdPattern { - mode: 3, - width: w, - height: h, - name: "Test ✓".into(), - id: "0bd2d3ba-1234-11d4-8f8f-aabbccddeeff".into(), - palette: None, - depth, - channels: vec![plane(1), plane(2), plane(3)], - alpha: alpha.then(|| plane(9)), - } -} - -/// #9318 review: a name the reader refuses (more than 65,536 UTF-16 units with its NUL) is -/// refused on write, so a saved library can't become a file that loads nothing. -#[test] -fn a_name_the_reader_refuses_is_refused_on_write() { - let long = PsdPattern { name: "a".repeat(65_536), ..pat(8, false) }; - assert!(matches!(write_pat_file(&[long]), Err(PsdError::LimitExceeded(_)))); - let longest = PsdPattern { name: "a".repeat(65_535), ..pat(8, false) }; - assert_eq!(parse_pat_file(&write_pat_file(std::slice::from_ref(&longest)).unwrap()).unwrap(), [longest]); -} - -/// #9318 review: more patterns than a `.pat` holds are refused on write, and a file claiming -/// more is refused on read rather than silently cut to the first 100,000. -#[test] -fn more_patterns_than_a_pat_file_holds_are_refused() { - let many = vec![pat(8, false); MAX_PAT_PATTERNS + 1]; - assert!(matches!(write_pat_file(&many), Err(PsdError::LimitExceeded(_)))); - let mut header = b"8BPT".to_vec(); - header.extend_from_slice(&1u16.to_be_bytes()); - header.extend_from_slice(&(MAX_PAT_PATTERNS as u32 + 1).to_be_bytes()); - assert!(matches!(parse_pat_file(&header), Err(PsdError::LimitExceeded(_)))); -} - -#[test] -fn block_and_pat_file_round_trip_at_every_depth() { - for depth in [8, 16, 32] { - for alpha in [false, true] { - let ps = vec![pat(depth, alpha), PsdPattern { name: "Second".into(), ..pat(depth, false) }]; - let blk = write_pattern_block(&ps).unwrap(); - assert_eq!(blk.len() % 4, 0); - assert_eq!(parse_pattern_block(&blk).unwrap(), ps); - let f = write_pat_file(&ps).unwrap(); - assert_eq!(parse_pat_file(&f).unwrap(), ps); - // Re-serialising is byte-stable. - assert_eq!(write_pattern_block(&parse_pattern_block(&blk).unwrap()).unwrap(), blk); - } - } -} - -/// Offsets of the virtual memory arrays of a one-pattern block (each at its "written" flag), -/// with whether each is written, and the end of the array list. -fn vma_slots(block: &[u8], p: &PsdPattern) -> (Vec<(usize, bool)>, usize) { - let rect = pattern_vma_rect_offset(4, p); - let end = rect + u32::from_be_bytes(block[rect - 4..rect].try_into().unwrap()) as usize; - let (mut at, mut slots) = (rect + 20, Vec::new()); - while at < end { - let written = u32::from_be_bytes(block[at..at + 4].try_into().unwrap()) != 0; - slots.push((at, written)); - at += 4; - if written { - at += 4 + u32::from_be_bytes(block[at..at + 4].try_into().unwrap()) as usize; - } - } - (slots, end) -} - -#[test] -fn transparency_goes_in_the_sheet_mask_array_like_photoshop() { - // #8054: transparency in the user mask array (slot 24) made Photoshop refuse the file; - // Photoshop keeps it in the sheet mask array (slot 25). - for depth in [8, 16, 32] { - let p = pat(depth, true); - let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let (slots, end) = vma_slots(&block, &p); - let written: Vec = slots.iter().enumerate().filter(|(_, s)| s.1).map(|(i, _)| i).collect(); - assert_eq!((slots.len(), written), (26, vec![0, 1, 2, 25]), "{depth}-bit"); - assert!(!block_has_user_mask(&block)); - // The layout older PhotoCraft builds wrote still opens, and is detected. - block[slots[24].0..end].rotate_left(4); - let (slots, _) = vma_slots(&block, &p); - assert!(slots[24].1 && !slots[25].1); - assert!(block_has_user_mask(&block)); - assert_eq!(parse_pattern_block(&block).unwrap(), vec![p]); - } - assert!(!block_has_user_mask(&write_pattern_block(&[pat(8, false)]).unwrap())); - for junk in [&[][..], &[0, 0, 0, 9, 1], &[0xff; 64]] { - assert!(!block_has_user_mask(junk)); - } -} - -#[test] -fn malformed_input_errors_without_panicking() { - let blk = write_pattern_block(&[pat(8, true)]).unwrap(); - for cut in [3, 10, 40, blk.len() - 5] { - let _ = parse_pattern_block(&blk[..cut]); - } - assert!(parse_pat_file(b"8BPS\0\x01").is_err()); - assert!(parse_pattern_block(&[]).unwrap().is_empty()); -} - -fn pattern_vma_rect_offset(pattern_start: usize, p: &PsdPattern) -> usize { - let name_units = p.name.encode_utf16().count() + 1; - pattern_start + 16 + name_units * 2 + 1 + p.id.len() + if p.mode == 2 { 768 } else { 0 } + 8 -} - -fn set_i32(bytes: &mut [u8], offset: usize, value: i32) { - bytes[offset..offset + 4].copy_from_slice(&value.to_be_bytes()); -} - -#[test] -fn hostile_pattern_rectangles_are_rejected_through_all_import_routes() { - let p = pat(8, false); - - // A subtraction of the hostile endpoints overflowed before rectangle validation. - let mut global = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - set_i32(&mut global, vma + 4, i32::MIN); - set_i32(&mut global, vma + 12, i32::MAX); - assert!(parse_pattern_block(&global).is_err()); - - let mut standalone = write_pat_file(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(10, &p); - set_i32(&mut standalone, vma + 4, i32::MIN); - set_i32(&mut standalone, vma + 12, i32::MAX); - assert!(parse_pat_file(&standalone).is_err()); - - let mut abr = crate::abr::write_v6( - 1, - &[crate::abr::AbrSample { id: String::new(), width: 1, height: 1, depth: 8, data: vec![0] }], - std::slice::from_ref(&p), - &[], - true, - ) - .unwrap(); - let section = abr.windows(4).position(|w| w == b"patt").unwrap(); - let vma = pattern_vma_rect_offset(section + 8, &p) + 4; - set_i32(&mut abr, vma + 4, i32::MIN); - set_i32(&mut abr, vma + 12, i32::MAX); - let parsed = crate::abr::parse(&abr).unwrap(); - assert!(parsed.patterns.is_empty()); - assert!(parsed.warnings.iter().any(|warning| warning.contains("embedded patterns unreadable"))); -} - -#[test] -fn huge_pattern_rect_with_tiny_channel_payload_is_rejected() { - // RGB32 needs 10.8 GB; CMYK16 plus alpha needs 9 GB. Both exceed the - // existing pattern budget, but their first plane fits on 64-bit targets. - // The complete metadata must be checked before allocating that first plane. - huge_pattern_rect_is_rejected(pat(32, false)); - let mut cmyk = pat(16, true); - cmyk.mode = 4; - cmyk.channels.push(vec![0; 5 * 3 * 2]); - huge_pattern_rect_is_rejected(cmyk); -} - -fn huge_pattern_rect_is_rejected(p: PsdPattern) { - let mut global = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - set_i32(&mut global, vma + 8, 30_000); - set_i32(&mut global, vma + 12, 30_000); - assert!(matches!(parse_pattern_block(&global), Err(PsdError::LimitExceeded(_)))); - - let mut standalone = write_pat_file(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(10, &p); - set_i32(&mut standalone, vma + 8, 30_000); - set_i32(&mut standalone, vma + 12, 30_000); - assert!(matches!(parse_pat_file(&standalone), Err(PsdError::LimitExceeded(_)))); - - let mut abr = crate::abr::write_v6( - 1, - &[crate::abr::AbrSample { id: String::new(), width: 1, height: 1, depth: 8, data: vec![0] }], - std::slice::from_ref(&p), - &[], - true, - ) - .unwrap(); - let section = abr.windows(4).position(|w| w == b"patt").unwrap(); - let vma = pattern_vma_rect_offset(section + 8, &p) + 4; - set_i32(&mut abr, vma + 8, 30_000); - set_i32(&mut abr, vma + 12, 30_000); - let parsed = crate::abr::parse(&abr).unwrap(); - assert!(parsed.patterns.is_empty()); - assert!(parsed.warnings.iter().any(|warning| warning.contains("embedded patterns unreadable"))); -} - -#[test] -fn offset_channel_rectangles_are_placed_inside_the_pattern() { - for depth in [8, 16, 32] { - let original = pat(depth, true); - let mut block = write_pattern_block(std::slice::from_ref(&original)).unwrap(); - let vma = pattern_vma_rect_offset(4, &original); - set_i32(&mut block, vma, -2); - set_i32(&mut block, vma + 4, -3); - set_i32(&mut block, vma + 8, 4); - set_i32(&mut block, vma + 12, 5); - - let parsed = parse_pattern_block(&block).unwrap(); - let parsed = parsed.first().unwrap(); - assert_eq!((parsed.width, parsed.height), (8, 6)); - let bytes_per_sample = usize::from(depth / 8); - for (actual, expected) in parsed.channels.iter().zip(&original.channels).chain(parsed.alpha.iter().zip(original.alpha.iter())) { - for y in 0..6usize { - for x in 0..8usize { - let at = (y * 8 + x) * bytes_per_sample; - let actual_sample = actual.get(at..at + bytes_per_sample).unwrap(); - if (2..5).contains(&y) && (3..8).contains(&x) { - let source_at = ((y - 2) * 5 + (x - 3)) * bytes_per_sample; - assert_eq!(actual_sample, expected.get(source_at..source_at + bytes_per_sample).unwrap()); - } else { - assert!(actual_sample.iter().all(|&sample| sample == 0)); - } - } - } - } - } -} - -#[test] -fn one_bit_offset_channel_placement_preserves_msb_first_pixels() { - let source = PlaneLayout { planes: 1, width: 5, height: 2, depth: 1, version: Version::Psd }; - let destination = PlaneLayout { planes: 1, width: 8, height: 4, depth: 1, version: Version::Psd }; - let placed = place_channel_plane(vec![0b1010_1000, 0b0101_0000], &source, 2, 1, &destination).unwrap(); - assert_eq!(placed, [0, 0b0010_1010, 0b0001_0100, 0]); -} - -#[test] -fn full_size_channels_reuse_the_decoded_allocation() { - for depth in [1, 8, 16, 32] { - let layout = PlaneLayout { planes: 1, width: 5, height: 3, depth, version: Version::Psd }; - let plane = vec![0x55; layout.decoded_len().unwrap()]; - let original = plane.as_ptr(); - let placed = place_channel_plane(plane, &layout, 0, 0, &layout).unwrap(); - assert_eq!(placed.as_ptr(), original); - let expected = if depth == 1 { 0x50 } else { 0x55 }; - assert!(placed.iter().all(|&byte| byte == expected)); - } -} - -#[test] -fn large_channel_padding_within_the_existing_budget_is_allowed() { - let mut p = pat(8, false); - p.mode = 1; - let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - // More than 64 MiB of implicit padding is valid: the fix must not introduce - // a smaller, padding-specific format limit to avoid the oversized RGB case. - set_i32(&mut block, vma + 8, 8193); - set_i32(&mut block, vma + 12, 8193); - let parsed = parse_pattern_block(&block).unwrap(); - let plane = &parsed[0].channels[0]; - assert_eq!(plane.len(), 8193 * 8193); - for y in 0..3 { - assert_eq!(&plane[y * 8193..y * 8193 + 5], &p.channels[0][y * 5..y * 5 + 5]); - } - assert_eq!(plane[5], 0); - assert_eq!(plane[plane.len() - 1], 0); -} - -#[test] -fn padded_plane_allocation_failure_is_an_error() { - // Capacity overflow is deterministic and never asks the OS for huge memory. - assert!(matches!(zeroed_pattern_plane(usize::MAX), Err(PsdError::OutOfMemory("not enough memory for the padded pattern channel")))); -} - -#[test] -fn tiny_channels_in_a_huge_pattern_rect_are_not_zero_padded_without_bound() { - // 3 channels of 5x3 padded to 30000x30000 would allocate 2.7 GB of zeros. - let p = pat(8, false); - let mut global = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - set_i32(&mut global, vma + 8, 30_000); - set_i32(&mut global, vma + 12, 30_000); - assert!(matches!(parse_pattern_block(&global), Err(PsdError::LimitExceeded("padded pattern channels exceed MAX_PADDED_PATTERN_BYTES")))); -} - -/// A one-channel gray pattern whose 5x3 channel is padded into a `size`x`size` rectangle. -fn padded_gray_block(size: i32) -> Vec { - let mut p = pat(8, false); - p.mode = 1; - p.channels.truncate(1); - let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - set_i32(&mut block, vma + 8, size); - set_i32(&mut block, vma + 12, size); - block -} - -#[test] -fn failed_pattern_block_keeps_partial_charge_for_the_next_block() { - let one = padded_gray_block(100); - let mut malformed = one.clone(); - malformed.extend_from_slice(&100u32.to_be_bytes()); - let mut budget = PatternBudget::with_decoded_limit(15_000); - assert!(parse_pattern_block_with(&malformed, &mut budget).is_err()); - assert_eq!(budget.decoded_left(), 5_000); - assert!(parse_pattern_block_with(&one, &mut budget).is_err()); - assert_eq!(budget.decoded_left(), 5_000); -} - -#[test] -fn padding_budget_is_shared_by_every_pattern_of_a_parse() { - // Each pattern pads 100x100 = 10000 bytes; a 15000-byte budget fits one, not two. Before - // the fix each pattern got a fresh allowance, so N tiny patterns committed N times the cap. - let one = padded_gray_block(100); - let mut budget = PatternBudget::with_decoded_limit(15_000); - assert_eq!(parse_pattern_block_with(&one, &mut budget).unwrap().len(), 1); - assert_eq!(budget.decoded_left(), 5_000); - - let two = [one.clone(), one.clone()].concat(); - let mut budget = PatternBudget::with_decoded_limit(15_000); - assert!(matches!(parse_pattern_block_with(&two, &mut budget), Err(PsdError::LimitExceeded(_)))); - // Charges are monotonic: the first pattern's 10000 bytes stay charged even when the second - // record fails. - assert_eq!(budget.decoded_left(), 5_000); - - // Two blocks of one document share a budget too. - let mut budget = PatternBudget::with_decoded_limit(15_000); - assert!(parse_pattern_block_with(&one, &mut budget).is_ok()); - assert!(parse_pattern_block_with(&one, &mut budget).is_err()); -} - -#[test] -fn channels_at_different_depths_are_rejected() { - // The second colour channel claims 8 bits in a 16-bit pattern. It used to be accepted with - // the pattern's depth taken from the last channel, so the result couldn't be written back. - let p = pat(16, false); - let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let first = pattern_vma_rect_offset(4, &p) + 20; - let first_len = u32::from_be_bytes(block[first + 4..first + 8].try_into().unwrap()) as usize; - let second = first + 8 + first_len; - block[second + 8..second + 12].copy_from_slice(&8u32.to_be_bytes()); - block[second + 28..second + 30].copy_from_slice(&8u16.to_be_bytes()); - let err = parse_pattern_block(&block).unwrap_err().to_string(); - assert!(err.contains("different depths"), "{err}"); -} - -#[test] -fn zero_size_pattern_rectangles_are_rejected() { - let p = pat(8, false); - let mut block = write_pattern_block(std::slice::from_ref(&p)).unwrap(); - let vma = pattern_vma_rect_offset(4, &p); - set_i32(&mut block, vma + 8, 0); - assert!(parse_pattern_block(&block).is_err()); -} diff --git a/crates/psd/src/pixels.rs b/crates/psd/src/pixels.rs deleted file mode 100644 index 04f7c28ae8..0000000000 --- a/crates/psd/src/pixels.rs +++ /dev/null @@ -1,465 +0,0 @@ -//! Sample helpers and RGBA8 convenience extraction. -//! -//! These are conveniences for previews and tests; they perform no color -//! management. 16-bit samples are scaled with rounding, 32-bit float samples -//! are clamped to 0..=1 (no tone mapping or gamma), CMYK is converted -//! naively (`r = c' * k' / 255` using the stored, inverted values). - -use crate::error::{PsdError, Result}; -use crate::file::PsdFile; -use crate::header::{ColorMode, Header, Version}; -use crate::layer::{CHANNEL_REAL_USER_MASK, CHANNEL_TRANSPARENCY, CHANNEL_USER_MASK, LayerRecord, Rect}; -use std::borrow::Cow; - -/// Interprets planar big-endian bytes as u16 samples. -pub fn samples_u16(bytes: &[u8]) -> Vec { - bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect() -} - -/// Interprets planar big-endian bytes as f32 samples. -pub fn samples_f32(bytes: &[u8]) -> Vec { - bytes.as_chunks::<4>().0.iter().map(|c| f32::from_be_bytes([c[0], c[1], c[2], c[3]])).collect() -} - -/// Encodes u16 samples as big-endian bytes. -pub fn u16_to_bytes(samples: &[u16]) -> Vec { - samples.iter().flat_map(|s| s.to_be_bytes()).collect() -} - -/// Encodes f32 samples as big-endian bytes. -pub fn f32_to_bytes(samples: &[f32]) -> Vec { - samples.iter().flat_map(|s| s.to_be_bytes()).collect() -} - -/// Allocates `len` bytes, reporting a machine without that much memory instead of aborting. -fn try_buffer(len: usize) -> Result> { - let mut out = Vec::new(); - out.try_reserve_exact(len).map_err(|_| PsdError::OutOfMemory("not enough memory for the converted plane"))?; - Ok(out) -} - -/// Expands a 1-bit plane (MSB first, rows padded to bytes) to one byte per -/// pixel (0 or 1). Errors with [`PsdError::LimitExceeded`] when the plane -/// size overflows or cannot be allocated. -pub fn unpack_bits(bytes: &[u8], width: usize, height: usize) -> Result> { - unpack_bits_with(bytes, width, height, |bit| bit) -} - -/// Shared 1-bit expansion; `map` turns each bit (0 or 1) into the output byte. -fn unpack_bits_with(bytes: &[u8], width: usize, height: usize, map: impl Fn(u8) -> u8) -> Result> { - let len = width.checked_mul(height).ok_or(PsdError::LimitExceeded("plane size overflow"))?; - let rb = width.div_ceil(8); - let mut out = try_buffer(len)?; - for y in 0..height { - for x in 0..width { - let b = y.checked_mul(rb).and_then(|row| bytes.get(row + x / 8)).copied().unwrap_or(0); - out.push(map((b >> (7 - (x % 8))) & 1)); - } - } - Ok(out) -} - -/// Converts one plane of samples at `depth` to 8-bit. -pub fn plane_to_u8(bytes: &[u8], depth: u16, width: usize, height: usize) -> Result> { - Ok(match depth { - 1 => unpack_bits_with(bytes, width, height, |b| if b == 1 { 0 } else { 255 })?, - 8 => { - let mut out = try_buffer(bytes.len())?; - out.extend_from_slice(bytes); - out - } - 16 => { - let chunks = bytes.as_chunks::<2>().0; - let mut out = try_buffer(chunks.len())?; - out.extend(chunks.iter().map(|b| ((u32::from(u16::from_be_bytes(*b)) * 255 + 32767) / 65535) as u8)); - out - } - 32 => { - let chunks = bytes.as_chunks::<4>().0; - let mut out = try_buffer(chunks.len())?; - out.extend(chunks.iter().map(|b| { - let v = f32::from_be_bytes(*b); - if v.is_nan() { 0 } else { (v.clamp(0.0, 1.0) * 255.0).round() as u8 } - })); - out - } - d => return Err(PsdError::Unsupported(format!("depth {d}"))), - }) -} - -/// An 8-bit RGBA image positioned in document coordinates. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct RgbaImage { - /// Left edge in document coordinates. - pub left: i32, - /// Top edge in document coordinates. - pub top: i32, - /// Width. - pub width: u32, - /// Height. - pub height: u32, - /// Interleaved RGBA, row-major. - pub data: Vec, -} - -/// An 8-bit single-channel image (e.g. a layer mask). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct GrayImage { - /// Left edge. - pub left: i32, - /// Top edge. - pub top: i32, - /// Width. - pub width: u32, - /// Height. - pub height: u32, - /// Samples. - pub data: Vec, - /// Value outside the rectangle (masks only). - pub default_value: u8, -} - -fn interleave(mode: ColorMode, color: &[Cow<'_, [u8]>], alpha: Option<&[u8]>, palette: &[u8], n: usize) -> Result> { - if color.len() != color_channel_count(mode)? || color.iter().any(|p| p.len() != n) || alpha.is_some_and(|p| p.len() != n) { - return Err(PsdError::invalid("channel size mismatch")); - } - let len = n - .checked_mul(4) - .filter(|&len| len as u64 <= crate::compression::MAX_DECODED_BYTES) - .ok_or(PsdError::LimitExceeded("RGBA output exceeds MAX_DECODED_BYTES"))?; - let mut out = Vec::new(); - out.try_reserve_exact(len).map_err(|_| PsdError::OutOfMemory("not enough memory for RGBA output"))?; - out.resize(len, 255); - if mode == ColorMode::Rgb { - let [r, g, b] = color else { return Err(PsdError::invalid("RGB requires three channels")) }; - let rgb = r.iter().zip(g.iter()).zip(b.iter()); - match alpha { - Some(alpha) => { - for (rgba, (((r, g), b), a)) in out.as_chunks_mut::<4>().0.iter_mut().zip(rgb.zip(alpha)) { - *rgba = [*r, *g, *b, *a]; - } - } - None => { - for (rgba, ((r, g), b)) in out.as_chunks_mut::<4>().0.iter_mut().zip(rgb) { - *rgba = [*r, *g, *b, 255]; - } - } - } - return Ok(out); - } - for i in 0..n { - let (r, g, b) = match mode { - ColorMode::Rgb => (color[0][i], color[1][i], color[2][i]), - ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => (color[0][i], color[0][i], color[0][i]), - ColorMode::Indexed => { - let idx = usize::from(color[0][i]); - let p = |k: usize| palette.get(k * 256 + idx).copied().unwrap_or(0); - (p(0), p(1), p(2)) - } - ColorMode::Cmyk => { - let k = u32::from(color[3][i]); - let f = |c: u8| ((u32::from(c) * k + 127) / 255) as u8; - (f(color[0][i]), f(color[1][i]), f(color[2][i])) - } - m => return Err(PsdError::Unsupported(format!("rgba8 for color mode {m:?}"))), - }; - out[i * 4] = r; - out[i * 4 + 1] = g; - out[i * 4 + 2] = b; - out[i * 4 + 3] = alpha.map_or(255, |a| a[i]); - } - Ok(out) -} - -fn color_channel_count(mode: ColorMode) -> Result { - match mode { - ColorMode::Rgb => Ok(3), - ColorMode::Cmyk => Ok(4), - ColorMode::Grayscale | ColorMode::Indexed | ColorMode::Bitmap | ColorMode::Duotone => Ok(1), - m => Err(PsdError::Unsupported(format!("rgba8 for color mode {m:?}"))), - } -} - -/// One 8-bit sample matted against white at alpha `a`, back to straight colour (rounded, at most -/// 255). At `a == 0` there is no colour to recover and the sample is kept. -fn unmatte_u8(c: u8, a: u8) -> u8 { - let a = u32::from(a); - ((u32::from(c) + a).saturating_sub(255) * 255 + a / 2).checked_div(a).map_or(c, |straight| straight.min(255) as u8) -} - -/// [`unmatte_u8`] of every sample, one row per alpha: `table[a][c]`. Built per call (64 KiB, a -/// division per entry) rather than per pixel, and not as a static, which would add 64 KiB to -/// every binary that links this crate. -fn unmatte_u8_table() -> Vec<[u8; 256]> { - (0..=255).map(|a| std::array::from_fn(|c| unmatte_u8(c as u8, a))).collect() -} - -fn unmatte_to_u8(color: &[u8], alpha: &[u8], depth: u16) -> Result> { - let convert = |c: f32, a: f32| { - let straight = if a > 0.0 { (c + a - 1.0) / a } else { c }; - (straight.clamp(0.0, 1.0) * 255.0).round() as u8 - }; - Ok(match depth { - 16 => color - .as_chunks::<2>() - .0 - .iter() - .zip(alpha.as_chunks::<2>().0) - .map(|(c, a)| convert(f32::from(u16::from_be_bytes(*c)) / 65535.0, f32::from(u16::from_be_bytes(*a)) / 65535.0)) - .collect(), - 32 => color.as_chunks::<4>().0.iter().zip(alpha.as_chunks::<4>().0).map(|(c, a)| convert(f32::from_be_bytes(*c), f32::from_be_bytes(*a))).collect(), - d => return Err(PsdError::Unsupported(format!("RGB composite depth {d}"))), - }) -} - -/// A borrowed view of a layer with the file context needed to decode it. -#[derive(Debug, Clone, Copy)] -pub struct Layer<'a> { - /// Index in [`PsdFile::layers`]. - pub index: usize, - /// The record. - pub record: &'a LayerRecord, - header: &'a Header, -} - -impl<'a> Layer<'a> { - /// Name, preferring `luni`. - pub fn name(&self) -> String { - self.record.name() - } - - /// PSD/PSB version of the containing file. - pub fn version(&self) -> Version { - self.header.version - } - - /// Decodes a channel (planar, big-endian samples). - pub fn channel_bytes(&self, id: i16) -> Result> { - self.record.decode_channel(id, self.header.depth, self.header.version) - } - - /// Layer pixels as RGBA8 (transparency channel as alpha; the user mask is - /// *not* applied, see [`Self::user_mask`]). Supports RGB, grayscale and - /// CMYK at 8/16/32 bits. - pub fn rgba8(&self) -> Result { - let rect = self.record.rect; - let (w, h) = rect.size()?; - let n = w.checked_mul(h).ok_or(PsdError::LimitExceeded("layer size overflow"))?; - let depth = self.header.depth; - let mode = self.header.color_mode; - let cc = color_channel_count(mode)?; - // The planes (one per colour channel, filled in for channels the layer lacks, and alpha) - // coexist with the RGBA output, so the cap covers all of them, not the output alone. - if n.checked_mul(cc + 2 + 4).is_none_or(|len| len as u64 > crate::compression::MAX_DECODED_BYTES) { - return Err(PsdError::LimitExceeded("RGBA output exceeds MAX_DECODED_BYTES")); - } - let mut color = Vec::with_capacity(cc); - for id in 0..cc as i16 { - let plane = if self.record.channel(id).is_some() { - let bytes = self.channel_bytes(id)?; - if depth == 8 { bytes } else { plane_to_u8(&bytes, depth, w, h)? } - } else { - vec![if mode == ColorMode::Cmyk { 255 } else { 0 }; n] - }; - if plane.len() != n { - return Err(PsdError::invalid("channel size mismatch")); - } - color.push(Cow::Owned(plane)); - } - let alpha = match self.record.channel(CHANNEL_TRANSPARENCY) { - Some(_) => { - let bytes = self.channel_bytes(CHANNEL_TRANSPARENCY)?; - Some(if depth == 8 { bytes } else { plane_to_u8(&bytes, depth, w, h)? }) - } - None => None, - }; - let data = interleave(mode, &color, alpha.as_deref(), &[], n)?; - Ok(RgbaImage { left: rect.left, top: rect.top, width: w as u32, height: h as u32, data }) - } - - /// The user mask (channel -3 if present, else -2) as 8-bit gray, with its - /// rectangle and default color. `None` if the layer has no mask channel. - pub fn user_mask(&self) -> Option> { - let id = if self.record.channel(CHANNEL_REAL_USER_MASK).is_some() { - CHANNEL_REAL_USER_MASK - } else if self.record.channel(CHANNEL_USER_MASK).is_some() { - CHANNEL_USER_MASK - } else { - return None; - }; - Some((|| { - let rect: Rect = self.record.channel_rect(id); - let (w, h) = rect.size()?; - let data = plane_to_u8(&self.channel_bytes(id)?, self.header.depth, w, h)?; - let default_value = match (self.record.layer_mask(), id) { - (Some(m), CHANNEL_REAL_USER_MASK) => m.real.map_or(m.default_color, |r| r.background), - (Some(m), _) => m.default_color, - (None, _) => 0, - }; - Ok(GrayImage { left: rect.left, top: rect.top, width: w as u32, height: h as u32, data, default_value }) - })()) - } -} - -impl PsdFile { - /// Borrowed view of layer `index`. - pub fn layer(&self, index: usize) -> Option> { - self.layers().get(index).map(|record| Layer { index, record, header: &self.header }) - } - - /// Iterates over layers in file order (bottom-most first). - pub fn iter_layers(&self) -> impl Iterator> { - self.layers().iter().enumerate().map(|(index, record)| Layer { index, record, header: &self.header }) - } - - /// The merged composite as RGBA8. Supports RGB, grayscale, CMYK, indexed, - /// duotone (as gray) and bitmap at all depths. Alpha comes from the first - /// extra channel when [`PsdFile::merged_has_alpha`] is true. Removes the - /// white matte from RGB composites before reducing precision. - pub fn composite_rgba8(&self) -> Result { - let h = &self.header; - h.validate()?; - let (w, hh) = (h.width as usize, h.height as usize); - let n = w.checked_mul(hh).ok_or(PsdError::LimitExceeded("composite size overflow"))?; - // Same budget as `Layer::rgba8`: refuse before decoding or converting any plane. - if n.checked_mul(4).is_none_or(|len| len as u64 > crate::compression::MAX_DECODED_BYTES) { - return Err(PsdError::LimitExceeded("RGBA output exceeds MAX_DECODED_BYTES")); - } - let cc = color_channel_count(h.color_mode)?; - if usize::from(h.channels) < cc { - return Err(PsdError::invalid("fewer channels than the color mode requires")); - } - let all = self.decode_merged()?; - let plane = h.row_bytes().checked_mul(hh).ok_or(PsdError::LimitExceeded("plane size overflow"))?; - let alpha_bytes = if self.merged_has_alpha() { - Some(all.get(cc * plane..(cc + 1) * plane).ok_or_else(|| PsdError::invalid("alpha channel size mismatch"))?) - } else { - None - }; - let get = |i: usize| -> Result> { - let bytes = all.get(i * plane..(i + 1) * plane).ok_or_else(|| PsdError::invalid("channel size mismatch"))?; - if h.depth == 8 { Ok(Cow::Borrowed(bytes)) } else { plane_to_u8(bytes, h.depth, w, hh).map(Cow::Owned) } - }; - let mut color = Vec::with_capacity(cc); - for i in 0..cc { - color.push( - if h.color_mode == ColorMode::Rgb - && h.depth != 8 - && let Some(alpha) = alpha_bytes - { - let bytes = all.get(i * plane..(i + 1) * plane).ok_or_else(|| PsdError::invalid("channel size mismatch"))?; - Cow::Owned(unmatte_to_u8(bytes, alpha, h.depth)?) - } else { - get(i)? - }, - ); - } - let alpha = if self.merged_has_alpha() { Some(get(cc)?) } else { None }; - let mut data = interleave(h.color_mode, &color, alpha.as_deref(), &self.color_mode_data, n)?; - if h.color_mode == ColorMode::Rgb && h.depth == 8 && alpha.is_some() { - let table = unmatte_u8_table(); - for pixel in data.as_chunks_mut::<4>().0 { - let row = &table[usize::from(pixel[3])]; - for c in pixel.iter_mut().take(3) { - *c = row[usize::from(*c)]; - } - } - } - Ok(RgbaImage { left: 0, top: 0, width: h.width, height: h.height, data }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn float_composite_removes_white_matte_without_changing_native_data() { - let mut file = crate::testgen::merged_only(Version::Psd, ColorMode::Rgb, 32, crate::Compression::Raw, 1, 1); - file.header.channels = 4; - let native = f32_to_bytes(&[0.75, 0.875, 1.0, 0.25]); - file.image_data = crate::ImageData::encode(crate::Compression::Raw, &native, &file.header).unwrap(); - assert_eq!(file.composite_rgba8().unwrap().data, [0, 128, 255, 64]); - assert_eq!(file.decode_merged().unwrap(), native); - } - - /// #5694: the 8-bit RGB composite unmattes through a table; every (sample, alpha) pair comes - /// out exactly as the per-pixel division it replaced (kept here as the reference). - #[test] - fn rgba8_composite_unmattes_every_sample_and_alpha_as_the_division_did() { - let mut file = crate::testgen::merged_only(Version::Psd, ColorMode::Rgb, 8, crate::Compression::Raw, 256, 256); - file.header.channels = 4; - // Pixel (x, y): red x, green 255 - x, blue x ^ y, alpha y. - let (x, y) = (|i: usize| (i % 256) as u8, |i: usize| (i / 256) as u8); - let plane = |f: &dyn Fn(usize) -> u8| (0..256 * 256).map(f).collect::>(); - let planes = [plane(&|i| x(i)), plane(&|i| 255 - x(i)), plane(&|i| x(i) ^ y(i)), plane(&|i| y(i))]; - file.image_data = crate::ImageData::encode(crate::Compression::Raw, &planes.concat(), &file.header).unwrap(); - let mut expected: Vec = (0..256 * 256).flat_map(|i| planes.each_ref().map(|p| p[i])).collect(); - for pixel in expected.as_chunks_mut::<4>().0 { - let a = u32::from(pixel[3]); - for c in pixel.iter_mut().take(3) { - if let Some(straight) = ((u32::from(*c) + a).saturating_sub(255) * 255 + a / 2).checked_div(a) { - *c = straight.min(255) as u8; - } - } - } - assert_eq!(file.composite_rgba8().unwrap().data, expected); - } - - #[test] - fn oversized_layer_preview_rejects_missing_channels_before_allocating() { - let mut file = crate::testgen::small(Version::Psb, crate::Compression::Raw); - file.layers_mut().push(LayerRecord { rect: Rect::from_xywh(0, 0, 300000, 300000), ..Default::default() }); - assert!(matches!(file.iter_layers().last().unwrap().rgba8(), Err(PsdError::LimitExceeded(_)))); - } - - #[test] - fn sample_conversions() { - assert_eq!(samples_u16(&[0x12, 0x34, 0xff, 0xff]), vec![0x1234, 0xffff]); - assert_eq!(u16_to_bytes(&[0x1234]), vec![0x12, 0x34]); - let f = f32_to_bytes(&[0.5, -1.0]); - assert_eq!(samples_f32(&f), vec![0.5, -1.0]); - } - - #[test] - fn unpack_bits_rows() { - assert_eq!(unpack_bits(&[0b1010_0000, 0b1000_0000], 3, 2).unwrap(), vec![1, 0, 1, 1, 0, 0]); - } - - #[test] - fn plane_to_u8_depths() { - assert_eq!(plane_to_u8(&[0xff, 0xff, 0, 0, 0x80, 0x00], 16, 3, 1).unwrap(), vec![255, 0, 128]); - assert_eq!(plane_to_u8(&f32_to_bytes(&[0.0, 1.0, 2.0, -1.0, f32::NAN]), 32, 5, 1).unwrap(), vec![0, 255, 255, 0, 0]); - assert_eq!(plane_to_u8(&[0b1000_0000], 1, 2, 1).unwrap(), vec![0, 255]); - assert!(plane_to_u8(&[], 12, 0, 0).is_err()); - } - - /// A plane size that overflows or cannot be allocated is an error, not a panic or abort. - #[test] - fn plane_conversion_reports_absurd_sizes() { - assert!(matches!(unpack_bits(&[0], usize::MAX / 2, 4), Err(PsdError::LimitExceeded(_)))); - assert!(matches!(plane_to_u8(&[0], 1, usize::MAX / 2, 4), Err(PsdError::LimitExceeded(_)))); - assert!(matches!(unpack_bits(&[0], 1 << 40, 1 << 20), Err(PsdError::LimitExceeded(_) | PsdError::OutOfMemory(_)))); - } - - /// A bitmap composite whose RGBA output is over the decode budget is refused up front. - #[test] - fn composite_rgba8_checks_the_output_budget_first() { - let mut file = crate::testgen::small(Version::Psb, crate::Compression::Zip); - file.header.color_mode = ColorMode::Bitmap; - file.header.depth = 1; - file.header.channels = 1; - file.header.width = 60_000; - file.header.height = 60_000; - assert!(matches!(file.composite_rgba8(), Err(PsdError::LimitExceeded("RGBA output exceeds MAX_DECODED_BYTES")))); - } - - #[test] - fn rgb_interleave_checks_planes_and_preserves_alpha() { - let color = [Cow::Borrowed(&[1, 2][..]), Cow::Borrowed(&[3, 4][..]), Cow::Borrowed(&[5, 6][..])]; - assert_eq!(interleave(ColorMode::Rgb, &color, Some(&[7, 8]), &[], 2).unwrap(), [1, 3, 5, 7, 2, 4, 6, 8]); - assert_eq!(interleave(ColorMode::Rgb, &color, None, &[], 2).unwrap(), [1, 3, 5, 255, 2, 4, 6, 255]); - assert!(interleave(ColorMode::Rgb, &color[..2], None, &[], 2).is_err()); - assert!(interleave(ColorMode::Rgb, &color, Some(&[7]), &[], 2).is_err()); - } -} diff --git a/crates/psd/src/resources.rs b/crates/psd/src/resources.rs deleted file mode 100644 index 1ac69ed25d..0000000000 --- a/crates/psd/src/resources.rs +++ /dev/null @@ -1,404 +0,0 @@ -//! Image resources section (`8BIM` resource blocks). - -use crate::descriptor::UnicodeString; -use crate::error::{PsdError, Result}; -use crate::io::{Reader, WriteExt, read_pascal, write_pascal}; - -/// Well-known resource ids. -pub mod ids { - /// Resolution info (`ResolutionInfo` structure). - pub const RESOLUTION_INFO: u16 = 1005; - /// Target layer index. - pub const LAYER_STATE: u16 = 1024; - /// Layer group ids (one u16 per layer). - pub const LAYER_GROUP_INFO: u16 = 1026; - /// Legacy (Photoshop 4) thumbnail, BGR. - pub const THUMBNAIL_PS4: u16 = 1033; - /// Thumbnail (JFIF). - pub const THUMBNAIL: u16 = 1036; - /// Global lighting angle. - pub const GLOBAL_ANGLE: u16 = 1037; - /// ICC profile. - pub const ICC_PROFILE: u16 = 1039; - /// Global altitude. - pub const GLOBAL_ALTITUDE: u16 = 1049; - /// Version info (has real merged data flag). - pub const VERSION_INFO: u16 = 1057; - /// EXIF data 1. - pub const EXIF: u16 = 1058; - /// XMP metadata. - pub const XMP: u16 = 1060; - /// Document timeline settings (versioned descriptor). - pub const TIMELINE_INFO: u16 = 1075; -} - -/// One image resource block. -#[derive(Debug, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ImageResource { - /// Signature, normally `8BIM` (also `MeSa`, `AgHg`, `PHUT`, `DCSR` seen in the wild). - pub signature: [u8; 4], - /// Resource id. - pub id: u16, - /// Pascal name bytes (usually empty). - pub name: Vec, - /// Resource data (without the even padding). - pub data: Vec, -} - -/// Fixed-point resolution info (resource 1005). -/// -/// `h_res_fixed` and `v_res_fixed` are always pixels per inch (16.16 fixed). -/// `h_res_unit` and `v_res_unit` only say how to display that number -/// (1 = pixels/inch, 2 = pixels/cm) and do not rescale the stored value. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ResolutionInfo { - /// Horizontal resolution, 16.16 fixed point, always pixels per inch. - pub h_res_fixed: u32, - /// Display unit for the horizontal resolution (1 = px/in, 2 = px/cm). - pub h_res_unit: u16, - /// Ruler unit for width (1 in, 2 cm, 3 pt, 4 pica, 5 column). - pub width_unit: u16, - /// Vertical resolution, 16.16 fixed point, always pixels per inch. - pub v_res_fixed: u32, - /// Display unit for the vertical resolution (1 = px/in, 2 = px/cm). - pub v_res_unit: u16, - /// Ruler unit for height (1 in, 2 cm, 3 pt, 4 pica, 5 column). - pub height_unit: u16, -} - -impl ResolutionInfo { - /// Resolution info for `dpi` pixels per inch in both directions. - pub fn from_dpi(dpi: f64) -> Self { - let f = (dpi * 65536.0).round().clamp(0.0, u32::MAX as f64) as u32; - ResolutionInfo { h_res_fixed: f, h_res_unit: 1, width_unit: 1, v_res_fixed: f, v_res_unit: 1, height_unit: 1 } - } - /// Horizontal resolution in pixels per inch. - pub fn h_res(&self) -> f64 { - f64::from(self.h_res_fixed) / 65536.0 - } - /// Vertical resolution in pixels per inch. - pub fn v_res(&self) -> f64 { - f64::from(self.v_res_fixed) / 65536.0 - } - /// Parses 16 bytes. - pub fn from_bytes(b: &[u8]) -> Result { - let mut r = Reader::new(b); - Ok(ResolutionInfo { - h_res_fixed: r.u32()?, - h_res_unit: r.u16()?, - width_unit: r.u16()?, - v_res_fixed: r.u32()?, - v_res_unit: r.u16()?, - height_unit: r.u16()?, - }) - } - /// Serializes to 16 bytes. - pub fn to_bytes(&self) -> Vec { - let mut v = Vec::with_capacity(16); - v.put_u32(self.h_res_fixed); - v.put_u16(self.h_res_unit); - v.put_u16(self.width_unit); - v.put_u32(self.v_res_fixed); - v.put_u16(self.v_res_unit); - v.put_u16(self.height_unit); - v - } -} - -/// Version info (resource 1057). -#[derive(Debug, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct VersionInfo { - /// Version (1). - pub version: u32, - /// `false` when the merged image is a placeholder. - pub has_real_merged_data: bool, - /// Writer application name. - pub writer: UnicodeString, - /// Reader application name. - pub reader: UnicodeString, - /// File version. - pub file_version: u32, -} - -impl VersionInfo { - /// Parses resource data. - pub fn from_bytes(b: &[u8]) -> Result { - let mut r = Reader::new(b); - Ok(VersionInfo { - version: r.u32()?, - has_real_merged_data: r.u8()? != 0, - writer: UnicodeString::read(&mut r)?, - reader: UnicodeString::read(&mut r)?, - file_version: r.u32()?, - }) - } - /// Serializes. - pub fn to_bytes(&self) -> Vec { - let mut v = Vec::new(); - v.put_u32(self.version); - v.put_u8(u8::from(self.has_real_merged_data)); - self.writer.write(&mut v); - self.reader.write(&mut v); - v.put_u32(self.file_version); - v - } -} - -/// Typed view of a known resource. -#[derive(Debug, Clone, PartialEq)] -#[non_exhaustive] -pub enum ResourceData<'a> { - /// 1005 - ResolutionInfo(ResolutionInfo), - /// 1024: index of the target layer. - LayerState(u16), - /// 1026: group id per layer. - LayerGroupInfo(Vec), - /// 1036 / 1033: raw thumbnail resource (28-byte header + JFIF/raw data). - Thumbnail(&'a [u8]), - /// 1037: global lighting angle in degrees. - GlobalAngle(i32), - /// 1039: ICC profile bytes. - IccProfile(&'a [u8]), - /// 1049: global altitude. - GlobalAltitude(i32), - /// 1057 - VersionInfo(VersionInfo), - /// 1058: EXIF bytes. - Exif(&'a [u8]), - /// 1060: XMP packet (UTF-8). - Xmp(&'a [u8]), - /// 1075: document timeline settings; tracks and rational times remain descriptor data. - TimelineInfo(crate::VersionedDescriptor), - /// A `mani` legacy animation resource in the plug-in resource id range (4000..=4999). - Animation(crate::animation::AnimationResource<'a>), -} - -impl ImageResource { - /// A new `8BIM` resource with an empty name. - pub fn new(id: u16, data: Vec) -> Self { - ImageResource { signature: *b"8BIM", id, name: Vec::new(), data } - } - - /// Typed parse of well-known resources. Returns `None` for unknown ids, - /// `Some(Err)` if the data is malformed. - pub fn parsed(&self) -> Option>> { - let d = &self.data[..]; - let be_i32 = |d: &[u8]| -> Result { Reader::new(d).i32() }; - Some(match self.id { - ids::RESOLUTION_INFO => ResolutionInfo::from_bytes(d).map(ResourceData::ResolutionInfo), - ids::LAYER_STATE => Reader::new(d).u16().map(ResourceData::LayerState), - ids::LAYER_GROUP_INFO => { - if !d.len().is_multiple_of(2) { - Err(PsdError::invalid("layer group info has odd length")) - } else { - Ok(ResourceData::LayerGroupInfo(d.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect())) - } - } - ids::THUMBNAIL | ids::THUMBNAIL_PS4 => Ok(ResourceData::Thumbnail(d)), - ids::GLOBAL_ANGLE => be_i32(d).map(ResourceData::GlobalAngle), - ids::ICC_PROFILE => Ok(ResourceData::IccProfile(d)), - ids::GLOBAL_ALTITUDE => be_i32(d).map(ResourceData::GlobalAltitude), - ids::VERSION_INFO => VersionInfo::from_bytes(d).map(ResourceData::VersionInfo), - ids::EXIF => Ok(ResourceData::Exif(d)), - ids::XMP => Ok(ResourceData::Xmp(d)), - ids::TIMELINE_INFO => crate::animation::parse_descriptor(d).map(ResourceData::TimelineInfo), - 4000..=4999 if d.starts_with(b"mani") => crate::animation::AnimationResource::from_bytes(d).map(ResourceData::Animation), - _ => return None, - }) - } - - /// XMP packet as a string (resource 1060). - pub fn xmp_str(&self) -> Option<&str> { - (self.id == ids::XMP).then(|| std::str::from_utf8(&self.data).ok()).flatten() - } - - pub(crate) fn read(r: &mut Reader<'_>) -> Result { - let signature = r.array::<4>()?; - if !matches!(&signature, b"8BIM" | b"MeSa" | b"AgHg" | b"PHUT" | b"DCSR") { - return Err(PsdError::InvalidSignature { expected: "8BIM resource", found: signature }); - } - let id = r.u16()?; - let name = read_pascal(r, 2)?; - let len = r.u32()?; - let data = r.bytes_u64(u64::from(len))?.to_vec(); - if len % 2 == 1 { - r.skip(1)?; - } - Ok(ImageResource { signature, id, name, data }) - } - - pub(crate) fn write(&self, out: &mut Vec) -> Result<()> { - out.put(&self.signature); - out.put_u16(self.id); - write_pascal(out, &self.name, 2); - out.put_len(self.data.len() as u64, false)?; - out.put(&self.data); - if self.data.len() % 2 == 1 { - out.put_u8(0); - } - Ok(()) - } -} - -pub(crate) fn read_section(r: &mut Reader<'_>) -> Result> { - let len = r.u32()?; - let mut s = r.sub(u64::from(len))?; - let mut v = Vec::new(); - while !s.is_empty() { - v.push(ImageResource::read(&mut s)?); - } - Ok(v) -} - -/// Serialized size of the resource section [`write_section`] writes, its length field included. -pub(crate) fn section_len(res: &[ImageResource]) -> u64 { - res.iter().fold(4u64, |n, r| { - let name = 1 + r.name.len().min(255); - let name = name + name % 2; - let data = r.data.len().saturating_add(r.data.len() % 2); - n.saturating_add((4 + 2 + name + 4) as u64).saturating_add(data as u64) - }) -} - -pub(crate) fn write_section(out: &mut Vec, res: &[ImageResource]) -> Result<()> { - let at = out.begin_len(false); - for r in res { - r.write(out)?; - } - out.end_len(at, false) -} - -/// Builds the data for a 1057 version info resource, with the writer and reader names Photoshop -/// 2026 writes ("Adobe Photoshop", "Adobe Photoshop 2026"), without a NUL terminator. -pub fn version_info_resource(has_real_merged_data: bool) -> ImageResource { - ImageResource::new( - ids::VERSION_INFO, - VersionInfo { - version: 1, - has_real_merged_data, - writer: UnicodeString::new("Adobe Photoshop"), - reader: UnicodeString::new("Adobe Photoshop 2026"), - file_version: 1, - } - .to_bytes(), - ) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn roundtrip(res: &[ImageResource]) -> Vec { - let mut out = Vec::new(); - write_section(&mut out, res).unwrap(); - let back = read_section(&mut Reader::new(&out)).unwrap(); - assert_eq!(back, res); - out - } - - #[test] - fn empty_section() { - assert_eq!(roundtrip(&[]), vec![0, 0, 0, 0]); - } - - #[test] - fn odd_data_is_padded() { - let out = roundtrip(&[ImageResource::new(1000, vec![1, 2, 3])]); - // len(4) + sig(4) + id(2) + name(2) + size(4) + data(3) + pad(1) - assert_eq!(out.len(), 4 + 4 + 2 + 2 + 4 + 4); - assert_eq!(*out.last().unwrap(), 0); - } - - #[test] - fn named_resources() { - let mut r = ImageResource::new(2000, vec![9; 4]); - r.name = b"path".to_vec(); - let mut r2 = ImageResource::new(2001, vec![]); - r2.name = b"abc".to_vec(); - r2.signature = *b"MeSa"; - roundtrip(&[r, r2]); - } - - #[test] - fn bad_signature() { - let mut out = Vec::new(); - write_section(&mut out, &[ImageResource::new(1, vec![])]).unwrap(); - out[4] = b'X'; - assert!(read_section(&mut Reader::new(&out)).is_err()); - } - - #[test] - fn truncation_errors() { - let mut out = Vec::new(); - write_section(&mut out, &[ImageResource::new(1005, ResolutionInfo::from_dpi(72.0).to_bytes())]).unwrap(); - for cut in 0..out.len() { - assert!(read_section(&mut Reader::new(&out[..cut])).is_err()); - } - } - - #[test] - fn typed_resolution() { - let ri = ResolutionInfo::from_dpi(300.0); - let r = ImageResource::new(ids::RESOLUTION_INFO, ri.to_bytes()); - match r.parsed() { - Some(Ok(ResourceData::ResolutionInfo(p))) => { - assert_eq!(p, ri); - assert!((p.h_res() - 300.0).abs() < 1e-9); - assert!((p.v_res() - 300.0).abs() < 1e-9); - } - other => panic!("{other:?}"), - } - } - - #[test] - fn typed_misc() { - let r = ImageResource::new(ids::GLOBAL_ANGLE, 120i32.to_be_bytes().to_vec()); - assert_eq!(r.parsed(), Some(Ok(ResourceData::GlobalAngle(120)))); - let r = ImageResource::new(ids::GLOBAL_ALTITUDE, 30i32.to_be_bytes().to_vec()); - assert_eq!(r.parsed(), Some(Ok(ResourceData::GlobalAltitude(30)))); - let r = ImageResource::new(ids::LAYER_STATE, vec![0, 2]); - assert_eq!(r.parsed(), Some(Ok(ResourceData::LayerState(2)))); - let r = ImageResource::new(ids::LAYER_GROUP_INFO, vec![0, 1, 0, 2]); - assert_eq!(r.parsed(), Some(Ok(ResourceData::LayerGroupInfo(vec![1, 2])))); - let r = ImageResource::new(ids::LAYER_GROUP_INFO, vec![0]); - assert!(matches!(r.parsed(), Some(Err(_)))); - let r = ImageResource::new(ids::ICC_PROFILE, vec![1]); - assert_eq!(r.parsed(), Some(Ok(ResourceData::IccProfile(&[1])))); - let r = ImageResource::new(ids::EXIF, vec![2]); - assert_eq!(r.parsed(), Some(Ok(ResourceData::Exif(&[2])))); - let r = ImageResource::new(ids::THUMBNAIL, vec![3]); - assert_eq!(r.parsed(), Some(Ok(ResourceData::Thumbnail(&[3])))); - let r = ImageResource::new(ids::XMP, b"".to_vec()); - assert_eq!(r.xmp_str(), Some("")); - assert_eq!(ImageResource::new(4242, vec![]).parsed(), None); - } - - #[test] - fn version_info_roundtrip() { - let r = version_info_resource(false); - match r.parsed() { - Some(Ok(ResourceData::VersionInfo(v))) => { - assert!(!v.has_real_merged_data); - assert_eq!(v.to_bytes(), r.data); - } - other => panic!("{other:?}"), - } - } - - /// Byte for byte what Photoshop 2026 writes (every Photoshop-authored oracle in the corpus): - /// u32 count + UTF-16BE, no NUL terminator. - #[test] - fn version_info_matches_photoshop_bytes() { - let mut want = vec![0, 0, 0, 1, 1]; - for s in ["Adobe Photoshop", "Adobe Photoshop 2026"] { - want.extend_from_slice(&(s.len() as u32).to_be_bytes()); - want.extend(s.encode_utf16().flat_map(u16::to_be_bytes)); - } - want.extend_from_slice(&[0, 0, 0, 1]); - assert_eq!(version_info_resource(true).data, want); - } -} diff --git a/crates/psd/src/rows.rs b/crates/psd/src/rows.rs deleted file mode 100644 index f5f95f74d4..0000000000 --- a/crates/psd/src/rows.rs +++ /dev/null @@ -1,234 +0,0 @@ -//! Decoding a channel a band of rows at a time: [`ChannelData::row_decoder`]. -//! -//! [`ChannelData::decode`] returns the whole plane, so turning a layer into tiles holds every -//! channel's plane plus an interleaved copy at once: for a 20000×15000 RGBA layer that is 2.4 GB -//! on top of the tiles. A [`RowDecoder`] hands out any band of rows instead. RLE and raw channels -//! are read band by band (a channel still in its [`Stored`](crate::Stored) source reads only the -//! band's bytes: RLE's per-row byte counts give each row's offset); ZIP streams cannot be entered -//! part way, so a ZIP channel is inflated once, when the decoder is made. - -use std::borrow::Cow; - -use crate::compression::{Compression, MAX_DECODED_BYTES, PlaneLayout, decode_planes, packbits}; -use crate::error::{PsdError, Result}; -use crate::header::Version; -use crate::layer::ChannelData; -use crate::source::Stored; - -/// Where a channel's encoded bytes are. -enum Bytes<'a> { - Memory(&'a [u8]), - Source(&'a Stored), -} - -impl Bytes<'_> { - fn len(&self) -> u64 { - match self { - Bytes::Memory(b) => b.len() as u64, - Bytes::Source(s) => s.len, - } - } - - fn get(&self, at: u64, len: u64) -> Result> { - match self { - Bytes::Memory(b) => { - let range = usize::try_from(at).ok().zip(usize::try_from(len).ok()).and_then(|(a, n)| b.get(a..a.checked_add(n)?)); - range - .map(Cow::Borrowed) - .ok_or(PsdError::UnexpectedEof { offset: usize::try_from(at).unwrap_or(usize::MAX), needed: usize::try_from(len).unwrap_or(usize::MAX) }) - } - Bytes::Source(s) => { - if at.checked_add(len).is_none_or(|end| end > s.len) { - return Err(PsdError::UnexpectedEof { - offset: usize::try_from(at).unwrap_or(usize::MAX), - needed: usize::try_from(len).unwrap_or(usize::MAX), - }); - } - s.read_part(at, len).map(Cow::Owned) - } - } - } -} - -enum Kind<'a> { - /// Rows at `row * row_bytes`. - Raw(Bytes<'a>), - /// `offsets[r]..offsets[r + 1]` are row `r`'s PackBits bytes (offsets from the start of the - /// data, after the count table). - Rle { bytes: Bytes<'a>, offsets: Vec }, - /// The whole decoded plane. - Decoded(Vec), - /// No data and no rows. - Empty, -} - -/// Decodes bands of rows of one channel: see the [module docs](self). -pub struct RowDecoder<'a> { - kind: Kind<'a>, - row_bytes: usize, - height: usize, -} - -impl ChannelData { - /// A decoder of this channel's rows, for a `width × height` plane. Fails where - /// [`Self::decode`] would on everything it can check without decoding the rows (sizes, the - /// RLE count table, the whole of a ZIP stream); a damaged row fails when its band is decoded. - pub fn row_decoder(&self, width: usize, height: usize, depth: u16, version: Version) -> Result> { - let layout = PlaneLayout { planes: 1, width, height, depth, version }; - let total = layout.decoded_len()?; - let row_bytes = layout.row_bytes(); - let bytes = match &self.stored { - Some(s) => Bytes::Source(s), - None => Bytes::Memory(&self.data), - }; - let kind = match self.compression { - None if total == 0 => Kind::Empty, - None => return Err(PsdError::invalid("channel has no data")), - Some(Compression::Raw) => { - if bytes.len() < total as u64 { - return Err(PsdError::UnexpectedEof { offset: usize::try_from(bytes.len()).unwrap_or(usize::MAX), needed: total - bytes.len() as usize }); - } - Kind::Raw(bytes) - } - Some(Compression::Rle) => { - let size: u64 = if version.is_psb() { 4 } else { 2 }; - let table_len = (height as u64).saturating_mul(size); - if table_len > bytes.len() { - return Err(PsdError::UnexpectedEof { offset: 0, needed: usize::try_from(table_len - bytes.len()).unwrap_or(usize::MAX) }); - } - let table = bytes.get(0, table_len)?; - let mut offsets = Vec::new(); - offsets.try_reserve_exact(height + 1).map_err(|_| PsdError::OutOfMemory("not enough memory for the RLE row table"))?; - let mut at = table_len; - offsets.push(at); - for c in table.chunks_exact(size as usize) { - let n = match *c { - [a, b] => u64::from(u16::from_be_bytes([a, b])), - [a, b, c, d] => u64::from(u32::from_be_bytes([a, b, c, d])), - _ => 0, - }; - at = at.saturating_add(n); - offsets.push(at); - } - let data_len = bytes.len() - table_len; - // As `decode_planes` checks: PackBits expands at most 64x. - if (total as u64) > data_len.saturating_mul(64) { - return Err(PsdError::Decompress("RLE data too short for declared size".into())); - } - if at > bytes.len() { - return Err(PsdError::UnexpectedEof { - offset: usize::try_from(bytes.len()).unwrap_or(usize::MAX), - needed: usize::try_from(at - bytes.len()).unwrap_or(usize::MAX), - }); - } - Kind::Rle { bytes, offsets } - } - Some(c) => Kind::Decoded(decode_planes(c, &self.encoded()?, &layout)?), - }; - Ok(RowDecoder { kind, row_bytes, height }) - } -} - -impl RowDecoder<'_> { - /// Bytes per decoded row. - pub fn row_bytes(&self) -> usize { - self.row_bytes - } - - /// Number of rows. - pub fn height(&self) -> usize { - self.height - } - - /// Rows `r0..r1` as planar big-endian samples (`(r1 - r0) × row_bytes` bytes). - pub fn rows(&self, r0: usize, r1: usize) -> Result> { - if r0 > r1 || r1 > self.height { - return Err(PsdError::invalid(format!("rows {r0}..{r1} outside 0..{}", self.height))); - } - let n = (r1 - r0).checked_mul(self.row_bytes).ok_or(PsdError::LimitExceeded("band size overflow"))?; - if n as u64 > MAX_DECODED_BYTES { - return Err(PsdError::LimitExceeded("decoded channel data exceeds MAX_DECODED_BYTES")); - } - let mut out = Vec::new(); - out.try_reserve_exact(n).map_err(|_| PsdError::OutOfMemory("not enough memory for the decoded channel data"))?; - match &self.kind { - Kind::Empty => {} - Kind::Raw(bytes) => out.extend_from_slice(&bytes.get((r0 * self.row_bytes) as u64, n as u64)?), - Kind::Decoded(plane) => { - out.extend_from_slice(plane.get(r0 * self.row_bytes..r1 * self.row_bytes).ok_or_else(|| PsdError::invalid("decoded plane too short"))?) - } - Kind::Rle { bytes, offsets } => { - let (Some(&start), Some(&end)) = (offsets.get(r0), offsets.get(r1)) else { - return Err(PsdError::invalid("RLE row table too short")); - }; - let band = bytes.get(start, end - start)?; - for r in r0..r1 { - let (Some(&a), Some(&b)) = (offsets.get(r), offsets.get(r + 1)) else { - return Err(PsdError::invalid("RLE row table too short")); - }; - let row = band.get((a - start) as usize..(b - start) as usize).ok_or_else(|| PsdError::invalid("RLE row outside its band"))?; - packbits::decode_into(row, self.row_bytes, &mut out)?; - } - } - } - Ok(out) - } -} - -#[cfg(test)] -mod tests { - use crate::source::Source; - use crate::{PsdFile, testgen}; - - /// Every channel of every generated file, decoded in uneven bands from memory and from a - /// source, is its whole-plane decode. - #[test] - fn bands_join_up_to_the_whole_plane() { - let mut checked = 0; - for case in testgen::all_cases() { - let bytes = case.file.to_bytes().unwrap(); - let eager = PsdFile::from_bytes(&bytes).unwrap(); - let lazy = PsdFile::from_source(Source::new(bytes)).unwrap(); - let (d, v) = (eager.header.depth, eager.header.version); - for file in [&eager, &lazy] { - for rec in file.layers() { - for ch in &rec.channels { - let (w, h) = rec.channel_rect(ch.id).size().unwrap(); - let whole = ch.decode(w, h, d, v); - let dec = ch.row_decoder(w, h, d, v); - let (Ok(whole), Ok(dec)) = (whole, dec) else { continue }; - let mut joined = Vec::new(); - let mut r = 0; - for step in [1, 3, 2, 7].iter().cycle() { - if r >= h { - break; - } - let r1 = (r + step).min(h); - joined.extend(dec.rows(r, r1).unwrap()); - r = r1; - } - assert_eq!(joined, whole, "{}", case.name); - assert!(dec.rows(0, h + 1).is_err()); - checked += 1; - } - } - } - } - assert!(checked > 100, "{checked}"); - } - - #[test] - fn a_damaged_rle_row_fails_its_band() { - use crate::Compression; - use crate::layer::ChannelData; - // Two rows of 4 bytes: a valid row, then one that ends early. - let mut data = vec![0, 2, 0, 2]; - data.extend([0xFD, 7]); // header -3: 1 - (-3) = 4 copies of 7 - data.extend([0x01, 9]); // a literal of 2 bytes, only 1 present - let ch = ChannelData::new(0, Some(Compression::Rle), data); - let dec = ch.row_decoder(4, 2, 8, crate::Version::Psd).unwrap(); - assert_eq!(dec.rows(0, 1).unwrap(), vec![7; 4]); - assert!(dec.rows(1, 2).is_err()); - assert!(ch.decode(4, 2, 8, crate::Version::Psd).is_err()); - } -} diff --git a/crates/psd/src/shc.rs b/crates/psd/src/shc.rs deleted file mode 100644 index 135fd33e62..0000000000 --- a/crates/psd/src/shc.rs +++ /dev/null @@ -1,251 +0,0 @@ -//! Photoshop contour preset files (`.shc`), the Layer Style dialog's Contour Editor Load/Save. -//! -//! Layout from Adobe's public "Photoshop File Formats Specification" (Additional File Formats › -//! Contours): a 4-byte type `8BFS`, a `u16` version (1) and a `u32` count of contours. Each -//! contour is a `u32` version (1 or 2), a Unicode name, a `u16` point count and the points as two -//! `u16`s each (vertical first, then horizontal). Version 2 then has one boolean byte per point -//! ("whether the point is continuous"); both versions end with a 4-byte minimum and maximum -//! input range. All values are big-endian. -//! -//! The spec leaves two details open, handled defensively: -//! - The name is read like the spec's other Unicode strings (a `u32` UTF-16 code-unit count that -//! includes a trailing null, as in `.aco`); a name whose count leaves out the null and is -//! followed by one is read too. Names are written with the null counted. -//! - Coordinates are read as 0..=255 levels, the scale of the layer-style contour descriptors -//! (`ShpC` points); the input range is written as 0..=255. - -use crate::error::{PsdError, Result}; -use crate::io::{Reader, WriteExt}; - -/// Most contours read from one file. -pub const MAX_CONTOURS: usize = 4096; -/// Most points in one contour (the counts are 16-bit; Photoshop allows far fewer). -pub const MAX_POINTS: usize = 256; -/// Longest name read or written, in UTF-16 code units. -pub const MAX_NAME_UNITS: usize = 1024; - -/// One contour point: input (horizontal) and output (vertical), `0..=255`, and whether the curve -/// passes smoothly through it (`false` = a corner). -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct ShcPoint { - /// Input level, `0..=255`. - pub input: f32, - /// Output level, `0..=255`. - pub output: f32, - /// Smooth (`true`) or corner (`false`). - pub continuous: bool, -} - -/// One named contour. -#[derive(Debug, Clone, PartialEq)] -pub struct ShcContour { - /// Preset name. - pub name: String, - /// Points, in file order. - pub points: Vec, -} - -fn read_name(r: &mut Reader<'_>) -> Result { - let n = u64::from(r.u32()?); - r.check_count(n, 2)?; - let n = usize::try_from(n).map_err(|_| PsdError::LimitExceeded("contour name length"))?; - let mut units = Vec::with_capacity(n.min(MAX_NAME_UNITS)); - // The last unit read, not the last one kept: past the cap the counted null is read but not kept. - let mut last = None; - for _ in 0..n { - let u = r.u16()?; - last = Some(u); - if units.len() < MAX_NAME_UNITS { - units.push(u); - } - } - // A count that leaves out the terminator: the null follows. - if last != Some(0) && r.peek_rest().get(..2) == Some(&[0, 0]) { - r.u16()?; - } - while units.last() == Some(&0) { - units.pop(); - } - Ok(String::from_utf16_lossy(&units)) -} - -/// Parse an `.shc` file. Bad signatures, unknown versions, truncation and impossible counts are -/// errors; never panics. -pub fn parse(data: &[u8]) -> Result> { - let mut r = Reader::new(data); - let sig = r.array::<4>()?; - if &sig != b"8BFS" { - return Err(PsdError::InvalidSignature { expected: "8BFS", found: sig }); - } - let version = r.u16()?; - if version != 1 { - return Err(PsdError::UnsupportedVersion(version)); - } - let count = u64::from(r.u32()?); - // A contour takes at least 4 (version) + 4 (name) + 2 (points) + 8 (range) bytes. - r.check_count(count, 18)?; - let count = usize::try_from(count).map_err(|_| PsdError::LimitExceeded("contour count"))?; - if count > MAX_CONTOURS { - return Err(PsdError::LimitExceeded("too many contours in an .shc file")); - } - let mut out = Vec::with_capacity(count); - for _ in 0..count { - let v = r.u32()?; - if v != 1 && v != 2 { - return Err(PsdError::invalid(format!("unknown contour version {v}"))); - } - let name = read_name(&mut r)?; - let n = usize::from(r.u16()?); - r.check_count(n as u64, if v == 2 { 5 } else { 4 })?; - if n > MAX_POINTS { - return Err(PsdError::LimitExceeded("too many points in a contour")); - } - let mut points = Vec::with_capacity(n); - for _ in 0..n { - let output = f32::from(r.u16()?).min(255.0); - let input = f32::from(r.u16()?).min(255.0); - points.push(ShcPoint { input, output, continuous: true }); - } - if v == 2 { - for p in &mut points { - p.continuous = r.u8()? != 0; - } - } - // Minimum and maximum input range: not needed to draw the curve. - r.skip(8)?; - out.push(ShcContour { name, points }); - } - Ok(out) -} - -/// Write an `.shc` file (every contour as version 2, with its corner flags). Fails when a contour -/// has more than [`MAX_POINTS`] points or there are more than [`MAX_CONTOURS`]. -pub fn write(contours: &[ShcContour]) -> Result> { - if contours.len() > MAX_CONTOURS { - return Err(PsdError::LimitExceeded("too many contours for an .shc file")); - } - let mut out = Vec::with_capacity(10 + contours.len() * 64); - out.put(b"8BFS"); - out.put_u16(1); - out.put_u32(contours.len() as u32); - for c in contours { - let n = u16::try_from(c.points.len()).ok().filter(|n| usize::from(*n) <= MAX_POINTS).ok_or(PsdError::LimitExceeded("too many points in a contour"))?; - out.put_u32(2); - // Capped on a character boundary, so a surrogate pair is never split. - let units = crate::io::utf16_units(&c.name, MAX_NAME_UNITS); - out.put_u32(units.len() as u32 + 1); - for u in units { - out.put_u16(u); - } - out.put_u16(0); - out.put_u16(n); - let level = |v: f32| if v.is_finite() { v.round().clamp(0.0, 255.0) as u16 } else { 0 }; - for p in &c.points { - out.put_u16(level(p.output)); - out.put_u16(level(p.input)); - } - for p in &c.points { - out.put_u8(u8::from(p.continuous)); - } - out.put_u32(0); - out.put_u32(255); - } - Ok(out) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn shc_round_trips_and_rejects_hostile_input() { - let cone = ShcContour { - name: "Cone".into(), - points: vec![ - ShcPoint { input: 0.0, output: 0.0, continuous: true }, - ShcPoint { input: 128.0, output: 255.0, continuous: false }, - ShcPoint { input: 255.0, output: 0.0, continuous: true }, - ], - }; - let bytes = write(std::slice::from_ref(&cone)).unwrap(); - assert_eq!(&bytes[..4], b"8BFS"); - assert_eq!(parse(&bytes).unwrap(), vec![cone.clone()]); - - // Version 1 without corner flags, with a name count that leaves out the null. - let mut v1 = b"8BFS".to_vec(); - v1.put_u16(1); - v1.put_u32(1); - v1.put_u32(1); - v1.put_u32(2); - v1.put_u16(u16::from(b'O')); - v1.put_u16(u16::from(b'K')); - v1.put_u16(0); - v1.put_u16(2); - for v in [0u16, 0, 255, 255] { - v1.put_u16(v); - } - v1.put_u32(0); - v1.put_u32(255); - let c = parse(&v1).unwrap(); - assert_eq!(c[0].name, "OK"); - assert!(c[0].points.iter().all(|p| p.continuous) && c[0].points[1].input == 255.0); - - // Truncations, a wrong signature and absurd counts are errors, never panics. - for cut in 0..bytes.len() { - assert!(parse(&bytes[..cut]).is_err(), "cut at {cut}"); - } - assert!(parse(b"8BFX\0\x01\0\0\0\0").is_err()); - assert!(parse(b"8BFS\0\x01\xff\xff\xff\xff").is_err()); - let many = ShcContour { name: String::new(), points: vec![ShcPoint { input: 0.0, output: 0.0, continuous: true }; MAX_POINTS + 1] }; - assert!(write(&[many]).is_err()); - } - - fn pts(n: usize) -> Vec { - (0..n).map(|i| ShcPoint { input: (i * 10) as f32, output: (i * 20) as f32, continuous: i % 2 == 0 }).collect() - } - - #[test] - fn shc_name_cap_never_splits_a_surrogate_pair() { - let name = format!("{}\u{1F600}", "a".repeat(MAX_NAME_UNITS - 1)); - let c = ShcContour { name, points: pts(2) }; - let back = parse(&write(&[c]).unwrap()).unwrap(); - assert_eq!(back[0].name, "a".repeat(MAX_NAME_UNITS - 1)); - } - - #[test] - fn shc_names_at_and_over_the_cap_keep_the_stream_in_sync() { - for len in [MAX_NAME_UNITS, MAX_NAME_UNITS + 1, MAX_NAME_UNITS * 3] { - for first_points in [0, 3] { - let long = ShcContour { name: "b".repeat(len), points: pts(first_points) }; - let next = ShcContour { name: "Next".into(), points: pts(4) }; - let back = parse(&write(&[long, next.clone()]).unwrap()).unwrap_or_else(|e| panic!("len {len}, points {first_points}: {e}")); - assert_eq!(back.len(), 2); - assert_eq!(back[0].name, "b".repeat(len.min(MAX_NAME_UNITS))); - assert_eq!(back[0].points.len(), first_points); - assert_eq!(back[1], next, "len {len}, points {first_points}"); - } - } - } - - #[test] - fn shc_name_count_without_null_at_the_cap_still_reads() { - // A hostile/foreign file: 1024 units counted, no null counted, null follows. - let mut v = b"8BFS".to_vec(); - v.put_u16(1); - v.put_u32(1); - v.put_u32(1); - v.put_u32(MAX_NAME_UNITS as u32); - for _ in 0..MAX_NAME_UNITS { - v.put_u16(u16::from(b'c')); - } - v.put_u16(0); - v.put_u16(1); - v.put_u16(7); - v.put_u16(9); - v.put_u32(0); - v.put_u32(255); - let c = parse(&v).unwrap(); - assert_eq!(c[0].name, "c".repeat(MAX_NAME_UNITS)); - assert_eq!((c[0].points[0].input, c[0].points[0].output), (9.0, 7.0)); - } -} diff --git a/crates/psd/src/slices.rs b/crates/psd/src/slices.rs deleted file mode 100644 index 5d9cd50b39..0000000000 --- a/crates/psd/src/slices.rs +++ /dev/null @@ -1,531 +0,0 @@ -//! Slices image resource (id 1050), from the Adobe Photoshop File Format Specification. -//! -//! Version 6 is a fixed binary layout (bounding rect, group name, then per slice: ids, origin, -//! optional layer id, name, type, rect, URL / target / message / alt strings, cell text and -//! alignment, background colour), optionally followed by a versioned descriptor carrying extra -//! per-slice data (layer-slice outsets). Versions 7 and 8 store everything as one versioned -//! descriptor (`baseName`, `bounds`, `slices` list). -//! -//! [`SlicesResource::to_bytes`] writes version 6, the documented binary layout every Photoshop -//! version reads. Unknown fields are not kept here; callers that need a byte-exact round trip -//! keep the raw resource while the slices are unchanged. - -use std::collections::HashMap; - -use crate::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; -use crate::error::{PsdError, Result}; -use crate::io::{Reader, WriteExt}; - -/// Resource id of the slices resource. -pub const SLICES: u16 = 1050; - -/// One slice record. -#[derive(Debug, Clone, PartialEq, Eq, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct SliceRecord { - /// Slice id. - pub id: u32, - /// Group id. - pub group_id: u32, - /// Origin: 0 auto-generated, 1 layer-based, 2 user-drawn. - pub origin: u32, - /// Layer id of a layer-based slice (the layer record's `lyid`). - pub layer_id: Option, - /// Slice name. - pub name: String, - /// Type: 0 no image, 1 image, 2 table. - pub kind: u32, - /// Left, top, right, bottom in document pixels. - pub rect: [i32; 4], - /// URL. - pub url: String, - /// Target frame. - pub target: String, - /// Status-bar message. - pub message: String, - /// Alt tag. - pub alt: String, - /// Cell text is HTML. - pub cell_text_is_html: bool, - /// Cell text. - pub cell_text: String, - /// Horizontal alignment. - pub horizontal_align: u32, - /// Vertical alignment. - pub vertical_align: u32, - /// Background colour as alpha, red, green, blue. - pub color: [u8; 4], - /// Layer-based slice outsets: top, left, bottom, right. - pub outsets: [i32; 4], -} - -/// The whole slices resource. -#[derive(Debug, Clone, PartialEq, Eq, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct SlicesResource { - /// Version read (6, 7 or 8); writing always produces 6. - pub version: u32, - /// Bounding rectangle of all slices: top, left, bottom, right. - pub bounds: [i32; 4], - /// Name of the slice group (the base name). - pub group_name: String, - /// Slices, including auto-generated ones as Photoshop saves them. - pub slices: Vec, -} - -fn ustr(r: &mut Reader<'_>) -> Result { - Ok(UnicodeString::read(r)?.to_string_lossy()) -} - -fn put_ustr(out: &mut Vec, s: &str) { - UnicodeString::new(s).write(out); -} - -// ---------- descriptor helpers (versions 7/8 and the v6 tail) ---------- - -/// A number as `i64`; float casts saturate (NaN reads as 0). -fn d_int(d: &Descriptor, key: &str) -> Option { - match d.get(key)? { - Value::Integer(v) => Some(i64::from(*v)), - Value::LargeInteger(v) => Some(*v), - Value::Double(v) => Some(*v as i64), - Value::UnitFloat { value, .. } => Some(*value as i64), - _ => None, - } -} - -/// A coordinate, clamped to the `i32` range instead of wrapping. -fn d_i32(d: &Descriptor, key: &str) -> Option { - d_int(d, key).map(|v| v.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32) -} - -/// An id. A 32-bit `long` holds the id's bits (ids past `i32::MAX` are written negative); any -/// other number outside the `u32` range is no id at all rather than a wrapped one. -fn d_u32(d: &Descriptor, key: &str) -> Option { - match d.get(key)? { - Value::Integer(v) => Some(*v as u32), - _ => u32::try_from(d_int(d, key)?).ok(), - } -} - -fn d_text(d: &Descriptor, key: &str) -> String { - match d.get(key) { - Some(Value::Text(t)) => t.to_string_lossy(), - _ => String::new(), - } -} - -fn d_enum(d: &Descriptor, key: &str) -> Option { - match d.get(key)? { - Value::Enumerated { value, .. } => Some(String::from_utf8_lossy(value.as_bytes()).into_owned()), - _ => None, - } -} - -fn d_bool(d: &Descriptor, key: &str) -> bool { - matches!(d.get(key), Some(Value::Boolean(true))) -} - -fn d_bounds(d: &Descriptor, key: &str) -> Option<[i32; 4]> { - let Value::Descriptor(b) = d.get(key)? else { return None }; - let g = |k: &str| d_i32(b, k).unwrap_or(0); - // top, left, bottom, right - Some([g("Top "), g("Left"), g("Btom"), g("Rght")]) -} - -fn origin_from(s: &str) -> u32 { - match s { - "autoGenerated" => 0, - "layerGenerated" | "layer" => 1, - _ => 2, - } -} - -fn kind_from(s: &str) -> u32 { - match s { - "noImage" => 0, - "Tbl " | "table" => 2, - _ => 1, - } -} - -fn slice_from_descriptor(d: &Descriptor) -> SliceRecord { - let b = d_bounds(d, "bounds").unwrap_or_default(); - let color = match (d_enum(d, "bgColorType").as_deref(), d.get("bgColor")) { - (Some("Clr "), Some(Value::Descriptor(c))) => { - let g = |k: &str| d_int(c, k).unwrap_or(0).clamp(0, 255) as u8; - let a = if c.get("alpha").is_some() { g("alpha") } else { 255 }; - [a, g("Rd "), g("Grn "), g("Bl ")] - } - _ => [0; 4], - }; - SliceRecord { - id: d_u32(d, "sliceID").unwrap_or(0), - group_id: d_u32(d, "groupID").unwrap_or(0), - origin: d_enum(d, "origin").map_or(2, |s| origin_from(&s)), - layer_id: d_u32(d, "layerID"), - name: d_text(d, "Nm "), - kind: d_enum(d, "Type").map_or(1, |s| kind_from(&s)), - // Descriptor bounds are top/left/bottom/right; records use left/top/right/bottom. - rect: [b[1], b[0], b[3], b[2]], - url: d_text(d, "url"), - target: d_text(d, "null"), - message: d_text(d, "Msge"), - alt: d_text(d, "altTag"), - cell_text_is_html: d_bool(d, "cellTextIsHTML"), - cell_text: d_text(d, "cellText"), - horizontal_align: 0, - vertical_align: 0, - color, - outsets: [ - d_i32(d, "topOutset").unwrap_or(0), - d_i32(d, "leftOutset").unwrap_or(0), - d_i32(d, "bottomOutset").unwrap_or(0), - d_i32(d, "rightOutset").unwrap_or(0), - ], - } -} - -fn bounds_descriptor(tlbr: [i32; 4]) -> Value { - Value::Descriptor( - Descriptor::new("Rct1") - .with("Top ", Value::Integer(tlbr[0])) - .with("Left", Value::Integer(tlbr[1])) - .with("Btom", Value::Integer(tlbr[2])) - .with("Rght", Value::Integer(tlbr[3])), - ) -} - -fn enumerated(ty: &str, v: &str) -> Value { - Value::Enumerated { type_id: Id::new(ty), value: Id::new(v) } -} - -impl SlicesResource { - /// Parses resource data (versions 6, 7 and 8). - pub fn from_bytes(data: &[u8]) -> Result { - let mut r = Reader::new(data); - let version = r.u32()?; - match version { - 6 => Self::read_v6(&mut r), - 7 | 8 => { - let vd = VersionedDescriptor::read(&mut r)?; - let d = &vd.descriptor; - let slices = match d.get("slices") { - Some(Value::List(items)) => items - .iter() - .filter_map(|v| match v { - Value::Descriptor(s) => Some(slice_from_descriptor(s)), - _ => None, - }) - .collect(), - _ => Vec::new(), - }; - Ok(SlicesResource { version, bounds: d_bounds(d, "bounds").unwrap_or_default(), group_name: d_text(d, "baseName"), slices }) - } - v => Err(PsdError::invalid(format!("unsupported slices resource version {v}"))), - } - } - - fn read_v6(r: &mut Reader<'_>) -> Result { - let bounds = [r.i32()?, r.i32()?, r.i32()?, r.i32()?]; - let group_name = ustr(r)?; - let n = r.u32()? as usize; - if n > r.remaining() / 16 { - return Err(PsdError::invalid("slice count exceeds the resource size")); - } - let mut slices = Vec::with_capacity(n); - for _ in 0..n { - let id = r.u32()?; - let group_id = r.u32()?; - let origin = r.u32()?; - let layer_id = if origin == 1 { Some(r.u32()?) } else { None }; - let name = ustr(r)?; - let kind = r.u32()?; - let rect = [r.i32()?, r.i32()?, r.i32()?, r.i32()?]; - let url = ustr(r)?; - let target = ustr(r)?; - let message = ustr(r)?; - let alt = ustr(r)?; - let cell_text_is_html = r.u8()? != 0; - let cell_text = ustr(r)?; - let horizontal_align = r.u32()?; - let vertical_align = r.u32()?; - let color = [r.u8()?, r.u8()?, r.u8()?, r.u8()?]; - slices.push(SliceRecord { - id, - group_id, - origin, - layer_id, - name, - kind, - rect, - url, - target, - message, - alt, - cell_text_is_html, - cell_text, - horizontal_align, - vertical_align, - color, - outsets: [0; 4], - }); - } - // Optional trailing descriptor (Photoshop 7+): per-slice extras such as outsets. - if r.remaining() >= 4 - && let Ok(vd) = VersionedDescriptor::read(r) - && let Some(Value::List(items)) = vd.descriptor.get("slices") - { - // Index each slice ID to its first occurrence once, so matching trailing - // descriptors against slices is linear rather than quadratic. Both the slice - // count and the descriptor-ID list are file-controlled, so a plain - // `find()` per descriptor is O(n*m) and lets a crafted resource burn CPU. - // `or_insert` preserves the original first-match behavior for duplicate IDs. - let mut id_to_index: HashMap = HashMap::with_capacity(slices.len()); - for (i, s) in slices.iter().enumerate() { - id_to_index.entry(s.id).or_insert(i); - } - for v in items { - let Value::Descriptor(d) = v else { continue }; - // An entry without a usable id belongs to no slice (not to slice 0). - let Some(id) = d_u32(d, "sliceID") else { continue }; - let extra = slice_from_descriptor(d); - if let Some(&i) = id_to_index.get(&id) { - slices[i].outsets = extra.outsets; - } - } - } - Ok(SlicesResource { version: 6, bounds, group_name, slices }) - } - - /// Serializes as version 6. A trailing descriptor with the outsets is added when any slice - /// has them, the way Photoshop extends the version 6 layout. - pub fn to_bytes(&self) -> Vec { - let mut out = Vec::new(); - out.put_u32(6); - for v in self.bounds { - out.put_i32(v); - } - put_ustr(&mut out, &self.group_name); - out.put_u32(self.slices.len() as u32); - for s in &self.slices { - out.put_u32(s.id); - out.put_u32(s.group_id); - out.put_u32(s.origin); - if s.origin == 1 { - out.put_u32(s.layer_id.unwrap_or(0)); - } - put_ustr(&mut out, &s.name); - out.put_u32(s.kind); - for v in s.rect { - out.put_i32(v); - } - put_ustr(&mut out, &s.url); - put_ustr(&mut out, &s.target); - put_ustr(&mut out, &s.message); - put_ustr(&mut out, &s.alt); - out.put_u8(u8::from(s.cell_text_is_html)); - put_ustr(&mut out, &s.cell_text); - out.put_u32(s.horizontal_align); - out.put_u32(s.vertical_align); - out.put(&s.color); - } - if self.slices.iter().any(|s| s.outsets != [0; 4]) { - let list = self - .slices - .iter() - .map(|s| { - Value::Descriptor( - Descriptor::new("slice") - .with("sliceID", Value::Integer(s.id as i32)) - .with("topOutset", Value::Integer(s.outsets[0])) - .with("leftOutset", Value::Integer(s.outsets[1])) - .with("bottomOutset", Value::Integer(s.outsets[2])) - .with("rightOutset", Value::Integer(s.outsets[3])), - ) - }) - .collect(); - VersionedDescriptor::new(Descriptor::new("null").with("slices", Value::List(list))).write(&mut out); - } - out - } - - /// Serializes in the version 7 descriptor form (what newer Photoshop versions write). - pub fn to_descriptor_bytes(&self) -> Vec { - let list = self - .slices - .iter() - .map(|s| { - let origin = match s.origin { - 0 => "autoGenerated", - 1 => "layerGenerated", - _ => "userGenerated", - }; - let kind = match s.kind { - 0 => "noImage", - 2 => "Tbl ", - _ => "Img ", - }; - let mut d = Descriptor::new("slice") - .with("sliceID", Value::Integer(s.id as i32)) - .with("groupID", Value::Integer(s.group_id as i32)) - .with("origin", enumerated("ESliceOrigin", origin)); - if let Some(l) = s.layer_id.filter(|_| s.origin == 1) { - d = d.with("layerID", Value::Integer(l as i32)); - } - d.with("Nm ", Value::Text(UnicodeString::new(&s.name))) - .with("Type", enumerated("ESliceType", kind)) - .with("bounds", bounds_descriptor([s.rect[1], s.rect[0], s.rect[3], s.rect[2]])) - .with("url", Value::Text(UnicodeString::new(&s.url))) - .with("null", Value::Text(UnicodeString::new(&s.target))) - .with("Msge", Value::Text(UnicodeString::new(&s.message))) - .with("altTag", Value::Text(UnicodeString::new(&s.alt))) - .with("cellTextIsHTML", Value::Boolean(s.cell_text_is_html)) - .with("cellText", Value::Text(UnicodeString::new(&s.cell_text))) - .with("horzAlign", enumerated("ESliceHorzAlign", "default")) - .with("vertAlign", enumerated("ESliceVertAlign", "default")) - .with("bgColorType", enumerated("ESliceBGColorType", "None")) - .with("topOutset", Value::Integer(s.outsets[0])) - .with("leftOutset", Value::Integer(s.outsets[1])) - .with("bottomOutset", Value::Integer(s.outsets[2])) - .with("rightOutset", Value::Integer(s.outsets[3])) - }) - .map(Value::Descriptor) - .collect(); - let d = Descriptor::new("null") - .with("bounds", bounds_descriptor(self.bounds)) - .with("slices", Value::List(list)) - .with("baseName", Value::Text(UnicodeString::new(&self.group_name))); - let mut out = Vec::new(); - out.put_u32(7); - VersionedDescriptor::new(d).write(&mut out); - out - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn sample() -> SlicesResource { - SlicesResource { - version: 6, - bounds: [0, 0, 80, 100], - group_name: "site".into(), - slices: vec![ - SliceRecord { id: 0, origin: 0, kind: 1, rect: [0, 0, 100, 10], ..Default::default() }, - SliceRecord { - id: 1, - group_id: 0, - origin: 2, - name: "logo".into(), - kind: 1, - rect: [20, 10, 60, 30], - url: "https://example.org/".into(), - target: "_blank".into(), - message: "hi".into(), - alt: "Logo".into(), - cell_text_is_html: true, - cell_text: "x".into(), - horizontal_align: 1, - vertical_align: 2, - color: [255, 10, 20, 30], - ..Default::default() - }, - SliceRecord { id: 2, origin: 1, layer_id: Some(7), kind: 0, rect: [5, 40, 25, 70], outsets: [1, 2, 3, 4], ..Default::default() }, - ], - } - } - - #[test] - fn v6_roundtrips() { - let s = sample(); - let bytes = s.to_bytes(); - let back = SlicesResource::from_bytes(&bytes).unwrap(); - assert_eq!(back, s); - assert_eq!(back.to_bytes(), bytes, "byte-stable"); - } - - #[test] - fn v7_descriptor_parses() { - let s = sample(); - let back = SlicesResource::from_bytes(&s.to_descriptor_bytes()).unwrap(); - assert_eq!(back.version, 7); - assert_eq!(back.group_name, "site"); - assert_eq!(back.bounds, s.bounds); - assert_eq!(back.slices.len(), 3); - assert_eq!(back.slices[1].rect, [20, 10, 60, 30]); - assert_eq!(back.slices[1].alt, "Logo"); - assert_eq!(back.slices[1].target, "_blank"); - assert_eq!(back.slices[2].origin, 1); - assert_eq!(back.slices[2].layer_id, Some(7)); - assert_eq!(back.slices[2].kind, 0); - assert_eq!(back.slices[2].outsets, [1, 2, 3, 4]); - } - - #[test] - fn out_of_range_descriptor_numbers_do_not_wrap() { - // sliceID 2^32+1 used to read as slice 1 and take that slice's outsets. - let wide = |key: &str| Descriptor::new("slice").with("sliceID", Value::LargeInteger((1 << 32) + 1)).with(key, Value::Integer(9)); - let mut plain = sample(); - for s in &mut plain.slices { - s.outsets = [0; 4]; - } - let mut bytes = plain.to_bytes(); - VersionedDescriptor::new(Descriptor::new("null").with("slices", Value::List(vec![Value::Descriptor(wide("topOutset"))]))).write(&mut bytes); - let back = SlicesResource::from_bytes(&bytes).unwrap(); - assert!(back.slices.iter().all(|s| s.outsets == [0; 4]), "{:?}", back.slices); - - // Descriptor form: ids out of the u32 range fall back to 0, coordinates clamp. - let d = wide("leftOutset") - .with("layerID", Value::LargeInteger(-1)) - .with("bottomOutset", Value::LargeInteger(1 << 40)) - .with("rightOutset", Value::Double(-1e12)) - .with("bounds", Value::Descriptor(Descriptor::new("Rct1").with("Top ", Value::LargeInteger((1 << 32) + 5)))); - let s = slice_from_descriptor(&d); - assert_eq!((s.id, s.layer_id), (0, None)); - assert_eq!(s.outsets, [0, 9, i32::MAX, i32::MIN]); - assert_eq!(s.rect[1], i32::MAX); - // A 32-bit long keeps the id's bits, as `to_descriptor_bytes` writes ids past i32::MAX. - assert_eq!(slice_from_descriptor(&Descriptor::new("slice").with("sliceID", Value::Integer(-1))).id, u32::MAX); - } - - #[test] - fn malformed_input_is_an_error() { - let bytes = sample().to_bytes(); - // Cuts inside the records; a damaged trailing descriptor is ignored on purpose. - for cut in [0, 3, 10, 30, 120] { - assert!(SlicesResource::from_bytes(&bytes[..cut]).is_err(), "cut at {cut}"); - } - let mut huge = 6u32.to_be_bytes().to_vec(); - huge.extend([0u8; 16]); - huge.extend(0u32.to_be_bytes()); - huge.extend(u32::MAX.to_be_bytes()); - assert!(SlicesResource::from_bytes(&huge).is_err()); - assert!(SlicesResource::from_bytes(&9u32.to_be_bytes()).is_err()); - } - - #[test] - fn trailing_descriptor_applies_outsets_to_first_matching_slice() { - // Two slices share id 1; the trailing descriptor must update the first one only, - // matching the pre-index behavior of `iter_mut().find()`. - let mut plain = SlicesResource { - version: 6, - bounds: [0, 0, 80, 100], - group_name: "site".into(), - slices: vec![ - SliceRecord { id: 1, origin: 0, kind: 1, rect: [0, 0, 10, 10], ..Default::default() }, - SliceRecord { id: 1, origin: 0, kind: 1, rect: [10, 10, 20, 20], ..Default::default() }, - ], - }; - for s in &mut plain.slices { - s.outsets = [0; 4]; - } - let mut bytes = plain.to_bytes(); - let extra = Descriptor::new("slice").with("sliceID", Value::Integer(1)).with("topOutset", Value::Integer(7)); - VersionedDescriptor::new(Descriptor::new("null").with("slices", Value::List(vec![Value::Descriptor(extra)]))).write(&mut bytes); - let back = SlicesResource::from_bytes(&bytes).unwrap(); - assert_eq!(back.slices[0].outsets, [7, 0, 0, 0], "first slice receives the outset"); - assert_eq!(back.slices[1].outsets, [0, 0, 0, 0], "later duplicate is untouched"); - } -} diff --git a/crates/psd/src/source.rs b/crates/psd/src/source.rs deleted file mode 100644 index e04e861a1f..0000000000 --- a/crates/psd/src/source.rs +++ /dev/null @@ -1,270 +0,0 @@ -//! Random-access byte sources, for parsing a file without reading all of it. -//! -//! [`PsdFile::from_source`](crate::PsdFile::from_source) reads the structure of a file (header, -//! resources, layer records, tagged blocks) and leaves the bulk of it, the encoded channel data -//! and the merged image, where it is: each [`ChannelData`](crate::ChannelData) records a -//! [`Stored`] range instead of a copy, and the bytes are read when the channel is decoded. A -//! 2 GB layered file then never needs 2 GB of memory just to be opened. - -use std::borrow::Cow; -use std::fmt; -use std::sync::Arc; - -use crate::error::{PsdError, Result}; - -/// Bytes that can be read at any offset, from any thread. -/// -/// Implemented for byte buffers and, on native targets, for [`std::fs::File`] (as -/// [`FileSource`]). The source must not change while a file parsed from it is in use: a -/// [`Stored`] range is an offset into it. -pub trait ReadAt: Send + Sync { - /// Total length in bytes. - fn len(&self) -> u64; - - /// `true` when the source holds no bytes. - fn is_empty(&self) -> bool { - self.len() == 0 - } - - /// Fills `buf` with the bytes at `offset..offset + buf.len()`. Fails, without a partial - /// result, when the range is not all inside the source or the read fails. - fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()>; -} - -fn out_of_range(offset: u64, needed: usize, len: u64) -> PsdError { - PsdError::UnexpectedEof { - offset: usize::try_from(offset).unwrap_or(usize::MAX), - needed: needed.saturating_sub(usize::try_from(len.saturating_sub(offset)).unwrap_or(usize::MAX)), - } -} - -impl ReadAt for [u8] { - fn len(&self) -> u64 { - <[u8]>::len(self) as u64 - } - - fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()> { - let src = usize::try_from(offset) - .ok() - .and_then(|start| self.get(start..start.checked_add(buf.len())?)) - .ok_or_else(|| out_of_range(offset, buf.len(), ReadAt::len(self)))?; - buf.copy_from_slice(src); - Ok(()) - } -} - -impl ReadAt for Vec { - fn len(&self) -> u64 { - self.as_slice().len() as u64 - } - - fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()> { - self.as_slice().read_at(offset, buf) - } -} - -impl ReadAt for Arc { - fn len(&self) -> u64 { - (**self).len() - } - - fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()> { - (**self).read_at(offset, buf) - } -} - -/// Largest single read from a [`FileSource`]. -#[cfg(any(unix, windows))] -const MAX_READ: usize = 64 << 20; - -/// An open file read at offsets (`pread` on Unix, `seek_read` on Windows), with its length taken -/// when it was opened. Reads from several threads at once need no lock. -#[cfg(any(unix, windows))] -#[derive(Debug)] -pub struct FileSource { - file: std::fs::File, - len: u64, -} - -#[cfg(any(unix, windows))] -impl FileSource { - /// Opens `path` for reading. - pub fn open(path: &std::path::Path) -> std::io::Result { - Self::new(std::fs::File::open(path)?) - } - - /// Wraps an open file. - pub fn new(file: std::fs::File) -> std::io::Result { - let len = file.metadata()?.len(); - Ok(FileSource { file, len }) - } - - /// The file. - pub fn file(&self) -> &std::fs::File { - &self.file - } -} - -#[cfg(any(unix, windows))] -impl ReadAt for FileSource { - fn len(&self) -> u64 { - self.len - } - - fn read_at(&self, offset: u64, buf: &mut [u8]) -> Result<()> { - if offset.checked_add(buf.len() as u64).is_none_or(|end| end > self.len) { - return Err(out_of_range(offset, buf.len(), self.len)); - } - let n = buf.len(); - let failed = |e: std::io::Error| PsdError::Read(format!("reading {n} bytes at offset {offset}: {e}")); - // Bounded reads, as `photocraft-format`'s `read_file` makes them: some Windows file - // systems reject a single read of gigabytes (#375). - let mut done = 0usize; - while done < n { - let Some(rest) = buf.get_mut(done..n.min(done + MAX_READ)) else { break }; - let at = offset + done as u64; - #[cfg(unix)] - let read = { - use std::os::unix::fs::FileExt; - self.file.read_at(rest, at) - }; - #[cfg(windows)] - let read = { - use std::os::windows::fs::FileExt; - self.file.seek_read(rest, at) - }; - match read { - Ok(0) => return Err(failed(std::io::ErrorKind::UnexpectedEof.into())), - Ok(k) => done += k, - Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} - Err(e) => return Err(failed(e)), - } - } - Ok(()) - } -} - -/// A shared [`ReadAt`]: what [`Stored`] ranges point into. Two handles are equal when they are -/// the same source. -#[derive(Clone)] -pub struct Source(Arc); - -impl Source { - /// Shares `source`. - pub fn new(source: impl ReadAt + 'static) -> Self { - Source(Arc::new(source)) - } - - /// Shares an already shared source. - pub fn from_arc(source: Arc) -> Self { - Source(source) - } - - /// The source. - pub fn get(&self) -> &dyn ReadAt { - &*self.0 - } - - /// Reads `len` bytes at `offset` into a new buffer. The buffer is reserved fallibly: a - /// range larger than memory is an error, not an abort. - pub fn read_vec(&self, offset: u64, len: u64) -> Result> { - let n = usize::try_from(len).map_err(|_| PsdError::LimitExceeded("length exceeds address space"))?; - if offset.checked_add(len).is_none_or(|end| end > self.0.len()) { - return Err(out_of_range(offset, n, self.0.len())); - } - let mut out = Vec::new(); - out.try_reserve_exact(n).map_err(|_| PsdError::OutOfMemory("not enough memory to read the data"))?; - out.resize(n, 0); - self.0.read_at(offset, &mut out)?; - Ok(out) - } -} - -impl fmt::Debug for Source { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Source({} bytes)", self.0.len()) - } -} - -impl PartialEq for Source { - fn eq(&self, other: &Self) -> bool { - Arc::ptr_eq(&self.0, &other.0) - } -} - -impl Eq for Source {} - -/// Encoded bytes left in their [`Source`] by a lazy parse: `len` bytes at `offset`. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Stored { - /// Where the bytes are. - pub source: Source, - /// Offset of the first byte. - pub offset: u64, - /// Number of bytes. - pub len: u64, -} - -impl Stored { - /// Reads the bytes. - pub fn read(&self) -> Result> { - self.source.read_vec(self.offset, self.len) - } - - /// Reads `len` bytes starting `at` bytes into the range. - pub fn read_part(&self, at: u64, len: u64) -> Result> { - if at.checked_add(len).is_none_or(|end| end > self.len) { - return Err(PsdError::invalid("read past the end of stored data")); - } - self.source.read_vec(self.offset + at, len) - } -} - -/// The bytes of a value that is either in memory (`data`) or still in its source (`stored`). -pub(crate) fn encoded<'a>(data: &'a [u8], stored: Option<&Stored>) -> Result> { - match stored { - Some(s) => s.read().map(Cow::Owned), - None => Ok(Cow::Borrowed(data)), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn slice_reads_are_bounds_checked() { - let v = vec![1u8, 2, 3, 4]; - let mut b = [0u8; 2]; - v.read_at(2, &mut b).unwrap(); - assert_eq!(b, [3, 4]); - assert!(v.read_at(3, &mut b).is_err()); - assert!(v.read_at(u64::MAX, &mut b).is_err()); - let s = Source::new(v); - assert_eq!(s.read_vec(1, 2).unwrap(), vec![2, 3]); - assert!(s.read_vec(1, u64::MAX).is_err()); - let st = Stored { source: s.clone(), offset: 1, len: 3 }; - assert_eq!(st.read().unwrap(), vec![2, 3, 4]); - assert_eq!(st.read_part(1, 2).unwrap(), vec![3, 4]); - assert!(st.read_part(2, 2).is_err()); - assert_eq!(st.source, s); - assert_ne!(st.source, Source::new(vec![1u8, 2, 3, 4])); - } - - #[cfg(any(unix, windows))] - #[test] - fn file_source_reads_at_offsets() { - use std::io::Write; - let dir = std::env::temp_dir().join(format!("photocraft-psd-source-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let path = dir.join("f.bin"); - std::fs::File::create(&path).unwrap().write_all(&[9, 8, 7, 6, 5]).unwrap(); - let f = FileSource::open(&path).unwrap(); - assert_eq!(ReadAt::len(&f), 5); - let mut b = [0u8; 3]; - f.read_at(2, &mut b).unwrap(); - assert_eq!(b, [7, 6, 5]); - assert!(f.read_at(3, &mut b).is_err()); - std::fs::remove_dir_all(&dir).unwrap(); - } -} diff --git a/crates/psd/src/tagged.rs b/crates/psd/src/tagged.rs deleted file mode 100644 index e54f4daf0b..0000000000 --- a/crates/psd/src/tagged.rs +++ /dev/null @@ -1,681 +0,0 @@ -//! Additional layer information ("tagged blocks"). -//! -//! Every block is stored raw (signature, key, data and the exact padding that -//! followed it in the file) so unknown and partially-understood blocks -//! round-trip byte for byte. [`TaggedBlock::parsed`] offers typed views of -//! simple, well-known keys. - -use crate::blend::BlendMode; -use crate::descriptor::UnicodeString; -use crate::error::{PsdError, Result}; -use crate::header::Version; -use crate::io::{Reader, Sink, WriteExt}; - -/// Keys whose length field is 8 bytes in PSB files: the thirteen the Adobe -/// specification lists, plus keys Photoshop also writes with 8-byte lengths -/// although the specification omits them (observed in real PSB files, e.g. -/// `lnkE` and `cinf` in the ag-psd test set, and expected by other PSB -/// readers such as psd-tools). Reading one of these with a 4-byte length -/// misaligns every block after it (#200). -pub const PSB_LONG_KEYS: [&[u8; 4]; 21] = [ - b"LMsk", b"Lr16", b"Lr32", b"Layr", b"Mt16", b"Mt32", b"Mtrn", b"Alph", b"FMsk", b"lnk2", b"FEid", b"FXid", b"PxSD", // spec - b"lnk3", b"lnkE", b"pths", b"extd", b"extn", b"FELS", b"cinf", b"artd", // observed -]; - -/// Returns `true` if `key` uses an 8-byte length in `version`. -pub fn uses_long_length(version: Version, key: &[u8; 4]) -> bool { - version.is_psb() && PSB_LONG_KEYS.contains(&key) -} - -/// A tagged block, stored raw. -#[derive(Debug, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct TaggedBlock { - /// `8BIM` or `8B64`. - pub signature: [u8; 4], - /// Four-character key. - pub key: [u8; 4], - /// Block data exactly as covered by the length field. - pub data: Vec, - /// Bytes that followed the data before the next block. `None` means - /// "default": zero-pad to a multiple of four for global blocks, two for - /// layer blocks. Parsing yields `None` whenever - /// the stored padding equals the default, so the model stays canonical. - pub padding: Option>, -} - -/// Layer section divider type (`lsct`). -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum SectionType { - /// 0: any other type of layer. - Other, - /// 1: open folder. - OpenFolder, - /// 2: closed folder. - ClosedFolder, - /// 3: bounding section divider (hidden in the UI; marks the group end - /// in bottom-to-top order). - BoundingDivider, - /// Unknown value. - Unknown(u32), -} - -impl SectionType { - /// From stored value. - pub fn from_u32(v: u32) -> Self { - match v { - 0 => SectionType::Other, - 1 => SectionType::OpenFolder, - 2 => SectionType::ClosedFolder, - 3 => SectionType::BoundingDivider, - v => SectionType::Unknown(v), - } - } - /// Stored value. - pub fn as_u32(self) -> u32 { - match self { - SectionType::Other => 0, - SectionType::OpenFolder => 1, - SectionType::ClosedFolder => 2, - SectionType::BoundingDivider => 3, - SectionType::Unknown(v) => v, - } - } - /// `true` for open or closed folders. - pub fn is_folder(self) -> bool { - matches!(self, SectionType::OpenFolder | SectionType::ClosedFolder) - } -} - -/// Section divider setting (`lsct` / `lsdk`). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct SectionDivider { - /// Divider type. - pub kind: SectionType, - /// Group blend mode (present if length >= 12). - pub blend_mode: Option, - /// Sub type: 0 normal, 1 scene group (present if length >= 16). - pub sub_type: Option, -} - -/// Typed view of a known block. -#[derive(Debug, Clone, PartialEq)] -#[non_exhaustive] -pub enum BlockData<'a> { - /// `luni` - UnicodeName(String), - /// `lsct` / `lsdk` - SectionDivider(SectionDivider), - /// `lyid` - LayerId(u32), - /// `lnsr` - NameSource([u8; 4]), - /// `clbl` - BlendClippedAsGroup(bool), - /// `infx` - BlendInteriorElements(bool), - /// `knko`: 0 none, 1 shallow, 2 deep. - Knockout(u8), - /// `tsly`: Transparency Shapes Layer. - TransparencyShapes(bool), - /// `lmgm`: Layer Mask Hides Effects ("layer mask as global mask"). - LayerMaskHidesEffects(bool), - /// `vmgm`: Vector Mask Hides Effects. - VectorMaskHidesEffects(bool), - /// `lspf`: bit 0 transparency, bit 1 composite, bit 2 position locked. - Protection(u32), - /// `lclr`: sheet color index (0 none, 1 red, 2 orange, 3 yellow, 4 green, - /// 5 blue, 6 violet, 7 gray). - SheetColor(u16), - /// `iOpa` - FillOpacity(u8), - /// `shmd`: metadata setting, raw. - MetadataSetting(&'a [u8]), -} - -impl TaggedBlock { - /// A new `8BIM` block with default padding. - pub fn new(key: [u8; 4], data: Vec) -> Self { - TaggedBlock { signature: *b"8BIM", key, data, padding: None } - } - - /// `true` for `MIB8` / `46B8`: the signatures [`crate::tiff`] gives a block whose data was - /// kept verbatim from a little-endian TIFF because its layout is unknown. Such a block is - /// written back exactly into a little-endian TIFF, and cannot go into a big-endian file - /// (a PSD) without being dropped: see [`Self::is_foreign_order`]. - pub fn is_foreign_order_signature(b: &[u8]) -> bool { - b.starts_with(b"MIB8") || b.starts_with(b"46B8") - } - - /// Whether this block's data is in little-endian layout (see - /// [`Self::is_foreign_order_signature`]). - pub fn is_foreign_order(&self) -> bool { - Self::is_foreign_order_signature(&self.signature) - } - - /// `true` for a "Saving Merged Transparency" marker: the merged image's first extra channel - /// is its transparency. The specification's keys are `Mtrn`, `Mt16` and `Mt32`; Photoshop - /// (27.11) writes `MTrn`, with a positive layer count, in a layered TIFF saved with Save - /// Transparency next to spot and alpha channels. - pub fn is_merged_transparency_marker(&self) -> bool { - matches!(&self.key, b"Mtrn" | b"MTrn" | b"Mt16" | b"Mt32") - } - - /// Key as a string (lossy). - pub fn key_str(&self) -> String { - String::from_utf8_lossy(&self.key).into_owned() - } - - pub(crate) fn default_padding(len: usize, alignment: usize) -> usize { - (alignment - len % alignment) % alignment - } - - /// Typed view for known keys. `None` for keys without a typed parser, - /// `Some(Err)` if a known key's data is malformed. - pub fn parsed(&self) -> Option>> { - let d = &self.data[..]; - let mut r = Reader::new(d); - Some(match &self.key { - b"luni" => UnicodeString::read(&mut r).map(|s| BlockData::UnicodeName(s.to_string_lossy())), - b"lsct" | b"lsdk" => parse_section(d).map(BlockData::SectionDivider), - b"lyid" => r.u32().map(BlockData::LayerId), - b"lnsr" => r.array().map(BlockData::NameSource), - b"clbl" => r.u8().map(|v| BlockData::BlendClippedAsGroup(v != 0)), - b"infx" => r.u8().map(|v| BlockData::BlendInteriorElements(v != 0)), - b"knko" => r.u8().map(BlockData::Knockout), - b"tsly" => r.u8().map(|v| BlockData::TransparencyShapes(v != 0)), - b"lmgm" => r.u8().map(|v| BlockData::LayerMaskHidesEffects(v != 0)), - b"vmgm" => r.u8().map(|v| BlockData::VectorMaskHidesEffects(v != 0)), - b"lspf" => r.u32().map(BlockData::Protection), - b"lclr" => r.u16().map(BlockData::SheetColor), - b"iOpa" => r.u8().map(BlockData::FillOpacity), - b"shmd" => Ok(BlockData::MetadataSetting(d)), - _ => return None, - }) - } - - /// `luni` block. Data is padded to a multiple of 4, as Photoshop does. - pub fn unicode_name(name: &str) -> Self { - let mut d = Vec::new(); - UnicodeString::new(name).write(&mut d); - while d.len() % 4 != 0 { - d.push(0); - } - Self::new(*b"luni", d) - } - - /// `lsct` block with all fields. - pub fn section_divider(kind: SectionType, blend_mode: Option, sub_type: Option) -> Self { - let mut d = Vec::new(); - d.put_u32(kind.as_u32()); - if let Some(b) = blend_mode { - d.put(b"8BIM"); - d.put(&b.key()); - if let Some(s) = sub_type { - d.put_u32(s); - } - } - Self::new(*b"lsct", d) - } - - /// `lyid` block. - pub fn layer_id(id: u32) -> Self { - Self::new(*b"lyid", id.to_be_bytes().to_vec()) - } - /// `lnsr` block. - pub fn name_source(src: [u8; 4]) -> Self { - Self::new(*b"lnsr", src.to_vec()) - } - fn flag(key: [u8; 4], v: u8) -> Self { - Self::new(key, vec![v, 0, 0, 0]) - } - /// `clbl` block. - pub fn blend_clipped_as_group(v: bool) -> Self { - Self::flag(*b"clbl", u8::from(v)) - } - /// `infx` block. - pub fn blend_interior_elements(v: bool) -> Self { - Self::flag(*b"infx", u8::from(v)) - } - /// `knko` block. - pub fn knockout(v: u8) -> Self { - Self::flag(*b"knko", v) - } - /// `tsly` block. - pub fn transparency_shapes(v: bool) -> Self { - Self::flag(*b"tsly", u8::from(v)) - } - /// `lmgm` block. - pub fn layer_mask_hides_effects(v: bool) -> Self { - Self::flag(*b"lmgm", u8::from(v)) - } - /// `vmgm` block. - pub fn vector_mask_hides_effects(v: bool) -> Self { - Self::flag(*b"vmgm", u8::from(v)) - } - /// `lspf` block. - pub fn protection(flags: u32) -> Self { - Self::new(*b"lspf", flags.to_be_bytes().to_vec()) - } - /// `lclr` block. - pub fn sheet_color(color: u16) -> Self { - let mut d = color.to_be_bytes().to_vec(); - d.extend_from_slice(&[0; 6]); - Self::new(*b"lclr", d) - } - /// `iOpa` block. - pub fn fill_opacity(v: u8) -> Self { - Self::flag(*b"iOpa", v) - } - - /// Strictly re-parses the internal structure of blocks whose data carries - /// its own sizes, so a block that a strict reader would reject is caught - /// here: `PlLd` (a `plcL` placed layer), `SoLd`/`SoLE` (`soLD` placed - /// layer data), `lnk2`/`lnk3`/`lnkD` (length-prefixed linked files) and - /// `lfx2` (object effects). Every inner length must stay inside the block - /// and the parse must end at the end of the data, apart from up to three - /// zero padding bytes. Other keys are not checked and return `Ok`. - /// - /// Layouts follow the Adobe Photoshop File Format specification - /// ("Additional Layer Information": Placed Layer, Placed Layer Data, - /// Linked Layer, Object Based Effects Layer Info). - pub fn check_structure(&self) -> Result<()> { - let d = &self.data[..]; - let mut r = Reader::new(d); - match &self.key { - b"PlLd" => { - expect_kind(&mut r, b"plcL")?; - let _version = r.u32()?; - crate::io::read_pascal(&mut r, 1)?; - // Page, total pages, anti-alias policy, layer type; transform (8 doubles). - r.skip(4 * 4 + 8 * 8)?; - let _warp_version = r.u32()?; - crate::descriptor::VersionedDescriptor::read(&mut r)?; - } - b"SoLd" | b"SoLE" => { - expect_kind(&mut r, b"soLD")?; - let _version = r.u32()?; - let d = crate::descriptor::VersionedDescriptor::read(&mut r)?; - check_placed_descriptor(&d.descriptor).map_err(|e| PsdError::invalid(format!("{}: {e}", self.key_str())))?; - } - b"lfx2" => { - let _effects_version = r.u32()?; - crate::descriptor::VersionedDescriptor::read(&mut r)?; - } - b"lnk2" | b"lnk3" | b"lnkD" => { - while r.remaining() >= 8 { - let len = r.u64()?; - let item = r.bytes_u64(len)?; - if !matches!(item.get(..4), Some(b"liFD" | b"liFE" | b"liFA")) { - return Err(PsdError::invalid(format!("{}: linked item of unknown type", self.key_str()))); - } - if item.get(..4) == Some(b"liFD") { - check_embedded_item(item).map_err(|e| PsdError::invalid(format!("{}: embedded file: {e}", self.key_str())))?; - } - // Items are padded to a multiple of 4. - let pad = ((4 - len % 4) % 4).min(r.remaining() as u64); - r.skip(pad as usize)?; - } - } - b"FEid" | b"FXid" => { - crate::filter_effects::FilterEffects::parse(d).map_err(|e| PsdError::invalid(format!("{}: {e}", self.key_str())))?; - return Ok(()); - } - _ => return Ok(()), - } - let rest = r.peek_rest(); - if rest.len() > 3 || rest.iter().any(|&b| b != 0) { - return Err(PsdError::invalid(format!("{}: {} unexpected bytes after the block structure", self.key_str(), rest.len()))); - } - Ok(()) - } - - pub(crate) fn write(&self, out: &mut Vec, version: Version, alignment: usize) -> Result<()> { - Self::write_parts(out, self.signature, self.key, &self.data, self.padding.as_deref(), version, alignment) - } - - /// Writes a block from its parts (no owned [`TaggedBlock`] needed). `padding: None` writes - /// zeros up to `alignment`. - pub(crate) fn write_parts( - out: &mut Vec, - signature: [u8; 4], - key: [u8; 4], - data: &[u8], - padding: Option<&[u8]>, - version: Version, - alignment: usize, - ) -> Result<()> { - out.put(&signature); - out.put(&key); - out.put_len(data.len() as u64, uses_long_length(version, &key))?; - out.put(data); - match padding { - Some(p) => out.put(p), - None => out.extend(std::iter::repeat_n(0u8, Self::default_padding(data.len(), alignment))), - } - Ok(()) - } - - /// Serialized size in bytes as a layer block (two-byte alignment). - pub fn encoded_len(&self, version: Version) -> usize { - self.encoded_len_aligned(version, 2) - } - - /// Serialized size in bytes as [`Self::write`] writes it with `alignment`. - pub(crate) fn encoded_len_aligned(&self, version: Version, alignment: usize) -> usize { - let l = if uses_long_length(version, &self.key) { 8 } else { 4 }; - let p = self.padding.as_ref().map_or(Self::default_padding(self.data.len(), alignment), Vec::len); - (8 + l + p).saturating_add(self.data.len()) - } -} - -/// Strict check of a `soLD` descriptor: the unique id and transform Photoshop needs to place the -/// layer, and a well-formed smart filter stack (`filterFX`: a `filterFXList` of `filterFX` -/// objects, each with a name, blend options, an enabled flag and a filter id). -fn check_placed_descriptor(d: &crate::descriptor::Descriptor) -> Result<()> { - use crate::descriptor::Value; - if !matches!(d.get("Idnt"), Some(Value::Text(_))) { - return Err(PsdError::invalid("no Idnt (unique id)")); - } - match d.get("Trnf") { - Some(Value::List(l)) if l.len() == 8 && l.iter().all(|v| matches!(v, Value::Double(_))) => {} - _ => return Err(PsdError::invalid("Trnf is not eight doubles")), - } - let Some(fx) = d.get("filterFX") else { return Ok(()) }; - let Value::Descriptor(fx) = fx else { return Err(PsdError::invalid("filterFX is not an object")) }; - let Some(Value::List(list)) = fx.get("filterFXList") else { return Err(PsdError::invalid("filterFX has no filterFXList")) }; - for (i, item) in list.iter().enumerate() { - let Value::Descriptor(f) = item else { return Err(PsdError::invalid(format!("filter {i} is not an object"))) }; - let ok = matches!(f.get("Nm "), Some(Value::Text(_))) - && matches!(f.get("blendOptions"), Some(Value::Descriptor(_))) - && matches!(f.get("enab"), Some(Value::Boolean(_))) - && matches!(f.get("filterID"), Some(Value::Integer(_))) - && f.get("Fltr").is_none_or(|v| matches!(v, Value::Descriptor(_))); - if !ok { - return Err(PsdError::invalid(format!("filter {i} lacks Nm/blendOptions/enab/filterID"))); - } - } - Ok(()) -} - -/// Strict check of one embedded (`liFD`) linked-layer item: type, version, unique id, file name, -/// file type and creator, data length, optional open descriptor, then the file data, which must -/// fit in the item (version 5+ fields follow it). -fn check_embedded_item(item: &[u8]) -> Result<()> { - let mut r = Reader::new(item); - r.skip(4)?; - let version = r.u32()?; - if !(1..=16).contains(&version) { - return Err(PsdError::invalid(format!("version {version}"))); - } - crate::io::read_pascal(&mut r, 1)?; - crate::io::read_unicode_units(&mut r)?; - r.skip(8)?; // file type, creator - let len = r.u64()?; - if r.u8()? != 0 { - crate::descriptor::VersionedDescriptor::read(&mut r)?; - } - r.bytes_u64(len)?; - Ok(()) -} - -fn expect_kind(r: &mut Reader<'_>, kind: &'static [u8; 4]) -> Result<()> { - let found = r.array::<4>()?; - if &found != kind { - return Err(PsdError::invalid(format!("expected {} structure, found {:?}", String::from_utf8_lossy(kind), String::from_utf8_lossy(&found)))); - } - Ok(()) -} - -fn parse_section(d: &[u8]) -> Result { - let mut r = Reader::new(d); - let kind = SectionType::from_u32(r.u32()?); - let mut blend_mode = None; - let mut sub_type = None; - if r.remaining() >= 8 { - let sig = r.array::<4>()?; - if &sig != b"8BIM" { - return Err(PsdError::InvalidSignature { expected: "8BIM", found: sig }); - } - blend_mode = Some(BlendMode::from_key(r.array()?)); - if r.remaining() >= 4 { - sub_type = Some(r.u32()?); - } - } - Ok(SectionDivider { kind, blend_mode, sub_type }) -} - -/// `8BIM` / `8B64`, or the markers `MIB8` / `46B8` that [`crate::tiff`] gives a block kept -/// verbatim from a little-endian TIFF when its layout is unknown (its data is in that order). -pub(crate) fn is_sig(b: &[u8]) -> bool { - b.starts_with(b"8BIM") || b.starts_with(b"8B64") || TaggedBlock::is_foreign_order_signature(b) -} - -/// Reads tagged blocks until the reader is exhausted. Bytes that do not form -/// a block (fewer than 12 bytes or no valid signature) are returned as -/// trailing data. -pub(crate) fn read_blocks(r: &mut Reader<'_>, version: Version) -> Result<(Vec, Vec)> { - read_blocks_with(r, version, 2, |_, _, _, _, _| false) -} - -/// The callback consumes selected payloads before they are copied into owned blocks. -pub(crate) fn read_blocks_with( - r: &mut Reader<'_>, - version: Version, - alignment: usize, - mut consume: impl FnMut(usize, [u8; 4], [u8; 4], &[u8], &Option>) -> bool, -) -> Result<(Vec, Vec)> { - let mut blocks = Vec::new(); - loop { - let rest = r.peek_rest(); - if rest.len() < 12 || !is_sig(rest) { - let trailing = rest.to_vec(); - r.skip(rest.len())?; - return Ok((blocks, trailing)); - } - let signature = r.array::<4>()?; - let key = r.array::<4>()?; - let len = r.len_field(uses_long_length(version, &key))?; - let data = r.bytes_u64(len)?; - // Detect padding: the smallest k in 0..=3 such that the next block - // signature (or the end of the region) follows k bytes later. - let rest = r.peek_rest(); - let mut pad = None; - for k in 0..=3usize { - if k == rest.len() || (k < rest.len() && is_sig(&rest[k..])) { - pad = Some(k); - break; - } - } - // Opaque trailing bytes can follow canonical zero padding without another signature. - let default = TaggedBlock::default_padding(data.len(), alignment); - let pad = pad.unwrap_or_else(|| if rest.get(..default).is_some_and(|p| p.iter().all(|&b| b == 0)) { default } else { 0 }); - let pad_bytes = r.bytes(pad)?.to_vec(); - let padding = - if pad_bytes.len() == TaggedBlock::default_padding(data.len(), alignment) && pad_bytes.iter().all(|&b| b == 0) { None } else { Some(pad_bytes) }; - if !consume(blocks.len(), signature, key, data, &padding) { - blocks.push(TaggedBlock { signature, key, data: data.to_vec(), padding }); - } - } -} - -pub(crate) fn write_blocks(out: &mut Vec, blocks: &[TaggedBlock], version: Version, alignment: usize) -> Result<()> { - for b in blocks { - b.write(out, version, alignment)?; - } - Ok(()) -} - -/// [`write_blocks`] to a streaming [`Sink`]: each block's data goes straight through, so a large -/// opaque block (an embedded smart object) is never copied whole. -pub(crate) fn write_blocks_to( - out: &mut Sink<'_, W>, - blocks: &[TaggedBlock], - version: Version, - alignment: usize, -) -> std::io::Result<()> { - for b in blocks { - out.small(|o| { - o.put(&b.signature); - o.put(&b.key); - o.put_len(b.data.len() as u64, uses_long_length(version, &b.key)) - })?; - out.put(&b.data)?; - match &b.padding { - Some(p) => out.put(p)?, - None => out.zeros(TaggedBlock::default_padding(b.data.len(), alignment))?, - } - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn rt(blocks: &[TaggedBlock], version: Version) -> Vec { - let mut out = Vec::new(); - write_blocks(&mut out, blocks, version, 2).unwrap(); - let (back, trailing) = read_blocks(&mut Reader::new(&out), version).unwrap(); - assert_eq!(back, blocks); - assert!(trailing.is_empty()); - out - } - - #[test] - fn unicode_name_typed() { - let b = TaggedBlock::unicode_name("Ebene \u{e4}\u{1F600}"); - assert_eq!(b.data.len() % 4, 0); - assert_eq!(b.parsed(), Some(Ok(BlockData::UnicodeName("Ebene \u{e4}\u{1F600}".into())))); - rt(&[b], Version::Psd); - } - - #[test] - fn section_divider_variants() { - for (kind, bm, st, len) in [ - (SectionType::OpenFolder, None, None, 4), - (SectionType::ClosedFolder, Some(BlendMode::PassThrough), None, 12), - (SectionType::BoundingDivider, Some(BlendMode::Multiply), Some(1), 16), - ] { - let b = TaggedBlock::section_divider(kind, bm, st); - assert_eq!(b.data.len(), len); - match b.parsed() { - Some(Ok(BlockData::SectionDivider(s))) => { - assert_eq!(s.kind, kind); - assert_eq!(s.blend_mode, bm); - assert_eq!(s.sub_type, st); - } - other => panic!("{other:?}"), - } - } - let mut b = TaggedBlock::section_divider(SectionType::OpenFolder, Some(BlendMode::Normal), None); - b.data[4] = b'X'; - assert!(matches!(b.parsed(), Some(Err(_)))); - let mut lsdk = TaggedBlock::section_divider(SectionType::OpenFolder, None, None); - lsdk.key = *b"lsdk"; - assert!(matches!(lsdk.parsed(), Some(Ok(BlockData::SectionDivider(_))))); - } - - #[test] - fn section_type_values() { - for v in 0..6 { - assert_eq!(SectionType::from_u32(v).as_u32(), v); - } - assert!(SectionType::OpenFolder.is_folder()); - assert!(!SectionType::BoundingDivider.is_folder()); - } - - #[test] - fn simple_typed_blocks() { - assert_eq!(TaggedBlock::layer_id(7).parsed(), Some(Ok(BlockData::LayerId(7)))); - assert_eq!(TaggedBlock::name_source(*b"cont").parsed(), Some(Ok(BlockData::NameSource(*b"cont")))); - assert_eq!(TaggedBlock::blend_clipped_as_group(true).parsed(), Some(Ok(BlockData::BlendClippedAsGroup(true)))); - assert_eq!(TaggedBlock::blend_interior_elements(false).parsed(), Some(Ok(BlockData::BlendInteriorElements(false)))); - assert_eq!(TaggedBlock::knockout(2).parsed(), Some(Ok(BlockData::Knockout(2)))); - assert_eq!(TaggedBlock::transparency_shapes(false).parsed(), Some(Ok(BlockData::TransparencyShapes(false)))); - assert_eq!(TaggedBlock::layer_mask_hides_effects(true).parsed(), Some(Ok(BlockData::LayerMaskHidesEffects(true)))); - assert_eq!(TaggedBlock::vector_mask_hides_effects(true).parsed(), Some(Ok(BlockData::VectorMaskHidesEffects(true)))); - assert_eq!(TaggedBlock::vector_mask_hides_effects(true).data, vec![1, 0, 0, 0]); - assert!(matches!(TaggedBlock::new(*b"tsly", vec![]).parsed(), Some(Err(_))), "truncated flag is an error, not a panic"); - assert_eq!(TaggedBlock::protection(0x8000_0000).parsed(), Some(Ok(BlockData::Protection(0x8000_0000)))); - assert_eq!(TaggedBlock::sheet_color(3).parsed(), Some(Ok(BlockData::SheetColor(3)))); - assert_eq!(TaggedBlock::fill_opacity(128).parsed(), Some(Ok(BlockData::FillOpacity(128)))); - let shmd = TaggedBlock::new(*b"shmd", vec![0, 0, 0, 0]); - assert_eq!(shmd.parsed(), Some(Ok(BlockData::MetadataSetting(&[0, 0, 0, 0])))); - assert_eq!(TaggedBlock::new(*b"lfx2", vec![]).parsed(), None); - assert!(matches!(TaggedBlock::new(*b"lyid", vec![1]).parsed(), Some(Err(_)))); - } - - #[test] - fn default_padding_odd_data() { - let b = TaggedBlock::new(*b"abcd", vec![1, 2, 3]); - let out = rt(&[b.clone(), b], Version::Psd); - assert_eq!(out.len(), 2 * (12 + 4)); - } - - #[test] - fn explicit_padding_preserved() { - let mut a = TaggedBlock::new(*b"abcd", vec![1, 2, 3]); - a.padding = Some(vec![0; 3]); // pad-to-4 in a file that aligned to 4 - let mut b = TaggedBlock::new(*b"efgh", vec![1, 2]); - b.padding = Some(vec![0, 0]); - let mut c = TaggedBlock::new(*b"ijkl", vec![1]); - c.padding = Some(vec![]); // no padding at all - rt(&[a, b, c], Version::Psd); - } - - #[test] - fn signature_8b64_preserved() { - let mut b = TaggedBlock::new(*b"Lr16", vec![0; 6]); - b.signature = *b"8B64"; - rt(&[b], Version::Psb); - } - - #[test] - fn psb_long_keys() { - for key in PSB_LONG_KEYS { - assert!(uses_long_length(Version::Psb, key)); - assert!(!uses_long_length(Version::Psd, key)); - let b = TaggedBlock::new(*key, vec![7; 4]); - let out = rt(std::slice::from_ref(&b), Version::Psb); - assert_eq!(out.len(), 8 + 8 + 4); - assert_eq!(b.encoded_len(Version::Psb), out.len()); - let out = rt(std::slice::from_ref(&b), Version::Psd); - assert_eq!(out.len(), 8 + 4 + 4); - } - assert!(!uses_long_length(Version::Psb, b"luni")); - } - - #[test] - fn trailing_bytes_kept() { - let mut out = Vec::new(); - write_blocks(&mut out, &[TaggedBlock::layer_id(1)], Version::Psd, 2).unwrap(); - out.extend_from_slice(&[0; 8]); - let (blocks, trailing) = read_blocks(&mut Reader::new(&out), Version::Psd).unwrap(); - assert_eq!(blocks.len(), 1); - // The detector attributes up to 3 bytes of zeros to padding only when - // they reach the end; 8 zeros are not padding. - assert_eq!(trailing, vec![0; 8]); - } - - #[test] - fn short_trailing_pad_attributed_to_block() { - let mut out = Vec::new(); - write_blocks(&mut out, &[TaggedBlock::layer_id(1)], Version::Psd, 2).unwrap(); - out.extend_from_slice(&[0; 2]); - let (blocks, trailing) = read_blocks(&mut Reader::new(&out), Version::Psd).unwrap(); - assert_eq!(blocks[0].padding, Some(vec![0, 0])); - assert!(trailing.is_empty()); - } - - #[test] - fn overlong_length_errors() { - let mut out = Vec::new(); - out.put(b"8BIMabcd"); - out.put_u32(100); - out.put(&[0; 4]); - assert!(read_blocks(&mut Reader::new(&out), Version::Psd).is_err()); - } -} diff --git a/crates/psd/src/testgen.rs b/crates/psd/src/testgen.rs deleted file mode 100644 index 4898984445..0000000000 --- a/crates/psd/src/testgen.rs +++ /dev/null @@ -1,384 +0,0 @@ -//! Deterministic synthetic PSD/PSB generator for tests and fuzz seeds. -//! -//! Covers every depth (1, 8, 16, 32), color mode (Bitmap, Grayscale, -//! Indexed, RGB, CMYK, Lab, Multichannel, Duotone), every compression, -//! layers with masks (incl. real masks and parameters), nested groups, all -//! blend modes, Unicode names, empty (0×0) layers, large-ish bounds, -//! negative offsets, many tagged blocks, descriptors and image resources. - -use crate::blend::BlendMode; -use crate::compression::Compression; -use crate::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; -use crate::file::{GlobalLayerMask, LayerInfoPlacement, PsdFile}; -use crate::header::{ColorMode, Header, Version, row_bytes}; -use crate::image_data::ImageData; -use crate::layer::{BlendingRanges, ChannelData, LayerFlags, LayerInfo, LayerMask, LayerRecord, MaskData, MaskParameters, RealMask, Rect}; -use crate::resources::{ImageResource, ResolutionInfo, ids, version_info_resource}; -use crate::tagged::{SectionType, TaggedBlock}; - -/// A named generated file. -#[derive(Debug, Clone)] -pub struct Case { - /// Descriptive name. - pub name: String, - /// The model. - pub file: PsdFile, -} - -/// Deterministic pattern of planar samples for a `w × h` plane. -pub fn pattern_plane(w: usize, h: usize, depth: u16, seed: u32) -> Vec { - let mut out = Vec::with_capacity(row_bytes(w, depth) * h); - let s = seed as usize; - for y in 0..h { - match depth { - 1 => { - for bx in 0..row_bytes(w, 1) { - out.push(((bx * 37 + y * 11 + s) as u8) ^ 0x5a); - } - } - 8 => { - for x in 0..w { - // Mix smooth gradients and runs so RLE sees both. - let v = if (x / 4 + y) % 3 == 0 { (s * 17) as u8 } else { (x * 3 + y * 7 + s) as u8 }; - out.push(v); - } - } - 16 => { - for x in 0..w { - let v = ((x * 997 + y * 131 + s * 7919) % 65536) as u16; - out.extend_from_slice(&v.to_be_bytes()); - } - } - _ => { - for x in 0..w { - let v = ((x + y + s) % 17) as f32 / 16.0; - out.extend_from_slice(&v.to_be_bytes()); - } - } - } - } - out -} - -/// Number of channels used for a color mode in generated files. -pub fn mode_channels(mode: ColorMode) -> u16 { - match mode { - ColorMode::Multichannel => 2, - m => m.color_channels().unwrap_or(1), - } -} - -/// Valid depths for a color mode. -pub fn mode_depths(mode: ColorMode) -> &'static [u16] { - match mode { - ColorMode::Bitmap => &[1], - ColorMode::Indexed | ColorMode::Duotone => &[8], - ColorMode::Multichannel | ColorMode::Cmyk | ColorMode::Lab => &[8, 16], - _ => &[8, 16, 32], - } -} - -/// All color modes covered. -pub const MODES: [ColorMode; 8] = - [ColorMode::Bitmap, ColorMode::Grayscale, ColorMode::Indexed, ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab, ColorMode::Multichannel, ColorMode::Duotone]; - -fn color_mode_data(mode: ColorMode) -> Vec { - match mode { - ColorMode::Indexed => (0..768u32).map(|i| (i * 7 % 256) as u8).collect(), - // Duotone data is undocumented; any bytes are preserved. - ColorMode::Duotone => (0..24u8).collect(), - _ => Vec::new(), - } -} - -fn base_resources() -> Vec { - let mut named = ImageResource::new(2000, vec![1, 2, 3]); - named.name = b"Path 1".to_vec(); - vec![ - ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(72.0).to_bytes()), - ImageResource::new(ids::GLOBAL_ANGLE, 30i32.to_be_bytes().to_vec()), - ImageResource::new(ids::GLOBAL_ALTITUDE, 30i32.to_be_bytes().to_vec()), - ImageResource::new(ids::ICC_PROFILE, vec![0x42; 13]), - ImageResource::new(ids::XMP, b"".to_vec()), - named, - version_info_resource(true), - ] -} - -/// A flattened file (no layer section) with a patterned merged image. -pub fn merged_only(version: Version, mode: ColorMode, depth: u16, compression: Compression, w: u32, h: u32) -> PsdFile { - let channels = mode_channels(mode); - let header = Header::new(version, w, h, channels, depth, mode); - let mut planes = Vec::new(); - for c in 0..channels { - planes.extend(pattern_plane(w as usize, h as usize, depth, u32::from(c))); - } - let image_data = ImageData::encode(compression, &planes, &header).unwrap_or(ImageData::new(compression, Vec::new())); - PsdFile { - header, - color_mode_data: color_mode_data(mode), - resources: base_resources(), - layer_info: None, - layer_info_placement: LayerInfoPlacement::Section, - global_layer_mask: None, - global_blocks: Vec::new(), - layer_mask_trailing: Vec::new(), - image_data, - write_as_psb: false, - } -} - -/// Parameters for a generated raster layer. -struct LayerGen<'a> { - header: &'a Header, - compression: Compression, - rect: Rect, - name: &'a str, - blend: BlendMode, - mask: Option, - seed: u32, -} - -fn raster_layer(g: LayerGen<'_>) -> LayerRecord { - let (w, h) = g.rect.size().unwrap_or((0, 0)); - let depth = g.header.depth; - let v = g.header.version; - let cc = mode_channels(g.header.color_mode) as i16; - let mut channels = Vec::new(); - for id in -1..cc { - let plane = pattern_plane(w, h, depth, g.seed + (id + 1) as u32); - let comp = if id == -1 && g.compression == Compression::Rle { Compression::Zip } else { g.compression }; - channels.push(ChannelData::encode(id, comp, &plane, w, h, depth, v).expect("encode")); - } - let mut mask_data = MaskData::None; - if let Some(m) = g.mask { - let (mw, mh) = m.rect.size().unwrap_or((0, 0)); - channels.push(ChannelData::encode(-2, g.compression, &pattern_plane(mw, mh, depth, g.seed + 99), mw, mh, depth, v).expect("encode")); - if let Some(real) = m.real { - let (rw, rh) = real.rect.size().unwrap_or((0, 0)); - channels.push(ChannelData::encode(-3, g.compression, &pattern_plane(rw, rh, depth, g.seed + 7), rw, rh, depth, v).expect("encode")); - } - mask_data = MaskData::Mask(m); - } - let mut flags = LayerFlags(0); - flags.set_hidden(g.seed % 5 == 4); - LayerRecord { - rect: g.rect, - channels, - blend_mode: g.blend, - opacity: (255 - (g.seed * 13) % 128) as u8, - clipping: u8::from(g.seed % 7 == 3), - flags, - filler: 0, - mask: mask_data, - blending_ranges: BlendingRanges::full(cc as usize), - name: crate::io::encode_legacy_name(g.name), - blocks: vec![TaggedBlock::unicode_name(g.name), TaggedBlock::layer_id(g.seed + 1)], - extra_trailing: Vec::new(), - } -} - -fn group_record(header: &Header, name: &str, kind: SectionType, blend: BlendMode, id: u32) -> LayerRecord { - let cc = mode_channels(header.color_mode) as i16; - let channels = (-1..cc).map(|c| ChannelData::new(c, Some(Compression::Raw), Vec::new())).collect(); - let lsct = if kind == SectionType::BoundingDivider { - TaggedBlock::section_divider(kind, None, None) - } else { - TaggedBlock::section_divider(kind, Some(blend), Some(0)) - }; - LayerRecord { - channels, - blend_mode: blend, - name: crate::io::encode_legacy_name(name), - blending_ranges: BlendingRanges::full(cc as usize), - blocks: vec![TaggedBlock::unicode_name(name), TaggedBlock::layer_id(id), lsct], - ..Default::default() - } -} - -/// A sample versioned descriptor as used by `lfx2`/`SoCo`-style blocks. -pub fn sample_descriptor() -> VersionedDescriptor { - VersionedDescriptor::new( - Descriptor::new("null") - .with("Scl ", Value::UnitFloat { unit: *b"#Prc", value: 100.0 }) - .with("masterFXSwitch", Value::Boolean(true)) - .with( - "DrSh", - Value::Descriptor( - Descriptor::new("DrSh") - .with("enab", Value::Boolean(true)) - .with("Md ", Value::Enumerated { type_id: Id::new("BlnM"), value: Id::new("Mltp") }) - .with("Clr ", Value::Descriptor(Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)))) - .with("lagl", Value::UnitFloat { unit: *b"#Ang", value: 120.0 }) - .with("Nm ", Value::Text(UnicodeString::new_nul("Shadow"))), - ), - ) - .with("list", Value::List(vec![Value::Integer(1), Value::LargeInteger(-2)])), - ) -} - -fn extra_blocks(seed: u32) -> Vec { - let mut lfx2 = vec![0, 0, 0, 0]; - lfx2.extend(sample_descriptor().to_bytes()); - let mut odd = TaggedBlock::new(*b"zOdd", vec![1, 2, 3]); - odd.padding = Some(vec![0, 0, 0]); - let mut unpadded = TaggedBlock::new(*b"zNop", vec![9]); - unpadded.padding = Some(vec![]); - vec![ - TaggedBlock::name_source(*b"cont"), - TaggedBlock::blend_clipped_as_group(true), - TaggedBlock::blend_interior_elements(false), - TaggedBlock::knockout(0), - TaggedBlock::protection(seed % 8), - TaggedBlock::sheet_color((seed % 8) as u16), - TaggedBlock::fill_opacity(200), - TaggedBlock::new(*b"shmd", vec![0, 0, 0, 0]), - TaggedBlock::new(*b"lfx2", lfx2), - TaggedBlock::new(*b"fxrp", vec![0; 16]), - odd, - unpadded, - ] -} - -/// A layered file exercising masks, nested groups, blend modes, names, -/// empty layers, negative offsets and many tagged blocks. -pub fn layered(version: Version, mode: ColorMode, depth: u16, compression: Compression) -> PsdFile { - let (w, h) = (24u32, 16u32); - let channels = mode_channels(mode) + 1; - let header = Header::new(version, w, h, channels, depth, mode); - let mut layers = Vec::new(); - let mut seed = 0u32; - let mut next = |layers: &mut Vec, rect: Rect, name: &str, blend: BlendMode, mask: Option| { - seed += 1; - let mut rec = raster_layer(LayerGen { header: &header, compression, rect, name, blend, mask, seed }); - if seed.is_multiple_of(3) { - rec.blocks.extend(extra_blocks(seed)); - } - layers.push(rec); - }; - // Background. - next(&mut layers, Rect::from_xywh(0, 0, w, h), "Background", BlendMode::Normal, None); - // Negative offsets + simple mask. - next( - &mut layers, - Rect::from_xywh(-5, -3, 10, 7), - "Neg offset \u{1F600}", - BlendMode::Multiply, - Some(LayerMask::new(Rect::from_xywh(-2, -2, 6, 5), 0, LayerMask::FLAG_RELATIVE)), - ); - // Empty layer. - next(&mut layers, Rect::default(), "Empty", BlendMode::Screen, None); - // Large-ish bounds beyond the canvas. - next(&mut layers, Rect::from_xywh(-100, 5, 400, 2), "Wide", BlendMode::Overlay, None); - // Nested groups: outer [ layer, inner [ masked layer (real mask + params) ] ]. - let id0 = 1000; - layers.push(group_record(&header, "", SectionType::BoundingDivider, BlendMode::Normal, id0)); - next(&mut layers, Rect::from_xywh(2, 2, 5, 5), "In outer", BlendMode::Darken, None); - layers.push(group_record(&header, "", SectionType::BoundingDivider, BlendMode::Normal, id0 + 1)); - let real_mask = LayerMask { - rect: Rect::from_xywh(1, 1, 4, 3), - default_color: 255, - flags: LayerMask::FLAG_PARAMETERS, - parameters: Some(MaskParameters { flags: 0b0011, user_density: Some(200), user_feather: Some(1.5), vector_density: None, vector_feather: None }), - real: Some(RealMask { flags: 0, background: 255, rect: Rect::from_xywh(0, 0, 3, 3) }), - trailing: Vec::new(), - real_first: true, - }; - next(&mut layers, Rect::from_xywh(3, 3, 6, 4), "Grüße", BlendMode::ColorDodge, Some(real_mask)); - layers.push(group_record(&header, "Inner", SectionType::ClosedFolder, BlendMode::Normal, id0 + 2)); - layers.push(group_record(&header, "Outer", SectionType::OpenFolder, BlendMode::PassThrough, id0 + 3)); - // One small layer per blend mode. - for (i, m) in BlendMode::ALL.iter().enumerate() { - let name = format!("blend {:?}", m); - next(&mut layers, Rect::from_xywh(i as i32 % 20, i as i32 % 12, 3, 2), &name, *m, None); - } - next(&mut layers, Rect::from_xywh(0, 0, 2, 2), "unknown blend", BlendMode::Unknown(*b"zzzz"), None); - - let mut planes = Vec::new(); - for c in 0..channels { - planes.extend(pattern_plane(w as usize, h as usize, depth, 50 + u32::from(c))); - } - let image_data = ImageData::encode(compression, &planes, &header).expect("encode merged"); - let layer_info = LayerInfo { merged_alpha: true, layers, padding: None }; - let (placement, blocks) = match depth { - 16 | 32 => ( - LayerInfoPlacement::GlobalBlock { index: 1, signature: *b"8BIM", key: if depth == 16 { *b"Lr16" } else { *b"Lr32" }, padding: None }, - vec![TaggedBlock::new(*b"Patt", vec![]), TaggedBlock::new(*b"Txt2", vec![0, 1, 2, 3])], - ), - _ => (LayerInfoPlacement::Section, vec![TaggedBlock::new(*b"Patt", vec![]), TaggedBlock::new(*b"FMsk", vec![0; 10])]), - }; - PsdFile { - header, - color_mode_data: color_mode_data(mode), - resources: base_resources(), - layer_info: Some(layer_info), - layer_info_placement: placement, - global_layer_mask: Some(GlobalLayerMask { data: vec![0, 0, 0xff, 0xff, 0, 0, 0, 0, 0, 0, 0, 50, 128, 0] }), - global_blocks: blocks, - layer_mask_trailing: Vec::new(), - image_data, - write_as_psb: false, - } -} - -/// A tiny layered RGB file (useful for truncation sweeps). -pub fn small(version: Version, compression: Compression) -> PsdFile { - let header = Header::new(version, 4, 3, 4, 8, ColorMode::Rgb); - let mask = LayerMask::new(Rect::from_xywh(0, 0, 2, 2), 0, 0); - let layers = vec![ - raster_layer(LayerGen { - header: &header, - compression, - rect: Rect::from_xywh(0, 0, 4, 3), - name: "a", - blend: BlendMode::Normal, - mask: Some(mask), - seed: 1, - }), - group_record(&header, "", SectionType::BoundingDivider, BlendMode::Normal, 9), - raster_layer(LayerGen { header: &header, compression, rect: Rect::from_xywh(-1, 1, 2, 2), name: "b", blend: BlendMode::Screen, mask: None, seed: 2 }), - group_record(&header, "g", SectionType::OpenFolder, BlendMode::PassThrough, 10), - ]; - let mut planes = Vec::new(); - for c in 0..4 { - planes.extend(pattern_plane(4, 3, 8, c)); - } - PsdFile { - header: header.clone(), - color_mode_data: Vec::new(), - resources: vec![ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(72.0).to_bytes())], - layer_info: Some(LayerInfo { merged_alpha: true, layers, padding: None }), - layer_info_placement: LayerInfoPlacement::Section, - global_layer_mask: Some(GlobalLayerMask::default()), - global_blocks: vec![TaggedBlock::new(*b"Patt", vec![1, 2])], - layer_mask_trailing: Vec::new(), - image_data: ImageData::encode(compression, &planes, &header).expect("encode"), - write_as_psb: false, - } -} - -/// Every generated case. -pub fn all_cases() -> Vec { - let mut v = Vec::new(); - for version in [Version::Psd, Version::Psb] { - for mode in MODES { - for &depth in mode_depths(mode) { - for c in Compression::ALL { - v.push(Case { name: format!("merged {version:?} {mode:?} {depth}bit {c:?}"), file: merged_only(version, mode, depth, c, 13, 7) }); - } - } - } - for mode in [ColorMode::Grayscale, ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab] { - for &depth in mode_depths(mode).iter().filter(|&&d| d >= 8) { - for c in Compression::ALL { - v.push(Case { name: format!("layered {version:?} {mode:?} {depth}bit {c:?}"), file: layered(version, mode, depth, c) }); - } - } - } - for c in Compression::ALL { - v.push(Case { name: format!("small {version:?} {c:?}"), file: small(version, c) }); - } - v.push(Case { name: format!("1x1 canvas {version:?}"), file: merged_only(version, ColorMode::Rgb, 8, Compression::Rle, 1, 1) }); - } - v -} diff --git a/crates/psd/src/tiff.rs b/crates/psd/src/tiff.rs deleted file mode 100644 index 9fadf9a00c..0000000000 --- a/crates/psd/src/tiff.rs +++ /dev/null @@ -1,339 +0,0 @@ -//! Photoshop layer data embedded in TIFF files (layered TIFF). -//! -//! Photoshop keeps a layered TIFF's layers in two private tags, described by Adobe's -//! *Photoshop TIFF Technical Notes* (March 2002) together with the PSD specification: -//! -//! * **37724 `ImageSourceData`**: the string `"Adobe Photoshop Document Data Block\0"` -//! (`"Adobe Photoshop Document Data V0002\0"` for PSB-sized data, whose long keys carry -//! 8-byte lengths) followed by tagged blocks in the usual `8BIM` + key + length + data form, -//! each padded to a multiple of 4. `Layr` (8-bit), `Lr16` and `Lr32` hold the layer info, the -//! same structure as a PSD's layer info section; `LMsk` holds the global layer mask; every other -//! block is a global additional-layer-information block (`Patt`, `Anno`, `FMsk`, `Txt2`, …). -//! * **34377**: the PSD image resources (`8BIM` resource blocks, without the section length). -//! -//! **Byte order.** Adobe's note is silent, but Photoshop files show (and open-source readers such as psdtags -//! implement) that the block structure follows the TIFF's byte order: in an Intel-order (`II`) -//! file every integer and double is little-endian and every four-character signature and key is -//! stored reversed (`MIB8`, `ryaL`), while the pixel samples inside channel data stay big-endian -//! as in a PSD, and RLE row-count tables follow the container. [`ImageSourceData::from_bytes`] -//! normalizes either order to the big-endian PSD model, and [`ImageSourceData::to_bytes`] writes -//! either order, by transcoding every structure it knows field by field ([`transcode`]). -//! A block the transcoder does not know is never dropped on the way in: its bytes are kept -//! verbatim with the signature `MIB8` (`46B8` for `8B64`) marking that they are in little-endian -//! layout ([`TaggedBlock::is_foreign_order`]), so a later save to a little-endian TIFF writes it -//! back exactly. Only a save to the *other* byte order has to drop such a block, with a warning: -//! a byte-swapped block passed through unchanged would be read as garbage by every other -//! application (and would end the block list for readers that stop at a bad signature). - -use crate::descriptor::MAX_DEPTH; -use crate::error::{PsdError, Result}; -use crate::file::{GlobalLayerMask, LayerInfoPlacement, PsdFile}; -use crate::header::{Header, Version}; -use crate::image_data::ImageData; -use crate::io::{Reader, WriteExt}; -use crate::layer::{LayerInfo, LayerMask, mask_parameter_bytes}; -use crate::resources::ImageResource; -use crate::tagged::{TaggedBlock, read_blocks, uses_long_length}; - -/// The byte order of a TIFF container (and so of the Photoshop data inside it). -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum ByteOrder { - /// Motorola order (`MM`); the PSD byte order. - #[default] - Big, - /// Intel order (`II`). - Little, -} - -impl ByteOrder { - fn is_little(self) -> bool { - matches!(self, ByteOrder::Little) - } -} - -/// Header string of 37724 data with PSD-sized (4-byte) lengths. -pub const SIGNATURE: &[u8; 36] = b"Adobe Photoshop Document Data Block\0"; -/// Header string of 37724 data with PSB-sized (8-byte) lengths for the long keys. -pub const SIGNATURE_PSB: &[u8; 36] = b"Adobe Photoshop Document Data V0002\0"; - -/// The layer-info block key Photoshop uses for a bit depth. -pub fn layer_info_key(depth: u16) -> [u8; 4] { - match depth { - 16 => *b"Lr16", - 32 => *b"Lr32", - _ => *b"Layr", - } -} - -/// The contents of an `ImageSourceData` tag, in the big-endian PSD model. -#[derive(Debug, Clone, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct ImageSourceData { - /// PSD (4-byte lengths) or PSB (8-byte lengths for the long keys). - pub version: Version, - /// The byte order the data was read in (what [`Self::to_bytes`] should normally write back). - pub byte_order: ByteOrder, - /// The layers, from the `Layr` / `Lr16` / `Lr32` block. - pub layer_info: Option, - /// Which key held the layer info (`Layr` when there was none). - pub layer_info_key: [u8; 4], - /// The `LMsk` block. - pub global_layer_mask: Option, - /// Every other block, in stored order. - pub global_blocks: Vec, - /// Bytes after the last block that do not form a block. - pub trailing: Vec, -} - -impl Default for ImageSourceData { - fn default() -> Self { - ImageSourceData { - version: Version::Psd, - byte_order: ByteOrder::Big, - layer_info: None, - layer_info_key: *b"Layr", - global_layer_mask: None, - global_blocks: Vec::new(), - trailing: Vec::new(), - } - } -} - -fn block_order(rest: &[u8]) -> Result { - match rest.get(..4) { - None | Some(b"8BIM") | Some(b"8B64") => Ok(ByteOrder::Big), - Some(b"MIB8") | Some(b"46B8") => Ok(ByteOrder::Little), - Some(other) => { - Err(PsdError::InvalidSignature { expected: "8BIM or MIB8 (Photoshop image source data block)", found: [other[0], other[1], other[2], other[3]] }) - } - } -} - -impl ImageSourceData { - /// Parses a 37724 tag. Returns the data together with warnings about blocks that were - /// dropped because they could not be converted from the file's byte order. - pub fn from_bytes(data: &[u8]) -> Result<(Self, Vec)> { - let (version, rest) = match data.get(..36) { - Some(s) if s == SIGNATURE => (Version::Psd, &data[36..]), - Some(s) if s == SIGNATURE_PSB => (Version::Psb, &data[36..]), - _ => return Err(PsdError::invalid("not Photoshop image source data (missing \"Adobe Photoshop Document Data Block\")")), - }; - let byte_order = block_order(rest)?; - let mut warnings = Vec::new(); - let big; - let rest = if byte_order.is_little() { - let (b, w) = transcode::transcode_blocks(rest, version, ByteOrder::Little, ByteOrder::Big)?; - warnings = w; - big = b; - &big[..] - } else { - rest - }; - let (mut blocks, trailing) = read_blocks(&mut Reader::new(rest), version)?; - // Blocks in a TIFF are padded to 4 (`to_bytes` re-pads them), so zero padding is the - // canonical default here, as even-length padding is in a PSD. - for b in &mut blocks { - if b.padding.as_ref().is_some_and(|p| p.len() <= 3 && p.iter().all(|&x| x == 0)) { - b.padding = None; - } - } - let mut layer_info = None; - let mut layer_info_key = *b"Layr"; - if let Some(i) = blocks.iter().position(|b| matches!(&b.key, b"Layr" | b"Lr16" | b"Lr32")) { - let b = blocks.remove(i); - layer_info = Some(LayerInfo::read_body(&b.data, version)?); - layer_info_key = b.key; - } - let global_layer_mask = blocks.iter().position(|b| &b.key == b"LMsk").map(|i| GlobalLayerMask { data: blocks.remove(i).data }); - Ok((ImageSourceData { version, byte_order, layer_info, layer_info_key, global_layer_mask, global_blocks: blocks, trailing }, warnings)) - } - - /// Serializes the data in `order`. Returns the bytes and warnings about blocks that were - /// dropped because they could not be converted to a little-endian layout. - pub fn to_bytes(&self, order: ByteOrder) -> Result<(Vec, Vec)> { - Self::finish(self.body()?, self.version, order) - } - - /// [`Self::to_bytes`] that frees the layers once their block is written, before the bytes - /// are converted to `order` (a copy of them all): a layered TIFF save holds them one time - /// fewer (#6607). - pub fn into_bytes(self, order: ByteOrder) -> Result<(Vec, Vec)> { - let (body, version) = (self.body()?, self.version); - drop(self); - Self::finish(body, version, order) - } - - /// The signature, then the blocks in big-endian order. - fn body(&self) -> Result> { - let version = self.version; - let signature = if version.is_psb() { SIGNATURE_PSB } else { SIGNATURE }; - let len_field = |key: &[u8; 4]| if uses_long_length(version, key) { 8u64 } else { 4 }; - // Reserved at its exact length, as the buffer holds all the layers' pixels: one that is a - // few bytes short doubles at its last append, copying them once more (#6607). - let mut len = signature.len() as u64; - let info_pad = match &self.layer_info { - Some(info) => { - let pad = info.pad_len(version, 4)?; - len = len.saturating_add(8 + len_field(&self.layer_info_key)).saturating_add(info.unpadded_len(version)?).saturating_add(pad as u64); - pad - } - None => 0, - }; - if let Some(m) = &self.global_layer_mask { - let pad = TaggedBlock::default_padding(m.data.len(), 4); - len = len.saturating_add(8 + len_field(b"LMsk")).saturating_add(m.data.len() as u64).saturating_add(pad as u64); - } - len = self.global_blocks.iter().fold(len, |n, b| n.saturating_add(b.encoded_len_aligned(version, 4) as u64)); - len = len.saturating_add(self.trailing.len() as u64); - let no_memory = || PsdError::OutOfMemory("not enough memory for the layer data"); - let mut body = Vec::new(); - body.try_reserve_exact(usize::try_from(len).map_err(|_| no_memory())?).map_err(|_| no_memory())?; - body.put(signature); - if let Some(info) = &self.layer_info { - // Written straight into the body, padded to 4 inside its length (as a padded copy - // would be): a separate buffer for it would hold all the pixels a second time. - let long = uses_long_length(version, &self.layer_info_key); - body.put(b"8BIM"); - body.put(&self.layer_info_key); - let at = body.begin_len(long); - info.write_unpadded(&mut body, version)?; - body.resize(body.len() + info_pad, 0); - body.end_len(at, long)?; - } - // Blocks without explicit padding are padded to 4 as they are written (alignment 4), so - // the global mask and blocks are written from the model, without a copy of their data. - // The signature stays (a foreign-order marker included). - if let Some(m) = &self.global_layer_mask { - TaggedBlock::write_parts(&mut body, *b"8BIM", *b"LMsk", &m.data, None, version, 4)?; - } - for b in &self.global_blocks { - b.write(&mut body, version, 4)?; - } - body.put(&self.trailing); - Ok(body) - } - - /// The `body` (signature included) converted to `order`. - fn finish(body: Vec, version: Version, order: ByteOrder) -> Result<(Vec, Vec)> { - if !order.is_little() { - return Ok((body, Vec::new())); - } - let signature = if version.is_psb() { SIGNATURE_PSB } else { SIGNATURE }; - let blocks = body.get(signature.len()..).ok_or_else(|| PsdError::invalid("image source data without its signature"))?; - // Converted behind the signature, into one buffer sized for both. - transcode::transcode_blocks_after(signature, blocks, version, ByteOrder::Big, ByteOrder::Little) - } - - /// The layers, global mask and global blocks of a PSD as image source data (byte order Big). - pub fn from_psd(file: &PsdFile) -> Self { - let key = match &file.layer_info_placement { - LayerInfoPlacement::GlobalBlock { key, .. } => *key, - LayerInfoPlacement::Section => layer_info_key(file.header.depth), - }; - ImageSourceData { - version: file.header.version, - byte_order: ByteOrder::Big, - layer_info: file.layer_info.clone(), - layer_info_key: key, - global_layer_mask: file.global_layer_mask.clone(), - global_blocks: file.global_blocks.clone(), - trailing: file.layer_mask_trailing.clone(), - } - } - - /// [`Self::from_psd`] that moves the layers, global mask and global blocks out of `file` - /// instead of copying them: a layered TIFF save would otherwise hold every layer's pixels - /// twice (#6607). `file` keeps its header, resources and merged image. - pub fn take_from_psd(file: &mut PsdFile) -> Self { - let key = match &file.layer_info_placement { - LayerInfoPlacement::GlobalBlock { key, .. } => *key, - LayerInfoPlacement::Section => layer_info_key(file.header.depth), - }; - ImageSourceData { - version: file.header.version, - byte_order: ByteOrder::Big, - layer_info: file.layer_info.take(), - layer_info_key: key, - global_layer_mask: file.global_layer_mask.take(), - global_blocks: std::mem::take(&mut file.global_blocks), - trailing: std::mem::take(&mut file.layer_mask_trailing), - } - } - - /// Assembles a PSD model from this data plus the parts a TIFF stores natively: the header - /// (dimensions, depth, colour mode, channel count), the image resources (tag 34377) and the - /// merged image (the TIFF's pixels). - pub fn into_psd(self, header: Header, resources: Vec, image_data: ImageData) -> PsdFile { - let placement = if matches!(&self.layer_info_key, b"Lr16" | b"Lr32") && self.layer_info.is_some() { - LayerInfoPlacement::GlobalBlock { index: 0, signature: *b"8BIM", key: self.layer_info_key, padding: None } - } else { - LayerInfoPlacement::Section - }; - PsdFile { - header, - color_mode_data: Vec::new(), - resources, - layer_info: self.layer_info, - layer_info_placement: placement, - global_layer_mask: self.global_layer_mask, - global_blocks: self.global_blocks, - layer_mask_trailing: self.trailing, - image_data, - write_as_psb: false, - } - } -} - -/// A block padded to a multiple of 4, as Photoshop writes them in TIFFs. -#[cfg(test)] -fn padded_block(key: [u8; 4], data: Vec) -> TaggedBlock { - let pad = (4 - data.len() % 4) % 4; - TaggedBlock { signature: *b"8BIM", key, data, padding: Some(vec![0; pad]) } -} - -/// Parses a 34377 tag (image resources). Little-endian resource blocks (`MIB8`) are converted; -/// resource payloads other than the typed numeric ones are kept as stored. -pub fn resources_from_bytes(data: &[u8]) -> Result<(Vec, Vec)> { - let order = block_order(data)?; - let mut warnings = Vec::new(); - let big; - let data = if order.is_little() { - let (b, w) = transcode::transcode_resources(data, ByteOrder::Little, ByteOrder::Big)?; - warnings = w; - big = b; - &big[..] - } else { - data - }; - let mut r = Reader::new(data); - let mut out = Vec::new(); - while !r.is_empty() { - // Photoshop pads the tag to an even length; a lone trailing byte is not a resource. - if r.remaining() < 12 && r.peek_rest().iter().all(|&b| b == 0) { - break; - } - out.push(ImageResource::read(&mut r)?); - } - Ok((out, warnings)) -} - -/// Serializes image resources for a 34377 tag (big-endian, which every reader expects). -pub fn resources_to_bytes(resources: &[ImageResource]) -> Result> { - let mut out = Vec::new(); - for r in resources { - r.write(&mut out)?; - } - Ok(out) -} - -/// Field-by-field byte-order conversion of Photoshop structures. -/// -/// Every function reads one structure in the source order and writes it in the target order, -/// so output lengths equal input lengths and every length field stays valid. Layouts follow the -/// Adobe PSD specification; the walker only needs to know where the integers, doubles and -/// four-character keys are, not what they mean. -pub mod transcode; - -#[cfg(test)] -mod tests; diff --git a/crates/psd/src/tiff/tests.rs b/crates/psd/src/tiff/tests.rs deleted file mode 100644 index 533e534430..0000000000 --- a/crates/psd/src/tiff/tests.rs +++ /dev/null @@ -1,1043 +0,0 @@ -use super::transcode::*; -use super::*; -use crate::compression::Compression; -use crate::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; -use crate::header::ColorMode; -use crate::testgen; - -/// Keys the generator plants that the transcoder (rightly) does not know. -const UNKNOWN: [&[u8; 4]; 3] = [b"zOdd", b"zNop", b"Txt2"]; - -/// #6607: moving the layers out of a PSD writes the bytes copying them does, and leaves the -/// rest of the file (its merged image) as it was. The big-endian body is reserved at its exact -/// length, so the buffer is never grown (a copy of every layer's pixels). -#[test] -fn taking_the_layers_writes_the_same_bytes_as_copying_them() { - for case in testgen::all_cases() { - for order in [ByteOrder::Big, ByteOrder::Little] { - let copied = ImageSourceData::from_psd(&case.file).to_bytes(order); - let mut file = case.file.clone(); - let taken = ImageSourceData::take_from_psd(&mut file).into_bytes(order); - match (copied, taken) { - (Ok(a), Ok(b)) => { - assert_eq!(a, b, "{} {order:?}", case.name); - if !order.is_little() { - assert_eq!(b.0.capacity(), b.0.len(), "{}: the body grew", case.name); - } - } - (a, b) => assert_eq!(a.is_err(), b.is_err(), "{} {order:?}", case.name), - } - assert!(file.layer_info.is_none() && file.global_blocks.is_empty() && file.global_layer_mask.is_none(), "{}", case.name); - assert_eq!(file.image_data, case.file.image_data, "{}", case.name); - assert_eq!(file.header, case.file.header, "{}", case.name); - } - } -} - -/// `d` without the blocks a little-endian round trip drops, and without the layer-info -/// padding (which follows the body length, so it changes when blocks are dropped). -fn known(d: &ImageSourceData) -> ImageSourceData { - let mut d = d.clone(); - d.byte_order = ByteOrder::Big; - d.global_blocks.retain(|b| !UNKNOWN.contains(&&b.key)); - if d.layer_info.is_none() { - d.layer_info_key = *b"Layr"; - } - if let Some(info) = &mut d.layer_info { - info.padding = None; - for l in &mut info.layers { - l.blocks.retain(|b| !UNKNOWN.contains(&&b.key)); - } - } - d -} - -fn roundtrip(d: &ImageSourceData) -> ImageSourceData { - let (big, w) = d.to_bytes(ByteOrder::Big).unwrap(); - assert!(w.is_empty(), "{w:?}"); - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(w.iter().all(|w| UNKNOWN.iter().any(|k| w.starts_with(std::str::from_utf8(*k).unwrap()))), "{w:?}"); - if w.is_empty() { - assert_eq!(big.len(), little.len()); - } - if big.len() > 36 { - assert_ne!(big, little); - assert!(little[36..].starts_with(b"MIB8")); - } - let (back_big, w) = ImageSourceData::from_bytes(&big).unwrap(); - assert!(w.is_empty(), "{w:?}"); - let (back_little, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - if little.len() > 36 { - assert_eq!(back_little.byte_order, ByteOrder::Little); - } - assert_eq!(known(&back_little), known(&back_big)); - // The little-endian bytes are a fixed point (from the second generation on when blocks - // were dropped, since the layer-info padding then follows the shorter body). - let (little2, _) = back_little.to_bytes(ByteOrder::Little).unwrap(); - let little3 = ImageSourceData::from_bytes(&little2).unwrap().0.to_bytes(ByteOrder::Little).unwrap().0; - assert_eq!(little3, little2); - back_big -} - -#[test] -fn generated_files_survive_both_orders() { - for case in testgen::all_cases() { - let d = ImageSourceData::from_psd(&case.file); - let back = roundtrip(&d); - assert_eq!(back.version, d.version, "{}", case.name); - assert_eq!(known(&back), known(&d), "{}", case.name); - // Nothing but the planted unknown blocks is lost on the little-endian path. - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(known(&back), known(&d), "{}", case.name); - } -} - -#[test] -fn same_order_transcoding_is_the_identity() { - for case in testgen::all_cases() { - let d = ImageSourceData::from_psd(&case.file); - let (big, _) = d.to_bytes(ByteOrder::Big).unwrap(); - let (same, w) = transcode_blocks(&big[36..], d.version, ByteOrder::Big, ByteOrder::Big).unwrap(); - assert!(w.is_empty()); - assert_eq!(same, big[36..].to_vec(), "{}", case.name); - } -} - -fn sample_layers() -> ImageSourceData { - let file = testgen::layered(Version::Psd, ColorMode::Rgb, 8, Compression::Rle); - ImageSourceData::from_psd(&file) -} - -#[test] -fn signature_selects_the_version() { - let mut d = sample_layers(); - let (b, _) = d.to_bytes(ByteOrder::Big).unwrap(); - assert!(b.starts_with(SIGNATURE)); - d.version = Version::Psb; - let (b, _) = d.to_bytes(ByteOrder::Big).unwrap(); - assert!(b.starts_with(SIGNATURE_PSB)); - assert_eq!(ImageSourceData::from_bytes(&b).unwrap().0.version, Version::Psb); - roundtrip(&d); -} - -#[test] -fn layer_key_follows_depth() { - assert_eq!(layer_info_key(8), *b"Layr"); - assert_eq!(layer_info_key(16), *b"Lr16"); - assert_eq!(layer_info_key(32), *b"Lr32"); - for (depth, comp) in [(16, Compression::ZipPrediction), (32, Compression::ZipPrediction), (16, Compression::Rle)] { - let file = testgen::layered(Version::Psd, ColorMode::Rgb, depth, comp); - let d = ImageSourceData::from_psd(&file); - assert_eq!(d.layer_info_key, layer_info_key(depth)); - let back = roundtrip(&d); - assert_eq!(back.layer_info_key, d.layer_info_key); - // The 16/32-bit model goes back into a PSD as a global block, like Photoshop's. - let psd = back.into_psd(file.header.clone(), file.resources.clone(), file.image_data.clone()); - assert!(matches!(psd.layer_info_placement, LayerInfoPlacement::GlobalBlock { .. })); - let again = PsdFile::from_bytes(&psd.to_bytes().unwrap()).unwrap(); - assert_eq!(known(&ImageSourceData::from_psd(&again)).layer_info, known(&d).layer_info); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(known(&back).layer_info, known(&d).layer_info, "depth {depth}"); - } -} - -#[test] -fn blocks_are_padded_to_four() { - let d = sample_layers(); - let (b, _) = d.to_bytes(ByteOrder::Big).unwrap(); - let mut at = 36; - while at < b.len() { - assert_eq!(&b[at..at + 4], b"8BIM"); - let len = u32::from_be_bytes(b[at + 8..at + 12].try_into().unwrap()) as usize; - at += 12 + len; - at += (4 - at % 4) % 4; - } - assert_eq!(at, b.len()); -} - -fn block_rt(key: [u8; 4], data: Vec) -> (Vec, Vec) { - let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(key, data.clone())], ..Default::default() }; - let (big, _) = d.to_bytes(ByteOrder::Big).unwrap(); - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - assert_eq!(back.global_blocks[0].data, data); - assert_eq!(back.to_bytes(ByteOrder::Big).unwrap().0, big); - (big, little) -} - -#[test] -fn descriptor_blocks_swap_keys_and_numbers() { - let mut desc = Descriptor::new("null"); - desc.items.push((Id::new("Opct"), Value::UnitFloat { unit: *b"#Prc", value: 75.5 })); - desc.items.push((Id::new("Nm "), Value::Text(UnicodeString::new_nul("Drop Shadow")))); - desc.items.push((Id::new("enab"), Value::Boolean(true))); - desc.items.push((Id::new("Md "), Value::Enumerated { type_id: Id::new("BlnM"), value: Id::new("Mltp") })); - desc.items.push((Id::new("list"), Value::List(vec![Value::Integer(-3), Value::Double(1.5), Value::LargeInteger(7)]))); - desc.items.push((Id::new("longKeyName"), Value::Descriptor(Descriptor::new("innr")))); - let mut data = 0u32.to_be_bytes().to_vec(); - data.extend(VersionedDescriptor::new(desc).to_bytes()); - let (big, little) = block_rt(*b"lfx2", data); - // Keys are reversed and the version field swapped in the little-endian bytes. - assert!(little[36..].starts_with(b"MIB82xfl")); - let body_at = 48; - assert_eq!(&little[body_at..body_at + 4], &[0, 0, 0, 0]); - assert_eq!(&little[body_at + 4..body_at + 8], &[16, 0, 0, 0]); - assert_eq!(&big[body_at + 4..body_at + 8], &[0, 0, 0, 16]); - assert!(little.windows(4).any(|w| w == b"crP#"), "unit key reversed"); - assert!(little.windows(11).any(|w| w == b"longKeyName"), "string ids are not reversed"); -} - -#[test] -fn descriptor_references_by_identifier_and_index_keep_their_class() { - use crate::descriptor::{Class, ReferenceItem}; - let class = || Class { name: UnicodeString::new(""), class_id: Id::new("Lyr ") }; - let desc = Descriptor::new("null") - .with("null", Value::Reference(vec![ReferenceItem::Identifier { class: class(), id: 7 }, ReferenceItem::Index { class: class(), index: 2 }])); - let mut data = 0u32.to_be_bytes().to_vec(); - data.extend(VersionedDescriptor::new(desc).to_bytes()); - block_rt(*b"lfx2", data); -} - -fn type_layer_data() -> Vec { - let mut data = Vec::new(); - data.put_u16(1); - for value in [1.5, 0.0, -0.25, 1.75, 12.5, -3.25] { - data.put_f64(value); - } - data.put_u16(50); - let text = Descriptor::new("TxLr").with("Txt ", Value::Text(UnicodeString::new_nul("Synthetic Ω 🦀"))); - data.extend(VersionedDescriptor::new(text).to_bytes()); - data.put_u16(1); - data.extend(VersionedDescriptor::new(Descriptor::new("warp")).to_bytes()); - for value in [11, -22, 333, 4_444] { - data.put_i32(value); - } - data -} - -fn tagged_payload<'a>(bytes: &'a [u8], signature_and_key: &[u8; 8], little: bool) -> &'a [u8] { - let block_at = bytes.windows(8).position(|window| window == signature_and_key).expect("tagged block"); - let length_at = block_at + 8; - let length_bytes: [u8; 4] = bytes.get(length_at..length_at + 4).expect("tagged block length").try_into().expect("four-byte length"); - let length = if little { u32::from_le_bytes(length_bytes) } else { u32::from_be_bytes(length_bytes) }; - let data_at = length_at + 4; - let data_end = data_at + usize::try_from(length).expect("test block length fits usize"); - bytes.get(data_at..data_end).expect("tagged block payload") -} - -fn legacy_little_endian_type_block() -> Vec { - let mut tysh = Vec::new(); - tysh.extend_from_slice(&1u16.to_le_bytes()); - for value in [1.5f64, 0.0, -0.25, 1.75, 12.5, -3.25] { - tysh.extend_from_slice(&value.to_le_bytes()); - } - tysh.extend_from_slice(&50u16.to_le_bytes()); - // Independently encode a little-endian `VersionedDescriptor` with a single TEXT value. - tysh.extend_from_slice(&16u32.to_le_bytes()); - tysh.extend_from_slice(&0u32.to_le_bytes()); // empty descriptor name - tysh.extend_from_slice(&0u32.to_le_bytes()); // four-character class id - tysh.extend_from_slice(b"rLxT"); // little-endian four-character class id - tysh.extend_from_slice(&1u32.to_le_bytes()); // one item - tysh.extend_from_slice(&0u32.to_le_bytes()); // four-character key - tysh.extend_from_slice(b" txT"); // little-endian four-character key - tysh.extend_from_slice(b"TXET"); // little-endian OSType - let mut units: Vec = "Synthetic Ω 🦀".encode_utf16().collect(); - units.push(0); // `new_nul`, matching the canonical fixture - tysh.extend_from_slice(&u32::try_from(units.len()).expect("short test string").to_le_bytes()); - for unit in units { - tysh.extend_from_slice(&unit.to_le_bytes()); - } - tysh.extend_from_slice(&1u16.to_le_bytes()); - // Empty warp descriptor, also encoded independently in little-endian order. - tysh.extend_from_slice(&16u32.to_le_bytes()); - tysh.extend_from_slice(&0u32.to_le_bytes()); // empty descriptor name - tysh.extend_from_slice(&4u32.to_le_bytes()); // `warp` is a four-byte string id - tysh.extend_from_slice(b"warp"); - tysh.extend_from_slice(&0u32.to_le_bytes()); // no items - for value in [11i32, -22, 333, 4_444] { - tysh.extend_from_slice(&value.to_le_bytes()); - } - - let mut image_source = super::SIGNATURE.to_vec(); - image_source.extend_from_slice(b"MIB8hSyT"); - image_source.extend_from_slice(&u32::try_from(tysh.len()).expect("short test block").to_le_bytes()); - image_source.extend_from_slice(&tysh); - let padding = (4 - tysh.len() % 4) % 4; - image_source.resize(image_source.len() + padding, 0); - image_source -} - -#[test] -fn type_block_write_keeps_text_descriptor_in_psd_order() { - let canonical = type_layer_data(); - let source = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"TySh", canonical.clone())], ..Default::default() }; - - let (little, warnings) = source.to_bytes(ByteOrder::Little).unwrap(); - assert!(warnings.is_empty(), "{warnings:?}"); - let payload = tagged_payload(&little, b"MIB8hSyT", true); - assert_eq!(payload.get(..2), Some(&[1, 0][..]), "TySh header stays in TIFF order"); - for (index, expected) in [1.5f64, 0.0, -0.25, 1.75, 12.5, -3.25].into_iter().enumerate() { - let start = 2 + index * 8; - let bytes: [u8; 8] = payload.get(start..start + 8).unwrap().try_into().unwrap(); - assert_eq!(f64::from_le_bytes(bytes), expected, "matrix element {index}"); - } - - let (text_descriptor, descriptor_len) = VersionedDescriptor::parse_prefix(canonical.get(52..).unwrap()).unwrap(); - let text_section_len = 2 + descriptor_len; - assert_eq!(payload.get(50..52), Some(&50u16.to_be_bytes()[..])); - assert_eq!(payload.get(52..56), Some(&16u32.to_be_bytes()[..])); - assert_eq!(payload.get(50..50 + text_section_len), canonical.get(50..50 + text_section_len)); - assert!(matches!(text_descriptor.descriptor.get("Txt "), Some(Value::Text(value)) if value.to_string_lossy() == "Synthetic Ω 🦀")); - let text_descriptor_from_output = VersionedDescriptor::parse_prefix(payload.get(52..).unwrap()).unwrap().0; - assert!(matches!(text_descriptor_from_output.descriptor.get("Txt "), Some(Value::Text(value)) if value.to_string_lossy() == "Synthetic Ω 🦀")); - - let warp_at = 50 + text_section_len; - assert_eq!(payload.get(warp_at..warp_at + 2), Some(&1u16.to_le_bytes()[..])); - let (_, warp_len) = VersionedDescriptor::parse_prefix(canonical.get(warp_at + 2..).unwrap()).unwrap(); - let warp_descriptor_at = warp_at + 2; - assert_eq!(payload.get(warp_descriptor_at..warp_descriptor_at + 4), Some(&16u32.to_le_bytes()[..])); - assert_eq!(payload.get(warp_descriptor_at + 4..warp_descriptor_at + 8), Some(&0u32.to_le_bytes()[..])); - assert_eq!(payload.get(warp_descriptor_at + 8..warp_descriptor_at + 12), Some(&4u32.to_le_bytes()[..])); - assert_eq!(payload.get(warp_descriptor_at + 12..warp_descriptor_at + 16), Some(b"warp".as_slice())); - assert_eq!(payload.get(warp_descriptor_at + 16..warp_descriptor_at + 20), Some(&0u32.to_le_bytes()[..])); - let bounds_at = warp_descriptor_at + warp_len; - for (index, expected) in [11i32, -22, 333, 4_444].into_iter().enumerate() { - let start = bounds_at + index * 4; - assert_eq!(payload.get(start..start + 4), Some(&expected.to_le_bytes()[..]), "bound {index}"); - } - - let (big, warnings) = source.to_bytes(ByteOrder::Big).unwrap(); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(tagged_payload(&big, b"8BIMTySh", false), canonical); - - let (reopened, warnings) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(reopened.global_blocks[0].data, canonical); - assert_eq!(reopened.to_bytes(ByteOrder::Big).unwrap().0, big); -} - -#[test] -fn legacy_little_endian_type_descriptor_still_imports() { - let input = legacy_little_endian_type_block(); - let (reopened, warnings) = ImageSourceData::from_bytes(&input).unwrap(); - assert!(warnings.is_empty(), "{warnings:?}"); - assert_eq!(reopened.global_blocks[0].data, type_layer_data()); -} - -#[test] -fn type_block_layout() { - let mut data = Vec::new(); - data.put_u16(1); - for v in [1.0, 0.0, 0.0, 1.0, 12.5, -3.0] { - data.put_f64(v); - } - data.put_u16(50); - data.extend(VersionedDescriptor::new(Descriptor::new("TxLr")).to_bytes()); - data.put_u16(1); - data.extend(VersionedDescriptor::new(Descriptor::new("warp")).to_bytes()); - for v in [0.0, 0.0, 100.0, 20.0] { - data.put_f64(v); - } - let (_, little) = block_rt(*b"TySh", data); - assert!(little[48..].starts_with(&[1, 0])); - assert_eq!(&little[50..58], &1.0f64.to_le_bytes()); -} - -#[test] -fn photoshop_type_block_switches_to_big_endian_after_its_matrix() { - let mut data = Vec::new(); - data.put_u16(1); - for v in [1.8054202887117468, 0.0, -0.143, 1.8063853899082987, 247.25, 2864.5] { - data.put_f64(v); - } - data.put_u16(50); - let text = Descriptor::new("TxLr").with("Txt ", Value::Text(UnicodeString::new_nul("Synthetic headline"))); - data.extend(VersionedDescriptor::new(text).to_bytes()); - data.put_u16(1); - data.extend(VersionedDescriptor::new(Descriptor::new("warp")).to_bytes()); - for v in [0, 0, 120, 30] { - data.put_i32(v); - } - let (_, mut little) = block_rt(*b"TySh", data.clone()); - // Photoshop uses big-endian text but returns to little-endian for warp/bounds. - let (_, used) = VersionedDescriptor::parse_prefix(&data[52..]).unwrap(); - little[98..100 + used].copy_from_slice(&data[50..52 + used]); - let (back, warnings) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(warnings.is_empty(), "{warnings:?}"); - assert!(!back.global_blocks[0].is_foreign_order()); - assert_eq!(back.global_blocks[0].data, data); - // The normalized model remains writable in either order. - for order in [ByteOrder::Big, ByteOrder::Little] { - let (bytes, warnings) = back.to_bytes(order).unwrap(); - assert!(warnings.is_empty()); - let (again, warnings) = ImageSourceData::from_bytes(&bytes).unwrap(); - assert!(warnings.is_empty()); - assert_eq!(again.global_blocks[0].data, data); - } -} - -#[test] -fn legacy_effects_and_adjustments() { - // lrFX with a drop shadow and a solid fill. - let mut fx = Vec::new(); - fx.put_u16(0); - fx.put_u16(3); - fx.put(b"8BIMcmnS"); - fx.put_u32(7); - fx.put_u32(0); - fx.put_u8(1); - fx.put_u16(0); - fx.put(b"8BIMdsdw"); - let mut sh = Vec::new(); - sh.put_u32(2); - for v in [5 << 16, 75 << 16, 120 << 16, 7 << 16] { - sh.put_i32(v); - } - for _ in 0..5 { - sh.put_u16(0); - } - sh.put(b"8BIMmul "); - sh.put_u8(1); - sh.put_u8(1); - sh.put_u8(191); - sh.put_u16(0); - sh.put_u16(0x1234); - sh.put_u16(0); - sh.put_u16(0); - sh.put_u16(0); - fx.put_u32(sh.len() as u32); - fx.put(&sh); - fx.put(b"8BIMsofi"); - let mut so = Vec::new(); - so.put_u32(2); - so.put(b"8BIMnorm"); - so.put_u16(0); - so.put_u16(0xffff); - so.put_u16(0); - so.put_u16(0); - so.put_u16(0); - so.put_u8(255); - so.put_u8(1); - so.put_u16(0); - so.put_u16(0xffff); - so.put_u16(0); - so.put_u16(0); - so.put_u16(0); - fx.put_u32(so.len() as u32); - fx.put(&so); - let (_, little) = block_rt(*b"lrFX", fx); - assert!(little.windows(8).any(|w| w == b"MIB8wdsd"), "effect keys reversed"); - assert!(little.windows(2).any(|w| w == [0x34, 0x12]), "colour component swapped"); - - // levl: version + 29 records + the Lvls extension. - let mut lv = Vec::new(); - lv.put_u16(2); - for i in 0..29 * 5 { - lv.put_u16(i as u16); - } - lv.put(b"Lvls"); - lv.put_u16(3); - lv.put_u16(33); - for i in 0..4 * 5 { - lv.put_u16(1000 + i as u16); - } - let (_, little) = block_rt(*b"levl", lv); - assert!(little.windows(4).any(|w| w == b"slvL")); - - // curv with the Crv extension. - let mut cv = vec![0u8]; - cv.put_u16(1); - cv.put_u32(0b101); - cv.put_u16(2); - cv.put_u16(0); - cv.put_u16(0); - cv.put_u16(255); - cv.put_u16(255); - cv.put_u16(1); - cv.put_u16(128); - cv.put_u16(100); - cv.put(b"Crv "); - cv.put_u16(4); - cv.put_u32(1); - cv.put_u16(2); - cv.put_u16(1); - cv.put_u16(7); - cv.put_u16(9); - block_rt(*b"curv", cv); - - for (key, data) in [ - (*b"hue2", vec![0, 2, 0, 0, 0, 10, 0, 20, 0, 30, 0, 40, 0, 50, 0, 60]), - (*b"brit", vec![0, 10, 0, 20, 0, 30, 1, 0]), - (*b"thrs", vec![0, 128, 0, 0]), - (*b"post", vec![0, 4, 0, 0]), - (*b"nvrt", vec![]), - (*b"expA", [1u16.to_be_bytes().to_vec(), 0.5f32.to_be_bytes().to_vec(), 0.0f32.to_be_bytes().to_vec(), 1.0f32.to_be_bytes().to_vec()].concat()), - (*b"blnc", vec![0; 20]), - (*b"mixr", vec![0, 1, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0]), - (*b"selc", vec![0, 1, 0, 0, 0, 5, 0, 6, 0, 7, 0, 8]), - (*b"phfl", vec![0, 3, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 25, 1, 0]), - (*b"phfl", vec![0, 2, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 0, 0, 25, 1, 0]), - (*b"lclr", vec![0, 1, 0, 0, 0, 0, 0, 0]), - (*b"fxrp", [1.5f64.to_be_bytes().to_vec(), 2.5f64.to_be_bytes().to_vec()].concat()), - (*b"brst", vec![0, 0, 0, 1, 0, 0, 0, 2]), - (*b"FMsk", vec![0, 0, 255, 255, 0, 0, 0, 0, 0, 0, 0, 50]), - (*b"lsct", [3u32.to_be_bytes().to_vec(), b"8BIMpass".to_vec()].concat()), - (*b"lspf", vec![0, 0, 0, 5]), - (*b"lnsr", b"layr".to_vec()), - (*b"knko", vec![1, 0, 0, 0]), - (*b"knko", vec![2, 0, 0, 0]), - (*b"infx", vec![1, 0, 0, 0]), - (*b"clbl", vec![0, 0, 0, 0]), - (*b"tsly", vec![0, 0, 0, 0]), - (*b"lmgm", vec![1, 0, 0, 0]), - (*b"vmgm", vec![1, 0, 0, 0]), - (*b"iOpa", vec![128, 0, 0, 0]), - ] { - let (big, little) = block_rt(key, data.clone()); - if data.len() >= 2 && key != *b"nvrt" { - assert_ne!(big, little, "{}", String::from_utf8_lossy(&key)); - } - } -} - -#[test] -fn global_layer_mask_block() { - let d = ImageSourceData { global_layer_mask: Some(GlobalLayerMask { data: vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 128, 0] }), ..Default::default() }; - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(w.is_empty()); - assert!(little[36..].starts_with(b"MIB8ksML")); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(back.global_layer_mask, d.global_layer_mask); - assert_eq!(back.global_layer_mask.unwrap().opacity(), Some(50)); -} - -#[test] -fn gradient_map_layout() { - let mut g = Vec::new(); - g.put_u16(3); - g.put_u8(0); - g.put_u8(1); - g.put(b"Lnr "); - g.put_u32(2); - g.put_u16(u16::from(b'a')); - g.put_u16(0); - g.put_u16(2); - for (loc, mid) in [(0u32, 50u32), (4096, 50)] { - g.put_u32(loc); - g.put_u32(mid); - g.put_u16(0); - g.put_u16(0x1111); - g.put_u16(0x2222); - g.put_u16(0x3333); - g.put_u16(0); - g.put_u16(0); - } - g.put_u16(2); - for loc in [0u32, 4096] { - g.put_u32(loc); - g.put_u32(50); - g.put_u16(100); - } - g.put_u16(2); - g.put_u16(1); - g.put_u16(32); - g.put_u16(0); - g.put_u32(0xdead_beef); - for _ in 0..12 { - g.put_u16(0); - } - let (_, little) = block_rt(*b"grdm", g); - assert!(little.windows(4).any(|w| w == 0xdead_beefu32.to_le_bytes())); - assert!(little.windows(4).any(|w| w == b" rnL")); -} - -#[test] -fn vector_mask_records() { - let mut v = Vec::new(); - v.put_u32(3); - v.put_u32(0); - // Closed length record, then two linked knots. - v.put_u16(0); - v.put_u16(2); - v.put_i16(1); - v.put(&[0; 20]); - for sel in [1u16, 1] { - v.put_u16(sel); - for i in 0..6 { - v.put_i32((i + 1) * 0x0010_0000); - } - } - let (_, little) = block_rt(*b"vmsk", v); - assert!(little.windows(4).any(|w| w == [0, 0, 0x10, 0]), "fixed-point coordinate swapped"); -} - -#[test] -fn pattern_block() { - let plane: Vec = (0..16u8).collect(); - let p = crate::patterns::PsdPattern { - mode: 3, - width: 4, - height: 4, - name: "dots".into(), - id: "abc".into(), - palette: None, - depth: 8, - channels: vec![plane.clone(), plane.clone(), plane.clone()], - alpha: Some(plane), - }; - let data = crate::patterns::write_pattern_block(std::slice::from_ref(&p)).unwrap(); - block_rt(*b"Patt", data.clone()); - // Little-endian pattern data parses back into the same pattern. - let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"Patt", data)], ..Default::default() }; - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(crate::patterns::parse_pattern_block(&back.global_blocks[0].data).unwrap(), vec![p]); -} - -#[test] -fn filter_effects_block() { - use crate::filter_effects::{EffectsPlane, FilterEffects, FilterEffectsItem}; - let plane = EffectsPlane::encode(Compression::Rle, &[1, 2, 3, 4, 5, 6], 3, 2, 8).unwrap(); - let mask = EffectsPlane::encode(Compression::Raw, &[9; 6], 3, 2, 8).unwrap(); - let rect = crate::layer::Rect { top: 0, left: 0, bottom: 2, right: 3 }; - let fx = FilterEffects { - version: 1, - items: vec![FilterEffectsItem { - id: "x".into(), - version: 1, - rect, - depth: 8, - max_channels: 1, - slots: vec![Some(plane.clone()), None, Some(plane)], - mask: Some((rect, mask)), - }], - }; - let data = fx.to_bytes(); - block_rt(*b"FEid", data.clone()); - let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"FEid", data)], ..Default::default() }; - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(FilterEffects::parse(&back.global_blocks[0].data).unwrap(), fx); -} - -/// Photoshop writes one `FEid` section per smart object: every section's lengths and -/// numbers are swapped, not only the first one's. -#[test] -fn filter_effects_block_swaps_every_section() { - use crate::filter_effects::{EffectsPlane, FilterEffects, FilterEffectsItem}; - let rect = crate::layer::Rect { top: 0, left: 0, bottom: 2, right: 3 }; - let item = |id: &str, v: u8| FilterEffectsItem { - id: id.into(), - version: 1, - rect, - depth: 8, - max_channels: 1, - slots: vec![Some(EffectsPlane::encode(Compression::Raw, &[v; 6], 3, 2, 8).unwrap()), None, None], - mask: None, - }; - let fx = FilterEffects { version: 1, items: vec![item("first", 1), item("second-object", 2)] }; - let data = fx.to_bytes(); - let len1 = u64::from_be_bytes(data[4..12].try_into().unwrap()) as usize; - let second = 12 + len1 + (4 - len1 % 4) % 4; - let len2 = &data[second..second + 8]; - block_rt(*b"FEid", data.clone()); - let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"FEid", data.clone())], ..Default::default() }; - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - // 36-byte signature, then `MIB8`, the reversed key and a u32 length: the block data. - let body = &little[36 + 12..]; - let mut swapped = len2.to_vec(); - swapped.reverse(); - assert_eq!(&body[second..second + 8], &swapped[..], "second section's length is little-endian"); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - assert_eq!(FilterEffects::parse(&back.global_blocks[0].data).unwrap(), fx); -} - -#[test] -fn metadata_setting_items() { - let desc = VersionedDescriptor::new(Descriptor::new("null")).to_bytes(); - let items = vec![crate::metadata::MetadataItem::new(*b"cmls", desc)]; - block_rt(*b"shmd", crate::metadata::write_shmd(&items)); - // An unknown item cannot be converted: it is dropped on its own, the rest stays. - let items = vec![ - crate::metadata::MetadataItem::new(*b"zzzz", vec![1, 2, 3, 4, 5, 6, 7, 8]), - crate::metadata::MetadataItem::new(*b"mdyn", vec![0, 0, 0, 1]), - crate::metadata::MetadataItem::new(*b"cmls", VersionedDescriptor::new(Descriptor::new("null")).to_bytes()), - ]; - let d = ImageSourceData { global_blocks: vec![TaggedBlock::new(*b"shmd", crate::metadata::write_shmd(&items))], ..Default::default() }; - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert_eq!(w.len(), 1, "{w:?}"); - assert!(w[0].starts_with("shmd item zzzz dropped"), "{}", w[0]); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty()); - let back_items = crate::metadata::parse_shmd(&back.global_blocks[0].data).unwrap(); - assert_eq!(back_items, items[1..].to_vec()); -} - -#[test] -fn unknown_descriptor_shaped_blocks_are_converted() { - // A key the transcoder has never heard of, holding a versioned descriptor (as every - // block Photoshop added since CS6 does): converted, not dropped. - let mut desc = Descriptor::new("null"); - desc.items.push((Id::new("Nm "), Value::Text(UnicodeString::new_nul("x")))); - let data = VersionedDescriptor::new(desc.clone()).to_bytes(); - block_rt(*b"Qqqq", data); - let mut with_version = 3u32.to_be_bytes().to_vec(); - with_version.extend(VersionedDescriptor::new(desc).to_bytes()); - block_rt(*b"Qqqq", with_version); - // Empty data needs no conversion either. - block_rt(*b"Mt32", Vec::new()); -} - -#[test] -fn linked_layer_items() { - // One embedded file (liFD, version 7) as photocraft-io writes it. - let mut item = Vec::new(); - item.put(b"liFD"); - item.put_u32(7); - item.put_u8(4); - item.put(b"uuid"); - let units: Vec = "a.png\0".encode_utf16().collect(); - item.put_u32(units.len() as u32); - for u in units { - item.put_u16(u); - } - item.put(b"png "); - item.put(b"8BIM"); - let bytes = [0x89, b'P', b'N', b'G', 1, 2, 3]; - item.put_u64(bytes.len() as u64); - item.put_u8(0); - item.put(&bytes); - item.put_u32(0); - item.put_f64(0.0); - item.put_u8(0); - let mut data = (item.len() as u64).to_be_bytes().to_vec(); - data.put(&item); - while !data.len().is_multiple_of(4) { - data.push(0); - } - let (_, little) = block_rt(*b"lnk2", data); - assert!(little.windows(4).any(|w| w == b"DFil"), "item type key reversed"); - assert!(little.windows(7).any(|w| w == bytes), "file bytes untouched"); -} - -#[test] -fn annotation_block() { - let mut a = Vec::new(); - a.put_u16(2); - a.put_u16(1); - a.put_u32(1); - let mut item = Vec::new(); - item.put(b"txtA"); - item.put_u8(0); - item.put_u8(1); - item.put_u16(0); - for v in [10, 20, 30, 40, 50, 60, 70, 80] { - item.put_i32(v); - } - item.put_u16(0); - for v in [0xffff, 0, 0, 0] { - item.put_u16(v); - } - for s in [&b"me"[..], b"note", b"2026"] { - item.put_u8(s.len() as u8); - item.put(s); - if (1 + s.len()) % 2 == 1 { - item.put_u8(0); - } - } - let text = [0xfe, 0xff, 0, b'h', 0, b'i']; - let mut d = Vec::new(); - d.put(b"txtC"); - d.put_u32(text.len() as u32); - d.put(&text); - item.put_u32(d.len() as u32 + 4); - item.put(&d); - a.put_u32(item.len() as u32 + 4); - a.put(&item); - let (_, little) = block_rt(*b"Anno", a); - assert!(little.windows(4).any(|w| w == b"Atxt")); - assert!(little.windows(6).any(|w| w == text), "text kept as stored"); -} - -#[test] -fn unknown_blocks_kept_in_big_dropped_in_little() { - let mut d = sample_layers(); - d.global_blocks.push(TaggedBlock::new(*b"Zzzz", vec![1, 2, 3, 4, 5])); - let (big, w) = d.to_bytes(ByteOrder::Big).unwrap(); - assert!(w.is_empty()); - let (back, w) = ImageSourceData::from_bytes(&big).unwrap(); - assert!(w.is_empty()); - assert_eq!(back.global_blocks, d.global_blocks); - // Big-endian data of unknown layout cannot go into a little-endian file. - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert_eq!(w.iter().filter(|w| w.starts_with("Zzzz block (5 bytes) dropped")).count(), 1, "{w:?}"); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty()); - assert_eq!(back.global_blocks.iter().map(|b| b.key).collect::>(), vec![*b"Patt", *b"FMsk"]); - assert_eq!(known(&back).layer_info, known(&d).layer_info); -} - -#[test] -fn unknown_blocks_from_a_little_endian_file_are_kept_with_their_byte_order() { - let d = sample_layers(); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - // A little-endian file with a block of unknown layout, among known ones. - let mut raw = little.clone(); - raw.extend_from_slice(b"MIB8zzzZ"); - raw.extend_from_slice(&6u32.to_le_bytes()); - raw.extend_from_slice(&[9, 8, 7, 6, 5, 4, 0, 0]); - raw.extend_from_slice(b"MIB8diyl"); - raw.extend_from_slice(&4u32.to_le_bytes()); - raw.extend_from_slice(&7u32.to_le_bytes()); - let (back, w) = ImageSourceData::from_bytes(&raw).unwrap(); - assert!(w.is_empty(), "{w:?}"); - assert_eq!(known(&back).layer_info, known(&d).layer_info); - let kept = back.global_blocks.iter().find(|b| &b.key == b"Zzzz").expect("kept"); - assert!(kept.is_foreign_order()); - assert_eq!(kept.signature, *b"MIB8"); - assert_eq!(kept.data, [9, 8, 7, 6, 5, 4]); - // The known block after it was still converted. - assert_eq!(back.global_blocks.iter().find(|b| &b.key == b"lyid").unwrap().data, 7u32.to_be_bytes()); - // Written back to a little-endian TIFF, the bytes are exactly what was read. - let (again, w) = back.to_bytes(ByteOrder::Little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - let tail = &raw[raw.len() - 18 - 16..]; - assert!(again.windows(tail.len()).any(|x| x == tail), "foreign-order block restored verbatim"); - assert_eq!(ImageSourceData::from_bytes(&again).unwrap().0.global_blocks, back.global_blocks); - // The big-endian (PSD) model keeps the marker, so a PSD writer can tell it apart. - let (big, _) = back.to_bytes(ByteOrder::Big).unwrap(); - assert!(big.windows(8).any(|x| x == b"MIB8Zzzz")); - assert_eq!(ImageSourceData::from_bytes(&big).unwrap().0.global_blocks, back.global_blocks); -} - -/// A PSB keeps `Mt16`/`Mt32`/`Mtrn`/`Alph` blocks of unknown layout verbatim, and their -/// length field is 8 bytes (a PSB long key). Writing them into a little-endian TIFF must -/// read that width; the old code looked the key up after reversing it for the target -/// order, which never matches `PSB_LONG_KEYS`. -#[test] -fn psb_foreign_order_long_key_roundtrips() { - let d = ImageSourceData { - version: Version::Psb, - byte_order: ByteOrder::Little, - global_blocks: vec![TaggedBlock { signature: *b"MIB8", key: *b"Mt16", data: vec![9, 8, 7, 6, 5, 4], padding: None }], - ..Default::default() - }; - let (little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert!(w.is_empty(), "{w:?}"); - assert_eq!(back.global_blocks, d.global_blocks, "the 8-byte length and the bytes survive"); -} - -#[test] -fn rle_counts_follow_the_container_and_samples_do_not() { - let file = testgen::layered(Version::Psd, ColorMode::Rgb, 16, Compression::Rle); - let d = ImageSourceData::from_psd(&file); - let (big, _) = d.to_bytes(ByteOrder::Big).unwrap(); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - let d = known(&d); - let (a, b) = (d.layer_info.as_ref().unwrap(), back.layer_info.as_ref().unwrap()); - for (la, lb) in a.layers.iter().zip(&b.layers) { - for (ca, cb) in la.channels.iter().zip(&lb.channels) { - assert_eq!(ca, cb); - let (w, h) = la.channel_rect(ca.id).size().unwrap(); - assert_eq!(ca.decode(w, h, 16, Version::Psd).unwrap(), cb.decode(w, h, 16, Version::Psd).unwrap()); - } - } - // The encoded samples (after the count table) are identical bytes in both files, while - // the count table itself is swapped. - let (rec, ch) = a - .layers - .iter() - .flat_map(|l| l.channels.iter().filter(|c| c.id >= -1 && c.compression == Some(Compression::Rle)).map(move |c| (l, c))) - .find(|(l, c)| l.rect.height() > 1 && c.data.len() > l.rect.height() as usize * 2 + 8) - .unwrap(); - let table = rec.rect.height() as usize * 2; - let samples = &ch.data[table..]; - assert!(big.windows(samples.len()).any(|w| w == samples)); - assert!(little.windows(samples.len()).any(|w| w == samples)); - let counts = &ch.data[..table]; - let swapped: Vec = counts.chunks(2).flat_map(|c| [c[1], c[0]]).collect(); - assert!(little.windows(table + samples.len()).any(|w| w[..table] == swapped[..] && w[table..] == *samples)); -} - -#[test] -fn blending_ranges_are_bytes_in_either_order() { - let mut file = testgen::layered(Version::Psd, ColorMode::Rgb, 8, Compression::Rle); - let ranges: Vec = [0u8, 0, 255, 255].repeat(10); - let marked: Vec = (1u8..=40).collect(); - for (i, l) in file.layer_info.as_mut().unwrap().layers.iter_mut().enumerate() { - l.blending_ranges.data = if i == 0 { marked.clone() } else { ranges.clone() }; - } - let d = ImageSourceData::from_psd(&file); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - // Written verbatim (what Photoshop writes in an `II` TIFF), not swapped per u32. - assert!(little.windows(marked.len()).any(|w| w == marked)); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - for (a, b) in d.layer_info.as_ref().unwrap().layers.iter().zip(&back.layer_info.as_ref().unwrap().layers) { - assert_eq!(a.blending_ranges, b.blending_ranges); - } -} - -#[test] -fn psb_sized_data_uses_long_lengths_and_counts() { - let file = testgen::layered(Version::Psb, ColorMode::Cmyk, 8, Compression::Rle); - let d = ImageSourceData::from_psd(&file); - assert_eq!(d.version, Version::Psb); - let back = roundtrip(&d); - assert_eq!(back.layer_info, d.layer_info); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(little[36..].starts_with(b"MIB8")); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(known(&back).layer_info, known(&d).layer_info); -} - -#[test] -fn resources_both_orders() { - let res = vec![ - ImageResource::new(1005, vec![0, 72, 0, 0, 0, 1, 0, 1, 0, 72, 0, 0, 0, 1, 0, 1]), - ImageResource::new(1037, vec![0, 0, 0, 120]), - ImageResource::new(1039, vec![1, 2, 3]), - ImageResource { signature: *b"8BIM", id: 1026, name: b"grp".to_vec(), data: vec![0, 1, 0, 1, 0, 0] }, - ]; - let big = resources_to_bytes(&res).unwrap(); - let (back, w) = resources_from_bytes(&big).unwrap(); - assert!(w.is_empty()); - assert_eq!(back, res); - let (little, w) = transcode_resources(&big, ByteOrder::Big, ByteOrder::Little).unwrap(); - assert!(w.is_empty()); - assert!(little.starts_with(b"MIB8")); - assert_eq!(little.len(), big.len()); - assert_eq!(&little[4..6], &[0xed, 3]); - let (back, w) = resources_from_bytes(&little).unwrap(); - assert!(w.is_empty()); - assert_eq!(back, res); - // The ICC blob is untouched by the swap. - assert!(little.windows(3).any(|w| w == [1, 2, 3])); - // An odd trailing pad byte is tolerated. - let mut padded = big.clone(); - padded.push(0); - assert_eq!(resources_from_bytes(&padded).unwrap().0, res); -} - -#[test] -fn malformed_input_errors_without_panicking() { - assert!(ImageSourceData::from_bytes(b"").is_err()); - assert!(ImageSourceData::from_bytes(b"Adobe Photoshop Document Data Block").is_err()); - let mut bad = SIGNATURE.to_vec(); - bad.extend_from_slice(b"XXXXLayr"); - assert!(ImageSourceData::from_bytes(&bad).is_err()); - let d = sample_layers(); - for order in [ByteOrder::Big, ByteOrder::Little] { - let (bytes, _) = d.to_bytes(order).unwrap(); - for cut in (0..bytes.len()).step_by(7).chain(bytes.len().saturating_sub(8)..bytes.len()) { - let _ = ImageSourceData::from_bytes(&bytes[..cut]); - } - // Bit flips in the structure (not the signature). - for i in (36..bytes.len()).step_by(13) { - let mut b = bytes.clone(); - b[i] ^= 0x5a; - let _ = ImageSourceData::from_bytes(&b); - } - } - // A block that claims more data than exists. - let mut huge = SIGNATURE.to_vec(); - huge.extend_from_slice(b"8BIMluni"); - huge.extend_from_slice(&u32::MAX.to_be_bytes()); - assert!(ImageSourceData::from_bytes(&huge).is_err()); - assert!(resources_from_bytes(b"8BIM\x03\xed\x00").is_err()); -} - -#[test] -fn into_psd_roundtrips_through_the_psd_writer() { - let file = testgen::layered(Version::Psd, ColorMode::Grayscale, 8, Compression::Zip); - let d = ImageSourceData::from_psd(&file); - let (little, _) = d.to_bytes(ByteOrder::Little).unwrap(); - let (back, _) = ImageSourceData::from_bytes(&little).unwrap(); - let psd = back.into_psd(file.header.clone(), file.resources.clone(), file.image_data.clone()); - let bytes = psd.to_bytes().unwrap(); - let again = PsdFile::from_bytes(&bytes).unwrap(); - let expected = known(&ImageSourceData::from_psd(&file)); - assert_eq!(known(&ImageSourceData::from_psd(&again)).layer_info, expected.layer_info); - assert_eq!(again.global_blocks, expected.global_blocks); - assert_eq!(again.layer_tree().len(), file.layer_tree().len()); -} - -/// Global blocks are padded as they are written, not on a copy: the bytes are those of the -/// former path (each block cloned with explicit padding to 4, written with `write_blocks`). -#[test] -fn global_blocks_written_without_copies_keep_their_bytes() { - for version in [Version::Psd, Version::Psb] { - let mut d = ImageSourceData { version, global_layer_mask: Some(GlobalLayerMask { data: vec![0, 1, 0, 2, 0, 3, 0, 4, 9] }), ..Default::default() }; - for n in 0..8u8 { - d.global_blocks.push(TaggedBlock::new(*b"FMsk", (0..n).collect())); - } - let mut explicit = TaggedBlock::new(*b"FMsk", vec![1, 2, 3]); - explicit.padding = Some(vec![]); - d.global_blocks.push(explicit); - let mut odd = TaggedBlock::new(*b"FMsk", vec![1, 2]); - odd.padding = Some(vec![0, 0, 0, 0, 0]); - d.global_blocks.push(odd); - let mut copies = vec![padded_block(*b"LMsk", d.global_layer_mask.as_ref().unwrap().data.clone())]; - for b in &d.global_blocks { - let mut b = b.clone(); - if b.padding.is_none() { - b.padding = Some(vec![0; (4 - b.data.len() % 4) % 4]); - } - copies.push(b); - } - let mut body = Vec::new(); - crate::tagged::write_blocks(&mut body, &copies, version, 2).unwrap(); - let signature = if version.is_psb() { SIGNATURE_PSB } else { SIGNATURE }; - assert_eq!(d.to_bytes(ByteOrder::Big).unwrap().0, [signature, &body[..]].concat()); - let (little, _) = transcode_blocks(&body, version, ByteOrder::Big, ByteOrder::Little).unwrap(); - assert_eq!(d.to_bytes(ByteOrder::Little).unwrap().0, [signature, &little[..]].concat()); - // Converted behind the signature in the buffer it starts with: never grown (growing - // would at least double it), so the body is not moved to make room. - let (after, _) = transcode_blocks_after(signature, &body, version, ByteOrder::Big, ByteOrder::Little).unwrap(); - assert_eq!(after, [signature, &little[..]].concat()); - assert_eq!(after.capacity(), signature.len() + body.len()); - } -} - -/// Nested structures are transcoded into one shared buffer. A block whose body fails -/// part-way leaves no partial bytes: dropped on the way out (with the enclosing lengths -/// patched as if it had never been there), or kept exactly as stored on the way in. -#[test] -fn a_nested_block_that_fails_part_way_leaves_nothing_behind() { - let clean = sample_layers(); - let mut fx = Vec::new(); - fx.put_u32(0); - fx.extend_from_slice(&VersionedDescriptor::new(Descriptor::new("null").with("Opct", Value::Double(1.0))).to_bytes()); - // A whole number of 4-byte units, so dropping it cannot change any padding. - fx.resize(fx.len().next_multiple_of(4), 0); - let mut d = clean.clone(); - d.layer_info.as_mut().unwrap().layers[0].blocks.insert(0, TaggedBlock::new(*b"lfx2", fx.clone())); - let (mut little, w) = d.to_bytes(ByteOrder::Little).unwrap(); - assert!(!w.iter().any(|w| w.starts_with("lfx2")), "{w:?}"); - // An unknown value type after the descriptor's header: parsing fails part-way. - let at = little.windows(4).position(|w| w == b"buod").unwrap(); - little[at..at + 4].copy_from_slice(b"????"); - let (back, w) = ImageSourceData::from_bytes(&little).unwrap(); - assert_eq!(w.iter().filter(|w| w.starts_with("lfx2 block")).count(), 1, "{w:?}"); - let kept = &back.layer_info.as_ref().unwrap().layers[0].blocks[0]; - assert!(kept.is_foreign_order()); - let stored = little.windows(4).position(|w| w == b"2xfl").unwrap() + 8; - assert_eq!(kept.data, little[stored..stored + fx.len()]); - // Big-endian data that fails part-way cannot go into a little-endian file: dropped. - let mut big_bad = d.clone(); - let mut broken = fx.clone(); - let at = broken.windows(4).position(|w| w == b"doub").unwrap(); - broken[at..at + 4].copy_from_slice(b"????"); - big_bad.layer_info.as_mut().unwrap().layers[0].blocks[0].data = broken; - let (little, w) = big_bad.to_bytes(ByteOrder::Little).unwrap(); - assert_eq!(w.iter().filter(|w| w.starts_with("lfx2 block")).count(), 1, "{w:?}"); - assert_eq!(little, clean.to_bytes(ByteOrder::Little).unwrap().0); -} diff --git a/crates/psd/src/tiff/transcode.rs b/crates/psd/src/tiff/transcode.rs deleted file mode 100644 index 15c33d4a9d..0000000000 --- a/crates/psd/src/tiff/transcode.rs +++ /dev/null @@ -1,1399 +0,0 @@ -use super::{ByteOrder, LayerMask, MAX_DEPTH, PsdError, Reader, Result, TaggedBlock, Version, mask_parameter_bytes, uses_long_length}; - -/// Converts the tagged blocks after the 37724 header string from `from` to `to`. -pub fn transcode_blocks(data: &[u8], version: Version, from: ByteOrder, to: ByteOrder) -> Result<(Vec, Vec)> { - let mut t = Tx::new(data, version, from, to); - t.blocks()?; - Ok(t.finish()) -} - -/// [`transcode_blocks`] written after `prefix`, in one buffer sized for both. -pub fn transcode_blocks_after(prefix: &[u8], data: &[u8], version: Version, from: ByteOrder, to: ByteOrder) -> Result<(Vec, Vec)> { - let mut out = Vec::new(); - out.try_reserve_exact(prefix.len().saturating_add(data.len())).map_err(|_| PsdError::OutOfMemory("not enough memory for the layer data"))?; - out.extend_from_slice(prefix); - let mut t = Tx::appending(out, data, version, from, to); - t.blocks()?; - Ok(t.finish()) -} - -/// Converts a layer-info body (the data of a `Layr` / `Lr16` / `Lr32` block) between orders. -pub fn transcode_layer_info(data: &[u8], version: Version, from: ByteOrder, to: ByteOrder) -> Result<(Vec, Vec)> { - let mut t = Tx::new(data, version, from, to); - t.layer_info()?; - Ok(t.finish()) -} - -/// Converts image-resource blocks (a 34377 tag) between orders. -pub fn transcode_resources(data: &[u8], from: ByteOrder, to: ByteOrder) -> Result<(Vec, Vec)> { - let mut t = Tx::new(data, Version::Psd, from, to); - t.resources()?; - Ok(t.finish()) -} - -/// A block signature as stored in `little` or big-endian data. Big-endian data (the model) -/// also carries the `MIB8` / `46B8` markers of blocks kept from a little-endian file. -fn is_sig(b: &[u8], little: bool) -> bool { - if little { - b.starts_with(b"MIB8") || b.starts_with(b"46B8") - } else { - b.starts_with(b"8BIM") || b.starts_with(b"8B64") || TaggedBlock::is_foreign_order_signature(b) - } -} - -fn height(top: i32, bottom: i32) -> usize { - usize::try_from(bottom.saturating_sub(top)).unwrap_or(0) -} - -/// Per layer record: the channel (id, length) list and the heights of the layer, mask and -/// real-mask rects. -type RecordShape = (Vec<(i16, u64)>, [usize; 3]); - -struct Tx<'a> { - r: Reader<'a>, - out: Vec, - from: ByteOrder, - to: ByteOrder, - version: Version, - warnings: Vec, - depth: usize, -} - -macro_rules! copy_int { - ($name:ident, $ty:ty) => { - fn $name(&mut self) -> Result<$ty> { - let v = self.r.$name()?; - self.out.extend_from_slice(&if self.to.is_little() { v.to_le_bytes() } else { v.to_be_bytes() }); - Ok(v) - } - }; -} - -impl<'a> Tx<'a> { - fn new(data: &'a [u8], version: Version, from: ByteOrder, to: ByteOrder) -> Self { - Self::appending(Vec::with_capacity(data.len()), data, version, from, to) - } - - /// A walker that appends to `out`. - fn appending(out: Vec, data: &'a [u8], version: Version, from: ByteOrder, to: ByteOrder) -> Self { - let r = if from.is_little() { Reader::new_little(data) } else { Reader::new(data) }; - Tx { r, out, from, to, version, warnings: Vec::new(), depth: 0 } - } - - fn finish(self) -> (Vec, Vec) { - (self.out, self.warnings) - } - - /// A walker over `data` (a nested structure) that writes into this walker's output: it - /// takes the buffer, so a nested structure is written once, not copied up per level. Hand - /// the buffer back with [`Self::adopt`] before returning, error or not. - fn nested<'b>(&mut self, data: &'b [u8], depth: usize) -> Tx<'b> { - let r = if self.from.is_little() { Reader::new_little(data) } else { Reader::new(data) }; - Tx { r, out: std::mem::take(&mut self.out), from: self.from, to: self.to, version: self.version, warnings: Vec::new(), depth } - } - - /// Takes the output buffer back from a [`Self::nested`] walker. - fn adopt(&mut self, child: &mut Tx<'_>) { - self.out = std::mem::take(&mut child.out); - } - - fn same_order(&self) -> bool { - self.from == self.to - } - - fn remaining(&self) -> usize { - self.r.remaining() - } - - copy_int!(u16, u16); - copy_int!(i16, i16); - copy_int!(u32, u32); - copy_int!(i32, i32); - copy_int!(u64, u64); - copy_int!(i64, i64); - copy_int!(f64, f64); - - fn u8(&mut self) -> Result { - let v = self.r.u8()?; - self.out.push(v); - Ok(v) - } - - fn f32(&mut self) -> Result<()> { - let b = self.r.array::<4>()?; - let v = if self.from.is_little() { f32::from_le_bytes(b) } else { f32::from_be_bytes(b) }; - self.out.extend_from_slice(&if self.to.is_little() { v.to_le_bytes() } else { v.to_be_bytes() }); - Ok(()) - } - - /// Bytes copied as they are. - fn raw(&mut self, n: usize) -> Result<()> { - let b = self.r.bytes(n)?; - self.out.extend_from_slice(b); - Ok(()) - } - - fn rest(&mut self) -> Result<()> { - let n = self.remaining(); - self.raw(n) - } - - /// A four-character signature or key: stored reversed in little-endian data. Returns the - /// canonical (big-endian) spelling. - fn key(&mut self) -> Result<[u8; 4]> { - let mut k = self.r.array::<4>()?; - if self.from.is_little() { - k.reverse(); - } - let mut w = k; - if self.to.is_little() { - w.reverse(); - } - self.out.extend_from_slice(&w); - Ok(k) - } - - fn len(&mut self, long: bool) -> Result { - if long { self.u64() } else { Ok(u64::from(self.u32()?)) } - } - - fn u16s(&mut self, n: usize) -> Result<()> { - for _ in 0..n { - self.u16()?; - } - Ok(()) - } - - /// Up to `n` `u16`s: a block shorter than its full layout keeps what it has. - fn u16s_upto(&mut self, n: usize) -> Result<()> { - for _ in 0..n { - if self.remaining() < 2 { - break; - } - self.u16()?; - } - Ok(()) - } - - fn i32s(&mut self, n: usize) -> Result<()> { - for _ in 0..n { - self.i32()?; - } - Ok(()) - } - - fn f64s(&mut self, n: usize) -> Result<()> { - for _ in 0..n { - self.f64()?; - } - Ok(()) - } - - /// `u16`s to the end (a lone odd byte is copied). - fn u16s_to_end(&mut self) -> Result<()> { - while self.remaining() >= 2 { - self.u16()?; - } - self.rest() - } - - fn u32s_to_end(&mut self) -> Result<()> { - while self.remaining() >= 4 { - self.u32()?; - } - self.rest() - } - - /// A Photoshop Unicode string: u32 count + UTF-16 units. - fn unicode(&mut self) -> Result<()> { - let n = self.u32()?; - self.r.check_count(u64::from(n), 2)?; - self.u16s(n as usize) - } - - /// A Pascal string padded to `align`. - fn pascal(&mut self, align: usize) -> Result<()> { - let n = usize::from(self.u8()?); - self.raw(n)?; - let total = 1 + n; - self.raw((align - total % align) % align) - } - - /// Transcodes the next `len` bytes with `f`; whatever `f` leaves is copied verbatim. - fn region(&mut self, len: u64, f: impl FnOnce(&mut Tx<'_>) -> Result<()>) -> Result<()> { - let data = self.r.bytes_u64(len)?; - let start = self.out.len(); - let mut child = self.nested(data, self.depth); - let res = f(&mut child).and_then(|()| child.rest()); - self.adopt(&mut child); - res?; - if self.out.len() - start != data.len() { - return Err(PsdError::invalid("byte-order conversion changed a structure's length")); - } - self.warnings.append(&mut child.warnings); - Ok(()) - } - - /// Reads a length field (4 bytes, or 8 when `long`), transcodes that many bytes with `f` - /// and writes the length of the result: blocks dropped inside shrink the field. - fn sized_region(&mut self, long: bool, f: impl FnOnce(&mut Tx<'_>) -> Result<()>) -> Result<()> { - self.sized_region_counting(long, false, f) - } - - /// [`Self::sized_region`] for a u32 length that counts its own 4 bytes. - fn sized_region_inclusive(&mut self, f: impl FnOnce(&mut Tx<'_>) -> Result<()>) -> Result<()> { - self.sized_region_counting(false, true, f) - } - - fn sized_region_counting(&mut self, long: bool, inclusive: bool, f: impl FnOnce(&mut Tx<'_>) -> Result<()>) -> Result<()> { - let mut len = self.r.len_field(long)?; - let at = self.out.len(); - self.out.extend_from_slice(if long { &[0u8; 8] } else { &[0u8; 4] }); - if inclusive { - len = len.checked_sub(4).ok_or_else(|| PsdError::invalid("length shorter than its own field"))?; - } - let data = self.r.bytes_u64(len)?; - let start = self.out.len(); - let mut child = self.nested(data, self.depth); - let res = f(&mut child).and_then(|()| child.rest()); - self.adopt(&mut child); - res?; - self.warnings.append(&mut child.warnings); - self.patch_len(at, long, (self.out.len() - start) as u64 + if inclusive { 4 } else { 0 })?; - Ok(()) - } - - /// Tries `f` on the rest of the data; it counts as a match only when at most three - /// trailing zero bytes are left. On a miss nothing is consumed or written. - fn attempt(&mut self, f: impl FnOnce(&mut Tx<'_>) -> Result<()>) -> bool { - let (reader, written) = (self.r.clone(), self.out.len()); - let ok = f(self).is_ok() && self.remaining() <= 3 && self.r.peek_rest().iter().all(|&b| b == 0); - if !ok { - self.r = reader; - self.out.truncate(written); - } - ok - } - - /// Blocks whose layout is not known by key are very often a versioned descriptor, - /// optionally behind a u32 version (every Photoshop block introduced since CS6 is): - /// recognized by parsing to the end. - fn descriptor_shaped(&mut self) -> bool { - self.attempt(|t| t.versioned_descriptor()) - || self.attempt(|t| { - t.u32()?; - t.versioned_descriptor() - }) - } - - /// Writes `n` into the length placeholder at `at`. - fn patch_len(&mut self, at: usize, long: bool, n: u64) -> Result<()> { - if long { - let b = if self.to.is_little() { n.to_le_bytes() } else { n.to_be_bytes() }; - if let Some(slot) = self.out.get_mut(at..at + 8) { - slot.copy_from_slice(&b); - } - } else { - let n = u32::try_from(n).map_err(|_| PsdError::LimitExceeded("structure too large for a 32-bit length"))?; - let b = if self.to.is_little() { n.to_le_bytes() } else { n.to_be_bytes() }; - if let Some(slot) = self.out.get_mut(at..at + 4) { - slot.copy_from_slice(&b); - } - } - Ok(()) - } - - /// An RLE row-count table (`rows` entries of 2 bytes, 4 in PSB data). - fn rle_counts(&mut self, rows: usize) -> Result<()> { - for _ in 0..rows { - if self.version.is_psb() { - if self.remaining() < 4 { - break; - } - self.u32()?; - } else { - if self.remaining() < 2 { - break; - } - self.u16()?; - } - } - Ok(()) - } - - /// Encoded channel data for a plane of `rows` rows: the compression field, then the RLE - /// row counts (container order) and the samples (always big-endian: copied). - fn channel_data(&mut self, rows: usize, long_counts: bool) -> Result<()> { - let saved = self.version; - if long_counts { - self.version = Version::Psb; - } - let compression = self.u16()?; - let res = if compression == 1 { self.rle_counts(rows) } else { Ok(()) }; - self.version = saved; - res?; - self.rest() - } - - // ---- image resources (34377) ---- - - fn resources(&mut self) -> Result<()> { - while self.remaining() >= 12 && is_sig(self.r.peek_rest(), self.from.is_little()) { - self.key()?; - let id = self.u16()?; - self.pascal(2)?; - let odd = self.r.clone().u32()? % 2 == 1; - self.sized_region(false, |t| t.resource_data(id))?; - if odd && self.remaining() > 0 { - self.raw(1)?; - } - } - self.rest() - } - - /// Typed numeric resources; every other payload is a byte blob (ICC, XMP, EXIF, …) or - /// unknown and is copied as stored. - fn resource_data(&mut self, id: u16) -> Result<()> { - match id { - // Resolution info: fixed 16.16 h res, u16 unit, u16 width unit, then the same for v. - 1005 => { - self.u32()?; - self.u16()?; - self.u16()?; - self.u32()?; - self.u16()?; - self.u16()?; - } - // Layer state (u16 target), layer group info (u16 per layer). - 1024 | 1026 => self.u16s_to_end()?, - // Global angle / altitude. - 1037 | 1049 => { - self.u32()?; - } - // Layer selection ids: u16 count + u32 ids. - 1069 => { - self.u16()?; - self.u32s_to_end()?; - } - // Version info: u32 version, u8 has real merged data, two Unicode strings, u32. - 1057 => { - self.u32()?; - self.u8()?; - self.unicode()?; - self.unicode()?; - self.u32()?; - } - // Grid and guides: u32 version, 2 × u32 grid, u32 count, (u32 location, u8 direction)… - 1032 => { - self.u32()?; - self.u32()?; - self.u32()?; - let n = self.u32()?; - for _ in 0..n { - if self.remaining() < 5 { - break; - } - self.u32()?; - self.u8()?; - } - } - // Path resources: 26-byte records. - 2000..=2997 | 2999 => self.path_records()?, - _ => {} - } - Ok(()) - } - - // ---- tagged blocks ---- - - /// Tagged blocks to the end; bytes that do not form a block are copied. - fn blocks(&mut self) -> Result<()> { - loop { - let rest = self.r.peek_rest(); - if rest.len() < 12 || !is_sig(rest, self.from.is_little()) { - return self.rest(); - } - self.block()?; - } - } - - fn block(&mut self) -> Result<()> { - let before = self.out.len(); - // A `MIB8` / `46B8` marker in big-endian data: a block kept verbatim from a - // little-endian file. Written back as it was into little-endian output (its `8BIM` - // signature reversed, as every signature there), copied as is otherwise. - if !self.from.is_little() && TaggedBlock::is_foreign_order_signature(self.r.peek_rest()) { - let sig = self.r.array::<4>()?; - let mut key = self.r.array::<4>()?; - // Only reached with `from == Big`: the key is canonical here whatever the - // target order. `TaggedBlock::write` sizes the length field from that same key. - // Reversing it for the target order before the check - // asked about a key `PSB_LONG_KEYS` never contains, so a PSB long key's 8-byte - // length was read as 4 and every later block was copied unconverted. - let long = uses_long_length(self.version, &key); - let len = self.r.len_field(long)?; - let data = self.r.bytes_u64(len)?; - if self.to.is_little() { - key.reverse(); - } - self.out.extend_from_slice(&sig); - self.out.extend_from_slice(&key); - let n = self.out.len(); - self.out.extend_from_slice(if long { &[0u8; 8] } else { &[0u8; 4] }); - self.patch_len(n, long, len)?; - self.out.extend_from_slice(data); - let rest = self.r.peek_rest(); - let pad = (0..=3usize).find(|&k| k == rest.len() || (k < rest.len() && is_sig(&rest[k..], self.from.is_little()))).unwrap_or(0); - let pad_bytes = self.r.bytes(pad)?; - self.out.extend_from_slice(pad_bytes); - return Ok(()); - } - let sig_at = self.out.len(); - let sig = self.key()?; - let key = self.key()?; - let long = uses_long_length(self.version, &key); - let len = self.r.len_field(long)?; - let len_at = self.out.len(); - self.out.extend_from_slice(if long { &[0u8; 8] } else { &[0u8; 4] }); - let data = self.r.bytes_u64(len)?; - // The body is transcoded straight into this output, after the length placeholder. - let data_at = self.out.len(); - let mut child = self.nested(data, self.depth + 1); - let handled = if child.depth > MAX_DEPTH { - Err(PsdError::LimitExceeded("tagged block nesting too deep")) - } else if data.is_empty() { - Ok(true) - } else { - child.block_body(&key) - }; - let rest = if matches!(handled, Ok(true)) { child.rest() } else { Ok(()) }; - self.adopt(&mut child); - rest?; - if !matches!(handled, Ok(true)) { - // A body that was not transcoded leaves nothing: it is copied as stored or dropped. - self.out.truncate(data_at); - } - // Padding: the smallest k in 0..=3 after which the next block (or the end) starts. - let rest = self.r.peek_rest(); - let pad = (0..=3usize).find(|&k| k == rest.len() || (k < rest.len() && is_sig(&rest[k..], self.from.is_little()))).unwrap_or(0); - let pad_bytes = self.r.bytes(pad)?; - match handled { - Ok(true) => { - self.warnings.append(&mut child.warnings); - self.patch_len(len_at, long, (self.out.len() - data_at) as u64)?; - self.out.extend_from_slice(pad_bytes); - } - Ok(false) if self.same_order() => { - self.patch_len(len_at, long, data.len() as u64)?; - self.out.extend_from_slice(data); - self.out.extend_from_slice(pad_bytes); - } - // Little-endian in, big-endian model: keep the bytes as they are, marked. - Ok(false) if self.from.is_little() => { - let marker: &[u8; 4] = if &sig == b"8B64" { b"46B8" } else { b"MIB8" }; - self.out[sig_at..sig_at + 4].copy_from_slice(marker); - self.patch_len(len_at, long, data.len() as u64)?; - self.out.extend_from_slice(data); - self.out.extend_from_slice(pad_bytes); - } - Ok(false) => { - self.out.truncate(before); - self.warnings.push(format!( - "{} block ({} bytes) dropped: its layout is unknown and cannot be converted to the file's byte order", - String::from_utf8_lossy(&key), - data.len() - )); - } - Err(e) if self.same_order() => return Err(PsdError::invalid(format!("{} block: {e}", String::from_utf8_lossy(&key)))), - Err(e) if self.from.is_little() => { - let marker: &[u8; 4] = if &sig == b"8B64" { b"46B8" } else { b"MIB8" }; - self.out[sig_at..sig_at + 4].copy_from_slice(marker); - self.patch_len(len_at, long, data.len() as u64)?; - self.out.extend_from_slice(data); - self.out.extend_from_slice(pad_bytes); - self.warnings.push(format!("{} block ({} bytes) kept as stored, in little-endian layout: {e}", String::from_utf8_lossy(&key), data.len())); - } - Err(e) => { - self.out.truncate(before); - self.warnings.push(format!("{} block ({} bytes) dropped: {e}", String::from_utf8_lossy(&key), data.len())); - } - } - Ok(()) - } - - /// Transcodes a block's data by key. `Ok(false)` for keys without a known layout. - fn block_body(&mut self, key: &[u8; 4]) -> Result { - match key { - b"Layr" | b"Lr16" | b"Lr32" => self.layer_info()?, - b"luni" => self.unicode()?, - b"lsct" | b"lsdk" => { - self.u32()?; - if self.remaining() >= 8 { - self.key()?; - self.key()?; - } - if self.remaining() >= 4 { - self.u32()?; - } - } - // lyvr layer version, sn2P and vowv (shape and vector flags). - b"lyid" | b"lspf" | b"lyvr" | b"sn2P" | b"vowv" => { - self.u32()?; - } - // Text-engine global data: a textual structure, no byte order. - b"Txt2" => self.rest()?, - b"lnsr" => { - self.key()?; - } - // Advanced Blending flags and fill opacity: one byte, then padding (Adobe spec, - // "Additional Layer Information"; `lmgm`/`vmgm` = layer/vector mask hides effects). - b"clbl" | b"infx" | b"knko" | b"tsly" | b"lmgm" | b"vmgm" | b"iOpa" => { - self.u8()?; - } - b"lclr" => self.u16s_upto(4)?, - b"fxrp" => { - while self.remaining() >= 8 { - self.f64()?; - } - } - b"brst" => self.u32s_to_end()?, - b"LMsk" => self.u16s_upto(6)?, - b"FMsk" => self.u16s_to_end()?, - b"shmd" => self.metadata_setting()?, - // Effects (lfxs: the effects as applied to a group), content credentials (CAI). - b"lfx2" | b"lmfx" | b"lfxs" | b"CAI " => { - self.u32()?; - self.versioned_descriptor()?; - } - b"SoCo" | b"GdFl" | b"PtFl" | b"vstk" | b"blwh" | b"vibA" | b"CgEd" | b"artb" | b"artd" | b"cinf" | b"cust" | b"PxSD" | b"GenI" | b"OCIO" - | b"extn" | b"pths" => { - self.versioned_descriptor()?; - } - // Color Lookup: u16 version, then the descriptor. - b"clrL" => { - self.u16()?; - self.versioned_descriptor()?; - } - b"lnk2" | b"lnk3" | b"lnkD" | b"lnkE" => self.linked_layers()?, - b"Anno" => self.annotations()?, - b"vogk" => { - self.u32()?; - self.versioned_descriptor()?; - } - b"vscg" => { - self.key()?; - self.versioned_descriptor()?; - } - b"SoLd" | b"SoLE" => { - self.key()?; - self.u32()?; - self.versioned_descriptor()?; - } - b"PlLd" => { - self.key()?; - self.u32()?; - self.pascal(1)?; - for _ in 0..4 { - self.u32()?; - } - self.f64s(8)?; - self.u32()?; - self.versioned_descriptor()?; - } - // Type: version, transform, text version + descriptor, warp version + descriptor, - // and the bounds as four 32-bit values (the specification says doubles; Photoshop - // writes 16 bytes). - b"TySh" => self.type_layer()?, - b"vmsk" | b"vsms" => { - self.u32()?; - self.u32()?; - self.path_records()?; - } - b"Patt" | b"Pat2" | b"Pat3" => { - while self.remaining() >= 4 { - let len = self.r.clone().u32()?; - if len == 0 { - self.u32()?; - continue; - } - self.sized_region(false, Tx::pattern)?; - // Each pattern is padded to a multiple of 4. - let pad = ((4 - len % 4) % 4) as usize; - self.raw(pad.min(self.remaining()))?; - } - } - b"FEid" | b"FXid" => self.filter_effects()?, - b"lrFX" => self.legacy_effects()?, - b"levl" => { - self.u16()?; - for _ in 0..29 * 5 { - if self.remaining() < 2 { - break; - } - self.u16()?; - } - if self.remaining() >= 4 { - self.key()?; - } - self.u16s_to_end()?; - } - b"curv" => self.curves()?, - b"hue2" => { - self.u16()?; - self.u8()?; - self.u8()?; - self.u16s_to_end()?; - } - b"brit" => self.u16s_upto(3)?, - b"thrs" | b"post" => { - self.u16()?; - } - b"nvrt" => {} - b"expA" => { - self.u16()?; - for _ in 0..3 { - self.f32()?; - } - } - b"blnc" => self.u16s_upto(9)?, - b"mixr" | b"selc" => self.u16s_to_end()?, - b"phfl" => match self.u16()? { - 2 => { - self.u16s(5)?; - self.u32()?; - self.u8()?; - } - 3 => { - for _ in 0..4 { - self.u32()?; - } - self.u8()?; - } - v => return Err(PsdError::Unsupported(format!("photo filter version {v}"))), - }, - b"grdm" => self.gradient_map()?, - _ if !self.same_order() => return Ok(self.descriptor_shaped()), - _ => return Ok(false), - } - Ok(true) - } - - /// `lnk2` / `lnk3` / `lnkD` / `lnkE` (linked and embedded smart-object files): items of - /// u64 length + data, each padded to 4. Item: type (`liFD` embedded, `liFE` external, - /// `liFA` alias), version 1–7, Pascal uuid, Unicode name, file type and creator keys, u64 - /// data length, open-descriptor flag (+ descriptor), per-type fields, the file bytes for - /// `liFD`, then the fields later versions added. - fn linked_layers(&mut self) -> Result<()> { - while self.remaining() >= 8 { - let len = self.r.clone().u64()?; - self.sized_region(true, |t| { - let kind = t.key()?; - let version = t.u32()?; - t.pascal(1)?; - t.unicode()?; - t.key()?; - t.key()?; - let data_len = t.u64()?; - if t.u8()? != 0 { - t.versioned_descriptor()?; - } - if &kind == b"liFE" && version > 3 { - t.i32()?; - for _ in 0..4 { - t.u8()?; - } - t.f64()?; - } - if &kind == b"liFE" { - t.u64()?; - } - if &kind == b"liFA" { - t.raw(8)?; - } - let data_len = usize::try_from(data_len).map_err(|_| PsdError::LimitExceeded("linked file length"))?; - if &kind == b"liFD" { - t.raw(data_len)?; - } - if version >= 5 { - t.unicode()?; - } - if version >= 6 { - t.f64()?; - } - if version >= 7 { - t.u8()?; - } - if &kind == b"liFE" && version == 2 { - t.raw(data_len)?; - } - Ok(()) - })?; - let pad = ((4 - len % 4) % 4) as usize; - self.raw(pad.min(self.remaining()))?; - } - Ok(()) - } - - /// `Anno`: u16 major, u16 minor, u32 count, then per annotation a self-counting u32 - /// length, type key, open and flags bytes, u16 optional blocks, icon and popup rects, a - /// colour, three even-padded Pascal strings, and a self-counting data block (key, u32 - /// size, text with its own byte-order mark). - fn annotations(&mut self) -> Result<()> { - self.u16()?; - self.u16()?; - let n = self.u32()?; - for _ in 0..n { - if self.remaining() < 4 { - break; - } - self.sized_region_inclusive(|t| { - t.key()?; - t.u8()?; - t.u8()?; - t.u16()?; - t.i32s(8)?; - t.u16s(5)?; - t.pascal(2)?; - t.pascal(2)?; - t.pascal(2)?; - t.sized_region_inclusive(|d| { - d.key()?; - d.u32()?; - Ok(()) - }) - })?; - } - Ok(()) - } - - // ---- layer info ---- - - fn layer_info(&mut self) -> Result<()> { - let count = self.i16()?; - let n = usize::from(count.unsigned_abs()); - self.r.check_count(n as u64, 34)?; - // Per layer: the channel ids and lengths, and the heights of the layer, mask and - // real-mask rects (what each channel's RLE count table spans). - let mut records: Vec = Vec::with_capacity(n); - for _ in 0..n { - let top = self.i32()?; - self.i32()?; - let bottom = self.i32()?; - self.i32()?; - let nch = self.u16()?; - if nch > crate::layer::MAX_LAYER_CHANNELS { - return Err(PsdError::LimitExceeded("too many channels in layer")); - } - let mut chans = Vec::with_capacity(usize::from(nch)); - let psb = self.version.is_psb(); - for _ in 0..nch { - let id = self.i16()?; - let len = self.len(psb)?; - chans.push((id, len)); - } - let sig = self.key()?; - if &sig != b"8BIM" { - return Err(PsdError::InvalidSignature { expected: "8BIM (layer blend mode)", found: sig }); - } - self.key()?; - for _ in 0..4 { - self.u8()?; - } - let mut heights = [height(top, bottom), 0, 0]; - let mut mask_heights = (0usize, 0usize); - self.sized_region(false, |t| { - let mut mh = (0, 0); - t.sized_region(false, |m| { - mh = m.mask()?; - Ok(()) - })?; - mask_heights = mh; - // Blending ranges are bytes (black low/high, white low/high per channel), so - // Photoshop stores them in the same order in either byte order: an Intel-order - // layered TIFF holds the default ranges as `00 00 ff ff`. Swapping them as u32s - // turned every range into `ff ff 00 00`, which hides every pixel of the layer. - t.sized_region(false, |x| x.rest())?; - t.pascal(4)?; - t.blocks() - })?; - heights[1] = mask_heights.0; - heights[2] = mask_heights.1; - records.push((chans, heights)); - } - for (chans, heights) in &records { - for &(id, len) in chans { - if len == 0 { - continue; - } - if len == 1 { - return Err(PsdError::invalid("channel data length 1")); - } - let rows = match id { - -2 => heights[1], - -3 => heights[2], - _ => heights[0], - }; - self.region(len, |t| t.channel_data(rows, false))?; - } - } - self.rest() - } - - /// A layer mask record. Returns the heights of the mask and real-mask rects. - fn mask(&mut self) -> Result<(usize, usize)> { - let whole = self.r.peek_rest(); - if whole.is_empty() { - return Ok((0, 0)); - } - let top = self.i32()?; - self.i32()?; - let bottom = self.i32()?; - self.i32()?; - self.u8()?; - let flags = self.u8()?; - let mut real_h = 0; - if self.remaining() <= 2 { - return Ok((height(top, bottom), 0)); - } - let has_parameters = flags & LayerMask::FLAG_PARAMETERS != 0; - // The helper only looks at lengths and the parameter-flags byte, so it reads the - // same in either order. - let real_first = has_parameters && LayerMask::real_before_parameters(whole); - let mut read_real = |t: &mut Tx<'_>| -> Result<()> { - if t.remaining() >= 18 { - t.u8()?; - t.u8()?; - let rt = t.i32()?; - t.i32()?; - let rb = t.i32()?; - t.i32()?; - real_h = height(rt, rb); - } - Ok(()) - }; - if real_first { - read_real(self)?; - } - if has_parameters { - let pf = self.u8()?; - let need = mask_parameter_bytes(pf); - if need > self.remaining() { - return Err(PsdError::UnexpectedEof { offset: self.r.pos(), needed: need - self.remaining() }); - } - if pf & 1 != 0 { - self.u8()?; - } - if pf & 2 != 0 { - self.f64()?; - } - if pf & 4 != 0 { - self.u8()?; - } - if pf & 8 != 0 { - self.f64()?; - } - } - if !real_first { - read_real(self)?; - } - Ok((height(top, bottom), real_h)) - } - - // ---- descriptors ---- - - /// Photoshop's Intel-order TIFF type blocks can use PSD byte order for the - /// text descriptor, then container order again for warp and bounds (#4758). - fn type_layer(&mut self) -> Result<()> { - self.u16()?; - self.f64s(6)?; - self.type_descriptor(50, ByteOrder::Big)?; - self.type_descriptor(1, self.to)?; - self.i32s(4) - } - - fn type_descriptor(&mut self, version: u16, to: ByteOrder) -> Result<()> { - let [hi, lo] = version.to_be_bytes(); - let from = if self.from.is_little() && self.r.peek_rest().starts_with(&[hi, lo, 0, 0, 0, 16]) { ByteOrder::Big } else { self.from }; - let data = self.r.peek_rest(); - let mut descriptor = Tx::new(data, self.version, from, to); - descriptor.depth = self.depth; - descriptor.u16()?; - descriptor.versioned_descriptor()?; - let used = data.len() - descriptor.remaining(); - self.r.bytes(used)?; - self.warnings.append(&mut descriptor.warnings); - self.out.extend_from_slice(&descriptor.out); - Ok(()) - } - - fn versioned_descriptor(&mut self) -> Result<()> { - self.u32()?; - self.descriptor() - } - - fn descriptor(&mut self) -> Result<()> { - if self.depth > MAX_DEPTH { - return Err(PsdError::LimitExceeded("descriptor nesting too deep")); - } - self.depth += 1; - self.unicode()?; - self.id()?; - let n = self.u32()?; - self.r.check_count(u64::from(n), 10)?; - for _ in 0..n { - self.id()?; - self.value()?; - } - self.depth -= 1; - Ok(()) - } - - fn id(&mut self) -> Result<()> { - let n = self.u32()?; - if n == 0 { - self.key()?; - } else { - self.raw(usize::try_from(n).map_err(|_| PsdError::LimitExceeded("id length"))?)?; - } - Ok(()) - } - - fn class(&mut self) -> Result<()> { - self.unicode()?; - self.id() - } - - fn value(&mut self) -> Result<()> { - if self.depth > MAX_DEPTH { - return Err(PsdError::LimitExceeded("descriptor nesting too deep")); - } - let ty = self.key()?; - match &ty { - b"obj " => { - let n = self.u32()?; - self.r.check_count(u64::from(n), 8)?; - for _ in 0..n { - self.reference_item()?; - } - } - b"Objc" | b"GlbO" => self.descriptor()?, - b"VlLs" => { - let n = self.u32()?; - self.r.check_count(u64::from(n), 4)?; - self.depth += 1; - for _ in 0..n { - self.value()?; - } - self.depth -= 1; - } - b"doub" => { - self.f64()?; - } - b"UntF" => { - self.key()?; - self.f64()?; - } - b"UnFl" => { - self.key()?; - let n = self.u32()?; - self.r.check_count(u64::from(n), 8)?; - self.f64s(n as usize)?; - } - b"TEXT" => self.unicode()?, - b"enum" => { - self.id()?; - self.id()?; - } - b"long" => { - self.i32()?; - } - b"comp" => { - self.i64()?; - } - b"bool" => { - self.u8()?; - } - b"type" | b"GlbC" => self.class()?, - b"alis" | b"Pth " | b"tdta" => { - let n = self.u32()?; - self.raw(usize::try_from(n).map_err(|_| PsdError::LimitExceeded("descriptor data length"))?)?; - } - b"ObAr" => { - self.u32()?; - self.descriptor()?; - } - other => return Err(PsdError::Unsupported(format!("descriptor OSType {:?}", String::from_utf8_lossy(other)))), - } - Ok(()) - } - - fn reference_item(&mut self) -> Result<()> { - let ty = self.key()?; - match &ty { - b"prop" => { - self.class()?; - self.id()?; - } - b"Clss" => self.class()?, - b"Enmr" => { - self.class()?; - self.id()?; - self.id()?; - } - b"rele" => { - self.class()?; - self.i32()?; - } - b"Idnt" | b"indx" => { - self.class()?; - self.u32()?; - } - b"name" => { - self.class()?; - self.unicode()?; - } - other => return Err(PsdError::Unsupported(format!("reference item type {:?}", String::from_utf8_lossy(other)))), - } - Ok(()) - } - - // ---- other block layouts ---- - - /// `shmd`: u32 count, then per item signature, key, copy flag, 3 bytes, u32 length, data. - /// An item whose layout is unknown is dropped on its own (and the count patched) rather - /// than taking the whole block with it. - fn metadata_setting(&mut self) -> Result<()> { - let n = self.r.u32()?; - self.r.check_count(u64::from(n), 16)?; - let count_at = self.out.len(); - self.out.extend_from_slice(&[0; 4]); - let mut kept = 0u32; - for _ in 0..n { - let before = self.out.len(); - self.key()?; - let key = self.key()?; - self.u8()?; - self.raw(3)?; - let same = self.same_order(); - let res = self.sized_region(false, |t| match &key { - b"cmls" | b"mlst" | b"cust" | b"tmln" | b"sgrp" | b"cinf" => t.versioned_descriptor(), - // mdyn (dynamic metadata) is one u32. - b"mdyn" => t.u32s_to_end(), - _ if same => Ok(()), - _ if t.descriptor_shaped() => Ok(()), - _ => Err(PsdError::Unsupported(format!("metadata item {:?}", String::from_utf8_lossy(&key)))), - }); - match res { - Ok(()) => kept += 1, - Err(e) if same => return Err(e), - Err(e) => { - self.out.truncate(before); - self.warnings.push(format!("shmd item {} dropped: {e}", String::from_utf8_lossy(&key))); - } - } - } - self.patch_len(count_at, false, u64::from(kept)) - } - - /// 26-byte path records: a u16 selector then, for knots, six fixed-point coordinates. - fn path_records(&mut self) -> Result<()> { - while self.remaining() >= 26 { - let selector = self.u16()?; - match selector { - 1 | 2 | 4 | 5 => self.i32s(6)?, - // Length records: knot count, path operation, then fields Photoshop writes as - // 16-bit values (zero in practice). - 0 | 3 => self.u16s(12)?, - // Clipboard: four fixed-point coordinates and a resolution. - 7 => { - self.i32s(5)?; - self.raw(4)?; - } - 8 => { - self.u16()?; - self.raw(22)?; - } - _ => self.raw(24)?, - } - } - Ok(()) - } - - /// One pattern of a `Patt` block (the data after its u32 length). - fn pattern(t: &mut Tx<'_>) -> Result<()> { - t.u32()?; - let mode = t.u32()?; - t.u16()?; - t.u16()?; - t.unicode()?; - t.pascal(1)?; - if mode == 2 { - t.raw(768)?; - // Some writers follow the palette with 4 extra bytes before the array list version. - let next_is_version = t.r.clone().u32().is_ok_and(|v| v == 3); - if !next_is_version && t.remaining() >= 4 { - t.raw(4)?; - } - } - t.u32()?; - t.sized_region(false, |v| { - v.i32s(4)?; - let count = v.u32()?; - for _ in 0..count.saturating_add(2) { - if v.remaining() < 4 { - break; - } - if v.u32()? == 0 { - continue; - } - if v.r.clone().u32()? == 0 { - v.u32()?; - continue; - } - v.sized_region(false, |c| { - c.u32()?; - let ct = c.i32()?; - c.i32()?; - let cb = c.i32()?; - c.i32()?; - c.u16()?; - let comp = c.u8()?; - if comp == 1 { - let saved = c.version; - c.version = Version::Psd; - let res = c.rle_counts(height(ct, cb)); - c.version = saved; - res?; - } - Ok(()) - })?; - } - Ok(()) - }) - } - - /// `FEid` / `FXid`: version, then one section per smart object (u64 length, items with - /// per-channel planes and 4-byte RLE counts), each padded to 4 bytes. - fn filter_effects(&mut self) -> Result<()> { - self.u32()?; - loop { - let len = self.r.clone().len_field(true)?; - self.filter_effects_section()?; - // Mirrors `FilterEffects::parse`: the last section's padding may be cut short. - let pad = usize::try_from((4 - len % 4) % 4).unwrap_or(0).min(self.remaining()); - self.raw(pad)?; - let rest = self.r.peek_rest(); - if rest.len() <= 3 && rest.iter().all(|&b| b == 0) { - return Ok(()); - } - if rest.len() < 8 { - return Err(PsdError::invalid(format!("filter effects: {} unexpected bytes after the data", rest.len()))); - } - } - } - - fn filter_effects_section(&mut self) -> Result<()> { - self.sized_region(true, |t| { - while !t.r.is_empty() { - t.pascal(1)?; - t.u32()?; - t.sized_region(true, |it| { - let top = it.i32()?; - it.i32()?; - let bottom = it.i32()?; - it.i32()?; - let rect_h = height(top, bottom); - it.u32()?; - let max = it.u32()?; - if max > crate::filter_effects::MAX_SLOTS { - return Err(PsdError::LimitExceeded("filter effects: too many channels")); - } - for _ in 0..max + 2 { - if it.u32()? != 0 { - it.effects_plane(rect_h)?; - } - } - Ok(()) - })?; - if !t.r.is_empty() && t.u8()? != 0 { - let top = t.i32()?; - t.i32()?; - let bottom = t.i32()?; - t.i32()?; - t.effects_plane(height(top, bottom))?; - } - } - Ok(()) - }) - } - - fn effects_plane(&mut self, rows: usize) -> Result<()> { - self.sized_region(true, |p| p.channel_data(rows, true)) - } - - /// `lrFX`: version, count, then effects (`cmnS`, `dsdw`, `isdw`, `oglw`, `iglw`, `bevl`, - /// `sofi`), each a signature, key, u32 size and fixed fields. - fn legacy_effects(&mut self) -> Result<()> { - self.u16()?; - let n = self.u16()?; - for _ in 0..n { - if self.remaining() < 12 { - break; - } - self.key()?; - let key = self.key()?; - self.sized_region(false, |t| { - // A colour: u16 space + 4 × u16 components. - let colour = |t: &mut Tx<'_>| t.u16s(5); - let blend = |t: &mut Tx<'_>| -> Result<()> { - t.key()?; - t.key()?; - Ok(()) - }; - match &key { - b"cmnS" => { - t.u32()?; - t.u8()?; - t.u16()?; - } - b"dsdw" | b"isdw" => { - t.u32()?; - t.i32s(4)?; - colour(t)?; - blend(t)?; - t.u8()?; - t.u8()?; - t.u8()?; - if t.remaining() >= 10 { - colour(t)?; - } - } - b"oglw" => { - t.u32()?; - t.i32s(2)?; - colour(t)?; - blend(t)?; - t.u8()?; - t.u8()?; - if t.remaining() >= 10 { - colour(t)?; - } - } - b"iglw" => { - t.u32()?; - t.i32s(2)?; - colour(t)?; - blend(t)?; - t.u8()?; - t.u8()?; - if t.remaining() >= 11 { - t.u8()?; - colour(t)?; - } - } - b"bevl" => { - t.u32()?; - t.i32s(3)?; - blend(t)?; - blend(t)?; - colour(t)?; - colour(t)?; - for _ in 0..6 { - t.u8()?; - } - if t.remaining() >= 20 { - colour(t)?; - colour(t)?; - } - } - b"sofi" => { - t.u32()?; - blend(t)?; - colour(t)?; - t.u8()?; - t.u8()?; - if t.remaining() >= 10 { - colour(t)?; - } - } - _ => {} - } - Ok(()) - })?; - } - Ok(()) - } - - /// `curv`: pad byte, version, channel bitmap, per set bit a point list; then an optional - /// `Crv ` extension with per-channel point lists. - fn curves(&mut self) -> Result<()> { - self.u8()?; - self.u16()?; - let bits = self.u32()?; - for bit in 0..32 { - if bits & (1 << bit) == 0 { - continue; - } - if self.remaining() < 2 { - break; - } - let n = self.u16()?; - self.u16s(usize::from(n) * 2)?; - } - if self.remaining() >= 10 { - self.key()?; - self.u16()?; - let n = self.u32()?; - for _ in 0..n { - if self.remaining() < 4 { - break; - } - self.u16()?; - let pts = self.u16()?; - self.u16s(usize::from(pts) * 2)?; - } - } - Ok(()) - } - - /// `grdm`: version, reverse, dither, [method key], name, colour stops, transparency - /// stops, then the noise-gradient fields (a u32 seed among u16s). - fn gradient_map(&mut self) -> Result<()> { - let version = self.u16()?; - self.u8()?; - self.u8()?; - if version == 3 { - self.key()?; - } - self.unicode()?; - let n = self.u16()?; - for _ in 0..n { - if self.remaining() < 20 { - break; - } - self.u32()?; - self.u32()?; - self.u16s(6)?; - } - let nt = self.u16()?; - for _ in 0..nt { - if self.remaining() < 10 { - break; - } - self.u32()?; - self.u32()?; - self.u16()?; - } - // expansion, interpolation, length, mode, u32 seed, then u16 fields. - for _ in 0..4 { - if self.remaining() < 2 { - return Ok(()); - } - self.u16()?; - } - if self.remaining() >= 4 { - self.u32()?; - } - self.u16s_to_end() - } -} diff --git a/crates/psd/src/tree.rs b/crates/psd/src/tree.rs deleted file mode 100644 index 606d9b2087..0000000000 --- a/crates/psd/src/tree.rs +++ /dev/null @@ -1,126 +0,0 @@ -//! Nested layer tree reconstruction from section dividers. -//! -//! In the file, layers are stored bottom-to-top. A group appears as a -//! *bounding section divider* (`lsct` type 3, usually named -//! ``) below its children, followed by the children, followed -//! by the group's own record (`lsct` type 1 = open or 2 = closed folder). - -use crate::file::PsdFile; -use crate::tagged::SectionType; - -/// A node of the layer tree. Children are in file order (bottom-to-top). -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum LayerNode { - /// A non-group layer. - Layer { - /// Index into [`PsdFile::layers`]. - index: usize, - }, - /// A group (folder). - Group { - /// Index of the group's own record (the folder, top of the group). - index: usize, - /// Index of the bounding section divider, if one was found. - divider: Option, - /// Children, bottom-to-top. - children: Vec, - }, -} - -impl LayerNode { - /// Record index of this node. - pub fn index(&self) -> usize { - match self { - LayerNode::Layer { index } | LayerNode::Group { index, .. } => *index, - } - } - /// Children (empty for layers). - pub fn children(&self) -> &[LayerNode] { - match self { - LayerNode::Layer { .. } => &[], - LayerNode::Group { children, .. } => children, - } - } - /// `true` for groups. - pub fn is_group(&self) -> bool { - matches!(self, LayerNode::Group { .. }) - } - /// Total number of nodes in this subtree (including self). - pub fn count(&self) -> usize { - 1 + self.children().iter().map(LayerNode::count).sum::() - } -} - -impl PsdFile { - /// Builds the nested layer tree. Root nodes and children are ordered - /// bottom-to-top (file order). - /// - /// Malformed nesting is tolerated: a folder without a matching divider - /// becomes an empty group; unclosed dividers at the end are dropped and - /// their children are hoisted to the enclosing level. - /// - /// The tree can be as deep as the file nests its groups (up to ~16000 - /// levels). Code that walks it recursively should use - /// [`layer_tree_max_depth`](Self::layer_tree_max_depth). - pub fn layer_tree(&self) -> Vec { - self.layer_tree_max_depth(usize::MAX) - } - - /// [`layer_tree`](Self::layer_tree) with at most `max_depth` levels of - /// groups: a group nested `max_depth` or more groups deep (a root node is - /// at depth 0) keeps its node but not its children. Layers under a divider - /// that is never closed sit at the enclosing level, as in `layer_tree`. Built iteratively, so - /// no file can make it recurse, and the result is no deeper than - /// `max_depth + 1` levels, so walking or dropping it recursively is bounded. - pub fn layer_tree_max_depth(&self, max_depth: usize) -> Vec { - let layers = self.layers(); - // First pass: find the dividers a folder closes. A divider that is never closed opens no - // group; its layers belong to the enclosing level, so it opens no frame and every - // frame's depth is the final depth of its nodes (#5758). - let mut closed = vec![false; layers.len()]; - let mut open: Vec = Vec::new(); - for (i, rec) in layers.iter().enumerate() { - match rec.section_type() { - SectionType::BoundingDivider => open.push(i), - SectionType::OpenFolder | SectionType::ClosedFolder => { - if let Some(slot) = open.pop().and_then(|d| closed.get_mut(d)) { - *slot = true; - } - } - _ => {} - } - } - // Stack of (divider index, children); frame `k` holds the nodes at depth `k`. Frames - // past `max_depth` are tracked (to match dividers to folders) but collect nothing. - let mut stack: Vec<(Option, Vec)> = vec![(None, Vec::new())]; - let push = |stack: &mut Vec<(Option, Vec)>, node: LayerNode| { - if stack.len() <= max_depth.saturating_add(1) - && let Some(top) = stack.last_mut() - { - top.1.push(node); - } - }; - for (i, rec) in layers.iter().enumerate() { - match rec.section_type() { - SectionType::BoundingDivider => { - if closed.get(i).copied().unwrap_or(false) { - stack.push((Some(i), Vec::new())); - } - } - SectionType::OpenFolder | SectionType::ClosedFolder => { - let (divider, children) = if stack.len() > 1 { stack.pop().unwrap_or_default() } else { (None, Vec::new()) }; - push(&mut stack, LayerNode::Group { index: i, divider, children }); - } - _ => push(&mut stack, LayerNode::Layer { index: i }), - } - } - // Only closed dividers open frames, so none is left here; this just guards the invariant. - while stack.len() > 1 { - let (_, children) = stack.pop().unwrap_or_default(); - if let Some(top) = stack.last_mut() { - top.1.extend(children); - } - } - stack.pop().map(|(_, c)| c).unwrap_or_default() - } -} diff --git a/crates/psd/tests/csh.rs b/crates/psd/tests/csh.rs deleted file mode 100644 index c220d266ae..0000000000 --- a/crates/psd/tests/csh.rs +++ /dev/null @@ -1,101 +0,0 @@ -use photocraft_psd::PsdError; -use photocraft_psd::csh; -use photocraft_psd::path::{PathData, PsdKnot, PsdSubpath}; - -fn fixture(names: &[&str]) -> Vec { - let mut bytes = b"cush".to_vec(); - bytes.extend_from_slice(&2u32.to_be_bytes()); - bytes.extend_from_slice(&(names.len() as u32).to_be_bytes()); - for name in names { - let units: Vec = name.encode_utf16().chain(std::iter::once(0)).collect(); - bytes.extend_from_slice(&(units.len() as u32).to_be_bytes()); - for unit in units { - bytes.extend_from_slice(&unit.to_be_bytes()); - } - while !bytes.len().is_multiple_of(4) { - bytes.push(0); - } - bytes.extend_from_slice(&1u32.to_be_bytes()); - let mut body = vec![2, b'i', b'd']; - for bound in [-10i32, -20, 90, 180] { - body.extend_from_slice(&bound.to_be_bytes()); - } - let knot = PsdKnot { linked: true, pre: (0.125, 0.25), anchor: (0.5, 0.5), post: (0.75, 0.875) }; - let path = PathData::from_subpaths(&[PsdSubpath { closed: false, operation: 0, knots: vec![knot] }], false); - body.extend_from_slice(&path.to_bytes()); - while !body.len().is_multiple_of(4) { - body.push(0); - } - bytes.extend_from_slice(&(body.len() as u32).to_be_bytes()); - bytes.extend_from_slice(&body); - } - bytes -} - -#[test] -fn reads_multiple_names_padding_signed_bounds_and_cubic_controls() { - let bytes = fixture(&["Even", "Odd", "形😀"]); - let shapes = csh::parse(&bytes).unwrap(); - assert_eq!(shapes.iter().map(|s| s.name.as_str()).collect::>(), ["Even", "Odd", "形😀"]); - for shape in shapes { - assert_eq!(shape.bounds, [-10, -20, 90, 180]); - assert_eq!(shape.id, "id"); - let subpaths = shape.path.subpaths(); - assert_eq!(subpaths.len(), 1); - assert!(!subpaths[0].closed); - let knot = subpaths[0].knots[0]; - assert!(knot.linked); - assert_eq!(knot.pre, (0.125, 0.25)); - assert_eq!(knot.anchor, (0.5, 0.5)); - assert_eq!(knot.post, (0.75, 0.875)); - } -} - -#[test] -fn rejects_every_truncated_prefix_without_panicking() { - let bytes = fixture(&["One", "Two"]); - for end in 0..bytes.len() { - assert!(csh::parse(&bytes[..end]).is_err(), "accepted truncated prefix {end}"); - } -} - -#[test] -fn rejects_unsupported_headers_excessive_counts_and_invalid_unicode() { - let bytes = fixture(&["A"]); - for (offset, value) in [(4, 3u32), (8, u32::MAX), (12, u32::MAX), (24, u32::MAX)] { - let mut broken = bytes.clone(); - broken[offset..offset + 4].copy_from_slice(&value.to_be_bytes()); - assert!(csh::parse(&broken).is_err(), "offset {offset}"); - } - // The count and name limits answer before the reader runs out of bytes, so a removed limit - // cannot hide behind a truncation error. One past each limit is refused by the limit itself. - for (offset, value, limit) in [ - (8, u32::MAX, "CSH shape count"), - (8, csh::MAX_SHAPES as u32 + 1, "CSH shape count"), - (12, u32::MAX, "CSH name length"), - (12, csh::MAX_NAME_UNITS as u32 + 1, "CSH name length"), - ] { - let mut broken = bytes.clone(); - broken[offset..offset + 4].copy_from_slice(&value.to_be_bytes()); - assert_eq!(csh::parse(&broken), Err(PsdError::LimitExceeded(limit)), "offset {offset} value {value}"); - } - let mut broken = bytes.clone(); - broken[16..18].copy_from_slice(&0xd800u16.to_be_bytes()); - assert!(csh::parse(&broken).is_err()); - let mut trailing = bytes; - trailing.push(0); - assert!(csh::parse(&trailing).is_err()); -} - -#[test] -fn rejects_missing_knots_and_mismatched_open_closed_records() { - let bytes = fixture(&["A"]); - // Header/name/version/length = 28; id = 3; bounds = 16; two fill records = 52. - let length_record = 28 + 3 + 16 + 52; - let mut missing = bytes.clone(); - missing[length_record + 2..length_record + 4].copy_from_slice(&2u16.to_be_bytes()); - assert!(csh::parse(&missing).is_err()); - let mut mismatched = bytes; - mismatched[length_record..length_record + 2].copy_from_slice(&0u16.to_be_bytes()); - assert!(csh::parse(&mismatched).is_err()); -} diff --git a/crates/psd/tests/fixtures/atn/README.md b/crates/psd/tests/fixtures/atn/README.md deleted file mode 100644 index e0912ea462..0000000000 --- a/crates/psd/tests/fixtures/atn/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# Synthetic ATN parser fixtures - -These seven tiny files are original synthetic test data. The four version-16 files were independently -encoded field by field from the version-16 layout documented in `src/atn.rs`, without calling -PhotoCraft's writer; the three version-12 files (`v12-*.atn`) encode the version-12 layout documented -there (#10743). They are 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` | -| `v12-stop.atn` | 113 | Version 12: Stop with Unicode text and a Boolean | `293462a7d5cf0043fdc5135630524699f545679088c54bad83f4a86e15160271` | -| `v12-values.atn` | 562 | Version 12: named plug-in event, every legacy value and reference form, bare `warp`/`list`/`time` codes, an object array with three objects and two columns, unpaired UTF-16, opaque path/alias/data bytes, and a descriptorless step | `23d3f377996435988367365ee5c2a15462c0ed42ce506dc4a15039387ac6a853` | -| `v12-commands.atn` | 404 | Version 12: Gaussian Blur, Levels, Select All and Make Layer | `451958b686da9aab45e65ae902c86333b7149d72021c21904e3aae8e39eb77cb` | - -`tests/it/atn_contract.rs` checks the independently encoded version-16 bytes and expected public -structures; `tests/it/atn_v12.rs` (and `photocraft-engine`'s `tests/it/atn_v12.rs`) check the -version-12 files. The version-12 files follow the version 12 layout in `src/atn.rs`, assembled from -the measured grammar in #10603. Their `Idnt` reference follows the inferred index-like layout; no -real version 12 identifier reference was available. Saving them produces version 16, so keep them -out of the version-16 byte-identical corpus oracle. - -The files also seed the `atn` fuzz target: `cargo fuzz run atn crates/psd/tests/fixtures/atn` -(from `crates/psd`: `cargo fuzz run atn tests/fixtures/atn`). - -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 deleted file mode 100644 index 26b1bdd361..0000000000 Binary files a/crates/psd/tests/fixtures/atn/descriptors.atn and /dev/null differ diff --git a/crates/psd/tests/fixtures/atn/empty.atn b/crates/psd/tests/fixtures/atn/empty.atn deleted file mode 100644 index dbcd73d196..0000000000 Binary files a/crates/psd/tests/fixtures/atn/empty.atn and /dev/null differ diff --git a/crates/psd/tests/fixtures/atn/float-bits.atn b/crates/psd/tests/fixtures/atn/float-bits.atn deleted file mode 100644 index 0f272adea8..0000000000 Binary files a/crates/psd/tests/fixtures/atn/float-bits.atn and /dev/null differ diff --git a/crates/psd/tests/fixtures/atn/metadata.atn b/crates/psd/tests/fixtures/atn/metadata.atn deleted file mode 100644 index 29c5597e00..0000000000 Binary files a/crates/psd/tests/fixtures/atn/metadata.atn and /dev/null differ diff --git a/crates/psd/tests/fixtures/atn/v12-stop.atn b/crates/psd/tests/fixtures/atn/v12-stop.atn deleted file mode 100644 index 826bdabe55..0000000000 Binary files a/crates/psd/tests/fixtures/atn/v12-stop.atn and /dev/null differ diff --git a/crates/psd/tests/fixtures/atn/v12-values.atn b/crates/psd/tests/fixtures/atn/v12-values.atn deleted file mode 100644 index 0fc46dde8e..0000000000 Binary files a/crates/psd/tests/fixtures/atn/v12-values.atn and /dev/null differ diff --git a/crates/psd/tests/it/animation.rs b/crates/psd/tests/it/animation.rs deleted file mode 100644 index ac96b6a0b9..0000000000 --- a/crates/psd/tests/it/animation.rs +++ /dev/null @@ -1,262 +0,0 @@ -//! Synthetic only: no personal PSDs, paths, or copied descriptor payloads. - -use photocraft_psd::animation::{AnimationRecord, AnimationResource, frame_info, frame_sets, layer_frame_states, parse_descriptor}; -use photocraft_psd::descriptor::{Descriptor, Value, VersionedDescriptor}; -use photocraft_psd::metadata::{MetadataItem, parse_shmd, write_shmd}; -use photocraft_psd::{ImageResource, PsdBuilder, PsdFile, ResourceData, TaggedBlock, Version}; -use proptest::prelude::*; - -fn descriptor() -> VersionedDescriptor { - VersionedDescriptor::new( - Descriptor::default() - .with("AFSt", Value::Integer(7)) - .with( - "FrIn", - Value::List(vec![ - Value::Descriptor( - Descriptor::default().with("FrID", Value::Integer(-3)).with("FrDl", Value::Integer(3)).with("future", Value::Boolean(true)), - ), - Value::Descriptor(Descriptor::default().with("FrID", Value::Integer(21)).with("FrDl", Value::Integer(53))), - ]), - ) - .with( - "FSts", - Value::List(vec![Value::Descriptor( - Descriptor::default() - .with("FsID", Value::Integer(7)) - .with("AFrm", Value::Integer(0)) - .with("FsFr", Value::List(vec![Value::Integer(21), Value::Integer(-3)])) - .with("future", Value::RawData(vec![1, 2, 3])), - )]), - ), - ) -} - -fn resource(data: &[u8]) -> AnimationResource<'_> { - AnimationResource { - records: vec![ - AnimationRecord { key: *b"AnDs", data }, - AnimationRecord { key: *b"Roll", data: &[0; 8] }, - AnimationRecord { key: *b"next", data: &[9, 8, 7] }, - ], - } -} - -#[test] -fn raw_roundtrip_and_typed_views_preserve_order_and_unknown_data() { - let data = descriptor().to_bytes(); - let bytes = resource(&data).to_bytes().unwrap(); - let parsed = AnimationResource::from_bytes(&bytes).unwrap(); - assert_eq!(parsed, resource(&data)); - let d = parsed.records[0].descriptor().unwrap().unwrap(); - assert_eq!(d, descriptor()); - let frames = frame_info(&d.descriptor).unwrap(); - assert_eq!(frames.iter().map(|f| (f.id, f.delay_centiseconds)).collect::>(), [(-3, Some(3)), (21, Some(53))]); - assert_eq!(frames[0].descriptor.get("future"), Some(&Value::Boolean(true))); - let sets = frame_sets(&d.descriptor).unwrap(); - assert_eq!(sets[0].frame_ids, [21, -3], "playback order is not FrIn order or sorted id order"); - assert_eq!(sets[0].id, 7); - assert_eq!(sets[0].active_frame, Some(0)); - assert_eq!(sets[0].descriptor.get("future"), Some(&Value::RawData(vec![1, 2, 3]))); - assert!(parsed.records[1].descriptor().is_none()); - assert_eq!(parsed.to_bytes().unwrap(), bytes); -} - -#[test] -fn plugin_signature_not_a_single_resource_id_selects_the_parser() { - let data = descriptor().to_bytes(); - let bytes = resource(&data).to_bytes().unwrap(); - for id in [4000, 4003, 4999] { - let r = ImageResource::new(id, bytes.clone()); - assert!(matches!(r.parsed(), Some(Ok(ResourceData::Animation(_))))); - } - for id in [3999, 5000] { - assert!(ImageResource::new(id, bytes.clone()).parsed().is_none()); - } - assert!(ImageResource::new(4003, b"different plugin".to_vec()).parsed().is_none()); - assert!(matches!(ImageResource::new(4003, b"mani".to_vec()).parsed(), Some(Err(_)))); - assert!(matches!( - ImageResource::new(1075, VersionedDescriptor::new(Descriptor::default().with("Vrsn", Value::Integer(1))).to_bytes()).parsed(), - Some(Ok(ResourceData::TimelineInfo(_))) - )); -} - -#[test] -fn metadata_views_do_not_touch_xmp_or_other_items() { - let d = VersionedDescriptor::new(Descriptor::default().with("LaID", Value::Integer(42)).with( - "LaSt", - Value::List(vec![Value::Descriptor( - Descriptor::default() - .with("FrLs", Value::List(vec![Value::Integer(-3)])) - .with("blendOptions", Value::Descriptor(Descriptor::default().with("Opct", Value::Double(12.5)))), - )]), - )); - let items = vec![ - MetadataItem::new(*b"cust", vec![7, 9, 11]), - MetadataItem::new(*b"mlst", d.to_bytes()), - MetadataItem::new(*b"tmln", VersionedDescriptor::new(Descriptor::default().with("trackList", Value::List(vec![]))).to_bytes()), - MetadataItem::new(*b"next", vec![255; 4]), - ]; - let raw = write_shmd(&items); - let parsed = parse_shmd(&raw).unwrap(); - assert!(parsed[0].animation_descriptor().is_none()); - let layer_descriptor = parsed[1].animation_descriptor().unwrap().unwrap(); - assert_eq!(layer_descriptor, d); - let states = layer_frame_states(&layer_descriptor.descriptor).unwrap(); - assert_eq!(states.layer_id, 42); - assert_eq!(states.states[0].frame_ids, [-3]); - assert_eq!(states.states[0].descriptor.get("enab"), None, "missing visibility is not false"); - assert_eq!(states.states[0].descriptor.get("blendOptions"), Some(&Value::Descriptor(Descriptor::default().with("Opct", Value::Double(12.5))))); - assert!(parsed[2].animation_descriptor().unwrap().is_ok()); - assert!(parsed[3].animation_descriptor().is_none()); - assert_eq!(write_shmd(&parsed), raw); - let mut bad = parsed[1].clone(); - bad.signature = *b"nope"; - assert!(bad.animation_descriptor().unwrap().is_err()); -} - -#[test] -fn psd_and_psb_keep_animation_resources_and_metadata_byte_stable() { - let data = descriptor().to_bytes(); - let raw = resource(&data).to_bytes().unwrap(); - for version in [Version::Psd, Version::Psb] { - let mut file = PsdBuilder::new(1, 1).version(version).build().unwrap(); - file.resources.push(ImageResource::new(4003, raw.clone())); - file.global_blocks.push(TaggedBlock::new(*b"shmd", write_shmd(&[MetadataItem::new(*b"mlst", data.clone())]))); - let bytes = file.to_bytes().unwrap(); - let back = PsdFile::from_bytes(&bytes).unwrap(); - assert_eq!(back.to_bytes().unwrap(), bytes); - let animation = back.resource(4003).unwrap(); - assert!(matches!(animation.parsed(), Some(Ok(ResourceData::Animation(_))))); - } -} - -#[test] -fn every_truncation_and_hostile_envelope_length_is_rejected() { - let data = descriptor().to_bytes(); - let bytes = resource(&data).to_bytes().unwrap(); - for end in 0..bytes.len() { - assert!(AnimationResource::from_bytes(&bytes[..end]).is_err(), "prefix {end}"); - } - for at in [8, 20] { - for value in [0, 1, u32::MAX] { - let mut bad = bytes.clone(); - bad[at..at + 4].copy_from_slice(&value.to_be_bytes()); - assert!(AnimationResource::from_bytes(&bad).is_err(), "length {at} = {value}"); - } - } - for at in [0, 4, 12] { - let mut bad = bytes.clone(); - bad[at] = b'?'; - assert!(AnimationResource::from_bytes(&bad).is_err()); - } - let mut trailing = bytes.clone(); - trailing.push(0); - assert!(AnimationResource::from_bytes(&trailing).is_err()); -} - -#[test] -fn descriptor_padding_truncation_and_unknown_versions() { - let raw = descriptor().to_bytes(); - for end in 0..raw.len() { - assert!(parse_descriptor(&raw[..end]).is_err(), "descriptor prefix {end}"); - } - for padding in 0..=3 { - let mut padded = raw.clone(); - padded.extend(vec![0; padding]); - assert_eq!(parse_descriptor(&padded).unwrap(), descriptor()); - } - for tail in [vec![0; 4], vec![1], vec![0, 2]] { - let mut bad = raw.clone(); - bad.extend(tail); - assert!(parse_descriptor(&bad).is_err()); - } - let mut future = raw.clone(); - future[..4].copy_from_slice(&17u32.to_be_bytes()); - let bytes = resource(&future).to_bytes().unwrap(); - let r = AnimationResource::from_bytes(&bytes).unwrap(); - assert!(r.records[0].descriptor().unwrap().is_err()); - assert_eq!(r.to_bytes().unwrap(), bytes, "unsupported typed version must survive raw"); -} - -#[test] -fn absent_delays_and_duplicate_ids_are_not_silently_repaired() { - let d = Descriptor::default().with( - "FrIn", - Value::List(vec![ - Value::Descriptor(Descriptor::default().with("FrID", Value::Integer(4))), - Value::Descriptor(Descriptor::default().with("FrID", Value::Integer(4)).with("FrDl", Value::Integer(0))), - ]), - ); - let frames = frame_info(&d).unwrap(); - assert_eq!(frames.len(), 2); - assert_eq!(frames[0].delay_centiseconds, None); - assert_eq!(frames[1].delay_centiseconds, Some(0)); - let bytes = - AnimationResource { records: vec![AnimationRecord { key: *b"next", data: &[] }, AnimationRecord { key: *b"next", data: &[1] }] }.to_bytes().unwrap(); - assert_eq!(AnimationResource::from_bytes(&bytes).unwrap().to_bytes().unwrap(), bytes); -} - -#[test] -fn wrong_frame_and_set_types_return_errors() { - for value in [Value::Boolean(false), Value::List(vec![Value::Integer(1)]), Value::List(vec![Value::Descriptor(Descriptor::default())])] { - assert!(frame_info(&Descriptor::default().with("FrIn", value.clone())).is_err()); - assert!(frame_sets(&Descriptor::default().with("FSts", value)).is_err()); - } - for delay in [Value::Integer(-1), Value::Double(3.0)] { - let frame = Descriptor::default().with("FrID", Value::Integer(1)).with("FrDl", delay); - assert!(frame_info(&Descriptor::default().with("FrIn", Value::List(vec![Value::Descriptor(frame)]))).is_err()); - } - for (key, value) in [("FsID", Value::Boolean(false)), ("AFrm", Value::Double(0.0)), ("FsFr", Value::List(vec![Value::Boolean(true)]))] { - let mut set = Descriptor::default().with("FsID", Value::Integer(1)).with("FsFr", Value::List(vec![])); - set.items.retain(|(id, _)| !id.is(key)); - set = set.with(key, value); - assert!(frame_sets(&Descriptor::default().with("FSts", Value::List(vec![Value::Descriptor(set)]))).is_err()); - } -} - -#[test] -fn sparse_layer_states_retain_missing_properties_and_multiple_references() { - let first = Descriptor::default() - .with("FrLs", Value::List(vec![Value::Integer(21), Value::Integer(-3)])) - .with("enab", Value::Boolean(true)) - .with("Ofst", Value::Descriptor(Descriptor::default().with("Hrzn", Value::Integer(-7)).with("Vrtc", Value::Integer(12)))); - let second = Descriptor::default().with("FrLs", Value::List(vec![Value::Integer(99)])); - let d = Descriptor::default().with("LaID", Value::Integer(8)).with("LaSt", Value::List(vec![Value::Descriptor(first.clone()), Value::Descriptor(second)])); - let view = layer_frame_states(&d).unwrap(); - assert_eq!(view.states[0].frame_ids, [21, -3]); - assert_eq!(view.states[0].descriptor, &first); - assert_eq!(view.states[1].descriptor.get("Ofst"), None); - assert_eq!(view.states[1].descriptor.get("enab"), None); - for d in [ - Descriptor::default(), - Descriptor::default().with("LaID", Value::Boolean(true)), - Descriptor::default().with("LaID", Value::Integer(8)).with("LaSt", Value::Boolean(true)), - Descriptor::default().with("LaID", Value::Integer(8)).with("LaSt", Value::List(vec![Value::Integer(0)])), - ] { - assert!(layer_frame_states(&d).is_err()); - } - for state in [ - Descriptor::default(), - Descriptor::default().with("FrLs", Value::Integer(0)), - Descriptor::default().with("FrLs", Value::List(vec![Value::Boolean(true)])), - ] { - let d = Descriptor::default().with("LaID", Value::Integer(8)).with("LaSt", Value::List(vec![Value::Descriptor(state)])); - assert!(layer_frame_states(&d).is_err()); - } -} - -proptest! { - #[test] - fn arbitrary_animation_bytes_never_panic(data in proptest::collection::vec(any::(), 0..2048)) { - let _ = AnimationResource::from_bytes(&data); - let _ = parse_descriptor(&data); - } - - #[test] - fn opaque_record_roundtrip(data in proptest::collection::vec(any::(), 0..2048), key in any::<[u8; 4]>()) { - let r = AnimationResource { records: vec![AnimationRecord { key, data: &data }] }; - let bytes = r.to_bytes().unwrap(); - prop_assert_eq!(AnimationResource::from_bytes(&bytes).unwrap(), r); - } -} diff --git a/crates/psd/tests/it/atn_contract.rs b/crates/psd/tests/it/atn_contract.rs deleted file mode 100644 index f6c38bf81c..0000000000 --- a/crates/psd/tests/it/atn_contract.rs +++ /dev/null @@ -1,243 +0,0 @@ -//! 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}; - -#[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, 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()); -} - -#[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, 7, 11, 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(_)))); - } - // Version 12 (Photoshop 5) is read too (#10743): the smallest set parses to an empty set. - let mut v12 = FIXTURES[0].1.to_vec(); - v12[..4].copy_from_slice(&12_u32.to_be_bytes()); - assert!(atn::parse(&v12).unwrap().actions.is_empty()); - 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/it/atn_v12.rs b/crates/psd/tests/it/atn_v12.rs deleted file mode 100644 index 28f3921d1f..0000000000 --- a/crates/psd/tests/it/atn_v12.rs +++ /dev/null @@ -1,145 +0,0 @@ -use photocraft_psd::PsdError; -use photocraft_psd::atn; -use photocraft_psd::descriptor::{Class, Descriptor, Id, MAX_DEPTH, ObjectArray, ReferenceItem as R, UnicodeString, Value as V}; - -const STOP: &[u8] = include_bytes!("../fixtures/atn/v12-stop.atn"); -const VALUES: &[u8] = include_bytes!("../fixtures/atn/v12-values.atn"); -const COMMANDS: &[u8] = include_bytes!("../fixtures/atn/v12-commands.atn"); - -fn code(id: &[u8; 4]) -> Id { - Id::Code(*id) -} - -fn class(id: &[u8; 4]) -> Class { - Class { name: UnicodeString::default(), class_id: code(id) } -} - -fn descriptor(id: &[u8; 4], items: Vec<(Id, V)>) -> Descriptor { - Descriptor { name: UnicodeString::default(), class_id: code(id), items } -} - -/// The fixture bytes are independent of the version 16 writer and legacy reader. -#[test] -fn stop_and_named_event_preserve_headers_and_canonicalize_to_v16() { - let parsed = atn::parse(STOP).unwrap(); - assert_eq!(parsed.name, UnicodeString::new_nul("Legacy")); - let action = &parsed.actions[0]; - assert_eq!((action.function_key, action.shift, action.command, action.color), (3, true, false, 2)); - assert_eq!(action.name, UnicodeString::new_nul("Run")); - let step = &action.items[0]; - assert_eq!((step.expanded, step.enabled, step.with_dialog, step.dialog_options), (true, true, false, 2)); - assert_eq!(step.event, atn::AtnEvent::Code(*b"Stop")); - assert_eq!( - step.descriptor, - Some(descriptor(b"null", vec![(code(b"Msge"), V::Text(UnicodeString::new_nul("Review ✓"))), (code(b"Cntn"), V::Boolean(true)),])) - ); - let plugin = atn::parse(VALUES).unwrap(); - assert_eq!(plugin.actions[0].items[0].event, atn::AtnEvent::name("LegacyPlugin")); - assert!(plugin.actions[0].items[1].descriptor.is_none()); - for bytes in [STOP, VALUES, COMMANDS] { - let original = atn::parse(bytes).unwrap(); - let modern = atn::write(&original).unwrap(); - assert_eq!(&modern[..4], &16_u32.to_be_bytes()); - assert_eq!(atn::parse(&modern).unwrap(), original); - } -} - -#[test] -fn all_legacy_values_and_reference_classes_are_retained() { - let parsed = atn::parse(VALUES).unwrap(); - let actual = parsed.actions[0].items[0].descriptor.as_ref().unwrap(); - let floats = |values| V::UnitFloats { unit: *b"#Pxl", values }; - let expected = descriptor( - b"null", - vec![ - (code(b"warp"), V::Boolean(true)), - (code(b"list"), V::GlobalClass(class(b"list"))), - (code(b"time"), V::Enumerated { type_id: code(b"time"), value: code(b"warp") }), - (code(b"long"), V::Integer(-17)), - (code(b"comp"), V::LargeInteger(i64::MIN + 23)), - (code(b"doub"), V::Double(-0.5)), - (code(b"unit"), V::UnitFloat { unit: *b"#Pxl", value: 2.5 }), - (code(b"TEXT"), V::Text(UnicodeString(vec![0xd800, 0]))), - (code(b"Objc"), V::Descriptor(descriptor(b"warp", vec![(code(b"flag"), V::Boolean(false))]))), - (code(b"GlbO"), V::GlobalObject(descriptor(b"list", vec![]))), - (code(b"type"), V::Class(class(b"time"))), - (code(b"VlLs"), V::List(vec![V::Boolean(false), V::Descriptor(descriptor(b"time", vec![]))])), - ( - code(b"ObAr"), - V::ObjectArray(ObjectArray { - prefix: 3, - body: descriptor(b"time", vec![(code(b"Hrzn"), floats(vec![1.0, 2.0, 3.0])), (code(b"Vrtc"), floats(vec![4.0, 5.0, 6.0]))]), - }), - ), - ( - code(b"refs"), - V::Reference(vec![ - R::Property { class: class(b"Lyr "), key: code(b"Nm ") }, - R::Class(class(b"Dcmn")), - R::Enumerated { class: class(b"Lyr "), type_id: code(b"Ordn"), value: code(b"Trgt") }, - R::Offset { class: class(b"Lyr "), offset: -2 }, - R::Index { class: class(b"Lyr "), index: 3 }, - R::Identifier { class: class(b"Lyr "), id: 9 }, - R::Name { class: class(b"Lyr "), name: UnicodeString::new_nul("Layer ✓") }, - ]), - ), - (code(b"Pth "), V::Path(vec![0, 1, 255, 3])), - (code(b"alis"), V::Alias(b"alias".to_vec())), - (code(b"tdta"), V::RawData(vec![])), - ], - ); - assert_eq!(actual, &expected); -} - -fn with_descriptor(body: &[u8]) -> Vec { - let start = STOP.windows(4).position(|w| w == [255; 4]).unwrap() + 4; - let mut bytes = STOP[..start].to_vec(); - bytes.extend_from_slice(body); - bytes -} - -/// Reject every truncated fixture while preserving trailing data as a warning. -#[test] -fn truncations_fail_and_trailing_bytes_only_warn() { - for bytes in [STOP, VALUES, COMMANDS] { - for cut in 0..bytes.len() { - assert!(atn::parse(&bytes[..cut]).is_err(), "length {}, cut {cut}", bytes.len()); - } - let mut padded = bytes.to_vec(); - padded.extend_from_slice(b"junk"); - let mut parsed = atn::parse(&padded).unwrap(); - assert_eq!(parsed.warnings, ["4 trailing bytes ignored"]); - parsed.warnings.clear(); - assert_eq!(parsed, atn::parse(bytes).unwrap()); - } -} - -/// Reject excessive counts/depth and unsupported forms without dialect fallback. -#[test] -fn legacy_counts_depth_and_unknown_forms_fail_without_fallback() { - assert!(atn::parse(&with_descriptor(&u32::MAX.to_be_bytes())).is_err()); - for prefix in [b"VlLs".as_slice(), b"obj ", b"UnFl#Pxl", b"TEXT", b"Pth ", b"ObArtime\0\0\0\x03"] { - let mut body = b"\0\0\0\x01test".to_vec(); - body.extend_from_slice(prefix); - body.extend_from_slice(&u32::MAX.to_be_bytes()); - assert!(atn::parse(&with_descriptor(&body)).is_err()); - } - // The smallest descriptor item is a bare key/type and one Boolean byte. - assert!(atn::parse(&with_descriptor(b"\0\0\0\x01testbool\x01")).is_ok()); - for ty in [b"VlLs\0\0\0\x01".as_slice(), b"Objcnull\0\0\0\x01test"] { - let mut body = b"\0\0\0\x01test".to_vec(); - for _ in 0..=MAX_DEPTH { - body.extend_from_slice(ty); - } - body.extend_from_slice(b"bool\x01"); - assert!(matches!(atn::parse(&with_descriptor(&body)), Err(PsdError::LimitExceeded(_)))); - } - for body in [b"\0\0\0\x01testwhat\0".as_slice(), b"\0\0\0\x01testobj \0\0\0\x01whatLyr "] { - assert!(matches!(atn::parse(&with_descriptor(body)), Err(PsdError::Unsupported(_)))); - } - for version in [0_u32, 7, 11, 13, 17, 0x0005_1600] { - let mut bytes = STOP.to_vec(); - bytes[..4].copy_from_slice(&version.to_be_bytes()); - assert!(matches!(atn::parse(&bytes), Err(PsdError::Unsupported(message)) if message.contains(&version.to_string()))); - } -} diff --git a/crates/psd/tests/it/builder.rs b/crates/psd/tests/it/builder.rs deleted file mode 100644 index e5c6c09354..0000000000 --- a/crates/psd/tests/it/builder.rs +++ /dev/null @@ -1,309 +0,0 @@ -//! Builder and pixel extraction tests. - -use photocraft_psd::*; - -fn rgba_pattern(w: usize, h: usize, seed: u8) -> Vec { - let mut v = Vec::with_capacity(w * h * 4); - for y in 0..h { - for x in 0..w { - v.extend_from_slice(&[(x * 10) as u8 ^ seed, (y * 20) as u8, (x + y) as u8 ^ seed, if (x + y) % 3 == 0 { 0 } else { 200 + (x % 50) as u8 }]); - } - } - v -} - -fn built(b: &PsdBuilder) -> PsdFile { - let bytes = b.to_bytes().unwrap(); - let f = PsdFile::from_bytes(&bytes).unwrap(); - assert_eq!(f.to_bytes().unwrap(), bytes, "byte stable"); - assert_eq!(f, b.build().unwrap(), "model stable"); - f -} - -macro_rules! rgba8_case { - ($name:ident, $ver:expr, $comp:expr) => { - #[test] - fn $name() { - let px = rgba_pattern(7, 5, 3); - let mut b = PsdBuilder::new(10, 8).version($ver).compression($comp); - b.push_layer(LayerSpec::new("L", -2, 1, 7, 5, PixelData::Rgba8(px.clone()))); - let f = built(&b); - let img = f.layer(0).unwrap().rgba8().unwrap(); - assert_eq!((img.left, img.top, img.width, img.height), (-2, 1, 7, 5)); - assert_eq!(img.data, px); - } - }; -} - -rgba8_case!(rgba8_psd_raw, Version::Psd, Compression::Raw); -rgba8_case!(rgba8_psd_rle, Version::Psd, Compression::Rle); -rgba8_case!(rgba8_psd_zip, Version::Psd, Compression::Zip); -rgba8_case!(rgba8_psd_zipp, Version::Psd, Compression::ZipPrediction); -rgba8_case!(rgba8_psb_raw, Version::Psb, Compression::Raw); -rgba8_case!(rgba8_psb_rle, Version::Psb, Compression::Rle); -rgba8_case!(rgba8_psb_zip, Version::Psb, Compression::Zip); -rgba8_case!(rgba8_psb_zipp, Version::Psb, Compression::ZipPrediction); - -#[test] -fn rgba16_layers_scale_to_8bit() { - let n = 4 * 3; - let px: Vec = (0..n * 4).map(|i| (i as u16).wrapping_mul(5003)).collect(); - for comp in Compression::ALL { - let mut b = PsdBuilder::new(4, 3).depth(16).compression(comp); - b.push_layer(LayerSpec::new("x", 0, 0, 4, 3, PixelData::Rgba16(px.clone()))); - let f = built(&b); - assert!(matches!(f.layer_info_placement, LayerInfoPlacement::GlobalBlock { key: [b'L', b'r', b'1', b'6'], .. })); - let l = f.layer(0).unwrap(); - let img = l.rgba8().unwrap(); - let expect: Vec = px.iter().map(|&v| ((u32::from(v) * 255 + 32767) / 65535) as u8).collect(); - assert_eq!(img.data, expect); - // Raw 16-bit samples are exact. - let red = pixels::samples_u16(&l.channel_bytes(0).unwrap()); - assert_eq!(red, px.iter().step_by(4).copied().collect::>()); - } -} - -#[test] -fn grayscale_builder() { - let px: Vec = (0..6).flat_map(|i| [i * 40, 255 - i]).collect(); - let mut b = PsdBuilder::new(3, 2).color_mode(ColorMode::Grayscale); - b.push_layer(LayerSpec::new("g", 0, 0, 3, 2, PixelData::GrayA8(px.clone()))); - b.composite(PixelData::GrayA8(px.clone())); - let f = built(&b); - assert_eq!(f.header.color_mode, ColorMode::Grayscale); - let img = f.layer(0).unwrap().rgba8().unwrap(); - for i in 0..6 { - assert_eq!(&img.data[i * 4..i * 4 + 4], &[px[i * 2], px[i * 2], px[i * 2], px[i * 2 + 1]]); - } - let c = f.composite_rgba8().unwrap(); - assert_eq!(c.data, img.data); - assert_eq!(f.header.channels, 2); -} - -#[test] -fn grayscale16_builder() { - let px: Vec = vec![0, 65535, 32768, 65535]; - let mut b = PsdBuilder::new(2, 1).color_mode(ColorMode::Grayscale).depth(16); - b.push_layer(LayerSpec::new("g", 0, 0, 2, 1, PixelData::GrayA16(px))); - let f = built(&b); - assert_eq!(f.layer(0).unwrap().rgba8().unwrap().data, vec![0, 0, 0, 255, 128, 128, 128, 255]); -} - -#[test] -fn cmyk_builder_inverts_ink() { - // One pixel: C=0 M=0 Y=0 K=0 ink (white), one: K=255 (black). - let px = vec![0, 0, 0, 0, 255, 0, 0, 0, 255, 255]; - let mut b = PsdBuilder::new(2, 1).color_mode(ColorMode::Cmyk); - b.push_layer(LayerSpec::new("c", 0, 0, 2, 1, PixelData::Cmyka8(px.clone()))); - b.composite(PixelData::Cmyka8(px)); - let f = built(&b); - assert_eq!(f.header.channels, 4); - let l = f.layer(0).unwrap(); - assert_eq!(l.channel_bytes(0).unwrap(), vec![255, 255]); // stored inverted - assert_eq!(l.channel_bytes(3).unwrap(), vec![255, 0]); - assert_eq!(l.rgba8().unwrap().data, vec![255, 255, 255, 255, 0, 0, 0, 255]); - assert_eq!(f.composite_rgba8().unwrap().data, vec![255, 255, 255, 255, 0, 0, 0, 255]); -} - -#[test] -fn cmyk16_builder() { - let px = vec![0u16, 0, 0, 0, 65535]; - let mut b = PsdBuilder::new(1, 1).color_mode(ColorMode::Cmyk).depth(16); - b.push_layer(LayerSpec::new("c", 0, 0, 1, 1, PixelData::Cmyka16(px))); - let f = built(&b); - assert_eq!(f.layer(0).unwrap().rgba8().unwrap().data, vec![255, 255, 255, 255]); -} - -#[test] -fn layer_properties_roundtrip() { - let mut b = PsdBuilder::new(4, 4); - let mut spec = LayerSpec::new("Props \u{1F3A8}", 1, 1, 2, 2, PixelData::Rgba8(vec![9; 16])); - spec.blend_mode = BlendMode::SoftLight; - spec.opacity = 128; - spec.fill_opacity = Some(64); - spec.visible = false; - spec.clipping = true; - spec.extra_blocks.push(TaggedBlock::sheet_color(4)); - b.push_layer(spec); - let f = built(&b); - let r = &f.layers()[0]; - assert_eq!(r.name(), "Props \u{1F3A8}"); - assert_eq!(r.name, b"Props ?"); - assert_eq!(r.blend_mode, BlendMode::SoftLight); - assert_eq!(r.opacity, 128); - assert_eq!(r.fill_opacity(), 64); - assert!(!r.is_visible()); - assert_eq!(r.clipping, 1); - assert_eq!(r.layer_id(), Some(1)); - assert_eq!(r.block(b"lclr").unwrap().parsed(), Some(Ok(BlockData::SheetColor(4)))); -} - -#[test] -fn all_blend_modes_via_builder() { - let mut b = PsdBuilder::new(1, 1); - for m in BlendMode::ALL { - let mut s = LayerSpec::new(format!("{m:?}"), 0, 0, 1, 1, PixelData::Rgba8(vec![1, 2, 3, 4])); - s.blend_mode = m; - b.push_layer(s); - } - let f = built(&b); - let modes: Vec<_> = f.layers().iter().map(|l| l.blend_mode).collect(); - assert_eq!(modes, BlendMode::ALL.to_vec()); -} - -#[test] -fn masks_roundtrip() { - let mask_px: Vec = (0..12).map(|i| i * 20).collect(); - let mut s = LayerSpec::new("m", 0, 0, 3, 3, PixelData::Rgba8(vec![100; 36])); - s.mask = Some(MaskSpec { rect: Rect::from_xywh(-1, 0, 4, 3), data: mask_px.clone(), default_color: 255, disabled: true }); - for depth in [8u16, 16] { - let mut b = PsdBuilder::new(3, 3).depth(depth); - let mut s = s.clone(); - if depth == 16 { - s.pixels = PixelData::Rgba16(vec![25700; 36]); - } - b.push_layer(s); - let f = built(&b); - let l = f.layer(0).unwrap(); - let m = l.user_mask().unwrap().unwrap(); - assert_eq!((m.left, m.top, m.width, m.height), (-1, 0, 4, 3)); - assert_eq!(m.data, mask_px); - assert_eq!(m.default_value, 255); - assert!(l.record.layer_mask().unwrap().disabled()); - // Mask is not applied to rgba8. - assert!(l.rgba8().unwrap().data.chunks(4).all(|p| p == [100, 100, 100, 100])); - } -} - -#[test] -fn no_mask_returns_none() { - let mut b = PsdBuilder::new(1, 1); - b.push_layer(LayerSpec::new("x", 0, 0, 1, 1, PixelData::Rgba8(vec![0; 4]))); - let f = built(&b); - assert!(f.layer(0).unwrap().user_mask().is_none()); -} - -#[test] -fn empty_layer() { - let mut b = PsdBuilder::new(2, 2); - b.push_layer(LayerSpec::new("empty", 0, 0, 0, 0, PixelData::Rgba8(vec![]))); - let f = built(&b); - let img = f.layer(0).unwrap().rgba8().unwrap(); - assert_eq!((img.width, img.height), (0, 0)); - assert!(img.data.is_empty()); -} - -#[test] -fn composite_supplied_with_alpha() { - let px = vec![255, 0, 0, 128, 17, 89, 203, 0]; - let mut b = PsdBuilder::new(2, 1); - b.push_layer(LayerSpec::new("x", 0, 0, 2, 1, PixelData::Rgba8(px.clone()))); - b.composite(PixelData::Rgba8(px.clone())); - let f = built(&b); - assert_eq!(f.header.channels, 4); - assert!(f.layer_info.as_ref().unwrap().merged_alpha); - assert!(f.merged_has_alpha()); - assert_eq!(f.has_real_merged_data(), Some(true)); - assert_eq!(f.decode_merged().unwrap(), [255, 17, 127, 89, 127, 203, 128, 0]); - assert_eq!(f.composite_rgba8().unwrap().data, px); -} - -#[test] -fn composite_opaque_drops_alpha() { - let px: Vec = (0..6).flat_map(|i| [i, i, i, 255]).collect(); - let mut b = PsdBuilder::new(3, 2); - b.composite(PixelData::Rgba8(px.clone())); - let f = built(&b); - assert_eq!(f.header.channels, 3); - assert!(f.layer_info.is_none()); - assert_eq!(f.composite_rgba8().unwrap().data, px); -} - -#[test] -fn composite_16bit() { - let px: Vec = vec![65535, 0, 0, 65535, 0, 65535, 0, 32768]; - let mut b = PsdBuilder::new(2, 1).depth(16); - b.composite(PixelData::Rgba16(px)); - let f = built(&b); - assert_eq!(f.composite_rgba8().unwrap().data, vec![255, 0, 0, 255, 0, 255, 0, 128]); -} - -#[test] -fn placeholder_composite_is_flagged() { - let mut b = PsdBuilder::new(2, 2); - b.push_layer(LayerSpec::new("x", 0, 0, 1, 1, PixelData::Rgba8(vec![0; 4]))); - let f = built(&b); - assert_eq!(f.has_real_merged_data(), Some(false)); - assert!(f.composite_rgba8().unwrap().data.iter().all(|&v| v == 255)); -} - -#[test] -fn builder_resources() { - let b = PsdBuilder::new(1, 1).resolution(300.0).icc_profile(vec![1, 2, 3]); - let f = built(&b); - assert!((f.resolution().unwrap().v_res() - 300.0).abs() < 1e-9); - assert_eq!(f.icc_profile(), Some(&[1u8, 2, 3][..])); -} - -#[test] -fn builder_errors() { - let mut b = PsdBuilder::new(2, 2); - b.push_layer(LayerSpec::new("bad", 0, 0, 2, 2, PixelData::Rgba8(vec![0; 3]))); - assert!(b.build().is_err()); - let mut b = PsdBuilder::new(2, 2); - b.push_layer(LayerSpec::new("wrong fmt", 0, 0, 1, 1, PixelData::GrayA8(vec![0; 2]))); - assert!(b.build().is_err()); - let mut b = PsdBuilder::new(2, 2); - b.begin_group(GroupSpec::new("open")); - assert!(b.build().is_err()); - let mut b = PsdBuilder::new(2, 2); - assert!(b.end_group().is_err()); - assert!(PsdBuilder::new(1, 1).depth(32).build().is_err()); - assert!(PsdBuilder::new(1, 1).color_mode(ColorMode::Lab).build().is_err()); - let mut b = PsdBuilder::new(2, 2); - b.composite(PixelData::Rgba8(vec![0; 4])); - assert!(b.build().is_err()); - let mut b = PsdBuilder::new(2, 2); - let mut s = LayerSpec::new("m", 0, 0, 1, 1, PixelData::Rgba8(vec![0; 4])); - s.mask = Some(MaskSpec { rect: Rect::from_xywh(0, 0, 2, 2), data: vec![0; 3], default_color: 0, disabled: false }); - b.push_layer(s); - assert!(b.build().is_err()); -} - -#[test] -fn group_properties() { - let mut b = PsdBuilder::new(1, 1); - b.begin_group(GroupSpec { blend_mode: BlendMode::Multiply, opacity: 77, visible: false, ..GroupSpec::new("G") }); - b.push_layer(LayerSpec::new("x", 0, 0, 1, 1, PixelData::Rgba8(vec![0; 4]))); - b.end_group().unwrap(); - let f = built(&b); - let g = &f.layers()[2]; - assert_eq!(g.name(), "G"); - assert_eq!(g.opacity, 77); - assert!(!g.is_visible()); - let sd = g.section_divider().unwrap(); - assert_eq!(sd.kind, SectionType::OpenFolder); - assert_eq!(sd.blend_mode, Some(BlendMode::Multiply)); - assert_eq!(f.layers()[0].section_type(), SectionType::BoundingDivider); -} - -#[test] -fn psb_builder_large_canvas_header() { - let b = PsdBuilder::new(40_000, 1).version(Version::Psb).compression(Compression::Rle); - let f = built(&b); - assert_eq!(f.header.width, 40_000); - assert!(f.validate().is_ok()); -} - -#[test] -fn iter_layers_indices() { - let mut b = PsdBuilder::new(1, 1); - for i in 0..3 { - b.push_layer(LayerSpec::new(format!("l{i}"), 0, 0, 1, 1, PixelData::Rgba8(vec![0; 4]))); - } - let f = built(&b); - let v: Vec<_> = f.iter_layers().map(|l| (l.index, l.name())).collect(); - assert_eq!(v, vec![(0, "l0".into()), (1, "l1".into()), (2, "l2".into())]); - assert!(f.layer(3).is_none()); - assert_eq!(f.layer(0).unwrap().version(), Version::Psd); -} diff --git a/crates/psd/tests/it/common/atn_roundtrip.rs b/crates/psd/tests/it/common/atn_roundtrip.rs deleted file mode 100644 index ded43b55e2..0000000000 --- a/crates/psd/tests/it/common/atn_roundtrip.rs +++ /dev/null @@ -1,71 +0,0 @@ -//! Shared round-trip invariant for the `.atn` parser contract suite. -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/it/corpus.rs b/crates/psd/tests/it/corpus.rs deleted file mode 100644 index a61f911e23..0000000000 --- a/crates/psd/tests/it/corpus.rs +++ /dev/null @@ -1,129 +0,0 @@ -//! Corpus test (feature `corpus`; run with `cargo xtask test-corpus`): iterates -//! `corpus/psd/**/*.{psd,psb}` and `corpus/psd-tools/**/*.{psd,psb}` at the workspace root -//! (gitignored, fetched and verified by `cargo xtask corpus --all`). A missing corpus fails. -#![cfg(feature = "corpus")] - -use std::path::{Path, PathBuf}; - -use photocraft_psd::PsdFile; - -fn collect(dir: &Path, out: &mut Vec) { - let Ok(rd) = std::fs::read_dir(dir) else { return }; - for e in rd.flatten() { - let p = e.path(); - if p.is_dir() { - collect(&p, out); - } else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("psd") || e.eq_ignore_ascii_case("psb")) { - out.push(p); - } - } -} - -/// The existing pinned ag-psd corpus includes public animation cases. Exercise typed syntax -/// against those without adding personal files or new corpus pins. -#[test] -fn corpus_animation_syntax() { - use photocraft_psd::ResourceData; - use photocraft_psd::animation::{frame_info, frame_sets, layer_frame_states}; - use photocraft_psd::metadata::parse_shmd; - - let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/psd/ag-psd/read-write"); - for (case, delay) in [("animation-frame", Some(30)), ("animation-offset", Some(50)), ("animation-effects", None)] { - for name in ["src.psd", "expected.psd"] { - let path = root.join(case).join(name); - let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}; run cargo xtask corpus --psd", path.display())); - let psd = PsdFile::from_bytes(&bytes).unwrap(); - let mut found = 0; - let mut decoded_descriptors = 0; - for resource in &psd.resources { - if let Some(Ok(ResourceData::Animation(animation))) = resource.parsed() { - found += 1; - assert_eq!(animation.to_bytes().unwrap(), resource.data); - for record in &animation.records { - if let Some(d) = record.descriptor() { - let d = d.unwrap(); - decoded_descriptors += 1; - let frames = frame_info(&d.descriptor).unwrap(); - assert_eq!(frames.len(), 2, "{case}/{name}"); - assert!(frames.iter().all(|f| f.delay_centiseconds == delay), "{case}/{name}"); - let sets = frame_sets(&d.descriptor).unwrap(); - assert_eq!(sets.len(), 1); - assert_eq!(sets[0].frame_ids.len(), 2); - assert!(sets[0].frame_ids.iter().all(|id| frames.iter().any(|f| f.id == *id))); - } - } - } - } - assert_eq!(found, 1, "{case}/{name}"); - assert_eq!(decoded_descriptors, 1, "expected one decoded AnDs descriptor in {case}/{name}"); - let mut state_layers = 0; - for layer in psd.layers() { - for block in &layer.blocks { - if block.key == *b"shmd" { - for item in parse_shmd(&block.data).unwrap() { - if item.key == *b"mlst" { - let d = item.animation_descriptor().unwrap().unwrap(); - let states = layer_frame_states(&d.descriptor).unwrap(); - assert!(!states.states.is_empty()); - state_layers += 1; - } - } - } - } - } - assert_eq!(state_layers, 2, "{case}/{name}"); - assert_eq!(psd.to_bytes().unwrap(), bytes); - } - } -} - -/// Files known to be invalid upstream, with the reason. They are reported but -/// do not fail the test. -const KNOWN_BAD: &[(&str, &str)] = - &[("group-divider-blend-mode.psd", "malformed merged image data; strict parsing rejects it, but the importer recovers its group (#6152)")]; - -#[test] -fn corpus_parse_and_byte_stable() { - for dir in ["corpus/psd", "corpus/psd-tools"] { - parse_and_byte_stable(&Path::new(env!("CARGO_MANIFEST_DIR")).join("../..").join(dir)); - } -} - -fn parse_and_byte_stable(root: &Path) { - assert!(root.is_dir(), "{} is missing: run `cargo xtask corpus --all`", root.display()); - let mut files = Vec::new(); - collect(root, &mut files); - files.sort(); - let mut failures = Vec::new(); - for p in &files { - let name = p.strip_prefix(root).unwrap_or(p).display().to_string(); - let bytes = match std::fs::read(p) { - Ok(b) => b, - Err(e) => { - failures.push(format!("{name}: read error {e}")); - continue; - } - }; - match PsdFile::from_bytes(&bytes) { - Err(e) => { - if let Some((_, why)) = KNOWN_BAD.iter().find(|(f, _)| name.ends_with(f)) { - eprintln!("KNOWN {name}: parse error: {e} ({why})"); - } else { - eprintln!("FAIL {name}: parse error: {e}"); - failures.push(format!("{name}: parse: {e}")); - } - } - Ok(f) => match f.to_bytes() { - Ok(out) if out == bytes => eprintln!("ok {name} ({} layers)", f.layers().len()), - Ok(out) => { - let first = out.iter().zip(&bytes).position(|(a, b)| a != b).unwrap_or(out.len().min(bytes.len())); - eprintln!("DIFF {name}: first difference at {first} (len {} vs {})", out.len(), bytes.len()); - failures.push(format!("{name}: not byte stable (first diff at {first})")); - } - Err(e) => failures.push(format!("{name}: write: {e}")), - }, - } - } - eprintln!("corpus {}: {} files, {} failures", root.display(), files.len(), failures.len()); - assert!(failures.is_empty(), "corpus failures:\n{}", failures.join("\n")); -} diff --git a/crates/psd/tests/it/corpus_atn.rs b/crates/psd/tests/it/corpus_atn.rs deleted file mode 100644 index 32f6367714..0000000000 --- a/crates/psd/tests/it/corpus_atn.rs +++ /dev/null @@ -1,60 +0,0 @@ -//! Corpus test (feature `corpus`; run with `cargo xtask test-corpus`): every `.atn` under -//! `corpus/atn/` (gitignored, fetched by `cargo xtask corpus --atn`) parses, and writing it back -//! reproduces the bytes exactly. A missing corpus fails. -#![cfg(feature = "corpus")] - -use std::path::{Path, PathBuf}; - -use photocraft_psd::atn; - -fn collect(dir: &Path, out: &mut Vec) { - // An unreadable folder fails the test rather than shrinking the corpus. - let rd = std::fs::read_dir(dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display())); - for e in rd { - let p = e.unwrap_or_else(|e| panic!("{}: {e}", dir.display())).path(); - if p.is_dir() { - collect(&p, out); - } else if p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("atn")) { - out.push(p); - } - } -} - -/// Sets in the corpus; raise, never lower. -const FLOOR: usize = 16; - -#[test] -fn atn_corpus_parses_and_is_byte_stable() { - let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/atn"); - assert!(root.is_dir(), "{} is missing: run `cargo xtask corpus --atn`", root.display()); - let mut files = Vec::new(); - collect(&root, &mut files); - files.sort(); - let mut failures = Vec::new(); - let (mut actions, mut steps) = (0usize, 0usize); - for p in &files { - let name = p.strip_prefix(&root).unwrap_or(p).display().to_string(); - let bytes = std::fs::read(p).unwrap(); - let file = match atn::parse(&bytes) { - Ok(f) => f, - Err(e) => { - failures.push(format!("{name}: {e}")); - continue; - } - }; - if !file.warnings.is_empty() { - failures.push(format!("{name}: warnings {:?}", file.warnings)); - } - actions += file.actions.len(); - steps += file.actions.iter().map(|a| a.items.len()).sum::(); - match atn::write(&file) { - Ok(written) if written == bytes => {} - Ok(written) => failures.push(format!("{name}: rewritten bytes differ ({} vs {} bytes)", written.len(), bytes.len())), - Err(e) => failures.push(format!("{name}: write failed: {e}")), - } - println!("{name}: {} actions, {} steps", file.actions.len(), file.actions.iter().map(|a| a.items.len()).sum::()); - } - println!("{} files, {actions} actions, {steps} steps", files.len()); - assert!(files.len() >= FLOOR, "only {} .atn files; the corpus floor is {FLOOR}", files.len()); - assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); -} diff --git a/crates/psd/tests/it/layer_block_order.rs b/crates/psd/tests/it/layer_block_order.rs deleted file mode 100644 index fb2646c691..0000000000 --- a/crates/psd/tests/it/layer_block_order.rs +++ /dev/null @@ -1,26 +0,0 @@ -//! The global layer block retains its insertion position and neighboring opaque blocks. -use photocraft_psd::*; - -#[test] -fn global_layer_block_roundtrips_with_opaque_neighbors() { - for version in [Version::Psd, Version::Psb] { - for depth in [16, 32] { - for index in 0..=2 { - for signature in [*b"8BIM", *b"8B64"] { - let mut file = testgen::layered(version, ColorMode::Rgb, depth, Compression::Raw); - file.global_blocks = vec![TaggedBlock::new(*b"zz01", vec![7, 8, 9]), TaggedBlock::new(*b"zz02", vec![10, 11])]; - file.layer_info_placement = LayerInfoPlacement::GlobalBlock { - index, - signature, - key: if depth == 16 { *b"Lr16" } else { *b"Lr32" }, - padding: Some(vec![31, 32, 33]), - }; - let bytes = file.to_bytes().unwrap(); - let parsed = PsdFile::from_bytes(&bytes).unwrap(); - assert_eq!(parsed, file, "{version:?} {depth} {index} {signature:?}"); - assert_eq!(parsed.to_bytes().unwrap(), bytes); - } - } - } - } -} diff --git a/crates/psd/tests/it/main.rs b/crates/psd/tests/it/main.rs deleted file mode 100644 index fef8708849..0000000000 --- a/crates/psd/tests/it/main.rs +++ /dev/null @@ -1,15 +0,0 @@ -//! The crate's integration tests, linked into one test binary. - -mod animation; -mod atn_contract; -mod atn_v12; -mod builder; -mod corpus; -mod corpus_atn; -mod layer_block_order; -mod malformed; -mod merged_recovery; -mod proptests; -mod roundtrip; -mod swatch_malformed; -mod tree; diff --git a/crates/psd/tests/it/malformed.rs b/crates/psd/tests/it/malformed.rs deleted file mode 100644 index cd8a0d7dab..0000000000 --- a/crates/psd/tests/it/malformed.rs +++ /dev/null @@ -1,283 +0,0 @@ -//! Malformed input handling: every error path must return `Err`, never panic. - -use photocraft_psd::testgen; -use photocraft_psd::*; -use proptest::prelude::*; - -fn truncation_sweep(bytes: &[u8], name: &str) { - for cut in 0..bytes.len() { - let r = PsdFile::from_bytes(&bytes[..cut]); - assert!(r.is_err(), "{name}: truncation at {cut}/{} parsed successfully", bytes.len()); - } - assert!(PsdFile::from_bytes(bytes).is_ok(), "{name}: full file must parse"); -} - -macro_rules! trunc { - ($name:ident, $ver:expr, $comp:expr) => { - #[test] - fn $name() { - let b = testgen::small($ver, $comp).to_bytes().unwrap(); - truncation_sweep(&b, stringify!($name)); - } - }; -} - -trunc!(truncate_small_psd_raw, Version::Psd, Compression::Raw); -trunc!(truncate_small_psd_rle, Version::Psd, Compression::Rle); -trunc!(truncate_small_psd_zip, Version::Psd, Compression::Zip); -trunc!(truncate_small_psd_zipp, Version::Psd, Compression::ZipPrediction); -trunc!(truncate_small_psb_raw, Version::Psb, Compression::Raw); -trunc!(truncate_small_psb_rle, Version::Psb, Compression::Rle); -trunc!(truncate_small_psb_zip, Version::Psb, Compression::Zip); -trunc!(truncate_small_psb_zipp, Version::Psb, Compression::ZipPrediction); - -#[test] -fn truncate_merged_only_all_modes() { - for mode in testgen::MODES { - for &depth in testgen::mode_depths(mode) { - let b = testgen::merged_only(Version::Psd, mode, depth, Compression::Rle, 5, 3).to_bytes().unwrap(); - truncation_sweep(&b, &format!("{mode:?} {depth}")); - } - } -} - -#[test] -fn truncate_builder_16bit_lr16() { - let mut b = PsdBuilder::new(3, 2).depth(16); - b.push_layer(LayerSpec::new("x", 0, 0, 3, 2, PixelData::Rgba16(vec![1000; 24]))); - let bytes = b.to_bytes().unwrap(); - truncation_sweep(&bytes, "builder 16"); -} - -#[test] -fn empty_input() { - assert!(matches!(PsdFile::from_bytes(&[]), Err(PsdError::UnexpectedEof { .. }))); -} - -#[test] -fn bad_file_signature() { - let mut b = testgen::small(Version::Psd, Compression::Raw).to_bytes().unwrap(); - b[..4].copy_from_slice(b"8BPX"); - assert!(matches!(PsdFile::from_bytes(&b), Err(PsdError::InvalidSignature { .. }))); -} - -#[test] -fn bad_version() { - let mut b = testgen::small(Version::Psd, Compression::Raw).to_bytes().unwrap(); - for v in [0u16, 3, 0xffff] { - b[4..6].copy_from_slice(&v.to_be_bytes()); - assert_eq!(PsdFile::from_bytes(&b), Err(PsdError::UnsupportedVersion(v))); - } -} - -#[test] -fn bad_depth_and_channels() { - let good = testgen::small(Version::Psd, Compression::Raw).to_bytes().unwrap(); - let mut b = good.clone(); - b[22..24].copy_from_slice(&7u16.to_be_bytes()); - assert!(PsdFile::from_bytes(&b).is_err()); - let mut b = good.clone(); - b[12..14].copy_from_slice(&0u16.to_be_bytes()); - assert!(PsdFile::from_bytes(&b).is_err()); - let mut b = good; - b[12..14].copy_from_slice(&57u16.to_be_bytes()); - assert!(PsdFile::from_bytes(&b).is_err()); -} - -#[test] -fn oversized_dimensions_rejected() { - let mut b = testgen::small(Version::Psb, Compression::Raw).to_bytes().unwrap(); - b[14..18].copy_from_slice(&300_001u32.to_be_bytes()); - assert!(matches!(PsdFile::from_bytes(&b), Err(PsdError::LimitExceeded(_)))); -} - -#[test] -fn zero_dimensions_rejected() { - // Height is bytes 14..18 and width 18..22; the spec range starts at 1. - let good = testgen::small(Version::Psd, Compression::Raw).to_bytes().unwrap(); - for range in [14..18, 18..22, 14..22] { - let mut b = good.clone(); - b[range.clone()].fill(0); - let err = PsdFile::from_bytes(&b).unwrap_err(); - assert!(err.to_string().contains("at least 1x1"), "{range:?}: {err}"); - } - let mut f = testgen::small(Version::Psd, Compression::Raw); - f.header.width = 0; - assert!(f.validate().is_err(), "a zero-sized header must not pass the writer's validation"); -} - -#[test] -fn huge_declared_dimensions_small_data() { - // 300000² RLE image with 16 bytes of data must fail fast, not allocate. - let mut f = testgen::merged_only(Version::Psb, ColorMode::Grayscale, 8, Compression::Rle, 1, 1); - f.header.width = 300_000; - f.header.height = 300_000; - let b = f.to_bytes().unwrap(); - assert!(PsdFile::from_bytes(&b).is_err()); - // ZIP over `MAX_DECODED_BYTES` is not inflated at parse time (#2926); decoding refuses it. - f.image_data.compression = Compression::Zip; - f.image_data.data = compression::zip_compress(&[0; 100]); - let b = f.to_bytes().unwrap(); - assert!(matches!(PsdFile::from_bytes(&b).and_then(|f| f.decode_merged()), Err(PsdError::LimitExceeded(_)))); -} - -#[test] -fn bad_resource_signature() { - let f = testgen::small(Version::Psd, Compression::Raw); - let mut b = f.to_bytes().unwrap(); - // header 26 + color mode len 4 + resources len 4 → first resource sig. - b[34..38].copy_from_slice(b"XXXX"); - assert!(matches!(PsdFile::from_bytes(&b), Err(PsdError::InvalidSignature { .. }))); -} - -#[test] -fn bad_layer_blend_signature() { - let f = testgen::small(Version::Psd, Compression::Raw); - let b = f.to_bytes().unwrap(); - let pos = b.windows(8).position(|w| w == b"8BIMnorm").expect("blend sig"); - let mut b2 = b.clone(); - b2[pos..pos + 4].copy_from_slice(b"XBIM"); - assert!(PsdFile::from_bytes(&b2).is_err()); -} - -#[test] -fn oversized_section_lengths() { - let f = testgen::small(Version::Psd, Compression::Raw); - let b = f.to_bytes().unwrap(); - // Color mode data length. - let mut b2 = b.clone(); - b2[26..30].copy_from_slice(&u32::MAX.to_be_bytes()); - assert!(PsdFile::from_bytes(&b2).is_err()); - // Resource section length. - let mut b3 = b.clone(); - b3[30..34].copy_from_slice(&u32::MAX.to_be_bytes()); - assert!(PsdFile::from_bytes(&b3).is_err()); -} - -#[test] -fn corrupt_zip_merged_rejected() { - let mut f = testgen::small(Version::Psd, Compression::Zip); - let n = f.image_data.data.len(); - f.image_data.data[n / 2] ^= 0xff; - f.image_data.data[n / 2 + 1] ^= 0x55; - let b = f.to_bytes().unwrap(); - assert!(PsdFile::from_bytes(&b).is_err()); -} - -#[test] -fn corrupt_layer_channel_is_lazy_error() { - let mut f = testgen::small(Version::Psd, Compression::Rle); - let ch = &mut f.layers_mut()[0].channels[1]; - let id = ch.id; - for b in ch.data.iter_mut() { - *b = 0x7f; - } - let bytes = f.to_bytes().unwrap(); - let p = PsdFile::from_bytes(&bytes).expect("lazy: parse succeeds"); - assert!(p.layers()[0].decode_channel(id, 8, Version::Psd).is_err()); - assert!(p.layer(0).unwrap().rgba8().is_err()); -} - -#[test] -fn negative_layer_rect_decode_errors() { - let mut f = testgen::small(Version::Psd, Compression::Raw); - f.layers_mut()[0].rect = Rect { top: 10, left: 0, bottom: 0, right: 4 }; - let b = f.to_bytes().unwrap(); - let p = PsdFile::from_bytes(&b).unwrap(); - assert!(p.layers()[0].decode_channel(0, 8, Version::Psd).is_err()); - assert!(p.layer(0).unwrap().rgba8().is_err()); -} - -#[test] -fn too_many_layer_channels() { - let f = testgen::small(Version::Psd, Compression::Raw); - let b = f.to_bytes().unwrap(); - let li = b.windows(4).position(|w| w == [0, 0xff, 0xff, 0xff]).is_some(); - let _ = li; - // Construct directly: layer count 1, rect, channel count 0xffff. - let mut f2 = testgen::merged_only(Version::Psd, ColorMode::Rgb, 8, Compression::Raw, 1, 1); - f2.layer_info = Some(LayerInfo::default()); - let mut b2 = f2.to_bytes().unwrap(); - // Find layer info: after resources. Locate the 2-byte count (0) and - // replace with a malformed record. - let res_len = u32::from_be_bytes(b2[30..34].try_into().unwrap()) as usize; - let lm = 34 + res_len; - let mut rec = vec![0, 1]; - rec.extend_from_slice(&[0; 16]); - rec.extend_from_slice(&0xffffu16.to_be_bytes()); - let li_len = rec.len() as u32; - let mut section = li_len.to_be_bytes().to_vec(); - section.extend_from_slice(&rec); - let mut out = b2[..lm].to_vec(); - out.extend_from_slice(&(section.len() as u32).to_be_bytes()); - out.extend_from_slice(§ion); - let old_lm_len = u32::from_be_bytes(b2[lm..lm + 4].try_into().unwrap()) as usize; - out.extend_from_slice(&b2[lm + 4 + old_lm_len..]); - b2 = out; - assert!(matches!(PsdFile::from_bytes(&b2), Err(PsdError::LimitExceeded(_)) | Err(PsdError::UnexpectedEof { .. }))); -} - -proptest! { - #![proptest_config(ProptestConfig::with_cases(256))] - - #[test] - fn random_bytes_never_panic(data in proptest::collection::vec(any::(), 0..512)) { - let _ = PsdFile::from_bytes(&data); - } - - #[test] - fn random_bytes_with_valid_header_never_panic(tail in proptest::collection::vec(any::(), 0..512)) { - let mut data = testgen::small(Version::Psd, Compression::Raw).to_bytes().unwrap()[..26].to_vec(); - data.extend(tail); - let _ = PsdFile::from_bytes(&data); - } - - #[test] - fn mutations_never_panic( - idx in proptest::collection::vec(any::(), 1..8), - vals in proptest::collection::vec(any::(), 8), - psb in any::(), - comp in 0usize..4, - ) { - let v = if psb { Version::Psb } else { Version::Psd }; - let mut b = testgen::small(v, Compression::ALL[comp]).to_bytes().unwrap(); - for (i, ix) in idx.iter().enumerate() { - let at = ix.index(b.len()); - b[at] = vals[i]; - } - if let Ok(f) = PsdFile::from_bytes(&b) { - // Anything that parses must also be writable and decodable - // without panicking. - let _ = f.to_bytes(); - let _ = f.decode_merged(); - let _ = f.composite_rgba8(); - let _ = f.layer_tree(); - for l in f.iter_layers() { - let _ = l.rgba8(); - let _ = l.user_mask(); - let _ = l.name(); - for bl in &l.record.blocks { - let _ = bl.parsed(); - } - } - for r in &f.resources { - let _ = r.parsed(); - } - } - } - - #[test] - fn parsed_mutants_are_byte_stable( - idx in any::(), - val in any::(), - ) { - let mut b = testgen::small(Version::Psd, Compression::Rle).to_bytes().unwrap(); - let at = idx.index(b.len()); - b[at] = val; - if let Ok(f) = PsdFile::from_bytes(&b) { - let out = f.to_bytes().unwrap(); - let g = PsdFile::from_bytes(&out).unwrap(); - prop_assert_eq!(g, f); - } - } -} diff --git a/crates/psd/tests/it/merged_recovery.rs b/crates/psd/tests/it/merged_recovery.rs deleted file mode 100644 index 40e310d8a4..0000000000 --- a/crates/psd/tests/it/merged_recovery.rs +++ /dev/null @@ -1,43 +0,0 @@ -//! Opt-in merged-image recovery must not weaken strict parsing or lose encoded bytes. - -use photocraft_psd::{Compression, PsdError, PsdFile, Version, compression, testgen}; - -#[test] -fn recovery_is_explicit_and_preserves_the_original_file() { - for version in [Version::Psd, Version::Psb] { - for compression in Compression::ALL { - let mut original = testgen::small(version, compression); - original.image_data.data.pop(); - let bytes = original.to_bytes().unwrap(); - let strict_error = PsdFile::from_bytes(&bytes).unwrap_err(); - for want in [false, true] { - let rejected = PsdFile::from_bytes_and_merged_recovering(&bytes, |_| want, |_| false).unwrap_err(); - assert_eq!(rejected, strict_error); - let (file, merged) = PsdFile::from_bytes_and_merged_recovering(&bytes, |_| want, |_| true).unwrap(); - assert_eq!(merged.unwrap().unwrap_err(), strict_error); - assert_eq!(file, original); - assert_eq!(file.to_bytes().unwrap(), bytes, "{version:?} {compression:?}"); - } - } - } -} - -#[test] -fn recovery_does_not_accept_missing_compression_or_incomplete_layers() { - let original = testgen::small(Version::Psd, Compression::Raw); - let bytes = original.to_bytes().unwrap(); - let merged_offset = bytes.len() - original.image_data.data.len() - 2; - for cut in [merged_offset - 1, merged_offset, merged_offset + 1] { - assert!(PsdFile::from_bytes_and_merged_recovering(&bytes[..cut], |_| true, |_| true).is_err(), "cut {cut}"); - } -} - -#[test] -fn recovery_never_suppresses_a_merged_stream_limit_error() { - let mut original = testgen::small(Version::Psd, Compression::Zip); - original.image_data.data = compression::zip_compress(&vec![0; (1 << 20) + 4096]); - let bytes = original.to_bytes().unwrap(); - for want in [false, true] { - assert!(matches!(PsdFile::from_bytes_and_merged_recovering(&bytes, |_| want, |_| true), Err(PsdError::LimitExceeded(_)))); - } -} diff --git a/crates/psd/tests/it/proptests.rs b/crates/psd/tests/it/proptests.rs deleted file mode 100644 index 23d6bcd01b..0000000000 --- a/crates/psd/tests/it/proptests.rs +++ /dev/null @@ -1,549 +0,0 @@ -//! Property-based round-trip tests. - -use photocraft_psd::compression::{PlaneLayout, decode_planes, encode_planes, packbits}; -use photocraft_psd::testgen; -use photocraft_psd::*; -use proptest::prelude::*; - -fn version() -> impl Strategy { - prop_oneof![Just(Version::Psd), Just(Version::Psb)] -} -fn compression() -> impl Strategy { - prop_oneof![Just(Compression::Raw), Just(Compression::Rle), Just(Compression::Zip), Just(Compression::ZipPrediction)] -} -fn depth() -> impl Strategy { - prop_oneof![Just(1u16), Just(8), Just(16), Just(32)] -} - -proptest! { - #![proptest_config(ProptestConfig::with_cases(128))] - - #[test] - fn packbits_roundtrip(data in proptest::collection::vec(any::(), 0..600)) { - let enc = packbits::encode_vec(&data); - prop_assert_eq!(packbits::decode(&enc, data.len()).unwrap(), data.clone()); - // Worst case expansion is 1 header byte per 128 literal bytes. - prop_assert!(enc.len() <= data.len() + data.len().div_ceil(128)); - } - - #[test] - fn packbits_runs_roundtrip(runs in proptest::collection::vec((any::(), 1usize..300), 0..20)) { - let data: Vec = runs.iter().flat_map(|&(b, n)| std::iter::repeat_n(b, n)).collect(); - let enc = packbits::encode_vec(&data); - prop_assert_eq!(packbits::decode(&enc, data.len()).unwrap(), data); - } - - #[test] - fn packbits_decode_garbage_never_panics(data in proptest::collection::vec(any::(), 0..64), n in 0usize..512) { - let _ = packbits::decode(&data, n); - } - - #[test] - fn channel_codecs_roundtrip( - w in 0usize..40, h in 0usize..12, planes in 1usize..4, - d in depth(), v in version(), c in compression(), seed in any::(), - ) { - let l = PlaneLayout { planes, width: w, height: h, depth: d, version: v }; - let n = l.decoded_len().unwrap(); - let mut x = seed; - let data: Vec = (0..n).map(|_| { x = x.wrapping_mul(6364136223846793005).wrapping_add(1); if x >> 62 == 0 { 0 } else { (x >> 33) as u8 } }).collect(); - let enc = encode_planes(c, &data, &l).unwrap(); - prop_assert_eq!(decode_planes(c, &enc, &l).unwrap(), data); - } - - #[test] - fn channel_decode_garbage_never_panics( - data in proptest::collection::vec(any::(), 0..128), - w in 0usize..20, h in 0usize..8, d in depth(), v in version(), c in 0u16..5, - ) { - let l = PlaneLayout { planes: 1, width: w, height: h, depth: d, version: v }; - let _ = decode_planes(Compression::from_u16(c), &data, &l); - } - - #[test] - fn generated_small_files_roundtrip(v in version(), c in compression()) { - let f = testgen::small(v, c); - let b = f.to_bytes().unwrap(); - let p = PsdFile::from_bytes(&b).unwrap(); - prop_assert_eq!(&p, &f); - prop_assert_eq!(p.to_bytes().unwrap(), b); - } - - #[test] - fn merged_only_random_sizes_roundtrip( - w in 1u32..30, h in 1u32..10, v in version(), c in compression(), mode_ix in 0usize..8, depth_ix in 0usize..3, - ) { - let mode = testgen::MODES[mode_ix]; - let depths = testgen::mode_depths(mode); - let d = depths[depth_ix % depths.len()]; - let f = testgen::merged_only(v, mode, d, c, w, h); - let b = f.to_bytes().unwrap(); - let p = PsdFile::from_bytes(&b).unwrap(); - prop_assert_eq!(&p, &f); - prop_assert_eq!(p.to_bytes().unwrap(), b); - } - - #[test] - fn builder_random_layers_roundtrip( - layers in proptest::collection::vec( - (-20i32..20, -20i32..20, 0u32..9, 0u32..9, any::(), 0usize..28, any::(), "[a-zA-Z0-9 äöü😀]{0,12}"), - 0..6, - ), - v in version(), c in compression(), sixteen in any::(), - ) { - let depth = if sixteen { 16 } else { 8 }; - let mut b = PsdBuilder::new(16, 16).version(v).compression(c).depth(depth); - let mut expected = Vec::new(); - for (i, (x, y, w, h, op, bm, vis, name)) in layers.iter().enumerate() { - let n = (*w * *h) as usize; - let px8: Vec = (0..n * 4).map(|k| (k * 31 + i * 7) as u8).collect(); - let pixels = if sixteen { - PixelData::Rgba16(px8.iter().map(|&p| u16::from(p) * 257).collect()) - } else { - PixelData::Rgba8(px8.clone()) - }; - let mut s = LayerSpec::new(name.clone(), *x, *y, *w, *h, pixels); - s.opacity = *op; - s.blend_mode = BlendMode::ALL[*bm]; - s.visible = *vis; - b.push_layer(s); - expected.push((name.clone(), px8, *op, BlendMode::ALL[*bm], *vis)); - } - let bytes = b.to_bytes().unwrap(); - let f = PsdFile::from_bytes(&bytes).unwrap(); - prop_assert_eq!(f.to_bytes().unwrap(), bytes); - prop_assert_eq!(f.layers().len(), expected.len()); - for (l, (name, px, op, bm, vis)) in f.iter_layers().zip(expected) { - prop_assert_eq!(l.name(), name); - prop_assert_eq!(l.rgba8().unwrap().data, px); - prop_assert_eq!(l.record.opacity, op); - prop_assert_eq!(l.record.blend_mode, bm); - prop_assert_eq!(l.record.is_visible(), vis); - } - } - - #[test] - fn tagged_blocks_roundtrip( - blocks in proptest::collection::vec( - (any::<[u8; 4]>(), proptest::collection::vec(any::(), 0..40), any::(), 0usize..4), - 0..8, - ), - v in version(), - ) { - let mut f = testgen::small(v, Compression::Raw); - for (key, data, b64, pad) in blocks { - let mut tb = TaggedBlock::new(key, data); - if b64 { tb.signature = *b"8B64"; } - // Only padding patterns the detector can recover are modeled: - // zeros up to 3 bytes. - tb.padding = match pad { 0 => None, n => Some(vec![0; n - 1]) }; - if tb.padding.as_ref().is_some_and(|p| p.len() == (4 - tb.data.len() % 4) % 4) { - tb.padding = None; - } - f.global_blocks.push(tb); - } - let b = f.to_bytes().unwrap(); - let p = PsdFile::from_bytes(&b).unwrap(); - prop_assert_eq!(&p, &f); - prop_assert_eq!(p.to_bytes().unwrap(), b); - } -} - -// The three standalone swatch/gradient parsers sit outside `PsdFile::from_bytes`, so their -// round-trip invariants and no-panic guarantee get their own properties here. `write` covers only -// what each format can express, so each property states the invariant that actually holds instead -// of claiming byte equality everywhere. - -/// A position or midpoint the writer can actually store: the file keeps 1/4096ths, so generating -/// arbitrary `0.0..=1.0` values would make every property fail on quantisation, not on a bug. -fn unit() -> impl Strategy { - (0.0f32..=1.0).prop_map(|v| (v * 4096.0).round() / 4096.0) -} - -proptest! { - #![proptest_config(ProptestConfig::with_cases(128))] - - #[test] - fn grd_roundtrip_keeps_stops_in_range( - stops in proptest::collection::vec((unit(), unit(), any::()), 0..12), - opacity in proptest::collection::vec((unit(), unit(), unit()), 0..12), - ) { - use photocraft_psd::grd::{self, GrdColor, GrdGradient, GrdStop}; - let g = GrdGradient { - name: "p".into(), - noise: false, - stops: stops.iter().map(|&(l, m, tone)| GrdStop { - location: l, - midpoint: m, - color: GrdColor::Rgb([tone as f32 / 255.0, 0.0, 0.0]), - }).collect(), - opacity: opacity.clone(), - }; - let bytes = grd::write(&[g]); - let parsed = grd::parse(&bytes).unwrap(); - prop_assert_eq!(parsed.len(), 1); - let back = &parsed[0]; - prop_assert_eq!(back.stops.len(), stops.len()); - prop_assert_eq!(back.opacity.len(), opacity.len()); - for (a, b) in back.stops.iter().zip(&stops) { - prop_assert!(a.location.is_finite() && (0.0..=1.0).contains(&a.location)); - prop_assert!((a.location - b.0).abs() < 1.0 / 4096.0); - prop_assert!(a.midpoint.is_finite() && (0.0..=1.0).contains(&a.midpoint)); - prop_assert!((a.midpoint - b.1).abs() < 0.01); - // The colour was written, so it must come back: a parser that zeroed every colour - // would pass a property that only looked at positions. - let GrdColor::Rgb([r, g, bl]) = a.color else { - prop_assert!(false, "colour must survive the round trip"); - return Ok(()); - }; - prop_assert!((r - b.2 as f32 / 255.0).abs() < 1.0 / 255.0, "red channel {r} lost"); - prop_assert!(g.is_finite() && g.abs() < 1.0 / 255.0, "green channel {g} corrupted"); - prop_assert!(bl.is_finite() && bl.abs() < 1.0 / 255.0, "blue channel {bl} corrupted"); - } - for (a, b) in back.opacity.iter().zip(&opacity) { - prop_assert!(a.0.is_finite() && (0.0..=1.0).contains(&a.0)); - prop_assert!((0.0..=1.0).contains(&a.1)); - prop_assert!(a.2.is_finite() && (0.0..=1.0).contains(&a.2)); - prop_assert!((a.0 - b.0).abs() < 1.0 / 4096.0); - prop_assert!((a.1 - b.1).abs() < 0.01); - prop_assert!((a.2 - b.2).abs() < 0.01, "transparency midpoint not preserved"); - } - } - - #[test] - fn ase_roundtrip_is_byte_stable_after_one_write( - swatches in proptest::collection::vec(("[ -~]{0,20}", any::()), 0..10), - ) { - use photocraft_psd::ase::{self, AseColor, AseEntry, AseFile, AseKind, AseSwatch}; - let mk = |(name, tone): &(String, u8)| AseSwatch { - name: name.clone(), - color: AseColor::Rgb([*tone as f32 / 255.0, 0.0, 0.0]), - kind: AseKind::Process, - }; - let file = AseFile { - entries: vec![ - AseEntry::Group { name: "g".into(), swatches: swatches.iter().take(3).map(mk).collect() }, - AseEntry::Group { name: "h".into(), swatches: swatches.iter().skip(3).map(mk).collect() }, - ], - }; - let bytes = ase::write(&file).unwrap(); - let back = ase::parse(&bytes).unwrap(); - prop_assert_eq!(back.swatch_count(), swatches.len()); - prop_assert_eq!(ase::write(&back).unwrap(), bytes, "a second round trip is byte-stable"); - } - - #[test] - fn aco_roundtrip_is_byte_stable( - swatches in proptest::collection::vec(("[ -~]{0,20}", any::(), any::()), 0..10), - ) { - use photocraft_psd::aco::{self, AcoColor, AcoSwatch}; - let s: Vec = swatches.iter().map(|(name, space, v)| AcoSwatch { - name: name.clone(), - color: match space % 3 { - 0 => AcoColor::Rgb([*v, 0, 0]), - 1 => AcoColor::Gray(*v), - _ => AcoColor::Lab { l: *v, a: -12800, b: 12700 }, - }, - }).collect(); - let bytes = aco::write(&s).unwrap(); - let back = aco::parse(&bytes).unwrap(); - prop_assert_eq!(&back.swatches, &s); - prop_assert_eq!(aco::write(&back.swatches).unwrap(), bytes, "a second round trip is byte-stable"); - } - - /// A name longer than the cap is truncated on the way in, so the file stays writable and the - /// bytes settle after one round trip. - #[test] - fn aco_long_names_settle_after_one_truncation(len in 1024usize..4000) { - use photocraft_psd::aco::{self, AcoColor, AcoSwatch}; - let s = vec![AcoSwatch { name: "x".repeat(len), color: AcoColor::Gray(5000) }]; - let once = aco::write(&s).unwrap(); - let back = aco::parse(&once).unwrap(); - prop_assert_eq!(back.swatches[0].name.encode_utf16().count(), aco::MAX_NAME_UNITS); - prop_assert_eq!(aco::write(&back.swatches).unwrap(), once); - } - - /// Pure junk rarely gets past the signature check, so most of each parser is never reached. - /// These damage files that are already valid instead, which is where the interesting inputs - /// live: well-formed structure with one byte corrupted. - #[test] - fn swatch_parsers_never_panic_on_damaged_valid_files( - idx in 0usize..4000, - bit in 0u32..8, - mask in 0u8..=255, - ) { - use photocraft_psd::{aco, ase, grd}; - let grd_bytes = { - use photocraft_psd::grd::{GrdColor, GrdGradient, GrdStop, write}; - write(&[GrdGradient { - name: "d".into(), - noise: false, - stops: vec![GrdStop { location: 0.25, midpoint: 0.5, color: GrdColor::Rgb([1.0, 0.5, 0.0]) }], - opacity: vec![(0.5, 1.0, 0.5)], - }]) - }; - let ase_bytes = { - use photocraft_psd::ase::{write, AseColor, AseEntry, AseFile, AseKind, AseSwatch}; - let sw = || AseSwatch { name: "d".into(), color: AseColor::Rgb([1.0, 0.0, 0.0]), kind: AseKind::Process }; - write(&AseFile { - entries: vec![AseEntry::Group { name: "g".into(), swatches: vec![sw()] }, AseEntry::Swatch(sw())], - }) - .unwrap() - }; - let aco_bytes = aco::write(&[aco::AcoSwatch { name: "d".into(), color: aco::AcoColor::Rgb([1, 2, 3]) }]).unwrap(); - - let damage = |mut b: Vec| -> Vec { - if !b.is_empty() { - let i = idx % b.len(); - b[i] ^= 1 << bit; - b[i] = b[i].wrapping_add(mask); - } - b - }; - let _ = grd::parse(&damage(grd_bytes)); - let _ = ase::parse(&damage(ase_bytes)); - let _ = aco::parse(&damage(aco_bytes)); - } - - /// Names that are not ASCII, so the name-unit cap can land between the two halves of a - /// surrogate pair. The cap counts UTF-16 code units, so that split is the boundary case. - #[test] - fn aco_non_ascii_names_are_capped_and_still_round_trip(len in 600usize..2600) { - use photocraft_psd::aco::{self, AcoColor, AcoSwatch}; - // One leading ASCII character, then two-unit pairs. Without it the cap would always - // fall on a pair boundary and the half-written case this property exists for would - // never happen. - let name = format!("a{}", "\u{1F600}".repeat(len / 2 + 1)); - let s = vec![AcoSwatch { name: name.clone(), color: AcoColor::Gray(5000) }]; - let once = aco::write(&s).unwrap(); - let back = aco::parse(&once).unwrap(); - let got = back.swatches[0].name.encode_utf16().count(); - prop_assert!(got <= aco::MAX_NAME_UNITS, "name came back as {got} units"); - // The cap cuts on a character, so the result is a prefix of the input: whole characters - // only, and never a lone surrogate. - prop_assert!(name.starts_with(&back.swatches[0].name), "the capped name must be a prefix of the input"); - prop_assert_eq!(aco::write(&back.swatches).unwrap(), once); - } - - /// Arbitrary bytes must never panic in any of the three parsers, whatever the length. - #[test] - fn swatch_parsers_never_panic_on_arbitrary_bytes(data in proptest::collection::vec(any::(), 0..400)) { - let _ = photocraft_psd::grd::parse(&data); - let _ = photocraft_psd::ase::parse(&data); - let _ = photocraft_psd::aco::parse(&data); - } -} - -// The five auxiliary binary parsers (image resources, metadata setting, patterns, filter-effects -// caches and the per-block tagged-block views) parse structures that sit outside the whole-file -// `PsdFile::from_bytes` path when read on their own. Their round-trip invariants and no-panic -// guarantee get their own properties here, so normal CI covers them: the matching fuzz targets run -// only on a manual trigger. - -/// A small, valid pattern at a byte-aligned depth, generated the way the unit `pat()` helper builds -/// one: `mode_channels(mode)` colour planes of `width × height × bytes-per-sample`, optional alpha. -fn pattern_strategy() -> impl Strategy { - (prop_oneof![Just(1u32), Just(3u32), Just(4u32)], 1u32..8, 1u32..6, prop_oneof![Just(8u16), Just(16), Just(32)], any::(), any::()).prop_map( - |(mode, width, height, depth, alpha, seed)| { - let bpp = usize::from(depth / 8); - let plane = |s: u64| (0..width as usize * height as usize * bpp).map(|i| (i as u64).wrapping_mul(31).wrapping_add(s) as u8).collect::>(); - let nc = patterns::mode_channels(mode); - patterns::PsdPattern { - mode, - width, - height, - name: "p".into(), - id: "0bd2d3ba-1234-11d4-8f8f-aabbccddeeff".into(), - palette: None, - depth, - channels: (0..nc).map(|c| plane(seed.wrapping_add(c as u64 + 1))).collect(), - alpha: alpha.then(|| plane(seed ^ 0xffff)), - } - }, - ) -} - -proptest! { - #![proptest_config(ProptestConfig::with_cases(128))] - - /// `shmd` is exact: Photoshop keeps each item's even padding inside its stored length, so a - /// built block writes, parses and re-writes byte for byte. - #[test] - fn metadata_shmd_round_trip_is_exact( - items in proptest::collection::vec((any::<[u8; 4]>(), proptest::collection::vec(any::(), 0..40)), 0..8), - ) { - use photocraft_psd::metadata::{MetadataItem, parse_shmd, write_shmd}; - let items: Vec = items.into_iter().map(|(k, d)| MetadataItem::new(k, d)).collect(); - let bytes = write_shmd(&items); - let back = parse_shmd(&bytes).unwrap(); - prop_assert_eq!(&back, &items); - prop_assert_eq!(write_shmd(&back), bytes); - } - - #[test] - fn metadata_shmd_never_panics(data in proptest::collection::vec(any::(), 0..400)) { - let _ = photocraft_psd::metadata::parse_shmd(&data); - } - - /// A built pattern round-trips through both the `Patt`/`Pat2`/`Pat3` block and the `.pat` file, - /// and re-serialising a parsed block is byte-stable. - #[test] - fn pattern_blocks_round_trip(ps in proptest::collection::vec(pattern_strategy(), 0..4)) { - use photocraft_psd::patterns::{parse_pat_file, parse_pattern_block, write_pat_file, write_pattern_block}; - let blk = write_pattern_block(&ps).unwrap(); - prop_assert_eq!(parse_pattern_block(&blk).unwrap(), ps.clone()); - prop_assert_eq!(write_pattern_block(&parse_pattern_block(&blk).unwrap()).unwrap(), blk); - let f = write_pat_file(&ps).unwrap(); - prop_assert_eq!(parse_pat_file(&f).unwrap(), ps); - } - - #[test] - fn pattern_parsers_never_panic(data in proptest::collection::vec(any::(), 0..400)) { - let _ = photocraft_psd::patterns::parse_pattern_block(&data); - let _ = photocraft_psd::patterns::parse_pat_file(&data); - } - - /// A filter-effects cache with one or more items (each with cached slots and an optional mask) - /// re-serialises and re-parses byte for byte, and the cached planes decode. - #[test] - fn filter_effects_round_trip(items in proptest::collection::vec(("[ -~]{0,8}", any::()), 0..4)) { - use photocraft_psd::compression::Compression; - use photocraft_psd::filter_effects::{EffectsPlane, FilterEffects, FilterEffectsItem}; - use photocraft_psd::layer::Rect; - let rect = Rect { top: 1, left: 2, bottom: 5, right: 6 }; - let plane = |v: u8| EffectsPlane::encode(Compression::Rle, &[v; 16], 4, 4, 8).unwrap(); - let items: Vec = items - .iter() - .map(|(id, mask)| { - let mut slots = vec![None; 26]; - slots[0] = Some(plane(10)); - slots[25] = Some(plane(255)); - FilterEffectsItem { id: id.clone(), version: 1, rect, depth: 8, max_channels: 24, slots, mask: mask.then(|| (rect, plane(128))) } - }) - .collect(); - let fx = FilterEffects { version: 3, items }; - let bytes = fx.to_bytes(); - let back = FilterEffects::parse(&bytes).unwrap(); - prop_assert_eq!(&back, &fx); - prop_assert_eq!(back.to_bytes(), bytes); - for it in &back.items { - if let Some((_, m)) = it.decoded_mask() { - prop_assert_eq!(m, vec![128; 16]); - } - } - } - - #[test] - fn filter_effects_never_panics(data in proptest::collection::vec(any::(), 0..400)) { - if let Ok(fx) = photocraft_psd::filter_effects::FilterEffects::parse(&data) { - for it in &fx.items { - let _ = it.decoded_mask(); - } - let _ = fx.to_bytes(); - } - } - - /// Resolution info is 16 fixed-point bytes; a built value survives a byte round trip. - #[test] - fn resolution_info_round_trips(dpi in 1.0f64..=10_000.0) { - use photocraft_psd::resources::ResolutionInfo; - let ri = ResolutionInfo::from_dpi(dpi); - prop_assert_eq!(ResolutionInfo::from_bytes(&ri.to_bytes()).unwrap(), ri); - } - - /// The typed view of an arbitrary resource id over arbitrary data never panics. - #[test] - fn resource_parsed_never_panics(id in any::(), data in proptest::collection::vec(any::(), 0..64)) { - use photocraft_psd::resources::ImageResource; - let r = ImageResource::new(id, data); - let _ = r.parsed(); - let _ = r.xmp_str(); - let _ = photocraft_psd::resources::VersionInfo::from_bytes(&r.data); - } - - /// `parsed` (typed) and `check_structure` (strict inner re-parse) over an arbitrary key and - /// arbitrary data never panic, only ever returning `Ok` / `Err` / `None`. - #[test] - fn tagged_block_views_never_panic(key in any::<[u8; 4]>(), data in proptest::collection::vec(any::(), 0..200)) { - let b = TaggedBlock::new(key, data); - let _ = b.parsed(); - let _ = b.check_structure(); - } - - /// Each well-known typed key over arbitrary data: every typed branch is reached and none panics. - #[test] - fn tagged_known_keys_never_panic(ki in 0usize..13, data in proptest::collection::vec(any::(), 0..64)) { - const KEYS: [&[u8; 4]; 13] = - [b"luni", b"lsct", b"lsdk", b"lyid", b"lnsr", b"clbl", b"infx", b"knko", b"tsly", b"lmgm", b"vmgm", b"lspf", b"lclr"]; - let b = TaggedBlock::new(*KEYS[ki], data); - let _ = b.parsed(); - } -} - -proptest! { - #![proptest_config(ProptestConfig::with_cases(256))] - - /// Pure random bytes rarely get past a header, so this damages a *valid* block one byte at a - /// time -- well-formed structure with one byte corrupted, where the interesting inputs live -- - /// across the metadata, pattern and filter-effects parsers. None may panic. - #[test] - fn aux_parsers_never_panic_on_damaged_valid_blocks(idx in 0usize..4000, bit in 0u32..8, add in 0u8..=255) { - use photocraft_psd::compression::Compression; - use photocraft_psd::filter_effects::{EffectsPlane, FilterEffects, FilterEffectsItem}; - use photocraft_psd::layer::Rect; - use photocraft_psd::metadata::{self, MetadataItem}; - use photocraft_psd::patterns::{self, PsdPattern}; - - let shmd = metadata::write_shmd(&[MetadataItem::new(*b"cmls", vec![1, 2, 3, 4]), MetadataItem::new(*b"cust", vec![9; 6])]); - let pattern = PsdPattern { - mode: 3, - width: 4, - height: 3, - name: "d".into(), - id: "0bd2d3ba".into(), - palette: None, - depth: 8, - channels: vec![vec![7u8; 12], vec![8u8; 12], vec![9u8; 12]], - alpha: None, - }; - let pat_block = patterns::write_pattern_block(std::slice::from_ref(&pattern)).unwrap(); - let pat_file = patterns::write_pat_file(std::slice::from_ref(&pattern)).unwrap(); - let rect = Rect { top: 1, left: 2, bottom: 5, right: 6 }; - let plane = EffectsPlane::encode(Compression::Rle, &[10u8; 16], 4, 4, 8).unwrap(); - let mut slots = vec![None; 26]; - slots[0] = Some(plane.clone()); - slots[25] = Some(plane.clone()); - let fx = FilterEffects { - version: 3, - items: vec![FilterEffectsItem { id: "x".into(), version: 1, rect, depth: 8, max_channels: 24, slots, mask: Some((rect, plane)) }], - } - .to_bytes(); - - let damage = |mut b: Vec| -> Vec { - if !b.is_empty() { - let i = idx % b.len(); - b[i] ^= 1u8 << bit; - b[i] = b[i].wrapping_add(add); - } - b - }; - let _ = metadata::parse_shmd(&damage(shmd)); - let _ = patterns::parse_pattern_block(&damage(pat_block)); - let _ = patterns::parse_pat_file(&damage(pat_file)); - if let Ok(f) = FilterEffects::parse(&damage(fx)) { - for it in &f.items { - let _ = it.decoded_mask(); - } - let _ = f.to_bytes(); - } - } - - /// Every `check_structure` key over arbitrary data: the strict inner re-parse for placed layers, - /// linked files, object effects and filter caches is entered and never panics. - #[test] - fn tagged_structural_keys_never_panic(ki in 0usize..8, data in proptest::collection::vec(any::(), 0..200)) { - const KEYS: [&[u8; 4]; 8] = [b"PlLd", b"SoLd", b"SoLE", b"lnk2", b"lnk3", b"lnkD", b"lfx2", b"FEid"]; - let b = TaggedBlock::new(*KEYS[ki], data); - let _ = b.check_structure(); - } -} diff --git a/crates/psd/tests/it/roundtrip.rs b/crates/psd/tests/it/roundtrip.rs deleted file mode 100644 index 1823900372..0000000000 --- a/crates/psd/tests/it/roundtrip.rs +++ /dev/null @@ -1,333 +0,0 @@ -//! Round-trip and byte-stability tests over generated files. - -use photocraft_psd::testgen::{self, MODES, mode_channels, mode_depths, pattern_plane}; -use photocraft_psd::*; - -fn assert_stable(file: &PsdFile, name: &str) { - let bytes = file.to_bytes().unwrap_or_else(|e| panic!("{name}: write failed: {e}")); - let parsed = PsdFile::from_bytes(&bytes).unwrap_or_else(|e| panic!("{name}: parse failed: {e}")); - assert_eq!(&parsed, file, "{name}: model round trip"); - let again = parsed.to_bytes().unwrap(); - assert_eq!(again, bytes, "{name}: byte stability"); -} - -#[test] -fn all_generated_cases_roundtrip() { - let cases = testgen::all_cases(); - assert!(cases.len() > 100, "only {} cases", cases.len()); - for c in &cases { - assert_stable(&c.file, &c.name); - } -} - -#[test] -fn all_generated_channels_decode() { - for c in testgen::all_cases() { - let f = &c.file; - let merged = f.decode_merged().unwrap_or_else(|e| panic!("{}: {e}", c.name)); - let (w, h) = (f.header.width as usize, f.header.height as usize); - assert_eq!(merged.len(), f.header.row_bytes() * h * usize::from(f.header.channels)); - for (i, layer) in f.layers().iter().enumerate() { - for ch in &layer.channels { - layer.decode_channel(ch.id, f.header.depth, f.header.version).unwrap_or_else(|e| panic!("{} layer {i} ch {}: {e}", c.name, ch.id)); - } - } - let _ = (w, h); - } -} - -#[test] -fn merged_only_decodes_to_pattern() { - for mode in MODES { - for &depth in mode_depths(mode) { - for c in Compression::ALL { - let f = testgen::merged_only(Version::Psd, mode, depth, c, 9, 5); - let dec = f.decode_merged().unwrap(); - let mut expect = Vec::new(); - for ch in 0..mode_channels(mode) { - expect.extend(pattern_plane(9, 5, depth, u32::from(ch))); - } - assert_eq!(dec, expect, "{mode:?} {depth} {c:?}"); - } - } - } -} - -macro_rules! layered_case { - ($name:ident, $ver:expr, $mode:expr, $depth:expr, $comp:expr) => { - #[test] - fn $name() { - let f = testgen::layered($ver, $mode, $depth, $comp); - assert_stable(&f, stringify!($name)); - assert!(f.layers().len() > 30); - let expect_placement = $depth != 8; - assert_eq!(matches!(f.layer_info_placement, LayerInfoPlacement::GlobalBlock { .. }), expect_placement); - } - }; -} - -layered_case!(layered_psd_rgb8_raw, Version::Psd, ColorMode::Rgb, 8, Compression::Raw); -layered_case!(layered_psd_rgb8_rle, Version::Psd, ColorMode::Rgb, 8, Compression::Rle); -layered_case!(layered_psd_rgb8_zip, Version::Psd, ColorMode::Rgb, 8, Compression::Zip); -layered_case!(layered_psd_rgb8_zipp, Version::Psd, ColorMode::Rgb, 8, Compression::ZipPrediction); -layered_case!(layered_psd_rgb16_raw, Version::Psd, ColorMode::Rgb, 16, Compression::Raw); -layered_case!(layered_psd_rgb16_rle, Version::Psd, ColorMode::Rgb, 16, Compression::Rle); -layered_case!(layered_psd_rgb16_zip, Version::Psd, ColorMode::Rgb, 16, Compression::Zip); -layered_case!(layered_psd_rgb16_zipp, Version::Psd, ColorMode::Rgb, 16, Compression::ZipPrediction); -layered_case!(layered_psd_rgb32_raw, Version::Psd, ColorMode::Rgb, 32, Compression::Raw); -layered_case!(layered_psd_rgb32_rle, Version::Psd, ColorMode::Rgb, 32, Compression::Rle); -layered_case!(layered_psd_rgb32_zip, Version::Psd, ColorMode::Rgb, 32, Compression::Zip); -layered_case!(layered_psd_rgb32_zipp, Version::Psd, ColorMode::Rgb, 32, Compression::ZipPrediction); -layered_case!(layered_psb_rgb8_raw, Version::Psb, ColorMode::Rgb, 8, Compression::Raw); -layered_case!(layered_psb_rgb8_rle, Version::Psb, ColorMode::Rgb, 8, Compression::Rle); -layered_case!(layered_psb_rgb8_zip, Version::Psb, ColorMode::Rgb, 8, Compression::Zip); -layered_case!(layered_psb_rgb8_zipp, Version::Psb, ColorMode::Rgb, 8, Compression::ZipPrediction); -layered_case!(layered_psb_rgb16_rle, Version::Psb, ColorMode::Rgb, 16, Compression::Rle); -layered_case!(layered_psb_rgb32_zipp, Version::Psb, ColorMode::Rgb, 32, Compression::ZipPrediction); -layered_case!(layered_psd_gray8_rle, Version::Psd, ColorMode::Grayscale, 8, Compression::Rle); -layered_case!(layered_psd_gray16_zipp, Version::Psd, ColorMode::Grayscale, 16, Compression::ZipPrediction); -layered_case!(layered_psd_gray32_zip, Version::Psd, ColorMode::Grayscale, 32, Compression::Zip); -layered_case!(layered_psd_cmyk8_rle, Version::Psd, ColorMode::Cmyk, 8, Compression::Rle); -layered_case!(layered_psd_cmyk16_raw, Version::Psd, ColorMode::Cmyk, 16, Compression::Raw); -layered_case!(layered_psb_cmyk8_zip, Version::Psb, ColorMode::Cmyk, 8, Compression::Zip); -layered_case!(layered_psd_lab8_rle, Version::Psd, ColorMode::Lab, 8, Compression::Rle); -layered_case!(layered_psb_lab16_zipp, Version::Psb, ColorMode::Lab, 16, Compression::ZipPrediction); - -macro_rules! merged_case { - ($name:ident, $mode:expr, $depth:expr) => { - #[test] - fn $name() { - for v in [Version::Psd, Version::Psb] { - for c in Compression::ALL { - let f = testgen::merged_only(v, $mode, $depth, c, 31, 3); - assert_stable(&f, stringify!($name)); - assert!(f.layer_info.is_none()); - } - } - } - }; -} - -merged_case!(merged_bitmap_1, ColorMode::Bitmap, 1); -merged_case!(merged_gray_8, ColorMode::Grayscale, 8); -merged_case!(merged_gray_16, ColorMode::Grayscale, 16); -merged_case!(merged_gray_32, ColorMode::Grayscale, 32); -merged_case!(merged_indexed_8, ColorMode::Indexed, 8); -merged_case!(merged_rgb_8, ColorMode::Rgb, 8); -merged_case!(merged_rgb_16, ColorMode::Rgb, 16); -merged_case!(merged_rgb_32, ColorMode::Rgb, 32); -merged_case!(merged_cmyk_8, ColorMode::Cmyk, 8); -merged_case!(merged_cmyk_16, ColorMode::Cmyk, 16); -merged_case!(merged_lab_8, ColorMode::Lab, 8); -merged_case!(merged_lab_16, ColorMode::Lab, 16); -merged_case!(merged_multichannel_8, ColorMode::Multichannel, 8); -merged_case!(merged_multichannel_16, ColorMode::Multichannel, 16); -merged_case!(merged_duotone_8, ColorMode::Duotone, 8); - -#[test] -fn psb_uses_long_section_lengths() { - let psd = testgen::small(Version::Psd, Compression::Raw).to_bytes().unwrap(); - let psb = testgen::small(Version::Psb, Compression::Raw).to_bytes().unwrap(); - // Layer & mask length (+4), layer info length (+4), 4 layers × channels × 4. - let f = testgen::small(Version::Psd, Compression::Raw); - let nch: usize = f.layers().iter().map(|l| l.channels.len()).sum(); - assert_eq!(psb.len(), psd.len() + 8 + nch * 4); - assert_eq!(psb[5], 2); -} - -#[test] -fn psb_rle_counts_are_u32() { - let psd = testgen::merged_only(Version::Psd, ColorMode::Grayscale, 8, Compression::Rle, 5, 4); - let psb = testgen::merged_only(Version::Psb, ColorMode::Grayscale, 8, Compression::Rle, 5, 4); - assert_eq!(psb.image_data.data.len(), psd.image_data.data.len() + 4 * 2); -} - -#[test] -fn psb_long_key_global_block() { - let mut f = testgen::small(Version::Psb, Compression::Rle); - f.global_blocks.push(TaggedBlock::new(*b"FMsk", vec![1, 2, 3, 4])); - f.global_blocks.push(TaggedBlock::new(*b"Alph", vec![5, 6])); - let b = f.to_bytes().unwrap(); - let p = PsdFile::from_bytes(&b).unwrap(); - assert_eq!(p, f); - // Reading the PSB bytes while pretending PSD must not silently succeed - // with the same structure. - let mut as_psd = b.clone(); - as_psd[5] = 1; - if let Ok(q) = PsdFile::from_bytes(&as_psd) { - assert_ne!(q, f); - } -} - -#[test] -fn edits_are_reencoded() { - let mut f = testgen::small(Version::Psd, Compression::Rle); - let v = f.header.version; - let layer = &mut f.layers_mut()[0]; - let (w, h) = layer.rect.size().unwrap(); - let new = vec![7u8; w * h]; - let ch = layer.channels.iter_mut().find(|c| c.id == 0).unwrap(); - ch.set_decoded(Compression::ZipPrediction, &new, w, h, 8, v).unwrap(); - let b = f.to_bytes().unwrap(); - let p = PsdFile::from_bytes(&b).unwrap(); - assert_eq!(p.layers()[0].decode_channel(0, 8, v).unwrap(), new); - assert_eq!(p.layers()[0].channel(0).unwrap().compression, Some(Compression::ZipPrediction)); -} - -#[test] -fn renaming_changes_luni_and_roundtrips() { - let mut f = testgen::small(Version::Psd, Compression::Raw); - let l = &mut f.layers_mut()[0]; - *l.block_mut(b"luni").unwrap() = TaggedBlock::unicode_name("Renamed \u{263a}"); - let p = PsdFile::from_bytes(&f.to_bytes().unwrap()).unwrap(); - assert_eq!(p.layers()[0].name(), "Renamed \u{263a}"); -} - -#[test] -fn unknown_blocks_and_resources_pass_through() { - let mut f = testgen::small(Version::Psd, Compression::Rle); - f.resources.push(ImageResource::new(9999, vec![1, 2, 3, 4, 5])); - f.global_blocks.push(TaggedBlock::new(*b"Q3Dx", (0..=255).collect())); - f.layers_mut()[0].blocks.push(TaggedBlock::new(*b"Vid!", vec![0xab; 7])); - f.layers_mut()[0].blend_mode = BlendMode::Unknown(*b"new!"); - assert_stable(&f, "unknown passthrough"); - let p = PsdFile::from_bytes(&f.to_bytes().unwrap()).unwrap(); - assert_eq!(p.layers()[0].blend_mode, BlendMode::Unknown(*b"new!")); - assert_eq!(p.global_block(b"Q3Dx").unwrap().data.len(), 256); -} - -#[test] -fn unknown_color_mode_passthrough() { - let mut f = testgen::merged_only(Version::Psd, ColorMode::Grayscale, 8, Compression::Raw, 2, 2); - f.header.color_mode = ColorMode::Unknown(5); - assert_stable(&f, "unknown mode"); -} - -#[test] -fn unknown_compression_passthrough() { - let mut f = testgen::small(Version::Psd, Compression::Raw); - f.layers_mut()[0].channels[0].compression = Some(Compression::Unknown(9)); - assert_stable(&f, "unknown channel compression"); - assert!(f.layers()[0].decode_channel(f.layers()[0].channels[0].id, 8, Version::Psd).is_err()); -} - -#[test] -fn trailing_section_bytes_preserved() { - let mut f = testgen::small(Version::Psd, Compression::Raw); - f.layer_mask_trailing = vec![0; 6]; - assert_stable(&f, "layer mask trailing"); - f.layers_mut()[1].extra_trailing = vec![0; 5]; - assert_stable(&f, "record trailing"); - f.layer_info.as_mut().unwrap().padding = Some(vec![0, 0, 0, 0]); - f.layers_mut()[1].extra_trailing.clear(); - assert_stable(&f, "layer info padding"); -} - -#[test] -fn global_mask_accessors() { - let f = testgen::layered(Version::Psd, ColorMode::Rgb, 8, Compression::Raw); - let gm = f.global_layer_mask.as_ref().unwrap(); - assert_eq!(gm.overlay_color_space(), Some(0)); - assert_eq!(gm.color_components(), Some([0xffff, 0, 0, 0])); - assert_eq!(gm.opacity(), Some(50)); - assert_eq!(gm.kind(), Some(128)); - assert_eq!(GlobalLayerMask::default().kind(), None); - assert_eq!(GlobalLayerMask::photoshop_default().data, gm.data); -} - -#[test] -fn file_accessors() { - let f = testgen::layered(Version::Psd, ColorMode::Rgb, 8, Compression::Rle); - assert!((f.resolution().unwrap().h_res() - 72.0).abs() < 1e-9); - assert_eq!(f.icc_profile().unwrap().len(), 13); - assert_eq!(f.has_real_merged_data(), Some(true)); - assert!(f.merged_has_alpha()); - assert!(f.validate().is_ok()); - let lfx = f.layers().iter().find_map(|l| l.block(b"lfx2")).expect("lfx2"); - let d = descriptor::VersionedDescriptor::from_bytes(&lfx.data[4..]).unwrap(); - assert_eq!(d, testgen::sample_descriptor()); -} - -#[test] -fn validate_rejects_bad_models() { - let mut f = testgen::merged_only(Version::Psd, ColorMode::Indexed, 8, Compression::Raw, 2, 2); - assert!(f.validate().is_ok()); - f.color_mode_data.pop(); - assert!(f.validate().is_err()); - let mut g = testgen::merged_only(Version::Psd, ColorMode::Rgb, 8, Compression::Raw, 2, 2); - g.header.width = 40_000; - assert!(g.validate().is_err()); - g.header.version = Version::Psb; - assert!(g.validate().is_ok()); -} - -#[test] -fn psd_too_large_for_32bit_errors_on_write() { - let mut f = testgen::small(Version::Psd, Compression::Raw); - // A resource larger than u32 can't be constructed cheaply; instead check - // RLE rows > 65535 bytes are rejected for PSD but allowed for PSB. - let l = photocraft_psd::compression::PlaneLayout { planes: 1, width: 70_000, height: 1, depth: 8, version: Version::Psd }; - let row: Vec = (0..70_000u32).map(|i| (i % 251) as u8).collect(); - assert!(compression::encode_planes(Compression::Rle, &row, &l).is_err()); - let l = compression::PlaneLayout { version: Version::Psb, ..l }; - assert!(compression::encode_planes(Compression::Rle, &row, &l).is_ok()); - f.header.version = Version::Psd; -} - -#[cfg(not(target_arch = "wasm32"))] -#[test] -fn save_and_open() { - let f = testgen::small(Version::Psd, Compression::Rle); - let dir = std::env::temp_dir().join(format!("photocraft-psd-test-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let p = dir.join("x.psd"); - f.save(&p).unwrap(); - let g = PsdFile::open(&p).unwrap().unwrap(); - assert_eq!(g, f); - let _ = std::fs::remove_dir_all(&dir); -} - -/// A density-only mask record written in the spec's order (parameters, then the real-mask -/// fields) used to be read back in Photoshop's order, which moved the density into the real -/// mask's background and dropped it from the parameters (#949). The model must survive the -/// round trip, not only the bytes. -#[test] -fn spec_order_density_only_mask_round_trips_as_a_model() { - let mut f = testgen::small(Version::Psd, Compression::Raw); - let layer = &mut f.layers_mut()[0]; - layer.mask = MaskData::Mask(LayerMask { - rect: Rect::from_xywh(0, 0, 1, 1), - default_color: 255, - flags: LayerMask::FLAG_PARAMETERS, - parameters: Some(MaskParameters { flags: 1, user_density: Some(64), ..Default::default() }), - real: Some(RealMask { flags: 0, background: 0, rect: Rect::from_xywh(0, 0, 1, 1) }), - trailing: vec![], - real_first: false, - }); - // The generated 2 x 2 mask channel is replaced by one that matches the 1 x 1 rectangle. - let mask_channel = layer.channels.iter_mut().find(|c| c.id == -2).expect("the generated layer has a mask channel"); - *mask_channel = ChannelData::encode(-2, Compression::Raw, &[64], 1, 1, 8, Version::Psd).unwrap(); - let b = f.to_bytes().unwrap(); - let g = PsdFile::from_bytes(&b).unwrap(); - assert_eq!(g, f, "model round trip"); - assert_eq!(g.layers()[0].decode_channel(-2, 8, Version::Psd).unwrap(), vec![64]); - assert_eq!(g.to_bytes().unwrap(), b, "byte stability"); -} - -/// Embedded data (smart-object files, and the like) is large next to the headers, so the output -/// is reserved at its exact size up front: no growth by doubling, which on the web is a single -/// unrecoverable multi-gigabyte `realloc` (#10024). -#[test] -fn to_bytes_reserves_the_whole_output_up_front() { - for version in [Version::Psd, Version::Psb] { - let mut f = testgen::small(version, Compression::Rle); - f.global_blocks.push(TaggedBlock::new(*b"Q3Dx", vec![0x5a; 3 << 20])); - f.layers_mut()[0].blocks.push(TaggedBlock::new(*b"Vid!", vec![0xab; 1 << 20])); - let b = f.to_bytes().unwrap(); - assert_eq!(b.capacity(), b.len(), "{version:?}: the output buffer grew past its reserve"); - assert_eq!(b.len() as u64, f.encoded_len().unwrap()); - let p = PsdFile::from_bytes(&b).unwrap(); - assert_eq!(p, f); - assert_eq!(p.to_bytes().unwrap(), b); - } -} diff --git a/crates/psd/tests/it/swatch_malformed.rs b/crates/psd/tests/it/swatch_malformed.rs deleted file mode 100644 index 91a83b4285..0000000000 --- a/crates/psd/tests/it/swatch_malformed.rs +++ /dev/null @@ -1,943 +0,0 @@ -//! `.grd`, `.ase` and `.aco` hostile-input handling. -//! -//! These three parsers are standalone entry points that `PsdFile::from_bytes` never reaches -//! (nothing in `file.rs` calls them), so the `parse.rs` fuzz target cannot exercise them. They are -//! also user-reachable: `grd::parse` backs the gradient-preset import in -//! `engine::preset_import_cmds`, and `ase`/`aco` back swatch import and export. Each module has its -//! own `hostile_input` unit test, but those assert `let _ = parse(...)` on mutations: a panic would -//! abort the test without saying which parser and which byte caused it. -//! -//! What this file adds: -//! 1. every single-bit flip in a valid file, each wrapped in `catch_unwind` so a panic is -//! reported with the exact byte and parser rather than as an opaque abort (§0.8: "parsers and -//! decoders get mutation-fuzz tests run under `catch_unwind`"); -//! 2. the round-trip and cap invariants the fuzz targets assert, checked deterministically so CI -//! covers them even though the `fuzz` job is workflow-dispatch only; -//! 3. inputs sized to *exceed* each advertised cap, because a cap asserted only against a file -//! that fits under it is a tautology — it cannot fail, so it proves nothing. -//! -//! The rule under test throughout: hostile input returns `Err`, never a panic and never an -//! unbounded allocation. - -use photocraft_psd::aco::{AcoColor, AcoSwatch}; -use photocraft_psd::grd::{GrdColor, GrdGradient, GrdStop}; -use photocraft_psd::{PsdError, aco, ase, grd}; -use std::panic::{RefUnwindSafe, UnwindSafe, catch_unwind}; - -fn sample_ase() -> Vec { - use photocraft_psd::ase::{AseColor, AseEntry, AseFile, AseKind, AseSwatch as Sw, write}; - let sw = |name: &str| Sw { name: name.into(), color: AseColor::Rgb([1.0, 0.0, 0.0]), kind: AseKind::Process }; - write(&AseFile { entries: vec![AseEntry::Group { name: "Brand".into(), swatches: vec![sw("Red"), sw("Blue")] }, AseEntry::Swatch(sw("Loose"))] }) - .expect("writing a sample .ase") -} - -fn sample_aco_swatches() -> Vec { - vec![ - AcoSwatch { name: "Pure Red".into(), color: AcoColor::Rgb([65535, 0, 0]) }, - AcoSwatch { name: "Cyan ink".into(), color: AcoColor::Cmyk([65535, 0, 0, 1234]) }, - AcoSwatch { name: "Lab".into(), color: AcoColor::Lab { l: 5321, a: -12800, b: 12700 } }, - AcoSwatch { name: "Gray".into(), color: AcoColor::Gray(5000) }, - AcoSwatch { name: "Book".into(), color: AcoColor::Other { space: 3, values: [1, 2, 3, 4] } }, - ] -} - -fn sample_aco() -> Vec { - aco::write(&sample_aco_swatches()).expect("writing a sample .aco") -} - -fn sample_grd() -> Vec { - use photocraft_psd::grd::write; - write(&[ - GrdGradient { - name: "Sunset".into(), - noise: false, - stops: vec![ - GrdStop { location: 0.0, midpoint: 0.5, color: GrdColor::Rgb([1.0, 0.0, 0.0]) }, - GrdStop { location: 1.0, midpoint: 0.5, color: GrdColor::Background }, - ], - opacity: vec![(0.0, 1.0, 0.5), (1.0, 0.25, 0.5)], - }, - GrdGradient { name: "Noisy".into(), noise: true, stops: Vec::new(), opacity: Vec::new() }, - ]) -} - -/// Flips every single bit of a valid file and requires that the parser returns or fails without -/// panicking. A flipped length or count must never be trusted into an allocation. -fn bitflip_sweep(bytes: &[u8], name: &str, parse: F) -where - F: Fn(&[u8]) -> Result + RefUnwindSafe + UnwindSafe, -{ - for byte in 0..bytes.len() { - for bit in 0..8 { - let mut b = bytes.to_vec(); - b[byte] ^= 1 << bit; - let r = catch_unwind(|| parse(&b)); - assert!(r.is_ok(), "{name}: parse panicked after flipping bit {bit} of byte {byte} of {}", bytes.len()); - } - } -} - -#[test] -fn ase_bitflips_never_panic() { - bitflip_sweep(&sample_ase(), "ase", ase::parse); -} - -#[test] -fn aco_bitflips_never_panic() { - bitflip_sweep(&sample_aco(), "aco", aco::parse); -} - -#[test] -fn grd_bitflips_never_panic() { - bitflip_sweep(&sample_grd(), "grd", grd::parse); -} - -fn assert_finite(values: &[f32], what: &str) { - for v in values { - assert!(v.is_finite(), "{what} component {v} is not finite"); - } -} - -/// Every number a parsed gradient carries must be finite and inside the ranges the module -/// documents, so a caller never divides by or formats a NaN and never reads past a 0..=1 bound. -fn assert_gradient_sane(g: &GrdGradient) { - for s in &g.stops { - assert!(s.location.is_finite() && (0.0..=1.0).contains(&s.location), "stop location {} out of range", s.location); - assert!(s.midpoint.is_finite() && (0.0..=1.0).contains(&s.midpoint), "stop midpoint {} out of range", s.midpoint); - match s.color { - GrdColor::Rgb(v) => assert_finite(&v, "RGB"), - GrdColor::Hsb(v) => assert_finite(&v, "HSB"), - GrdColor::Cmyk(v) => assert_finite(&v, "CMYK"), - GrdColor::Lab(v) => assert_finite(&v, "Lab"), - GrdColor::Gray(v) => assert!(v.is_finite(), "gray {v} is not finite"), - GrdColor::Foreground | GrdColor::Background => {} - } - } - for &(l, o, m) in &g.opacity { - assert!(l.is_finite() && (0.0..=1.0).contains(&l), "transparency location {l} out of range"); - assert!((0.0..=1.0).contains(&o), "opacity {o} outside 0..=1"); - assert!(m.is_finite() && (0.0..=1.0).contains(&m), "transparency midpoint {m} out of range"); - } -} - -/// A gradient file that parses must obey the caps the module advertises and keep every numeric -/// field finite, so callers never divide by or format a NaN. -#[test] -fn grd_parsed_values_respect_caps_and_are_finite() { - // No cap assertion here: the sample has two gradients and two stops, so a cap check would - // hold for any writer and prove nothing. `grd_gradient_count_is_capped` and - // `grd_stop_counts_are_capped` drive inputs over the caps instead. - for g in &grd::parse(&sample_grd()).expect("sample .grd parses") { - assert_gradient_sane(g); - } -} - -/// A file declaring more gradients than [`grd::MAX_GRADIENTS`] must be capped at the cap, not -/// trusted: the cap is the only thing between a file's own list length and the allocation it asks -/// for. The input deliberately exceeds the cap, otherwise the assertion below cannot fail. -#[test] -fn grd_gradient_count_is_capped() { - let over = vec![GrdGradient { name: "g".into(), ..Default::default() }; grd::MAX_GRADIENTS + 1]; - let bytes = grd::write(&over); - // Precondition: the file really must carry more gradients than the cap, or the assertion - // below would hold for the wrong reason (the writer capping rather than the reader). - // Precondition, by size: a file carrying one gradient more than the cap must be larger than - // the same file at the cap. Counting `Grdn` windows would not work — the object nests — and - // would keep passing even if the writer started capping, which is what this must catch. - let at_cap = grd::write(&over[..grd::MAX_GRADIENTS]).len(); - assert!(bytes.len() > at_cap, "the written file is not larger than the capped one: {} vs {at_cap}", bytes.len()); - let f = grd::parse(&bytes).expect("a file over the gradient cap still parses"); - assert_eq!(f.len(), grd::MAX_GRADIENTS, "gradients must be capped at MAX_GRADIENTS, not taken as declared"); -} - -/// Same for the per-gradient stop lists: colour stops and transparency stops are capped -/// separately, so both are driven over their cap. -#[test] -fn grd_stop_counts_are_capped() { - let stop = GrdStop { location: 0.5, midpoint: 0.5, color: GrdColor::Rgb([1.0, 0.0, 0.0]) }; - let over = GrdGradient { name: "wide".into(), noise: false, stops: vec![stop; grd::MAX_STOPS + 1], opacity: vec![(0.5, 1.0, 0.5); grd::MAX_STOPS + 1] }; - let bytes = grd::write(std::slice::from_ref(&over)); - // Precondition by size: a file carrying one stop more than the cap must be larger than the - // same file at the cap. Counting `Lctn` windows would not work — it appears in both the colour - // and the transparency list — and would keep passing even if the writer started capping, - // which is exactly what this must catch. Each list is driven on its own, since they are - // capped independently. - let capped_stops = over.stops[..grd::MAX_STOPS].to_vec(); - let capped_opacity = over.opacity[..grd::MAX_STOPS].to_vec(); - let colour_only_over = GrdGradient { opacity: Vec::new(), ..over.clone() }; - let colour_only_capped = GrdGradient { stops: capped_stops, opacity: Vec::new(), ..over.clone() }; - assert!(grd::write(&[colour_only_over]).len() > grd::write(&[colour_only_capped]).len(), "colour stops over the cap are not larger than at the cap"); - let trans_only_over = GrdGradient { stops: Vec::new(), ..over.clone() }; - let trans_only_capped = GrdGradient { stops: Vec::new(), opacity: capped_opacity, ..over }; - assert!(grd::write(&[trans_only_over]).len() > grd::write(&[trans_only_capped]).len(), "transparency stops over the cap are not larger than at the cap"); - let f = grd::parse(&bytes).expect("a file over the stop cap still parses"); - assert_eq!(f[0].stops.len(), grd::MAX_STOPS, "colour stops must be capped at MAX_STOPS"); - assert_eq!(f[0].opacity.len(), grd::MAX_STOPS, "transparency stops must be capped at MAX_STOPS"); -} - -/// `Opct` is a unit float (`UntF` + a 4-byte unit tag), not a `doub`, so patching it needs a -/// different offset from the RGB components. Every numeric field now passes through `finite()` -/// before any clamp, so this pins that a non-finite value is repaired first — saturated, or for a -/// NaN replaced by the field default — rather than reaching `f32::clamp`, which propagates NaN and -/// would hand it straight back out of the parser. Every non-finite shape is tried at both places. -#[test] -fn grd_non_finite_opacity_and_midpoint_do_not_survive() { - // 3.0e38 is finite as both f64 and f32, so it is not caught by the finiteness check and must - // be brought into range by the saturate-then-clamp path; it belongs here to keep that honest. - let bad = [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e300, 3.0e38]; - // `doub`: key + 4-byte OSType + 8-byte value. `UntF`: key + OSType + 4-byte unit tag + value. - // `Opct` is the interesting one: a unit float at a different offset from the RGB components, so - // both the `doub` and `UntF` shapes are patched. `Mdpn` is written as an integer here, which - // cannot carry a non-finite value at all, so it is skipped rather than pretended to be covered; - // a hostile file storing `Mdpn` as a double is still guarded by `finite()` and by the fuzz - // target's range assertion. - for key in ["Opct", "Rd ", "Grn ", "Bl "] { - for v in bad { - let mut b = sample_grd(); - let at = b.windows(4).position(|w| w == key.as_bytes()).unwrap_or_else(|| panic!("the sample stores {key:?}")); - let skip = match &b[at + 4..at + 8] { - b"doub" => 8usize, - b"UntF" => 12usize, - other => panic!("{key} is stored as {other:?}, which this test cannot patch"), - }; - b[at + skip..at + skip + 8].copy_from_slice(&v.to_be_bytes()); - let f = grd::parse(&b).unwrap_or_else(|e| panic!("{key} = {v} still parses: {e:?}")); - for g in &f { - assert_gradient_sane(g); - } - } - } -} - -/// `num` returns the raw f64 and `finite()` is the single guard every number passes through. This -/// pins that one policy end to end: only a NaN is truly absent and falls back to the documented -/// default (opacity 100 %, midpoint centred); every other shape — including `+/-inf` and a value -/// finite as `f64` but above `f32::MAX` — saturates and then clamps, so a large positive lands at -/// 1.0 and a large negative at 0.0, monotonic, never a snap back to the default. -/// `Mdpn` is written as a `long` by this crate's own writer, so no fixture can smuggle a -/// non-finite value into it and the guard inside `midpoint()` would never be exercised. The file -/// format allows a `double` there, so the descriptor is built by hand with `Mdpn` as a `doub`: -/// otherwise removing that guard changes nothing any test can see. -#[test] -fn grd_midpoint_stored_as_a_double_is_still_sanitised() { - use photocraft_psd::descriptor::{Descriptor, Value, VersionedDescriptor}; - for v in [f64::NAN, f64::INFINITY, 1e300, 3.0e38] { - // Driven through `Trns`, where the reader keeps the midpoint, rather than through `Clrs`, - // where a colour stop also needs a colour this descriptor does not carry. - let trns = Descriptor::new("TrnS").with("Mdpn", Value::Double(v)); - let grad = Descriptor::new("Grdn").with("Trns", Value::List(vec![Value::Descriptor(trns)])); - let outer = Descriptor::new("Grdn").with("Grad", Value::Descriptor(grad)); - let file = Descriptor::new("null").with("GrdL", Value::List(vec![Value::Descriptor(outer)])); - let mut g = b"8BGR".to_vec(); - g.extend_from_slice(&5u16.to_be_bytes()); - g.extend_from_slice(&VersionedDescriptor::new(file).to_bytes()); - - let parsed = grd::parse(&g).unwrap_or_else(|e| panic!("Mdpn = {v} still parses: {e:?}")); - let Some((_, _, m)) = parsed[0].opacity.first() else { panic!("the transparency stop was dropped") }; - // Pin the exact value, not just the range. Only a NaN is truly absent, so only it falls - // back to the centred default; every other shape saturates and then clamps, so a large - // positive lands at 1.0 and a large negative at 0.0 — monotonic, never a snap to 0.5. - let expected = if v.is_nan() { - 0.5 - } else if v > 0.0 { - 1.0 - } else { - 0.0 - }; - assert_eq!(*m, expected, "a midpoint of {v} must be {expected}, got {m}"); - } -} - -/// `.aco` stores CMYK as *ink* amounts in memory and the complement on disk: the file holds 0 for -/// 100 % ink and the reader adds the back. Nothing pinned that, so flipping either side would -/// silently invert every CMYK swatch. -#[test] -fn aco_cmyk_is_stored_inverted_and_reads_back_as_ink() { - let swatches = vec![AcoSwatch { name: "k".into(), color: AcoColor::Cmyk([65535, 0, 0, 1234]) }]; - let bytes = aco::write(&swatches).expect("writing one CMYK swatch"); - - // Version 1 section: version u16, count u16, then a 10-byte record. - let space = u16::from_be_bytes([bytes[4], bytes[5]]); - let stored: Vec = (0..4).map(|i| u16::from_be_bytes([bytes[6 + i * 2], bytes[7 + i * 2]])).collect(); - assert_eq!(space, aco::space::CMYK, "the record must be tagged CMYK"); - assert_eq!(stored, vec![0, u16::MAX, u16::MAX, u16::MAX - 1234], "the file stores the complement of the ink amounts"); - assert_eq!(aco::parse(&bytes).expect("the file parses").swatches, swatches, "the ink amounts must survive the round trip"); -} - -#[test] -fn grd_unrepresentable_numbers_follow_the_documented_policy() { - // The *second* transparency stop carries opacity 0.25; the first is already 1.0, so patching - // it could not tell "fell back to the default" from "the patch had no effect". - let patch = |key: &[u8], v: f64| { - let mut b = sample_grd(); - let at = b.windows(4).rposition(|w| w == key).expect("the sample stores the key"); - let skip = match &b[at + 4..at + 8] { - b"doub" => 8usize, - b"UntF" => 12usize, - other => panic!("stored as {other:?}"), - }; - b[at + skip..at + skip + 8].copy_from_slice(&v.to_be_bytes()); - grd::parse(&b).expect("still parses") - }; - // Opacity. A NaN is the only truly absent value, so it alone falls back to the 100 % default. - // Every other shape saturates then clamps, which is monotonic: a large positive stays opaque, - // a large negative becomes transparent. Nothing snaps the wrong way as the number grows. - for (v, expected) in [ - (f64::NAN, 1.0), // absent -> the field default (opaque) - (f64::INFINITY, 1.0), // saturates to the top of the range - (f64::NEG_INFINITY, 0.0), // saturates to the bottom - (1e300, 1.0), // over f32::MAX -> saturates up - (-1e300, 0.0), // under -f32::MAX -> saturates down - (3.0e38, 1.0), // finite as f32 -> clamps up - (-3.0e38, 0.0), // finite as f32 -> clamps down - ] { - let got = patch(b"Opct", v)[0].opacity[1].1; - assert_eq!(got, expected, "Opct = {v} must read back as {expected}, got {got}"); - } - // A colour channel has its own default (zero) for the absent case, and the same monotonic - // saturate-then-clamp for everything else. Pin the exact number: a value reaching the clamp - // from above would come back as 1.0, which is in range and would slip past a range-only check. - for (v, expected) in [ - (f64::NAN, 0.0), // absent -> the channel default - (f64::INFINITY, 1.0), // saturates up, then clamps to 1.0 - (f64::NEG_INFINITY, 0.0), // saturates down, then clamps to 0.0 - (1e300, 1.0), // over f32::MAX -> saturates up - (-1e300, 0.0), // under -f32::MAX -> saturates down - (3.0e38, 1.0), // finite as f32 -> clamps up - (-3.0e38, 0.0), // finite as f32 -> clamps down - ] { - let f = patch(b"Bl ", v); - let GrdColor::Rgb([_, _, b]) = f[0].stops[0].color else { panic!("expected an RGB stop") }; - assert_eq!(b, expected, "a blue component of {v} must be {expected}, got {b}"); - } -} - -/// A name long enough that the code-unit cap lands *between* the halves of a surrogate pair must -/// not be cut in half: a lone surrogate is ill-formed UTF-16, and writing it would make the file -/// unreadable to anything strict. Capping has to drop the whole character instead, and the file -/// must then survive its own round trip unchanged. -#[test] -fn aco_and_ase_never_split_a_surrogate_pair() { - // "a" plus 600 emoji: 1 + 1200 units, so a 1024-unit cap lands mid-pair. - let name = format!("a{}", "\u{1F600}".repeat(600)); - assert!(name.encode_utf16().count() > ase::MAX_NAME_UNITS, "the name must be longer than the cap"); - - let swatches = vec![aco::AcoSwatch { name: name.clone(), color: aco::AcoColor::Gray(5000) }]; - let once = aco::write(&swatches).expect("writing a long non-ASCII name is capped, not refused"); - let back = aco::parse(&once).expect("the written file parses"); - // The exact expected name, not merely "it is valid UTF-16": the cap must drop the whole - // character that does not fit, leaving "a" plus 511 complete pairs and nothing half-written. - let expected = format!("a{}", "\u{1F600}".repeat(511)); - assert_eq!(back.swatches[0].name, expected, "the capped name must be whole characters only"); - assert_eq!(aco::write(&back.swatches).unwrap(), once, "the file must be stable across a round trip"); - - use photocraft_psd::ase::{AseColor, AseEntry, AseFile, AseKind, AseSwatch, write}; - let file = AseFile { entries: vec![AseEntry::Swatch(AseSwatch { name, color: AseColor::Rgb([1.0, 0.0, 0.0]), kind: AseKind::Process })] }; - let a1 = write(&file).expect("writing a long non-ASCII name is capped, not refused"); - let ab = ase::parse(&a1).expect("the written file parses"); - let ase::AseEntry::Swatch(s) = &ab.entries[0] else { panic!("expected a loose swatch") }; - assert_eq!(s.name, expected, "the capped name must be whole characters only"); - assert_eq!(write(&ab).unwrap(), a1, "the file must be stable across a round trip"); -} - -/// Locations, midpoints and opacity are documented as 0..=1. A hostile file stores raw integers, -/// so the values are driven well outside that range and must come back clamped. -#[test] -fn grd_out_of_range_numbers_are_clamped() { - let g = GrdGradient { - name: "out of range".into(), - noise: false, - stops: vec![ - GrdStop { location: 2.0, midpoint: 5.0, color: GrdColor::Rgb([1.0, 0.0, 0.0]) }, - GrdStop { location: -3.0, midpoint: -1.0, color: GrdColor::Rgb([0.0, 1.0, 0.0]) }, - ], - opacity: vec![(9.0, 5.0, 7.0), (-2.0, -1.0, 42.0)], - }; - let f = grd::parse(&grd::write(&[g])).expect("out-of-range numbers still parse"); - assert_gradient_sane(&f[0]); - // Range membership alone would be a tautology once the values are already in range: assert the - // exact clamped result, so a clamp silently degrading into a pass-through is caught. Positive - // over-range -> 1.0, negative -> 0.0. - assert_eq!(f[0].stops[0].location, 1.0, "location 2.0 must clamp to 1.0"); - assert_eq!(f[0].stops[0].midpoint, 1.0, "midpoint 5.0 must clamp to 1.0"); - assert_eq!(f[0].stops[1].location, 0.0, "location -3.0 must clamp to 0.0"); - assert_eq!(f[0].stops[1].midpoint, 0.0, "midpoint -1.0 must clamp to 0.0"); - assert_eq!(f[0].opacity[0], (1.0, 1.0, 1.0), "all-positive over-range opacity must clamp to 1.0"); - assert_eq!(f[0].opacity[1], (0.0, 0.0, 1.0), "location/opacity clamp to 0.0, midpoint 42.0 to 1.0"); -} - -/// `num` returns the raw f64 unfiltered; `finite()` is the single guard, and a NaN is not the only -/// non-finite f32 it has to handle: a value that is finite as f64 and above `f32::MAX` (1e300) -/// would become an infinity on a bare cast, so `finite()` saturates it. Every numeric field must -/// come back finite, so both doors are checked. -#[test] -fn grd_huge_f64_does_not_overflow_to_infinity() { - for key in ["Rd ", "Grn ", "Bl "] { - let mut b = sample_grd(); - let at = b.windows(4).position(|w| w == key.as_bytes()).unwrap_or_else(|| panic!("the sample stores {key:?}")); - assert_eq!(&b[at + 4..at + 8], b"doub", "{key} is stored as a double"); - b[at + 8..at + 16].copy_from_slice(&1e300f64.to_be_bytes()); - let f = grd::parse(&b).expect("a huge but finite component still parses"); - for g in &f { - assert_gradient_sane(g); - } - } -} - -/// A hostile file carrying a NaN must have it replaced, not handed on: `Rd ` in the sample is a -/// double, so patching those eight bytes is enough to try to smuggle a NaN past the reader. -#[test] -fn grd_non_finite_numbers_do_not_survive_the_reader() { - let mut b = sample_grd(); - let at = b.windows(4).position(|w| w == b"Rd ").expect("the sample stores an RGB component"); - assert_eq!(&b[at + 4..at + 8], b"doub", "an RGB component is stored as a double"); - b[at + 8..at + 16].copy_from_slice(&f64::NAN.to_be_bytes()); - let f = grd::parse(&b).expect("a NaN component still parses"); - assert!(!f.is_empty()); - for g in &f { - assert_gradient_sane(g); - } -} - -/// An `.ase` that parses must stay within the swatch cap and re-serialize to the same number of -/// colours, so an import never silently drops or invents entries. -#[test] -fn ase_round_trip_preserves_swatch_count() { - use photocraft_psd::ase::write; - let f = ase::parse(&sample_ase()).expect("sample .ase parses"); - // No cap assertion: three swatches cannot exceed a cap of 100 000. `ase_swatch_cap_is_enforced_ - // on_hostile_input` drives a file that does. - let n = f.swatch_count(); - let out = write(&f).expect("re-writing a parsed .ase"); - let back = ase::parse(&out).expect("the rewritten .ase parses"); - assert_eq!(back.swatch_count(), n, "swatch count changed across a round trip"); -} - -/// A file with more colour blocks than [`ase::MAX_SWATCHES`] must be refused. Each block here is -/// the smallest legal colour block, so the file is small but the declared count is over the cap. -#[test] -fn ase_swatch_cap_is_enforced_on_hostile_input() { - let mut body = Vec::new(); - body.extend_from_slice(&0u16.to_be_bytes()); // name length 0 - body.extend_from_slice(b"Gray"); - body.extend_from_slice(&0f32.to_be_bytes()); // gray component - body.extend_from_slice(&2u16.to_be_bytes()); // colour type: process - let mut block = Vec::new(); - block.extend_from_slice(&1u16.to_be_bytes()); // block type: colour entry - block.extend_from_slice(&(body.len() as u32).to_be_bytes()); - block.extend_from_slice(&body); - - let total = ase::MAX_SWATCHES + 1; - let mut f = b"ASEF".to_vec(); - f.extend_from_slice(&1u16.to_be_bytes()); // major - f.extend_from_slice(&0u16.to_be_bytes()); // minor - f.extend_from_slice(&(total as u32).to_be_bytes()); - for _ in 0..total { - f.extend_from_slice(&block); - } - assert!(matches!(ase::parse(&f), Err(PsdError::LimitExceeded(_))), "a file over MAX_SWATCHES must be refused, not silently truncated"); - // The same file one block under the cap is accepted, so the cap is what refuses it. - f.truncate(f.len() - block.len()); - let trimmed = total - 1; - // signature (4) + major (2) + minor (2) puts the block count at offset 8. - f[8..12].copy_from_slice(&(trimmed as u32).to_be_bytes()); - assert!(ase::parse(&f).is_ok(), "a file exactly at MAX_SWATCHES must still parse"); -} - -/// A file with more group starts than [`ase::MAX_GROUPS`] must be refused. Each block here is an -/// empty group start, six bytes long. -#[test] -fn ase_group_cap_is_enforced_on_hostile_input() { - let mut block = Vec::new(); - block.extend_from_slice(&0xC001u16.to_be_bytes()); // block type: group start - block.extend_from_slice(&0u32.to_be_bytes()); // empty body: no name - - let total = ase::MAX_GROUPS + 1; - let mut f = b"ASEF".to_vec(); - f.extend_from_slice(&1u16.to_be_bytes()); // major - f.extend_from_slice(&0u16.to_be_bytes()); // minor - f.extend_from_slice(&(total as u32).to_be_bytes()); - for _ in 0..total { - f.extend_from_slice(&block); - } - assert!(matches!(ase::parse(&f), Err(PsdError::LimitExceeded(_))), "a file over MAX_GROUPS must be refused"); - // With one block fewer the file is exactly at the cap and parses. - f.truncate(f.len() - block.len()); - let trimmed = total - 1; - // signature (4) + major (2) + minor (2) puts the block count at offset 8. - f[8..12].copy_from_slice(&(trimmed as u32).to_be_bytes()); - let parsed = ase::parse(&f).expect("a file exactly at MAX_GROUPS must still parse"); - assert_eq!(parsed.entries.len(), ase::MAX_GROUPS, "every group up to the cap is kept"); -} - -/// A name longer than [`ase::MAX_NAME_UNITS`] is truncated on read rather than refused: the file -/// is legal, only the name is long, and `read_name` is the only thing standing between the declared -/// length and the string it builds. -#[test] -fn ase_over_long_name_is_truncated_on_read() { - let units = ase::MAX_NAME_UNITS + 976; // 2000 - let mut body = Vec::new(); - body.extend_from_slice(&(units as u16).to_be_bytes()); // name length, no trailing null here - for _ in 0..units { - body.extend_from_slice(&(b'x' as u16).to_be_bytes()); - } - body.extend_from_slice(b"Gray"); - body.extend_from_slice(&0f32.to_be_bytes()); - body.extend_from_slice(&2u16.to_be_bytes()); - - let mut f = b"ASEF".to_vec(); - f.extend_from_slice(&1u16.to_be_bytes()); - f.extend_from_slice(&0u16.to_be_bytes()); - f.extend_from_slice(&1u32.to_be_bytes()); // one block - f.extend_from_slice(&1u16.to_be_bytes()); // colour entry - f.extend_from_slice(&(body.len() as u32).to_be_bytes()); - f.extend_from_slice(&body); - - let parsed = ase::parse(&f).expect("an over-long name is truncated, not refused"); - let ase::AseEntry::Swatch(s) = &parsed.entries[0] else { panic!("expected a loose swatch") }; - assert_eq!(s.name.encode_utf16().count(), ase::MAX_NAME_UNITS, "name must be capped at MAX_NAME_UNITS"); -} - -/// An `.aco` that parses must re-serialize to the same swatch count, with no name over the cap. -#[test] -fn aco_round_trip_preserves_swatch_count() { - use photocraft_psd::aco::write; - // No cap assertion here. `aco::MAX_SWATCHES` is `u16::MAX` against a `u16` on-disk count, so it - // is unfalsifiable by construction, and the sample names are far shorter than the name cap; - // `aco_over_long_name_is_truncated_on_read` is where that cap is actually driven. - let f = aco::parse(&sample_aco()).expect("sample .aco parses"); - let out = write(&f.swatches).expect("re-writing parsed swatches"); - let back = aco::parse(&out).expect("the rewritten .aco parses"); - assert_eq!(back.swatches.len(), f.swatches.len(), "swatch count changed across a round trip"); -} - -/// A version 2 section whose name declares more units than [`aco::MAX_NAME_UNITS`] must come back -/// truncated. The count is written by hand because `write` will not emit one. -#[test] -fn aco_over_long_name_is_truncated_on_read() { - let units = 2000usize; - let mut f = Vec::new(); - f.extend_from_slice(&2u16.to_be_bytes()); // version 2 section - f.extend_from_slice(&1u16.to_be_bytes()); // one swatch - f.extend_from_slice(&0u16.to_be_bytes()); // colour space: RGB - for v in [1u16, 2, 3, 0] { - f.extend_from_slice(&v.to_be_bytes()); // the four stored values - } - // The count includes the terminating null, as `write` does and as the format requires. - f.extend_from_slice(&((units + 1) as u32).to_be_bytes()); - for _ in 0..units { - f.extend_from_slice(&(b'x' as u16).to_be_bytes()); - } - f.extend_from_slice(&0u16.to_be_bytes()); // terminating null - let parsed = aco::parse(&f).expect("an over-long name is truncated, not refused"); - assert_eq!(parsed.swatches[0].name.encode_utf16().count(), aco::MAX_NAME_UNITS, "name must be capped at MAX_NAME_UNITS"); -} - -/// `write` must cap too, or a long name from a caller is written whole. The declared length in -/// the version 2 record counts the terminating null, so it must read back as MAX_NAME_UNITS + 1. -#[test] -fn aco_write_caps_the_name() { - let swatches = vec![AcoSwatch { name: "x".repeat(5000), color: AcoColor::Gray(5000) }]; - let bytes = aco::write(&swatches).expect("an over-long name is capped on write, not refused"); - // Names go out as UTF-16 big-endian, so 'x' is the byte pair 00 78. - let run = [0u8, b'x']; - let mut needle = Vec::new(); - for _ in 0..8 { - needle.extend_from_slice(&run); - } - let at = bytes.windows(needle.len()).position(|w| w == needle.as_slice()).expect("the name is written into the file"); - let declared = u32::from_be_bytes([bytes[at - 4], bytes[at - 3], bytes[at - 2], bytes[at - 1]]); - assert_eq!(declared as usize, aco::MAX_NAME_UNITS + 1, "write must declare at most MAX_NAME_UNITS units plus the null"); - let back = aco::parse(&bytes).expect("the written file parses"); - assert_eq!(back.swatches[0].name.encode_utf16().count(), aco::MAX_NAME_UNITS); -} - -/// `write` must cap an over-long name too, and it must count the terminating null in the u16 -/// length field it writes. Without the cap that field would wrap, but only once the name passes -/// 65 535 units — so the case that proves it uses 70 000, not merely "long". -#[test] -fn ase_write_caps_the_name() { - use photocraft_psd::ase::{AseColor, AseEntry, AseFile, AseKind, AseSwatch, write}; - let sw = AseSwatch { name: "x".repeat(70_000), color: AseColor::Rgb([1.0, 0.0, 0.0]), kind: AseKind::Process }; - let bytes = write(&AseFile { entries: vec![AseEntry::Swatch(sw)] }).expect("an over-long name is capped, not refused"); - let run = [0u8, b'x']; - let mut needle = Vec::new(); - for _ in 0..8 { - needle.extend_from_slice(&run); - } - let at = bytes.windows(needle.len()).position(|w| w == needle.as_slice()).expect("the name is written into the file"); - let declared = u16::from_be_bytes([bytes[at - 2], bytes[at - 1]]) as usize; - assert_eq!(declared, ase::MAX_NAME_UNITS + 1, "write must declare at most MAX_NAME_UNITS units plus the null"); - let back = ase::parse(&bytes).expect("the written file parses"); - let ase::AseEntry::Swatch(s) = &back.entries[0] else { panic!("expected a loose swatch") }; - assert_eq!(s.name.encode_utf16().count(), ase::MAX_NAME_UNITS); -} - -/// Truncating a `.grd` anywhere must be an error: unlike `.aco` there is no optional second -/// section, so a prefix can never be a complete file. -#[test] -fn truncate_grd_is_always_an_error() { - let b = sample_grd(); - for cut in 0..b.len() { - let r = catch_unwind(|| grd::parse(&b[..cut])); - assert!(r.is_ok(), "grd: parse panicked on a {cut}/{}-byte prefix", b.len()); - assert!(r.unwrap().is_err(), "grd: truncation at {cut}/{} parsed successfully", b.len()); - } - assert!(grd::parse(&b).is_ok(), "grd: the full file must parse"); -} - -/// Truncating an `.ase` anywhere must be an error: the block count is fixed up front, so a prefix -/// cannot contain the number of blocks the header claims. -#[test] -fn truncate_ase_is_always_an_error() { - let b = sample_ase(); - for cut in 0..b.len() { - let r = catch_unwind(|| ase::parse(&b[..cut])); - assert!(r.is_ok(), "ase: parse panicked on a {cut}/{}-byte prefix", b.len()); - assert!(r.unwrap().is_err(), "ase: truncation at {cut}/{} parsed successfully", b.len()); - } - assert!(ase::parse(&b).is_ok(), "ase: the full file must parse"); -} - -/// Truncating an `.aco` inside its first section must be an error. A cut that lands exactly after a -/// complete first section is *not* an error — the reader stops there, having read the version 1 -/// section, and ignores whatever follows — so the sweep stops at that boundary rather than -/// claiming every prefix fails. The boundary is derived from the sample so adding a swatch -/// cannot silently weaken the sweep. -#[test] -fn truncate_aco_inside_first_section_is_an_error() { - let b = sample_aco(); - // version u16 + count u16, then one 10-byte colour record per swatch. - let first_section = 4 + sample_aco_swatches().len() * 10; - assert!(first_section <= b.len(), "the sample must contain a whole first section"); - for cut in 0..first_section { - let r = catch_unwind(|| aco::parse(&b[..cut])); - assert!(r.is_ok(), "aco: parse panicked on a {cut}/{first_section}-byte prefix"); - assert!(r.unwrap().is_err(), "aco: truncation inside the first section at {cut} parsed successfully"); - } - match catch_unwind(|| aco::parse(&b[..first_section])) { - Ok(Ok(_)) => {} - Ok(Err(e)) => panic!("aco: a complete first section must parse, got {e:?}"), - Err(_) => panic!("aco: a complete first section panicked"), - } - assert!(aco::parse(&b).is_ok(), "aco: the full file must parse"); -} - -/// Structural `.ase` cases the block reader has to survive: a group end with no start, a group -/// started inside another, a block length that disagrees with what the body consumes, and an -/// unknown colour model whose components are cut short. Each is a clean error or a clean parse, -/// never a panic and never a read past the block. -#[test] -fn ase_structurally_hostile_blocks() { - use photocraft_psd::ase::{AseColor, AseEntry}; - let header = |count: u32| { - let mut f = b"ASEF".to_vec(); - f.extend_from_slice(&1u16.to_be_bytes()); - f.extend_from_slice(&0u16.to_be_bytes()); - f.extend_from_slice(&count.to_be_bytes()); - f - }; - let block = |kind: u16, body: &[u8]| { - let mut b = kind.to_be_bytes().to_vec(); - b.extend_from_slice(&(body.len() as u32).to_be_bytes()); - b.extend_from_slice(body); - b - }; - let group_start = |name: &str| { - // The name is a u16 code-unit count followed by the units themselves, not raw bytes. - let units: Vec = name.encode_utf16().collect(); - let mut b = (units.len() as u16).to_be_bytes().to_vec(); - for u in units { - b.extend_from_slice(&u.to_be_bytes()); - } - block(0xC001, &b) - }; - let group_end = || block(0xC002, &[]); - let colour = |model: &[u8], floats: &[u8]| { - let mut b = 0u16.to_be_bytes().to_vec(); - b.extend_from_slice(model); - b.extend_from_slice(floats); - b.extend_from_slice(&2u16.to_be_bytes()); - block(0x0001, &b) - }; - - // A group end with no start: documented as ignored, so this parses and yields nothing. - let mut f = header(1); - f.extend_from_slice(&group_end()); - let parsed = ase::parse(&f).expect("an unbalanced group end must parse"); - assert!(parsed.entries.is_empty(), "a stray group end must not invent an entry or an empty group"); - - // A group started inside another: the outer one closes, both groups are emitted. - let mut f = header(3); - f.extend_from_slice(&group_start("outer")); - f.extend_from_slice(&group_start("inner")); - f.extend_from_slice(&colour(b"Gray", &1f32.to_be_bytes())); - let parsed = ase::parse(&f).expect("a nested group start must parse"); - assert_eq!(parsed.swatch_count(), 1, "the colour must land in exactly one group"); - // The message above is only true if the colour is in the *inner* group; check it. - let inner_holds_it = parsed.entries.iter().any(|e| matches!(e, AseEntry::Group { name, swatches } if name == "inner" && swatches.len() == 1)); - assert!(inner_holds_it, "the colour must land in the inner group, not the outer one"); - let names: Vec<&str> = parsed - .entries - .iter() - .filter_map(|e| match e { - AseEntry::Group { name, .. } => Some(name.as_str()), - AseEntry::Swatch(_) => None, - }) - .collect(); - assert_eq!(names, vec!["outer", "inner"], "both groups must be closed and emitted"); - - // A block length shorter than the body it describes: the colour's floats are cut off. - // Gray carries exactly one component, so declaring the block one byte shorter leaves that - // component half-read. It must be refused, not guessed at. - let mut short = 0u16.to_be_bytes().to_vec(); - short.extend_from_slice(b"Gray"); - short.extend_from_slice(&0f32.to_be_bytes()); - short.extend_from_slice(&2u16.to_be_bytes()); // colour type: process - let mut f = header(1); - let mut b = 0x0001u16.to_be_bytes().to_vec(); - b.extend_from_slice(&((short.len() - 4) as u32).to_be_bytes()); - b.extend_from_slice(&short); - f.extend_from_slice(&b); - let r = catch_unwind(|| ase::parse(&f)); - assert!(r.is_ok(), "a truncated colour component must not panic"); - assert!(r.unwrap().is_err(), "a colour component cut short must be refused, not guessed at"); - - // A block that ends after the components, with no colour type at all, is *accepted*: some - // writers omit it and the reader defaults it to process. Pinning that, because it is the one - // place this parser is deliberately lenient. - let mut f = header(1); - let mut b = 0x0001u16.to_be_bytes().to_vec(); - b.extend_from_slice(&(short.len().saturating_sub(2) as u32).to_be_bytes()); - b.extend_from_slice(&short[..short.len() - 2]); - f.extend_from_slice(&b); - let parsed = ase::parse(&f).expect("a colour block with no colour type is accepted by design"); - assert_eq!(parsed.swatch_count(), 1, "it must still yield exactly one swatch"); - - // An unknown colour model keeps whatever bytes follow it verbatim. - // The model tag is four bytes; give it four, then a known payload, so "kept verbatim" can be - // checked rather than merely asserted. - let mut f = header(1); - let payload = [1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; - f.extend_from_slice(&colour(b"XYZ ", &payload)); - let parsed = ase::parse(&f).expect("an unknown colour model is kept verbatim"); - assert_eq!(parsed.swatch_count(), 1, "an unknown model still yields one swatch"); - let AseEntry::Swatch(sw) = &parsed.entries[0] else { panic!("expected a loose swatch") }; - let AseColor::Other { model, data } = &sw.color else { panic!("an unknown model must be kept as Other, got {:?}", sw.color) }; - assert_eq!(model, b"XYZ ", "the model tag must be preserved verbatim"); - assert_eq!(data.as_slice(), &payload, "the component bytes must be preserved verbatim"); -} - -/// A `.aco` whose version 1 and version 2 sections disagree about the number of swatches is the -/// realistic hostile shape: Photoshop writes both, and a corrupted length lands in one of them. -/// The version 2 names must still line up with the version 1 colours they belong to. -#[test] -fn aco_mismatched_section_counts_do_not_panic() { - // version 1 with two colours and no names, then a version 2 section claiming five. - let mut f = vec![0u8, 1, 0, 2]; - for _ in 0..2 { - f.extend_from_slice(&[0, 0, 0, 1, 0, 2, 0, 3, 0, 0]); - } - f.extend_from_slice(&[0, 2, 0, 5]); - for _ in 0..5 { - f.extend_from_slice(&[0, 0, 0, 1, 0, 2, 0, 3, 0, 0]); - // An .aco record has no colour-type field, so a one-character name is exactly two units: - // two u16 values, not one. - f.extend_from_slice(&2u32.to_be_bytes()); - f.extend_from_slice(&[0, 78, 0, 0]); // 'N' and its null - } - let r = catch_unwind(|| aco::parse(&f)); - assert!(r.is_ok(), "mismatched section counts must not panic"); - let parsed = r.unwrap().expect("the version 2 section is the one with names"); - assert_eq!(parsed.swatches.len(), 5, "the named section is authoritative when present"); - for sw in &parsed.swatches { - assert_eq!(sw.name, "N", "each version 2 record must keep its name beside its own colour"); - } -} - -/// Deep descriptor nesting is the one hostile shape that aborts rather than returning: a stack -/// overflow is not a panic, so `catch_unwind` cannot catch it and it would take the process down. -/// `descriptor` bounds it at `MAX_DEPTH` and its own unit test drives `Descriptor::from_bytes` -/// directly; this drives the same limit through `grd::parse`, which is the path a user's gradient -/// preset actually takes, and asserts the specific error rather than merely surviving. -/// -/// The previous version of this test built `b"null"` repeated 2000 times, which is not a descriptor -/// at all — no item counts, no `Objc` tags — so the parser rejected it on the first field and -/// nothing ever recursed. It passed for the wrong reason. -#[test] -fn grd_deeply_nested_descriptor_hits_the_depth_limit() { - use photocraft_psd::descriptor::{Descriptor, MAX_DEPTH, Value, VersionedDescriptor}; - let mut d = Descriptor::new("null"); - for _ in 0..(MAX_DEPTH + 5) { - d = Descriptor::new("null").with("in ", Value::Descriptor(d)); - } - let mut g = b"8BGR".to_vec(); - g.extend_from_slice(&5u16.to_be_bytes()); - g.extend_from_slice(&VersionedDescriptor::new(d).to_bytes()); - // This is the real assertion: nesting past the limit is refused, not recursed into. - assert!(matches!(grd::parse(&g), Err(PsdError::LimitExceeded(_))), "nesting past MAX_DEPTH must be refused through the .grd path, not recursed into"); - - // The limit discriminates rather than being a blanket refusal: a shallow nesting is accepted - // (rejected later, for holding no gradients — a different error), while a deep one is a depth - // refusal. Each wrapper adds more than one unit of depth, so the exact crossover is an - // implementation detail; what matters is that normal files pass and runaway ones are stopped. - let build = |levels: usize| { - let mut d = Descriptor::new("null"); - for _ in 0..levels { - d = Descriptor::new("null").with("in ", Value::Descriptor(d)); - } - let mut g = b"8BGR".to_vec(); - g.extend_from_slice(&5u16.to_be_bytes()); - g.extend_from_slice(&VersionedDescriptor::new(d).to_bytes()); - g - }; - assert!(!matches!(grd::parse(&build(4)), Err(PsdError::LimitExceeded(_))), "a shallow descriptor must not be refused for depth"); - assert!( - matches!(grd::parse(&build(MAX_DEPTH + 1)), Err(PsdError::LimitExceeded(_))), - "a descriptor past the depth limit must be a depth refusal, not an abort" - ); -} - -/// Every colour model's components must come back finite and inside their documented range, not -/// just RGB. The writer only emits RGB and foreground/background stops, so each model is built by -/// hand with an out-of-range or non-representable value in every component, then driven through -/// `grd::parse`. Without this, the clamps on HSB, CMYK, Gray and the L* channel — and the finite -/// guard on the Lab a*/b* channels — have no test and can be removed unnoticed. -#[test] -fn grd_every_colour_model_is_clamped_and_finite() { - use photocraft_psd::descriptor::{Descriptor, Value, VersionedDescriptor}; - - // Build a one-stop gradient whose colour is `class_id` with the given (key, value) components. - let build = |class_id: &str, comps: &[(&str, f64)]| -> Vec { - let mut colour = Descriptor::new(class_id); - for (k, v) in comps { - colour = colour.with(k, Value::Double(*v)); - } - let stop = Descriptor::new("Clrt") - .with("Clr ", Value::Descriptor(colour)) - .with("Type", Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new("Clry"), value: photocraft_psd::descriptor::Id::new("UsrS") }) - .with("Lctn", Value::Integer(0)) - .with("Mdpn", Value::Integer(50)); - let grad = Descriptor::new("Grdn").with("Clrs", Value::List(vec![Value::Descriptor(stop)])); - let outer = Descriptor::new("Grdn").with("Grad", Value::Descriptor(grad)); - let file = Descriptor::new("null").with("GrdL", Value::List(vec![Value::Descriptor(outer)])); - let mut g = b"8BGR".to_vec(); - g.extend_from_slice(&5u16.to_be_bytes()); - g.extend_from_slice(&VersionedDescriptor::new(file).to_bytes()); - g - }; - - let hostile = [1e300, 3.0e38, -3.0e38, f64::NAN, f64::INFINITY, f64::NEG_INFINITY]; - for &x in &hostile { - // The exact boundary each clamp must land on, so a weaker clamp (e.g. a*/b* to -100..=100 - // instead of -128..=127, or a unit range to 0..=0.5) is caught, not just an out-of-range - // value. A NaN becomes 0.0 (the finite guard's fallback for `f`), a positive saturates to - // the top of the range, a negative to the bottom. - let unit = if x.is_nan() || x < 0.0 { 0.0f32 } else { 1.0 }; - let lab_l = if x.is_nan() || x < 0.0 { 0.0f32 } else { 100.0 }; - let lab_ab = if x.is_nan() { - 0.0f32 - } else if x > 0.0 { - 127.0 - } else { - -128.0 - }; - // RGB components are 0..=255 before the /255; the result must land in 0..=1. - let f = grd::parse(&build("RGBC", &[("Rd ", x), ("Grn ", x), ("Bl ", x)])).expect("RGB parses"); - let GrdColor::Rgb(rgb) = f[0].stops[0].color else { panic!("expected an RGB stop") }; - for v in rgb { - assert_eq!(v, unit, "RGB component for input {x} must saturate to {unit}"); - } - // HSB: hue 0..=360, saturation and brightness 0..=1. - let f = grd::parse(&build("HSBC", &[("H ", x), ("Strt", x), ("Brgh", x)])).expect("HSB parses"); - if let GrdColor::Hsb([h, sat, br]) = f[0].stops[0].color { - assert!(h.is_finite() && (0.0..=360.0).contains(&h), "hue {h} out of range for input {x}"); - assert_eq!(sat, unit, "saturation for input {x} must saturate to {unit}"); - assert_eq!(br, unit, "brightness for input {x} must saturate to {unit}"); - } else { - panic!("expected an HSB stop"); - } - // CMYK: every ink 0..=1. - let f = grd::parse(&build("CMYC", &[("Cyn ", x), ("Mgnt", x), ("Ylw ", x), ("Blck", x)])).expect("CMYK parses"); - if let GrdColor::Cmyk(c) = f[0].stops[0].color { - for v in c { - assert_eq!(v, unit, "CMYK ink for input {x} must saturate to {unit}"); - } - } else { - panic!("expected a CMYK stop"); - } - // Lab: L* 0..=100, a*/b* bounded to the CIELAB gamut -128..=127. - let f = grd::parse(&build("LbCl", &[("Lmnc", x), ("A ", x), ("B ", x)])).expect("Lab parses"); - if let GrdColor::Lab([l, a, b]) = f[0].stops[0].color { - assert_eq!(l, lab_l, "L* for input {x} must saturate to {lab_l}"); - assert_eq!(a, lab_ab, "a* for input {x} must saturate to the gamut edge {lab_ab}"); - assert_eq!(b, lab_ab, "b* for input {x} must saturate to the gamut edge {lab_ab}"); - } else { - panic!("expected a Lab stop"); - } - // Gray: 0..=1. - let f = grd::parse(&build("Grsc", &[("Gry ", x)])).expect("Gray parses"); - if let GrdColor::Gray(g) = f[0].stops[0].color { - assert_eq!(g, unit, "gray for input {x} must saturate to {unit}"); - } else { - panic!("expected a Gray stop"); - } - } -} - -/// Hue is circular, so an out-of-range hue must *wrap*, not clamp: 370 degrees is 10, not 360, and -/// -10 is 350, not 0. Clamping would hand back a different colour; this pins the wrap so a -/// regression to `clamp` is caught (both produce in-range values, so a range check alone would not). -#[test] -fn grd_hue_wraps_rather_than_clamping() { - use photocraft_psd::descriptor::{Descriptor, Id, Value, VersionedDescriptor}; - let build = |hue: f64| { - let colour = Descriptor::new("HSBC").with("H ", Value::Double(hue)).with("Strt", Value::Double(50.0)).with("Brgh", Value::Double(50.0)); - let stop = Descriptor::new("Clrt") - .with("Clr ", Value::Descriptor(colour)) - .with("Type", Value::Enumerated { type_id: Id::new("Clry"), value: Id::new("UsrS") }) - .with("Lctn", Value::Integer(0)) - .with("Mdpn", Value::Integer(50)); - let grad = Descriptor::new("Grdn").with("Clrs", Value::List(vec![Value::Descriptor(stop)])); - let outer = Descriptor::new("Grdn").with("Grad", Value::Descriptor(grad)); - let file = Descriptor::new("null").with("GrdL", Value::List(vec![Value::Descriptor(outer)])); - let mut g = b"8BGR".to_vec(); - g.extend_from_slice(&5u16.to_be_bytes()); - g.extend_from_slice(&VersionedDescriptor::new(file).to_bytes()); - g - }; - let hue_of = |bytes: &[u8]| -> f32 { - let f = grd::parse(bytes).expect("parses"); - let GrdColor::Hsb([h, _, _]) = f[0].stops[0].color else { panic!("expected an HSB stop") }; - h - }; - assert!((hue_of(&build(370.0)) - 10.0).abs() < 0.01, "370 degrees must wrap to 10, not clamp to 360"); - assert!((hue_of(&build(-10.0)) - 350.0).abs() < 0.01, "-10 degrees must wrap to 350, not clamp to 0"); - // And a value already in range is unchanged. - assert!((hue_of(&build(123.0)) - 123.0).abs() < 0.01, "an in-range hue must be unchanged"); - // Exactly 360 is in range and legal, so it is kept, not wrapped to 0 (a different position for - // anything that interpolates in HSB). Unconditional `rem_euclid(360)` would map it to 0, so this - // pins the in-range guard that keeps the boundary intact. - assert_eq!(hue_of(&build(360.0)), 360.0, "an in-range hue of exactly 360 must be preserved, not wrapped to 0"); - assert_eq!(hue_of(&build(0.0)), 0.0, "a hue of 0 must stay 0"); -} - -/// A signature-only or empty file must be a clean error, never a panic and never an -/// out-of-bounds read. -#[test] -fn empty_and_signature_only_inputs_error() { - fn no_panic_then_err(r: Result, Box>, what: &str) { - match r { - Ok(Ok(_)) => panic!("{what}: an empty file must be a clean error, not parse"), - Ok(Err(_)) => {} - Err(_) => panic!("{what}: parse panicked on an empty file"), - } - } - no_panic_then_err(catch_unwind(|| grd::parse(b"")), "grd"); - no_panic_then_err(catch_unwind(|| ase::parse(b"")), "ase"); - no_panic_then_err(catch_unwind(|| aco::parse(b"")), "aco"); - assert!(matches!(grd::parse(b"8BGR"), Err(PsdError::UnexpectedEof { .. }))); - assert!(matches!(grd::parse(b"8BG"), Err(PsdError::UnexpectedEof { .. }))); - assert!(ase::parse(b"ASEF").is_err()); - assert!(aco::parse(b"").is_err()); -} diff --git a/crates/psd/tests/it/tree.rs b/crates/psd/tests/it/tree.rs deleted file mode 100644 index ef448651fc..0000000000 --- a/crates/psd/tests/it/tree.rs +++ /dev/null @@ -1,249 +0,0 @@ -//! Layer tree reconstruction. - -use photocraft_psd::testgen; -use photocraft_psd::*; - -fn rec(name: &str, kind: Option) -> LayerRecord { - let mut r = LayerRecord { name: name.as_bytes().to_vec(), ..Default::default() }; - if let Some(k) = kind { - r.blocks.push(TaggedBlock::section_divider(k, Some(BlendMode::PassThrough), None)); - } - r -} - -fn file_with(records: Vec) -> PsdFile { - let mut f = testgen::merged_only(Version::Psd, ColorMode::Rgb, 8, Compression::Raw, 1, 1); - f.layer_info = Some(LayerInfo { layers: records, ..Default::default() }); - f -} - -fn names(f: &PsdFile, nodes: &[LayerNode]) -> String { - nodes - .iter() - .map(|n| match n { - LayerNode::Layer { index } => f.layers()[*index].name(), - LayerNode::Group { index, children, .. } => { - format!("{}[{}]", f.layers()[*index].name(), names(f, children)) - } - }) - .collect::>() - .join(",") -} - -const END: Option = Some(SectionType::BoundingDivider); -const OPEN: Option = Some(SectionType::OpenFolder); -const CLOSED: Option = Some(SectionType::ClosedFolder); - -#[test] -fn flat_layers() { - let f = file_with(vec![rec("a", None), rec("b", None), rec("c", None)]); - let t = f.layer_tree(); - assert_eq!(names(&f, &t), "a,b,c"); - assert!(t.iter().all(|n| !n.is_group())); -} - -#[test] -fn empty_file_has_empty_tree() { - let f = testgen::merged_only(Version::Psd, ColorMode::Rgb, 8, Compression::Raw, 1, 1); - assert!(f.layer_tree().is_empty()); -} - -#[test] -fn single_group() { - let f = file_with(vec![rec("bg", None), rec("", END), rec("x", None), rec("y", None), rec("G", OPEN)]); - let t = f.layer_tree(); - assert_eq!(names(&f, &t), "bg,G[x,y]"); - match &t[1] { - LayerNode::Group { index, divider, children } => { - assert_eq!(*index, 4); - assert_eq!(*divider, Some(1)); - assert_eq!(children.len(), 2); - } - _ => panic!(), - } -} - -#[test] -fn closed_group() { - let f = file_with(vec![rec("", END), rec("x", None), rec("G", CLOSED)]); - assert_eq!(names(&f, &f.layer_tree()), "G[x]"); -} - -#[test] -fn nested_groups() { - let f = file_with(vec![ - rec("", END), - rec("a", None), - rec("", END), - rec("b", None), - rec("Inner", CLOSED), - rec("c", None), - rec("Outer", OPEN), - rec("top", None), - ]); - let t = f.layer_tree(); - assert_eq!(names(&f, &t), "Outer[a,Inner[b],c],top"); - assert_eq!(t[0].count(), 5); -} - -#[test] -fn empty_group() { - let f = file_with(vec![rec("", END), rec("G", OPEN)]); - let t = f.layer_tree(); - assert_eq!(names(&f, &t), "G[]"); - assert!(t[0].children().is_empty()); -} - -#[test] -fn sibling_groups() { - let f = file_with(vec![rec("", END), rec("a", None), rec("G1", OPEN), rec("", END), rec("b", None), rec("G2", OPEN)]); - assert_eq!(names(&f, &f.layer_tree()), "G1[a],G2[b]"); -} - -#[test] -fn deeply_nested() { - let mut v = Vec::new(); - for _ in 0..50 { - v.push(rec("", END)); - } - v.push(rec("leaf", None)); - for i in 0..50 { - v.push(rec(&format!("g{i}"), OPEN)); - } - let f = file_with(v); - let t = f.layer_tree(); - assert_eq!(t.len(), 1); - assert_eq!(t[0].count(), 51); - let mut n = &t[0]; - let mut depth = 1; - while let Some(c) = n.children().first() { - n = c; - depth += 1; - } - assert_eq!(depth, 51); -} - -/// #2940: the capped tree keeps a group at the cap but not its children, so its depth is bounded -/// whatever the file nests. -#[test] -fn layer_tree_max_depth_drops_deeper_children() { - let mut v = vec![rec("", END), rec("", END), rec("", END), rec("x", None)]; - v.extend([rec("g2", OPEN), rec("g1", OPEN), rec("g0", OPEN), rec("top", None)]); - let f = file_with(v); - assert_eq!(names(&f, &f.layer_tree()), "g0[g1[g2[x]]],top"); - assert_eq!(names(&f, &f.layer_tree_max_depth(usize::MAX)), "g0[g1[g2[x]]],top"); - assert_eq!(names(&f, &f.layer_tree_max_depth(2)), "g0[g1[g2[]]],top"); - assert_eq!(names(&f, &f.layer_tree_max_depth(1)), "g0[g1[]],top"); - assert_eq!(names(&f, &f.layer_tree_max_depth(0)), "g0[],top"); -} - -fn depth(nodes: &[LayerNode]) -> usize { - // Iterative so a deep tree cannot overflow the test's stack. - let mut max = 0; - let mut todo: Vec<(&LayerNode, usize)> = nodes.iter().map(|n| (n, 1)).collect(); - while let Some((n, d)) = todo.pop() { - max = max.max(d); - todo.extend(n.children().iter().map(|c| (c, d + 1))); - } - max -} - -/// #5758: layers under a divider that is never closed are hoisted to the enclosing level, as -/// `layer_tree` does, also when the cap is shallower than the unclosed divider. -#[test] -fn layer_tree_max_depth_hoists_unclosed_divider_children() { - let f = file_with(vec![rec("a", None), rec("", END), rec("b", None), rec("c", None)]); - assert_eq!(names(&f, &f.layer_tree()), "a,b,c"); - assert_eq!(names(&f, &f.layer_tree_max_depth(1)), "a,b,c"); - assert_eq!(names(&f, &f.layer_tree_max_depth(0)), "a,b,c"); -} - -/// #5758: a closed group inside unclosed dividers sits at the depth it ends up at after hoisting, -/// so the cap keeps its node and drops only its deeper children. -#[test] -fn layer_tree_max_depth_keeps_closed_group_inside_unclosed_dividers() { - let mut v = vec![rec("", END), rec("", END)]; - v.extend([rec("", END), rec("", END), rec("x", None), rec("g1", OPEN), rec("g0", OPEN)]); - let f = file_with(v); - assert_eq!(names(&f, &f.layer_tree()), "g0[g1[x]]"); - assert_eq!(names(&f, &f.layer_tree_max_depth(1)), "g0[g1[]]"); - assert_eq!(names(&f, &f.layer_tree_max_depth(0)), "g0[]"); -} - -/// #5758: thousands of unclosed dividers around a closed chain stay bounded by the cap and keep -/// every layer the full tree has. -#[test] -fn layer_tree_max_depth_bounds_deep_unclosed_chain() { - let mut v = Vec::new(); - for i in 0..16_000 { - v.push(rec("", END)); - v.push(rec(&format!("l{i}"), None)); - } - v.extend([rec("", END), rec("", END), rec("", END), rec("x", None)]); - v.extend([rec("g2", OPEN), rec("g1", OPEN), rec("g0", OPEN)]); - let f = file_with(v); - let full = f.layer_tree(); - assert_eq!(full.len(), 16_001); - assert_eq!(depth(&full), 4); - let capped = f.layer_tree_max_depth(1); - assert!(depth(&capped) <= 2); - assert_eq!(capped.len(), 16_001); - assert_eq!(names(&f, &capped[16_000..]), "g0[g1[]]"); - assert_eq!(names(&f, &capped[..2]), "l0,l1"); -} -#[test] -fn folder_without_divider_is_empty_group() { - let f = file_with(vec![rec("a", None), rec("G", OPEN), rec("b", None)]); - assert_eq!(names(&f, &f.layer_tree()), "a,G[],b"); -} - -#[test] -fn unclosed_divider_hoists_children() { - let f = file_with(vec![rec("a", None), rec("", END), rec("b", None), rec("c", None)]); - assert_eq!(names(&f, &f.layer_tree()), "a,b,c"); -} - -#[test] -fn lsdk_is_honored() { - let mut end = rec("", None); - let mut b = TaggedBlock::section_divider(SectionType::BoundingDivider, None, None); - b.key = *b"lsdk"; - end.blocks.push(b); - let f = file_with(vec![end, rec("x", None), rec("G", OPEN)]); - assert_eq!(names(&f, &f.layer_tree()), "G[x]"); -} - -#[test] -fn other_section_type_is_layer() { - let f = file_with(vec![rec("a", Some(SectionType::Other)), rec("b", Some(SectionType::Unknown(9)))]); - assert_eq!(names(&f, &f.layer_tree()), "a,b"); -} - -#[test] -fn generated_layered_tree() { - let f = testgen::layered(Version::Psd, ColorMode::Rgb, 8, Compression::Rle); - let t = f.layer_tree(); - let outer = t.iter().find(|n| n.is_group()).expect("group"); - assert_eq!(f.layers()[outer.index()].name(), "Outer"); - assert_eq!(outer.children().len(), 2); - let inner = &outer.children()[1]; - assert!(inner.is_group()); - assert_eq!(f.layers()[inner.index()].name(), "Inner"); - assert_eq!(f.layers()[inner.index()].section_type(), SectionType::ClosedFolder); - assert_eq!(f.layers()[inner.children()[0].index()].name(), "Grüße"); -} - -#[test] -fn builder_groups_tree() { - let px = |n: usize| PixelData::Rgba8(vec![255; n * 4]); - let mut b = PsdBuilder::new(2, 2); - b.push_layer(LayerSpec::new("bg", 0, 0, 2, 2, px(4))); - b.begin_group(GroupSpec::new("A")); - b.push_layer(LayerSpec::new("a1", 0, 0, 1, 1, px(1))); - b.begin_group(GroupSpec { open: false, ..GroupSpec::new("B") }); - b.push_layer(LayerSpec::new("b1", 0, 0, 1, 1, px(1))); - b.end_group().unwrap(); - b.end_group().unwrap(); - let f = PsdFile::from_bytes(&b.to_bytes().unwrap()).unwrap(); - assert_eq!(names(&f, &f.layer_tree()), "bg,A[a1,B[b1]]"); -} diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 52aebd93d8..1c1b74d992 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -22,6 +22,18 @@ use std::sync::{Arc, RwLockReadGuard, RwLockWriteGuard}; use photocraft_color::{ColorMode, PixelFormat, SampleType, read_sample, read_samples, write_sample}; use photocraft_geom::{Rect, TILE_SIZE, TileCoord}; +/// The bytes a surface in `fmt` keeps for pixels written over `rect`: every tile the rect +/// touches, whole. Importers admit decoded pixels by their logical size; a narrow or scattered +/// rect stores up to `TILE_SIZE` times more, so admission charges this instead. +pub fn tile_storage_bytes(rect: Rect, fmt: &PixelFormat) -> u64 { + stored_tiles_bytes(rect.tile_count(), fmt) +} + +/// The bytes `tiles` whole tiles take in `fmt`. +pub fn stored_tiles_bytes(tiles: u64, fmt: &PixelFormat) -> u64 { + tiles.saturating_mul((TILE_SIZE as u64).pow(2)).saturating_mul(fmt.bytes_per_pixel() as u64) +} + /// A checked surface allocation could not be represented or reserved. #[derive(Clone, Debug, PartialEq, Eq)] pub enum AllocationError { diff --git a/crates/raster/src/memory/system.rs b/crates/raster/src/memory/system.rs index 998720b8b5..5ad4ebf5e5 100644 --- a/crates/raster/src/memory/system.rs +++ b/crates/raster/src/memory/system.rs @@ -127,12 +127,12 @@ pub(super) mod linux { } #[derive(Clone, Debug, PartialEq, Eq)] - struct Mount { - root: String, - mount_point: String, - fstype: String, - options: String, - super_options: String, + pub(super) struct Mount { + pub(super) root: String, + pub(super) mount_point: String, + pub(super) fstype: String, + pub(super) options: String, + pub(super) super_options: String, } /// Measures available RAM and free swap from `/proc/meminfo`, capped by the process's memory @@ -206,14 +206,14 @@ pub(super) mod linux { MembershipParse::Malformed => return CgroupLimits::Unreadable, }; let mountinfo = std::fs::read_to_string(proc_root.join("self/mountinfo")).ok(); - // A sandbox with no cgroup filesystem mounted and no `/sys/fs/cgroup` at all (Flatpak) - // shows the process its membership path but no interface files, so no limit is - // observable. Failing closed there reported 0 bytes free and refused every PSD on a - // machine with tens of GB. A present directory still takes the guarded path below. - // Only a confirmed NotFound counts as absent: a stat that fails for another reason - // (permissions) leaves the directory possibly present, so that case stays fail-closed. - let sys_root_absent = matches!(std::fs::metadata(sys_root), Err(e) if e.kind() == std::io::ErrorKind::NotFound); - if sys_root_absent && mountinfo.as_deref().is_some_and(lists_mounts_without_cgroup) { + // A sandbox with no cgroup filesystem mounted and no `/sys/fs/cgroup` at all (Flatpak) or + // only an empty mount-point directory left by `sysfs` shows the process its membership path + // but no interface files, so no limit is observable. Failing closed there reported 0 bytes + // free and refused every PSD on a machine with tens of GB. Only a present non-empty or + // unreadable directory takes the guarded path below: a stat or read_dir that fails for + // another reason (permissions, non-directory) leaves a mounted hierarchy possibly present, + // so that case stays fail-closed. + if sys_root_absent_or_empty(sys_root) && mountinfo.as_deref().is_some_and(lists_mounts_without_cgroup) { return CgroupLimits::NotConstrained; } @@ -273,16 +273,34 @@ pub(super) mod linux { MembershipParse::Parsed(membership) } + /// Whether `/sys/fs/cgroup` is absent (`ErrorKind::NotFound`) or a readable empty directory. + /// + /// Permission errors, non-directory paths, and unreadable directories return `false` and stay + /// fail-closed. + pub(super) fn sys_root_absent_or_empty(sys_root: &Path) -> bool { + match std::fs::metadata(sys_root) { + Err(e) => e.kind() == std::io::ErrorKind::NotFound, + Ok(meta) => meta.is_dir() && std::fs::read_dir(sys_root).is_ok_and(|mut entries| entries.next().is_none()), + } + } + /// Parses `/proc/self/mountinfo` into the mount fields used to locate a cgroup hierarchy. /// /// Malformed lines are skipped; callers fail closed when no matching mount is found. - fn parse_mountinfo(text: &str) -> Vec { + pub(super) fn parse_mountinfo(text: &str) -> Vec { let mut mounts = Vec::new(); for line in text.lines() { let fields: Vec<&str> = line.split_whitespace().collect(); let Some(separator) = fields.iter().position(|f| *f == "-") else { continue }; + let super_options = fields.get(separator + 3).copied().or_else(|| { + // `show_mountinfo` writes ` `; an empty source + // (e.g. a bubblewrap tmpfs mount) leaves two spaces between `fstype` and options. + let after = line.split_once(" - ")?.1.trim_start(); + let fstype = fields.get(separator + 1).copied()?; + after.strip_prefix(fstype)?.starts_with(" ").then(|| fields.get(separator + 2).copied()).flatten() + }); let (Some(root), Some(point), Some(fstype), Some(super_options)) = - (fields.get(3).copied(), fields.get(4).copied(), fields.get(separator + 1).copied(), fields.get(separator + 3).copied()) + (fields.get(3).copied(), fields.get(4).copied(), fields.get(separator + 1).copied(), super_options) else { continue; }; @@ -966,6 +984,23 @@ mod tests { assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + // Isolated case 1: a readable empty `/sys/fs/cgroup` mount-point directory with normal + // non-cgroup `mountinfo` also reports `NotConstrained`. + let (proc, sys) = fixture("empty-cgroup-mountpoint"); + write(&proc.join("self/cgroup"), "0::/app.slice/app-flatpak.scope\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // Isolated case 2: absent `/sys/fs/cgroup` with a bubblewrap empty-source non-cgroup mount + // (`- tmpfs rw,...`) parses cleanly and reports `NotConstrained`. + let (proc, _) = fixture("absent-cgroup-empty-source"); + let sys = proc.parent().unwrap().join("absent-sys"); + write(&proc.join("self/cgroup"), "0::/app.slice/app-flatpak.scope\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n26 20 0:24 / /tmp rw,nosuid,nodev - tmpfs rw,nosuid,nodev\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + // A truncated mount line may be the cgroup mount: with /sys/fs/cgroup absent, fail closed. let (proc, _) = fixture("truncated-mountinfo-line"); let sys = proc.parent().unwrap().join("absent-sys"); @@ -1269,4 +1304,91 @@ mod tests { assert_eq!(linux::available_at(&proc, &sys), Some((4 << 30) + (512 << 20)), "legacy helper keeps RAM + swap"); std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); } + + #[cfg(target_os = "linux")] + #[test] + fn linux_parse_mountinfo_handles_empty_mount_source() { + let tmpfs = "26 20 0:24 / /tmp rw,nosuid,nodev - tmpfs rw,nosuid,nodev,size=65536k\n"; + let cg2 = "30 20 0:26 /user.slice /sys/fs/cg\\0402 rw,relatime - cgroup2 rw,nsdelegate\n"; + let truncated = "31 20 0:27 / /sys/fs/cgroup rw - cgroup2 rw\n"; + let mounts = linux::parse_mountinfo(&format!("{tmpfs}{cg2}{truncated}")); + assert_eq!(mounts.len(), 2, "single-space line missing super_options is skipped"); + let m0 = &mounts[0]; + assert_eq!((&m0.root[..], &m0.mount_point[..], &m0.fstype[..]), ("/", "/tmp", "tmpfs")); + assert_eq!((&m0.options[..], &m0.super_options[..]), ("rw,nosuid,nodev", "rw,nosuid,nodev,size=65536k")); + let m1 = &mounts[1]; + assert_eq!((&m1.root[..], &m1.mount_point[..], &m1.fstype[..]), ("/user.slice", "/sys/fs/cg 2", "cgroup2")); + assert_eq!((&m1.options[..], &m1.super_options[..]), ("rw,relatime", "rw,nsdelegate")); + } + + /// An empty `/sys/fs/cgroup` directory only reports `NotConstrained` when `mountinfo` parses + /// cleanly with no cgroup mount; cgroup mounts (including empty-source lines), missing/empty/ + /// truncated `mountinfo`, non-empty directories, files, and unreadable directories fail closed. + #[cfg(target_os = "linux")] + #[test] + fn linux_empty_or_invalid_sys_root_fails_closed_unless_proven_unmounted() { + use std::os::unix::fs::PermissionsExt; + + let bad_mountinfo: [(&str, Option<&str>); 6] = [ + ("empty-sys-missing-mountinfo", None), + ("empty-sys-empty-mountinfo", Some("")), + ("empty-sys-garbage-mountinfo", Some("not a mountinfo line\n")), + ("empty-sys-truncated-mountinfo", Some("25 20 0:23 / /proc rw - proc proc rw\n30 20 0:26 / /sys/fs/cgroup rw - cgroup2\n")), + ("empty-sys-cgroup2-mount", Some("30 20 0:26 / /sys/fs/cgroup rw - cgroup2 cgroup2 rw\n")), + ("empty-sys-empty-source-cgroup2", Some("30 20 0:26 / /sys/fs/cgroup rw - cgroup2 rw\n")), + ]; + for (name, mountinfo) in bad_mountinfo { + let (proc, sys) = fixture(name); + write(&proc.join("self/cgroup"), "0::/app\n"); + if let Some(text) = mountinfo { + write(&proc.join("self/mountinfo"), text); + } + assert!(linux::sys_root_absent_or_empty(&sys), "{name}"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable, "{name}"); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } + + // Empty `/sys/fs/cgroup` with a v1 memory mount in `mountinfo` also fails closed. + let (proc, sys) = fixture("empty-sys-cgroup-v1-mount"); + write(&proc.join("self/cgroup"), "4:memory:/app\n"); + write(&proc.join("self/mountinfo"), "31 24 0:26 / /sys/fs/cgroup/memory rw - cgroup cgroup rw,memory\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // A non-empty `/sys/fs/cgroup` directory is not treated as unmounted even with non-cgroup mountinfo. + let (proc, sys) = fixture("non-empty-sys-root"); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + write(&sys.join("memory.max"), "1073741824\n"); + assert!(!linux::sys_root_absent_or_empty(&sys)); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // `sys_root` as a regular file and a `NotADirectory` path component return false and fail closed. + let (proc, _) = fixture("file-sys-root"); + let file_sys = proc.parent().unwrap().join("sys-as-file"); + write(&file_sys, ""); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + for path in [&file_sys, &file_sys.join("cgroup")] { + assert!(!linux::sys_root_absent_or_empty(path)); + assert_eq!(linux::cgroup_limits(&proc, path), linux::CgroupLimits::Unreadable); + } + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // An unreadable `/sys/fs/cgroup` directory (`read_dir` error) returns false and fails closed. + let (proc, sys) = fixture("unreadable-sys-root"); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + std::fs::set_permissions(&sys, std::fs::Permissions::from_mode(0o000)).unwrap(); + let read_blocked = std::fs::read_dir(&sys).is_err(); + let absent = linux::sys_root_absent_or_empty(&sys); + let limits = linux::cgroup_limits(&proc, &sys); + std::fs::set_permissions(&sys, std::fs::Permissions::from_mode(0o700)).unwrap(); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + if read_blocked { + assert!(!absent); + assert_eq!(limits, linux::CgroupLimits::Unreadable); + } + } } diff --git a/crates/raster/src/tests.rs b/crates/raster/src/tests.rs index 184a4c2121..6c9427d963 100644 --- a/crates/raster/src/tests.rs +++ b/crates/raster/src/tests.rs @@ -144,6 +144,30 @@ fn write_region_reference(surface: &mut Surface, r: Rect, data: &[f32]) { } } +/// Consumers identify tiles by their `Arc` pointer (e.g. ui-egui's histogram cache keys), so a +/// write through COW must hand the written copy a *new* tile, never keep the shared pointer: +/// mutating in place would make two different surfaces hash alike. This pins that invariant +/// for both `tile_mut` and `try_tile_mut`. +#[test] +fn writing_a_shared_surface_replaces_the_tile_not_its_bytes() { + let fmt = PixelFormat::GRAY8; + let mut a = Surface::with_default(fmt, &[0.0]); + a.write_pixel(10, 10, &[0.5]); + let coord = a.tiles().next().map(|(c, _)| *c).expect("the write allocated a tile"); + let before = Arc::as_ptr(a.tile(coord).expect("tile exists")) as usize; + for mutate in ["tile_mut", "try_tile_mut"] { + let mut b = a.clone(); + let ptr = Arc::as_ptr(b.tile(coord).expect("clone shares the tile")) as usize; + assert_eq!(ptr, before, "{}: the clone shares the tile before writing", mutate); + match mutate { + "tile_mut" => b.tile_mut(coord).bytes_mut().fill(255), + _ => b.try_tile_mut(coord).expect("allocation of a modest tile cannot fail").bytes_mut().fill(128), + } + let after = Arc::as_ptr(b.tile(coord).expect("tile exists")) as usize; + assert_ne!(after, ptr, "{}: a COW write must allocate a new tile", mutate); + } +} + #[test] fn region_writes_match_scalar_bytes_for_every_format() { let special = [ @@ -1019,6 +1043,17 @@ fn fallible_interleaved_writes_match_encoded_pixels_and_reject_bad_lengths() { } } +#[test] +fn tile_storage_counts_whole_tiles() { + let fmt = PixelFormat::RGBA8; + let tile = (TILE_SIZE as u64).pow(2) * 4; + assert_eq!(tile_storage_bytes(Rect::new(0, 0, 1, 1), &fmt), tile); + // A one-pixel column down four tiles keeps four whole tiles; straddling an edge, five. + assert_eq!(tile_storage_bytes(Rect::new(0, 0, 1, TILE_SIZE * 4), &fmt), 4 * tile); + assert_eq!(tile_storage_bytes(Rect::new(0, -1, 1, TILE_SIZE * 4), &fmt), 5 * tile); + assert_eq!(tile_storage_bytes(Rect::EMPTY, &fmt), 0); +} + /// The byte a row-callback test writes at pixel (x, y). fn row_byte(x: i32, y: i32) -> u8 { (x.wrapping_mul(7).wrapping_add(y.wrapping_mul(13)) & 0xff) as u8 diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index c4ef6d69f0..bf77cdbeb7 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -14,7 +14,7 @@ photocraft-geom = { workspace = true } photocraft-color = { workspace = true } photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } -photocraft-psd = { workspace = true } +craft-psd = { workspace = true } # No `system` feature: fontique's system backend links fontconfig on Linux. We scan font # directories ourselves (native) and always register the bundled fonts (native + web). parley = { version = "0.11", default-features = false, features = ["std"] } diff --git a/crates/text/src/engine_data.rs b/crates/text/src/engine_data.rs deleted file mode 100644 index 4acd08ac50..0000000000 --- a/crates/text/src/engine_data.rs +++ /dev/null @@ -1,456 +0,0 @@ -//! Photoshop's `EngineData`: the PostScript-like text engine document stored in `TySh`. -//! -//! Syntax (from observation of real files and public notes): dictionaries `<< /Key value … >>`, -//! arrays `[ … ]`, strings `( … )` holding UTF-16BE with a `FE FF` byte-order mark and `\` -//! escapes, numbers (`12`, `-1.5`, `.5`), `true`/`false`, and `/Name` values. - -use std::fmt::Write as _; - -#[derive(Clone, Debug, PartialEq)] -pub enum Value { - Dict(Vec<(String, Value)>), - Array(Vec), - String(String), - /// A string the file stored as plain bytes, without the `FE FF` mark (one char per byte). - /// Kept apart from [`Value::String`] so it is written back as the same bytes: Photoshop - /// rejects a `Txt2` whose raw strings come back as UTF-16 (#9091). - RawString(String), - Int(i64), - Real(f64), - Bool(bool), - Name(String), -} - -impl Value { - pub fn get(&self, key: &str) -> Option<&Value> { - match self { - Value::Dict(items) => items.iter().find(|(k, _)| k == key).map(|(_, v)| v), - _ => None, - } - } - /// Follows a path of dictionary keys. - pub fn path(&self, keys: &[&str]) -> Option<&Value> { - keys.iter().try_fold(self, |v, k| v.get(k)) - } - pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> { - match self { - Value::Dict(items) => items.iter_mut().find(|(k, _)| k == key).map(|(_, v)| v), - _ => None, - } - } - /// Sets (or appends) a dictionary entry. - pub fn set(&mut self, key: &str, v: Value) { - if let Value::Dict(items) = self { - match items.iter_mut().find(|(k, _)| k == key) { - Some(e) => e.1 = v, - None => items.push((key.to_string(), v)), - } - } - } - pub fn as_f64(&self) -> Option { - match self { - Value::Int(i) => Some(*i as f64), - // `inf`, `nan` and `1e999` parse as reals but are never a valid style number. - Value::Real(r) if r.is_finite() => Some(*r), - _ => None, - } - } - pub fn as_i64(&self) -> Option { - match self { - Value::Int(i) => Some(*i), - Value::Real(r) => Some(*r as i64), - _ => None, - } - } - pub fn as_bool(&self) -> Option { - match self { - Value::Bool(b) => Some(*b), - Value::Int(i) => Some(*i != 0), - _ => None, - } - } - pub fn as_str(&self) -> Option<&str> { - match self { - Value::String(s) | Value::RawString(s) | Value::Name(s) => Some(s), - _ => None, - } - } - pub fn as_array(&self) -> Option<&[Value]> { - match self { - Value::Array(a) => Some(a), - _ => None, - } - } - pub fn dict() -> Value { - Value::Dict(Vec::new()) - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ParseError(pub String); - -impl std::fmt::Display for ParseError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "EngineData: {}", self.0) - } -} -impl std::error::Error for ParseError {} - -const MAX_DEPTH: usize = 64; - -struct Parser<'a> { - b: &'a [u8], - i: usize, -} - -impl Parser<'_> { - fn ws(&mut self) { - while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\t' | b'\r' | b'\n' | 0) { - self.i += 1; - } - } - fn err(&self, m: &str) -> Result { - Err(ParseError(format!("{m} at byte {}", self.i))) - } - fn value(&mut self, depth: usize) -> Result { - if depth > MAX_DEPTH { - return self.err("nesting too deep"); - } - self.ws(); - let b = self.b; - match b.get(self.i) { - None => self.err("unexpected end"), - Some(b'<') if b.get(self.i + 1) == Some(&b'<') => { - self.i += 2; - let mut items = Vec::new(); - loop { - self.ws(); - match b.get(self.i) { - Some(b'>') if b.get(self.i + 1) == Some(&b'>') => { - self.i += 2; - return Ok(Value::Dict(items)); - } - Some(b'/') => { - let k = self.name(); - let v = self.value(depth + 1)?; - items.push((k, v)); - } - None => return self.err("unterminated dictionary"), - _ => return self.err("expected key"), - } - } - } - Some(b'[') => { - self.i += 1; - let mut items = Vec::new(); - loop { - self.ws(); - match b.get(self.i) { - Some(b']') => { - self.i += 1; - return Ok(Value::Array(items)); - } - None => return self.err("unterminated array"), - _ => items.push(self.value(depth + 1)?), - } - } - } - Some(b'(') => { - self.i += 1; - let mut raw = Vec::new(); - loop { - match b.get(self.i) { - None => return self.err("unterminated string"), - Some(b'\\') => { - if let Some(&c) = b.get(self.i + 1) { - raw.push(c); - } - self.i += 2; - } - Some(b')') => { - self.i += 1; - break; - } - Some(&c) => { - raw.push(c); - self.i += 1; - } - } - } - Ok(decode_string(&raw)) - } - Some(b'/') => Ok(Value::Name(self.name())), - Some(_) => { - let start = self.i; - while self.i < b.len() && !matches!(b[self.i], b' ' | b'\t' | b'\r' | b'\n' | b'[' | b']' | b'<' | b'>' | b'(' | b'/') { - self.i += 1; - } - let tok = std::str::from_utf8(&b[start..self.i]).unwrap_or(""); - match tok { - "true" => Ok(Value::Bool(true)), - "false" => Ok(Value::Bool(false)), - "" => { - self.i += 1; - self.err("unexpected byte") - } - t if t.contains('.') || t.contains('e') || t.contains('E') => t.parse().map(Value::Real).or_else(|_| self.err("bad number")), - t => t.parse().map(Value::Int).or_else(|_| t.parse().map(Value::Real).or_else(|_| self.err("bad token"))), - } - } - } - } - fn name(&mut self) -> String { - self.i += 1; // '/' - let start = self.i; - while self.i < self.b.len() && !matches!(self.b[self.i], b' ' | b'\t' | b'\r' | b'\n' | b'[' | b']' | b'<' | b'>' | b'(' | b'/') { - self.i += 1; - } - String::from_utf8_lossy(&self.b[start..self.i]).into_owned() - } -} - -fn decode_string(raw: &[u8]) -> Value { - if raw.len() >= 2 && raw[0] == 0xFE && raw[1] == 0xFF { - let u: Vec = raw[2..].as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect(); - Value::String(String::from_utf16_lossy(&u)) - } else { - Value::RawString(raw.iter().map(|&c| c as char).collect()) - } -} - -/// Parses an EngineData document (the top-level dictionary). -pub fn parse(data: &[u8]) -> Result { - let mut p = Parser { b: data, i: 0 }; - p.value(0) -} - -/// Serializes in Photoshop's layout (tab-indented, one key per line). -pub fn write(v: &Value) -> Vec { - let mut out = b"\n\n".to_vec(); - write_value(v, 0, &mut out); - out.push(b'\n'); - out -} - -/// Serializes `/key value` pairs without an enclosing dictionary: the layout of the document's -/// `Txt2` block (see [`crate::psd::build_txt2`]), which `parse_txt2` wraps in `<< >>` to parse. -pub fn write_bare(items: &[(String, Value)]) -> Vec { - let mut out = b"\n\n".to_vec(); - for (k, v) in items { - out.push(b'/'); - out.extend_from_slice(k.as_bytes()); - if is_container(v) { - out.push(b'\n'); - indent(&mut out, 1); - } else { - out.push(b' '); - } - write_value(v, 1, &mut out); - out.push(b'\n'); - } - out -} - -fn indent(out: &mut Vec, n: usize) { - out.extend(std::iter::repeat_n(b'\t', n)); -} - -fn is_container(v: &Value) -> bool { - matches!(v, Value::Dict(_)) || matches!(v, Value::Array(a) if a.iter().any(|x| matches!(x, Value::Dict(_) | Value::Array(_)))) -} - -fn write_value(v: &Value, depth: usize, out: &mut Vec) { - match v { - Value::Dict(items) => { - out.extend_from_slice(b"<<\n"); - for (k, v) in items { - indent(out, depth + 1); - out.push(b'/'); - out.extend_from_slice(k.as_bytes()); - if is_container(v) { - out.push(b'\n'); - indent(out, depth + 1); - } else { - out.push(b' '); - } - write_value(v, depth + 1, out); - out.push(b'\n'); - } - indent(out, depth); - out.extend_from_slice(b">>"); - } - Value::Array(items) if is_container(v) => { - out.extend_from_slice(b"[\n"); - for x in items { - indent(out, depth); - write_value(x, depth, out); - out.push(b'\n'); - } - indent(out, depth); - out.push(b']'); - } - Value::Array(items) => { - out.push(b'['); - for x in items { - out.push(b' '); - write_value(x, depth, out); - } - out.extend_from_slice(b" ]"); - } - Value::RawString(s) if s.chars().all(|c| u32::from(c) <= 0xFF) => { - out.push(b'('); - for c in s.chars() { - let c = u32::from(c) as u8; - if matches!(c, b'(' | b')' | b'\\') { - out.push(b'\\'); - } - out.push(c); - } - out.push(b')'); - } - Value::String(s) | Value::RawString(s) => { - out.push(b'('); - let mut raw = vec![0xFE, 0xFF]; - for u in s.encode_utf16() { - raw.extend_from_slice(&u.to_be_bytes()); - } - for c in raw { - if matches!(c, b'(' | b')' | b'\\') { - out.push(b'\\'); - } - out.push(c); - } - out.push(b')'); - } - Value::Int(i) => { - let _ = write!(Wrap(out), "{i}"); - } - Value::Real(r) => out.extend_from_slice(format_real(*r).as_bytes()), - Value::Bool(b) => out.extend_from_slice(if *b { b"true" } else { b"false" }), - Value::Name(n) => { - out.push(b'/'); - out.extend_from_slice(n.as_bytes()); - } - } -} - -struct Wrap<'a>(&'a mut Vec); -impl std::fmt::Write for Wrap<'_> { - fn write_str(&mut self, s: &str) -> std::fmt::Result { - self.0.extend_from_slice(s.as_bytes()); - Ok(()) - } -} - -/// Photoshop style: `1.0`, `.5`, `-.25`. -fn format_real(r: f64) -> String { - if !r.is_finite() { - return "0.0".into(); - } - if r.fract() == 0.0 && r.abs() < 1e15 { - return format!("{r:.1}"); - } - let mut s = format!("{r:.5}"); - while s.ends_with('0') { - s.pop(); - } - if matches!(s.as_str(), "0." | "-0.") { - return "0.0".into(); - } - if s.ends_with('.') { - s.push('0'); - } - if let Some(rest) = s.strip_prefix("0.") { - s = format!(".{rest}"); - } else if let Some(rest) = s.strip_prefix("-0.") { - s = format!("-.{rest}"); - } - s -} - -#[cfg(test)] -mod tests { - use super::*; - - const SAMPLE: &[u8] = b"\n\n<<\n\t/EngineDict\n\t<<\n\t\t/Editor\n\t\t<<\n\t\t\t/Text (\xFE\xFF\x00H\x00i\x00\\)\x00\r)\n\t\t>>\n\t\t/Nums [ 1.0 .5 -2 0 ]\n\t\t/Flag true\n\t\t/Kind /Roman\n\t\t/Runs [\n\t\t<<\n\t\t\t/A 1\n\t\t>>\n\t\t]\n\t>>\n>>"; - - #[test] - fn format_real_never_ends_with_bare_dot() { - assert_eq!(format_real(5.000001), "5.0"); - assert_eq!(format_real(12.000004), "12.0"); - assert_eq!(format_real(-5.000001), "-5.0"); - assert_eq!(format_real(1e20), "100000000000000000000.0"); - assert_eq!(format_real(0.5), ".5"); - assert_eq!(format_real(-0.25), "-.25"); - assert_eq!(format_real(1e-9), "0.0"); - assert_eq!(format_real(3.0), "3.0"); - } - - #[test] - fn parses_sample() { - let v = parse(SAMPLE).unwrap(); - assert_eq!(v.path(&["EngineDict", "Editor", "Text"]).and_then(Value::as_str), Some("Hi)\r")); - let nums: Vec = v.path(&["EngineDict", "Nums"]).unwrap().as_array().unwrap().iter().filter_map(Value::as_f64).collect(); - assert_eq!(nums, [1.0, 0.5, -2.0, 0.0]); - assert_eq!(v.path(&["EngineDict", "Flag"]).and_then(Value::as_bool), Some(true)); - assert_eq!(v.path(&["EngineDict", "Kind"]), Some(&Value::Name("Roman".into()))); - assert_eq!(v.path(&["EngineDict", "Runs"]).unwrap().as_array().unwrap()[0].get("A").and_then(Value::as_i64), Some(1)); - } - - #[test] - fn raw_strings_are_written_back_as_the_same_bytes() { - let v = parse(b"<< /2 (0100\\)) /3 (\xFE\xFF\x00h) >>").unwrap(); - assert_eq!(v.get("2"), Some(&Value::RawString("0100)".into()))); - assert_eq!(v.get("2").and_then(Value::as_str), Some("0100)")); - assert_eq!(v.get("3"), Some(&Value::String("h".into()))); - let bytes = write(&v); - assert!(bytes.windows(8).any(|w| w == b"(0100\\))"), "{:?}", String::from_utf8_lossy(&bytes)); - assert_eq!(parse(&bytes).unwrap(), v); - } - - #[test] - fn write_parse_roundtrip() { - let v = parse(SAMPLE).unwrap(); - let bytes = write(&v); - assert_eq!(parse(&bytes).unwrap(), v); - // Stable: writing twice gives identical bytes. - assert_eq!(write(&parse(&bytes).unwrap()), bytes); - } - - #[test] - fn reals_format_like_photoshop() { - assert_eq!(format_real(1.0), "1.0"); - assert_eq!(format_real(0.5), ".5"); - assert_eq!(format_real(-0.25), "-.25"); - assert_eq!(format_real(12.125), "12.125"); - } - - #[test] - fn tiny_reals_round_trip_as_numbers() { - for value in [0.000004, -0.000004] { - assert_eq!(format_real(value), "0.0"); - let source = Value::Dict(vec![( - "EngineDict".into(), - Value::Dict(vec![("StyleRun".into(), Value::Array(vec![Value::Dict(vec![("BaselineShift".into(), Value::Real(value))])]))]), - )]); - let encoded = write(&source); - let parsed = parse(&encoded).expect("formatted tiny real should parse"); - let baseline_shift = parsed - .path(&["EngineDict", "StyleRun"]) - .and_then(Value::as_array) - .and_then(|runs| runs.first()) - .and_then(|run| run.get("BaselineShift")) - .and_then(Value::as_f64); - assert_eq!(baseline_shift, Some(0.0)); - } - } - - #[test] - fn malformed_input_never_panics() { - for cut in 0..SAMPLE.len() { - let _ = parse(&SAMPLE[..cut]); - } - assert!(parse(b"<< /A").is_err()); - assert!(parse(&[b'['; 200]).is_err()); - } -} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 9764be6aa5..813ffdde3f 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -22,7 +22,8 @@ pub mod cjk; mod color_glyphs; pub mod craft_fonts; mod embolden; -pub mod engine_data; +// The EngineData syntax of type layers is PSD format code: it lives in craft-psd. +pub use craft_psd::engine_data; pub mod font_class; pub mod fonts; pub mod glyphs; diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs index 16d63c68b8..a9a5cd6973 100644 --- a/crates/text/src/psd.rs +++ b/crates/text/src/psd.rs @@ -9,13 +9,13 @@ //! Writing starts from the layer's original `TySh` (when present) and patches only the text, runs, //! paragraphs, fonts, shape and transform, so Photoshop-only settings survive an edit. +use craft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D, VersionedDescriptor}; use photocraft_color::{Color, ColorMode}; use photocraft_doc::TextLayer; use photocraft_doc::text::{ AntiAlias, Caps, CharStyle, FontBaseline, Kerning, Orientation, ParagraphRun, ParagraphStyle, TextAlign, TextRun, TextShape, TextWarp, }; use photocraft_geom::{Affine, Point}; -use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value as D, VersionedDescriptor}; use crate::engine_data::{self as ed, Value as E}; use crate::fonts::guess_from_postscript; diff --git a/crates/text/src/psd_styles.rs b/crates/text/src/psd_styles.rs index b28949a22f..4002aedbbd 100644 --- a/crates/text/src/psd_styles.rs +++ b/crates/text/src/psd_styles.rs @@ -245,7 +245,7 @@ pub fn write_style_sheets(tysh: &[u8], layer: &TextLayer, styles: &TextStyles, d let raw = crate::engine_data::write(&e); { let item = t.text.items.iter_mut().find(|(k, _)| k.is("EngineData"))?; - item.1 = photocraft_psd::descriptor::Value::RawData(raw) + item.1 = craft_psd::descriptor::Value::RawData(raw) } Some(write_tysh(&t)) } diff --git a/crates/text/src/render.rs b/crates/text/src/render.rs index 47da2de811..477568c8b0 100644 --- a/crates/text/src/render.rs +++ b/crates/text/src/render.rs @@ -2,7 +2,7 @@ use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; use photocraft_doc::text::AntiAlias; -use photocraft_geom::{Affine, Rect}; +use photocraft_geom::{Affine, Rect, TILE_SIZE}; use photocraft_raster::Surface; use skrifa::instance::{LocationRef, NormalizedCoord, Size}; use skrifa::outline::DrawSettings; @@ -52,6 +52,19 @@ fn fits_raster_budget(w: usize, h: usize, stride: usize, sample: SampleType, bol peak.is_some_and(|b| b <= max_bytes) } +/// Whether the whole tiles the output surface stores for `rect` fit `max_bytes`. A thin rectangle +/// (an extreme transform of short text) crosses many tiles while holding few pixels, so the pixel +/// budget alone doesn't bound them. `held` is what the accumulator keeps alive meanwhile: the +/// tiles are allocated while it is still in use. +fn fits_tile_budget(rect: Rect, format: PixelFormat, held: u64, max_bytes: u64) -> bool { + let tile_px = (TILE_SIZE as u64).pow(2); + rect.tile_count() + .checked_mul(tile_px) + .and_then(|px| px.checked_mul(format.bytes_per_pixel() as u64)) + .and_then(|b| b.checked_add(held)) + .is_some_and(|b| b <= max_bytes) +} + /// A zeroed buffer, or `None` when its bytes cannot be reserved. fn zeroed(len: usize) -> Option> { let mut v = Vec::new(); @@ -596,7 +609,12 @@ pub(crate) fn rasterize_passes( let n = format.mode.color_channels(); let stride = n + 1; let any_bold = colors.iter().any(|(_, b, _)| *b); - if !fits_raster_budget(w, h, stride, format.sample, any_bold, MAX_RASTER_BYTES) { + // The accumulator (f32 per sample) is live while the output tiles are allocated. + // u64 arithmetic: on a 32-bit target the usize product overflows before the budget check. + let Some(acc_bytes) = (w as u64).checked_mul(h as u64).and_then(|n| n.checked_mul((stride * size_of::()) as u64)) else { + return nothing(format); + }; + if !fits_raster_budget(w, h, stride, format.sample, any_bold, MAX_RASTER_BYTES) || !fits_tile_budget(rect, format, acc_bytes, MAX_RASTER_BYTES) { return nothing(format); } // Premultiplied accumulation. @@ -810,8 +828,8 @@ pub fn outlines(layout: &TextLayout, transform: &Affine, warp: Option<&Warp>) -> #[cfg(test)] mod tests { - use super::{MAX_PIXELS, fits_raster_budget, rect_from_bounds, zeroed}; - use photocraft_color::SampleType; + use super::{MAX_PIXELS, fits_raster_budget, fits_tile_budget, rect_from_bounds, zeroed}; + use photocraft_color::{PixelFormat, SampleType}; use photocraft_geom::Rect; /// Verifies underline and strikethrough decoration drawing bounds clip strictly to the text shape's explicit path span. @@ -844,6 +862,19 @@ mod tests { } } + #[test] + fn a_thin_rectangle_is_charged_for_the_tiles_it_crosses() { + let format = PixelFormat::RGBA8; + // One pixel high, 2^24 wide: 16 Mi pixels, but 65536 tiles of 256 KiB (16 GiB). + let thin = Rect::new(0, 0, 1 << 24, 1); + assert!(!fits_tile_budget(thin, format, 0, 4 << 30)); + // The same pixels in a square fit in 16 MiB of tiles. + let square = Rect::new(0, 0, 4096, 4096); + assert!(fits_tile_budget(square, format, 0, 64 << 20)); + assert!(!fits_tile_budget(square, format, 0, (64 << 20) - 1), "the allowance is exact"); + assert!(!fits_tile_budget(square, format, 1, 64 << 20), "the accumulator is charged with the tiles"); + } + #[test] fn bounds_are_clipped_without_overflow_and_oversized_rectangles_rejected() { let min = f64::from(i32::MIN); diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 881938091a..33fda2f45a 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1016,7 +1016,7 @@ fn txt2_with_styles(text: &str, styles: &[(usize, String)]) -> Vec { fn with_text_index(tysh: &[u8], index: i32) -> Vec { let mut t = crate::psd::parse_tysh(tysh).unwrap(); t.text.items.retain(|(k, _)| !k.is("TextIndex")); - t.text.items.push((photocraft_psd::descriptor::Id::new("TextIndex"), photocraft_psd::descriptor::Value::Integer(index))); + t.text.items.push((craft_psd::descriptor::Id::new("TextIndex"), craft_psd::descriptor::Value::Integer(index))); crate::psd::write_tysh(&t) } @@ -1784,7 +1784,7 @@ fn psd_text_fill_is_enabled_after_editing_a_legacy_export() { remove_fill_flags(&mut data); for (key, value) in &mut legacy.text.items { if key.as_bytes() == b"EngineData" { - *value = photocraft_psd::descriptor::Value::RawData(crate::engine_data::write(&data)); + *value = craft_psd::descriptor::Value::RawData(crate::engine_data::write(&data)); } } t.psd_raw = Some(crate::psd::write_tysh(&legacy).into()); @@ -1877,7 +1877,7 @@ fn psd_engine_data_keeps_only_oldstyle_among_numeral_tags() { /// (the ink box, as Photoshop writes it) both around `anchor` in a remote local space, and a /// `transform` that cancels the remote origin. fn legacy_tysh(source: &TextLayer, transform: Affine, anchor: [f64; 2], engine: &mut TextEngine) -> Vec { - use photocraft_psd::descriptor::{Descriptor, Id, Value as D}; + use craft_psd::descriptor::{Descriptor, Id, Value as D}; let layout = engine.layout(source, 72.0); let logical = layout.bounds().unwrap().map(f64::from); let ink = crate::render::ink_bounds(&layout).unwrap(); @@ -1907,7 +1907,7 @@ fn assert_transform_near(got: Affine, want: Affine, tolerance: f64, what: &str) /// fixed for left, centered and right text through import and a TySh round trip. #[test] fn legacy_tysh_point_origin_imports_and_round_trips_on_canvas() { - use photocraft_psd::descriptor::Value as D; + use craft_psd::descriptor::Value as D; let original = Affine { m: [4.1667, 0.0, 0.0, 4.1667, -32375.0, -32887.5] }; // The file's layout origin (the anchor on the first baseline) in its local space. @@ -2578,7 +2578,7 @@ fn txt2_frame_places_point_text_at_its_anchor() { /// `tysh` with its text-space `bounds` set to `r` (Photoshop's, where it drew the text). fn with_bounds(tysh: &[u8], r: [f64; 4]) -> Vec { - use photocraft_psd::descriptor::{Descriptor, Id, Value}; + use craft_psd::descriptor::{Descriptor, Id, Value}; let mut t = crate::psd::parse_tysh(tysh).unwrap(); let mut d = Descriptor::default(); for (k, v) in ["Left", "Top ", "Rght", "Btom"].iter().zip(r) { @@ -2891,7 +2891,7 @@ fn font_metadata_survives_tysh_and_named_style_rewrites() { } for (key, value) in &mut tysh.text.items { if key.as_bytes() == b"EngineData" { - *value = photocraft_psd::descriptor::Value::RawData(crate::engine_data::write(&data)); + *value = craft_psd::descriptor::Value::RawData(crate::engine_data::write(&data)); } } let raw = crate::psd::write_tysh(&tysh); diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 10b1838ead..d0dd5977bc 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -33,7 +33,7 @@ photocraft-format = { workspace = true } # Decoding the brand mark's PNG (`brand.rs`); already linked through photocraft-io. photocraft-codecs = { workspace = true } # Reading embedded thumbnail resources (1036/1033) for recent files in Home screen. -photocraft-psd = { workspace = true } +craft-psd = { workspace = true } egui = { workspace = true } egui_extras = { version = "0.37", default-features = false, features = ["svg"] } eframe = { workspace = true, features = ["wgpu", "accesskit", "clipboard"] } @@ -76,7 +76,7 @@ egui_kittest = { workspace = true, features = ["wgpu", "snapshot", "eframe"] } photocraft-testkit = { workspace = true } # examples/perf_scenarios.rs (a 500-brush .abr for the #210 import row) and large_file_bench.rs # (the generated 2 GB PSD and 4.4 GB PSB of P20, `fixtures`). -photocraft-psd = { workspace = true, features = ["testgen"] } +craft-psd = { workspace = true, features = ["testgen"] } # Isolated, self-cleaning folders for filesystem tests (the LUT folder, #6558). tempfile = "3" diff --git a/crates/ui-egui/examples/free_transform_bench.rs b/crates/ui-egui/examples/free_transform_bench.rs new file mode 100644 index 0000000000..c0fc35f36f --- /dev/null +++ b/crates/ui-egui/examples/free_transform_bench.rs @@ -0,0 +1,171 @@ +//! Free Transform stalls (#11103): two selected raster layers on a 24 MP document, one box. +//! +//! ```sh +//! cargo run --release -p photocraft-ui-egui --example free_transform_bench -- [--size 6000x4000] [--reps 9] [--steps 60] +//! ``` +//! +//! - begin: Ctrl+T (`transform_tool::begin`) and the first preview frame, then Esc. +//! - drag update: one pointer move and the preview frame it draws. "scale" drags the bottom-right +//! handle towards the top-left corner, shrinking the box from 100 % to 20 % at 100 % view zoom, +//! so the scale crosses ½ and ¼ (new mip levels) mid-drag; "move" drags the box by its middle. +//! +//! CPU side only: the egui frame and the texture preparation it does, not GPU upload or +//! presentation. A helper thread's work (a mip level built off the UI thread) isn't counted. + +use std::time::Instant; + +use photocraft_ui_egui::canvas::{ToolEvent, ViewXform}; +use photocraft_ui_egui::{PhotocraftApp, Services, transform_tool}; +use serde_json::json; + +fn arg(args: &[String], name: &str) -> Option { + args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned()) +} + +fn median(v: &[f64]) -> f64 { + let mut v = v.to_vec(); + v.sort_by(f64::total_cmp); + v.get(v.len() / 2).copied().unwrap_or(0.0) +} + +fn worst(v: &[f64]) -> f64 { + v.iter().copied().fold(0.0, f64::max) +} + +/// The view the frames draw through: 100 %, the document centred in a 1600 × 1000 canvas. +fn view(w: u32, h: u32) -> ViewXform { + ViewXform { + rect: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0)), + zoom: 1.0, + center: [w as f32 / 2.0, h as f32 / 2.0], + flip: false, + rotation: 0.0, + aspect: 1.0, + } +} + +/// The texture size limit a desktop GPU reports (egui's default without a renderer is 2048, +/// which would shrink the preview to a fraction of the layer and hide the cost being measured). +const MAX_TEXTURE_SIDE: usize = 16384; + +/// One frame drawing the open box's preview, in milliseconds. +fn frame(app: &PhotocraftApp, ctx: &egui::Context, xf: &ViewXform) -> f64 { + let input = egui::RawInput { screen_rect: Some(xf.rect), max_texture_side: Some(MAX_TEXTURE_SIDE), ..Default::default() }; + let start = Instant::now(); + let output = ctx.run_ui(input, |ui| transform_tool::draw_content(app, ui.painter(), xf)); + let ms = start.elapsed().as_secs_f64() * 1e3; + drop(output); + ms +} + +fn pointer(app: &mut PhotocraftApp, ev: ToolEvent) { + transform_tool::pointer(app, ev, egui::Modifiers::NONE); +} + +fn main() { + let args: Vec = std::env::args().collect(); + let (w, h) = + arg(&args, "--size").and_then(|s| s.split_once('x').and_then(|(a, b)| Some((a.parse::().ok()?, b.parse::().ok()?)))).unwrap_or((6000, 4000)); + let reps: usize = arg(&args, "--reps").and_then(|s| s.parse().ok()).unwrap_or(9).max(1); + let steps: usize = arg(&args, "--steps").and_then(|s| s.parse().ok()).unwrap_or(60).max(2); + + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": w, "height": h, "background": "white"})).expect("new document"); + // Two overlapping layers, each covering most of the canvas. + let (fw, fh) = (w * 2 / 3, h * 3 / 4); + let mut ids = Vec::new(); + for (name, x, y, color) in [("A", 0, 0, "#c03020"), ("B", w - fw, h - fh, "#2050c0")] { + let id = app.run("layer.new.layer", json!({"name": name})).expect("new layer")["layer"].as_u64().unwrap_or(0); + app.run("layer.select", json!({"layer": id})).expect("select"); + app.run("select.rect", json!({"x": x, "y": y, "width": fw, "height": fh})).expect("select.rect"); + app.run("edit.fill", json!({"contents": "color", "color": color})).expect("fill"); + app.run("select.deselect", json!({})).expect("deselect"); + ids.push(id); + } + if let (Some(a), Some(b)) = (ids.first(), ids.get(1)) { + app.run("layer.select", json!({"layer": a})).expect("select A"); + app.run("layer.select", json!({"layer": b, "mode": "add"})).expect("add B"); + } + app.sync_views(); + if let Some(v) = app.ui.views.first_mut() { + v.zoom = 1.0; + v.center = [w as f32 / 2.0, h as f32 / 2.0]; + v.fit_pending = false; + } + let xf = view(w, h); + let ctx = egui::Context::default(); + let _ = ctx.run_ui(egui::RawInput { max_texture_side: Some(MAX_TEXTURE_SIDE), ..Default::default() }, |_| {}); + + // Ctrl+T and its first preview frame. + let (mut begin, mut first, mut begin_total) = (Vec::new(), Vec::new(), Vec::new()); + for _ in 0..reps { + let t0 = Instant::now(); + transform_tool::begin(&mut app, &ctx).expect("Free Transform"); + let opened = t0.elapsed().as_secs_f64() * 1e3; + let drawn = frame(&app, &ctx, &xf); + begin.push(opened); + first.push(drawn); + begin_total.push(opened + drawn); + transform_tool::cancel(&mut app); + } + + // Drags: one pointer move + its frame per update. + let mut drag = |kind: &str| -> Vec { + transform_tool::begin(&mut app, &ctx).expect("Free Transform"); + let _ = frame(&app, &ctx, &xf); + let q = app.ui.transform.as_ref().map(|t| t.quad).unwrap_or_default(); + let (from, to) = if kind == "scale" { + // The bottom-right handle towards the top-left corner: 100 % → 20 %. + let (a, c) = (q[0], q[2]); + (c, [a[0] + 0.2 * (c[0] - a[0]), a[1] + 0.2 * (c[1] - a[1])]) + } else { + let m = [(q[0][0] + q[2][0]) / 2.0, (q[0][1] + q[2][1]) / 2.0]; + (m, [m[0] + 400.0, m[1] + 250.0]) + }; + pointer(&mut app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }); + let mut times = Vec::with_capacity(steps); + for s in 1..=steps { + let k = s as f64 / steps as f64; + let p = [from[0] + k * (to[0] - from[0]), from[1] + k * (to[1] - from[1])]; + let t0 = Instant::now(); + pointer(&mut app, ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 }); + let moved = t0.elapsed().as_secs_f64() * 1e3; + times.push(moved + frame(&app, &ctx, &xf)); + } + pointer(&mut app, ToolEvent::Up { x: to[0], y: to[1] }); + transform_tool::cancel(&mut app); + times + }; + let mut scale = Vec::new(); + let mut moving = Vec::new(); + for _ in 0..reps.min(3) { + scale.extend(drag("scale")); + moving.extend(drag("move")); + } + + if let Some(out) = arg(&args, "--json") { + use photocraft_testkit::perf::{process_peak_rss_bytes, report, row, write_report}; + let rss = photocraft_testkit::perf::current_rss_bytes().max(process_peak_rss_bytes()); + let rows = vec![ + row("Free Transform begin, 2 layers on 24 MP: Ctrl+T + first frame", &begin_total, rss, None), + row("Free Transform begin, 2 layers on 24 MP: Ctrl+T", &begin, rss, None), + row("Free Transform begin, 2 layers on 24 MP: first frame", &first, rss, None), + row("Free Transform drag update, 2 layers on 24 MP: scale through mip levels", &scale, rss, None), + row("Free Transform drag update, 2 layers on 24 MP: move", &moving, rss, None), + ]; + let rep = report("free_transform_bench", json!({"width": w, "height": h, "layers": 2, "reps": reps, "steps": steps}), rows, None); + if let Err(e) = write_report(&out, &rep) { + eprintln!("{e}"); + } + } + println!("{w}×{h}, 2 layers, {reps} reps, {steps} steps per drag"); + println!( + "begin: Ctrl+T {:.1} ms + first frame {:.1} ms = {:.1} ms (median; worst {:.1} ms)", + median(&begin), + median(&first), + median(&begin_total), + worst(&begin_total) + ); + println!("drag update, scale 100 % → 20 %: median {:.2} ms, worst {:.2} ms", median(&scale), worst(&scale)); + println!("drag update, move: median {:.2} ms, worst {:.2} ms", median(&moving), worst(&moving)); +} diff --git a/crates/ui-egui/examples/large_file_bench.rs b/crates/ui-egui/examples/large_file_bench.rs index fcf1228b26..fbdcd1642e 100644 --- a/crates/ui-egui/examples/large_file_bench.rs +++ b/crates/ui-egui/examples/large_file_bench.rs @@ -9,7 +9,7 @@ //! cargo run --release -p photocraft-ui-egui --example large_file_bench -- [--reps 3] [--only psd|psb] [--cache DIR] [--clean] [--json out.json] //! ``` //! -//! The fixtures (`photocraft_psd::fixtures`, about 6.4 GB together) are generated once into +//! The fixtures (`craft_psd::fixtures`, about 6.4 GB together) are generated once into //! `--cache` (default: `$PHOTOCRAFT_FIXTURE_DIR`, else `fixtures/` in the target directory next //! to this binary) and kept for the next run; `--clean` removes them afterwards. Each row also //! records the peak resident memory of its opens. Needs about 30 GB of memory for the PSB. @@ -17,8 +17,8 @@ use std::path::PathBuf; use std::time::{Duration, Instant}; +use craft_psd::fixtures::{PSB_4GB, PSD_2GB, Streamed}; use photocraft_engine::Session; -use photocraft_psd::fixtures::{PSB_4GB, PSD_2GB, Streamed}; use photocraft_testkit::perf::{RssSampler, row}; use serde_json::json; diff --git a/crates/ui-egui/examples/layers_panel_bench.rs b/crates/ui-egui/examples/layers_panel_bench.rs new file mode 100644 index 0000000000..7d1cf1b8e5 --- /dev/null +++ b/crates/ui-egui/examples/layers_panel_bench.rs @@ -0,0 +1,130 @@ +//! Per-frame CPU cost of the Layers panel with many groups (#13117): a group row that was scrolled +//! out of view used to paint its whole row (background, thumbnail, name, badges) every frame. This +//! is the before/after measure for that fix. +//! +//! ```sh +//! cargo run --release -p photocraft-ui-egui --example layers_panel_bench -- [--groups 300] [--frames 300] [--expanded] [--plain] [--json out.json] +//! ``` +//! +//! The document is built through Session commands on a tiny 64x48 canvas, so the canvas costs next +//! to nothing: `--groups N` top-level collapsed groups, each holding one pixel layer (`--expanded` +//! opens them all afterwards); `--plain` builds N plain pixel layers instead, a control whose rows +//! were already culled off-screen. The real `PhotocraftApp` runs in a plain CPU egui_kittest +//! harness (no wgpu), so a frame's time is the UI's own CPU work. After a warm-up, the row is the +//! median / p90 / max of `--frames` idle frames (`h.step()` each). + +use std::time::Instant; + +use egui_kittest::kittest::Queryable; +use photocraft_ui_egui::{PhotocraftApp, Services}; +use serde_json::{Value, json}; + +/// The app in an offscreen harness. +type H = egui_kittest::Harness<'static, PhotocraftApp>; + +/// The value after `name` on the command line, if any. +fn arg(args: &[String], name: &str) -> Option { + args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned()) +} + +/// Milliseconds since `t`. +fn ms(t: Instant) -> f64 { + t.elapsed().as_secs_f64() * 1000.0 +} + +/// One frame, timed. +fn frame(h: &mut H) -> f64 { + let t = Instant::now(); + h.step(); + ms(t) +} + +/// Result rows: name, then median, p90 and max frame time (ms). +struct Rows { + rows: Vec<(String, f64, f64, f64)>, +} + +impl Rows { + /// A row from frame times already taken. + fn add(&mut self, name: &str, v: Vec) { + let mut v: Vec = v.into_iter().filter(|t| t.is_finite()).collect(); + if v.is_empty() { + return; + } + v.sort_by(f64::total_cmp); + let (med, p90, max) = (v[v.len() / 2], v[(v.len() * 9 / 10).min(v.len() - 1)], v[v.len() - 1]); + println!("{name:<46} median {med:>8.3} ms p90 {p90:>8.3} max {max:>8.3}"); + self.rows.push((name.to_string(), med, p90, max)); + } +} + +/// `n` top-level collapsed groups (or plain layers), each group holding one pixel layer. +fn build(n: usize, plain: bool, expanded: bool) -> photocraft_engine::Session { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48})).expect("file.new"); + for i in 0..n { + s.execute("layer.new.layer", json!({"name": format!("Layer {i}")})).expect("layer.new.layer"); + if !plain { + // Group Layers makes a collapsed group; the next new layer lands above it, at the same level. + s.execute("layer.groupLayers", json!({"name": format!("Group {i}")})).expect("layer.groupLayers"); + } + } + if expanded && !plain { + s.execute("layer.setExpanded", json!({"all": true, "expanded": true})).expect("layer.setExpanded"); + } + s +} + +/// Builds the document, warms the app up, times idle frames and prints (and optionally writes) the row. +fn main() { + let args: Vec = std::env::args().collect(); + let groups: usize = arg(&args, "--groups").and_then(|v| v.parse().ok()).unwrap_or(300).max(1); + let frames: usize = arg(&args, "--frames").and_then(|v| v.parse().ok()).unwrap_or(300).max(3); + let expanded = args.iter().any(|a| a == "--expanded"); + let plain = args.iter().any(|a| a == "--plain"); + + let t = Instant::now(); + let session = build(groups, plain, expanded); + println!("built {groups} {} in {:.0} ms", if plain { "plain layers" } else { "groups" }, ms(t)); + + let mut h: H = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_pixels_per_point(1.0).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(session, Services::default()) + }); + // Warm up. The layer made last is the top one and is active, so the panel is scrolled to the + // top and most rows are off-screen. + for _ in 0..30 { + h.step(); + } + + // How many group rows are on screen (their disclosure widgets, which every group row registers). + let window = h.ctx.content_rect(); + let (on_screen, total) = if plain { + (0, 0) + } else { + let all: Vec<_> = h.query_all_by_label_contains("group Group ").map(|n| n.rect()).collect(); + (all.iter().filter(|r| window.intersects(**r)).count(), all.len()) + }; + if !plain { + println!("group rows on screen: {on_screen} of {total} listed (document has {groups})"); + } + + let mut rows = Rows { rows: Vec::new() }; + let times: Vec = (0..frames).map(|_| frame(&mut h)).collect(); + let what = if plain { "plain layers" } else { "groups" }; + rows.add(&format!("idle frame, {groups} {what} (panel at top)"), times); + + if let Some(out) = arg(&args, "--json") { + let r: Vec = rows.rows.iter().map(|(n, med, p90, max)| json!({"name": n, "median_ms": med, "p90_ms": p90, "max_ms": max})).collect(); + let report = json!({ + "groups": groups, + "frames": frames, + "expanded": expanded, + "plain": plain, + "group_rows_on_screen": on_screen, + "group_rows_listed": total, + "rows": r, + }); + std::fs::write(&out, serde_json::to_string_pretty(&report).expect("json")).expect("write json"); + } +} diff --git a/crates/ui-egui/examples/perf_scenarios.rs b/crates/ui-egui/examples/perf_scenarios.rs index 1f25292897..33dfb0eda3 100644 --- a/crates/ui-egui/examples/perf_scenarios.rs +++ b/crates/ui-egui/examples/perf_scenarios.rs @@ -1178,7 +1178,7 @@ fn background_job_scenarios(b: &mut Bench, sz: &Sizes) { } let brushes = "import 500 brushes: longest UI-thread step"; if b.wanted(brushes) { - use photocraft_psd::abr::{AbrSample, LegacyBrush, LegacyTip, write_v12}; + use craft_psd::abr::{AbrSample, LegacyBrush, LegacyTip, write_v12}; let list: Vec = (0..500) .map(|i| { let side = 40 + (i % 60) as u32; diff --git a/crates/ui-egui/src/alt_click_tests.rs b/crates/ui-egui/src/alt_click_tests.rs index 0c3ceda8e8..383f36f7d5 100644 --- a/crates/ui-egui/src/alt_click_tests.rs +++ b/crates/ui-egui/src/alt_click_tests.rs @@ -208,6 +208,34 @@ fn alt_click_sets_the_clone_source_and_a_drag_paints_it() { assert!(px[1] > 0.9 && px[0] < 0.1, "green cloned over red: {px:?}"); } +/// ⌥-click in one open document, then paint in another: the stroke clones from the first, as in +/// Photoshop, rather than from the same point of the document being painted. +#[test] +fn alt_click_in_one_document_clones_into_another() { + let mut app = two_colours(); + app.run("file.new", json!({"width": 200, "height": 100, "background": "white"})).unwrap(); + app.run("document.activate", json!({"document": 0})).unwrap(); + app.sync_views(); + let mut h = harness(app); + h.state_mut().ui.tool = Tool::CloneStamp; + h.state_mut().run("tools.setBrush", json!({"brush": {"size": 10, "hardness": 1.0}})).unwrap(); + let rev = h.state().session.active().unwrap().revision; + click(&mut h, 150.0, 50.0, Modifiers::ALT); + assert_eq!(h.state().session.active().unwrap().revision, rev, "⌥-click only sets the source"); + h.state_mut().run("document.activate", json!({"document": 1})).unwrap(); + h.state_mut().sync_views(); + let view = h.state().ui.views[0].clone(); + h.state_mut().ui.views[1] = view; + h.run_steps(2); + let source = h.state().session.documents()[0].doc.clone(); + drag(&mut h, [30.0, 50.0], [70.0, 50.0], Modifiers::NONE); + let app = h.state(); + assert_eq!(app.session.active_index(), Some(1)); + let px = app.session.active().unwrap().doc.layers[0].surface().unwrap().rgba(50, 50); + assert!(px[1] > 0.9 && px[0] < 0.1 && px[2] < 0.1, "green cloned from the other document over white: {px:?}"); + assert_eq!(*app.session.documents()[0].doc, *source, "the source document is only read"); +} + #[test] fn clone_stamp_paints_an_empty_layer_from_the_layers_below() { // The reported setup: a new empty layer on top, Sample: All Layers (or Current & Below). diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 06be98eed8..428aa6a1dc 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -90,6 +90,7 @@ impl PhotocraftApp { caps_lock: false, opacity_keys: None, control_rx: None, + agent_link: crate::AgentLinkStatus::default(), captures: crate::screenshot::Captures::default(), type_ime: type_tool::ImeState::default(), input_waiters: Vec::new(), @@ -153,6 +154,7 @@ impl PhotocraftApp { color_picker_preview: None, guide_drag: None, layer_box: None, + finished_pens: Vec::new(), crop: Default::default(), pcrop: Default::default(), hover_doc: None, @@ -192,6 +194,7 @@ impl PhotocraftApp { doc_hist_preview: None, hist_job: None, hist_uncached: None, + hist_sel_key: None, gpu: None, window_device: None, window_lost: false, diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index a78e2d3ea7..ccc49156fd 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -90,7 +90,10 @@ impl PhotocraftApp { return Ok(Vec::new()); } let import = self.services.import.as_ref().ok_or("no importer configured")?; - let opts = photocraft_engine::jobs::import_options(self.session.prefs()); + let opts = photocraft_io::ImportOptions { + keep_raw: self.session.prefs().raw_defaults.open_in_camera_raw, + ..photocraft_engine::jobs::import_options(self.session.prefs()) + }; // A PSD and a magic-detected TIFF both go through the typed IO path: only it carries // `PsdApprovalRequired` (and, for a PSD, the structured damaged flag), so a layered // TIFF's high-memory decision can raise its prompt instead of becoming a terminal diff --git a/crates/ui-egui/src/background_eraser_alt_click_tests.rs b/crates/ui-egui/src/background_eraser_alt_click_tests.rs index aa7adbcc0c..6cba450a77 100644 --- a/crates/ui-egui/src/background_eraser_alt_click_tests.rs +++ b/crates/ui-egui/src/background_eraser_alt_click_tests.rs @@ -161,21 +161,35 @@ fn a_click_without_alt_still_erases() { /// While ⌥ is held the cursor is the Eyedropper's pipette (`pipette_cursor`), where the /// Background Eraser otherwise shows its own tip; Control+⌥ keeps the tip. #[test] +#[cfg(not(target_arch = "wasm32"))] fn alt_shows_the_eyedropper_cursor() { let mut h = background_eraser(); + h.state_mut().run("tools.setBrush", json!({"brush": {"size": 40, "hardness": 1.0}})).unwrap(); + h.state_mut().run("prefs.set", json!({"path": "cursors.painting", "value": "fullSizeTip"})).unwrap(); let p = screen(&h, 150.0, 50.0); - let pipette = |h: &mut Harness<'static, PhotocraftApp>, m: Modifiers| { + let cursor = |h: &mut Harness<'static, PhotocraftApp>, m: Modifiers| { mods(h, m); h.hover_at(p); h.run_steps(2); - let layer = egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("pc-icon-cursor")); - let shown = h.ctx.memory(|memory| memory.areas().visible_layer_ids().contains(&layer)); - (shown, h.output().platform_output.cursor_icon) + let output = &h.output().platform_output; + (output.cursor_icon, output.cursor_image.clone()) }; - assert_eq!(pipette(&mut h, Modifiers::ALT), (true, egui::CursorIcon::None), "⌥: the pipette replaces the pointer"); - assert!(!pipette(&mut h, Modifiers::NONE).0, "without ⌥: the eraser's own tip"); - assert!(!pipette(&mut h, Modifiers::ALT | Modifiers::CTRL).0, "Control+⌥ is not the Eyedropper"); - assert!(pipette(&mut h, Modifiers::ALT).0, "⌥ again: the pipette again"); + let pipette = cursor(&mut h, Modifiers::ALT); + assert_eq!(pipette.0, egui::CursorIcon::Crosshair, "the native pipette has a visible OS fallback"); + assert!(pipette.1.is_some(), "⌥ uses an OS pipette bitmap"); + for modifiers in [Modifiers::NONE, Modifiers::ALT | Modifiers::CTRL] { + let tip = cursor(&mut h, modifiers); + assert_ne!(tip, pipette); + assert_eq!(tip.0, egui::CursorIcon::Crosshair, "eraser tip has a visible OS fallback"); + let image = tip.1.expect("the eraser's circular tip remains visible"); + let [x, y] = image.hotspot; + let alpha = |x, y| image.rgba[(usize::from(y) * usize::from(image.size[0]) + usize::from(x)) * 4 + 3]; + assert!(alpha(x, y) > 230, "Background Eraser retains the centre cross"); + for (dx, dy) in [(20, 0), (-20, 0), (0, 20), (0, -20)] { + assert!(alpha((i32::from(x) + dx) as u16, (i32::from(y) + dy) as u16) > 230, "40 px circular eraser tip at {modifiers:?}"); + } + } + assert_eq!(cursor(&mut h, Modifiers::ALT), pipette, "⌥ again: the same pipette bitmap"); } /// Control+⌥-drag stays the brush-resize gesture: it samples nothing and erases nothing. diff --git a/crates/ui-egui/src/brush_hud_rate_tests.rs b/crates/ui-egui/src/brush_hud_rate_tests.rs new file mode 100644 index 0000000000..2008891185 --- /dev/null +++ b/crates/ui-egui/src/brush_hud_rate_tests.rs @@ -0,0 +1,76 @@ +//! #11891: the Alt+right-drag brush HUD changes hardness at Photoshop's rate (50 screen points +//! down from 0 % give 13 %), and its readout has three lines: "Diameter :", "Hardness :" and +//! "Opacity :". The horizontal size change is unchanged. + +use egui::{Modifiers, PointerButton, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::brush_resize::{readout_label, resized}; +use crate::state::Tool; + +#[test] +fn fifty_points_down_from_zero_give_thirteen_percent() { + for zoom in [0.5, 1.0, 2.0] { + // The drag is in document pixels; 50 screen points is 50 / zoom of them. + let (_, hardness) = resized((13.0, 0.0), 0.0, f64::from(50.0 / zoom), zoom); + assert!((hardness - 0.13).abs() <= 0.02, "zoom {zoom}: {hardness}"); + } + assert_eq!(resized((13.0, 0.0), 0.0, -50.0, 1.0).1, 0.0, "up from 0 % stays 0 %"); +} + +#[test] +fn the_size_change_is_unchanged() { + assert_eq!(resized((13.0, 0.0), 50.0, 0.0, 1.0).0, 113.0); + assert_eq!(resized((13.0, 0.0), -278.0, 0.0, 1.0).0, 1.0); +} + +#[test] +fn labels_get_a_space_before_the_colon() { + assert_eq!(readout_label("Diameter:"), "Diameter :"); + assert_eq!(readout_label("Diamètre :"), "Diamètre :", "a translation's own spacing stays"); + assert_eq!(readout_label("Size"), "Size"); +} + +#[test] +fn the_readout_shows_diameter_hardness_and_opacity() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 13, "hardness": 0.0, "opacity": 1.0}})).unwrap(); + app.ui.tool = Tool::Brush; + app.sync_views(); + let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let c = h.state().last_canvas_rect.center(); + let alt = Modifiers::ALT; + h.event(egui::Event::ModifiersChanged(alt)); + h.event(egui::Event::PointerMoved(c)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: c, button: PointerButton::Secondary, pressed: true, modifiers: alt }); + h.run_steps(1); + for i in 1..=5 { + h.event(egui::Event::PointerMoved(c + vec2(0.0, 10.0 * i as f32))); + h.run_steps(1); + } + let hardness = h.state().session.tools.brush.hardness; + assert!((hardness - 0.13).abs() <= 0.02, "{hardness}"); + for label in ["Diameter :", "Hardness :", "Opacity :"] { + assert!(h.query_by_label(label).is_some(), "{label}"); + } + assert!(h.query_by_label("13%").is_some() && h.query_by_label("100%").is_some()); + h.event(egui::Event::PointerButton { pos: c + vec2(0.0, 50.0), button: PointerButton::Secondary, pressed: false, modifiers: alt }); + h.run_steps(2); +} diff --git a/crates/ui-egui/src/brush_mode_menu.rs b/crates/ui-egui/src/brush_mode_menu.rs index 6cb7957508..528928e8c3 100644 --- a/crates/ui-egui/src/brush_mode_menu.rs +++ b/crates/ui-egui/src/brush_mode_menu.rs @@ -189,15 +189,19 @@ pub(crate) fn is_gesture(tool: Tool, mods: egui::Modifiers) -> bool { mods.shift && !mods.alt && !mods.ctrl && !mods.command && !mods.mac_cmd && !items(tool).is_empty() } -/// Does a right-click with `mods` open the menu? The Shift gesture for every tool that has one, -/// and a plain right-click with the Eraser in Block mode, where the Brush Preset picker's Size and -/// Hardness mean nothing (#11937, as in the reference application). -/// A plain right-click opens it only where it would otherwise open the picker: with the Erase -/// preference it still erases. -pub(crate) fn opens_on(app: &PhotocraftApp, tool: Tool, mods: egui::Modifiers) -> bool { +/// Does a right-click with `mods` at document point `doc` open the menu? The Shift gesture for +/// every tool that has one, and a plain right-click with the Eraser in Block mode, where the Brush +/// Preset picker's Size and Hardness mean nothing (#11937), or with the Paint Bucket (#12530), as +/// in the reference application. +/// A plain right-click opens it only where it would otherwise open the picker or nothing: with the +/// Erase preference it still erases, and on the pasteboard its colour menu opens. +pub(crate) fn opens_on(app: &PhotocraftApp, tool: Tool, mods: egui::Modifiers, doc: Option<[f64; 2]>) -> bool { let plain = !mods.shift && !mods.alt && !mods.ctrl && !mods.command && !mods.mac_cmd; let block = tool == Tool::Eraser && app.ui.tool_options.eraser_mode == "block"; - is_gesture(tool, mods) || (plain && block && !crate::paint_mouse::right_erases(app, tool)) + let pasteboard = doc.is_some_and(|d| crate::canvas_tool_menu::pasteboard_at(app, tool, d)); + // An open Free Transform box owns the plain right-click: its transform menu opens instead. + let bucket = tool == Tool::PaintBucket && app.ui.transform.is_none(); + is_gesture(tool, mods) || (plain && (block || bucket) && !crate::paint_mouse::right_erases(app, tool) && !pasteboard) } /// The modifiers that decide a right-button gesture: the ones held when the button went down. @@ -228,11 +232,25 @@ pub(crate) fn menu_id() -> Id { Id::unique("canvas-brush-mode-menu") } -/// Opens the active tool's menu at screen point `pos`. -pub(crate) fn open(app: &mut PhotocraftApp, ctx: &Context, pos: [f32; 2]) { +/// Temp data: was the open menu opened by a plain right-click (not the Shift gesture)? +fn plain_id() -> Id { + menu_id().with("plain") +} + +/// The row drawn checked. The Paint Bucket's plain right-click menu checks none, as in the +/// reference application; its Shift+right-click menu checks the current mode. +pub(crate) fn checked(app: &PhotocraftApp, ctx: &Context, tool: Tool) -> Option { + let plain = ctx.data(|d| d.get_temp::(plain_id())).unwrap_or(false); + if plain && tool == Tool::PaintBucket { None } else { current(app, tool) } +} + +/// Opens the active tool's menu at screen point `pos`, for a right-click with `mods`. +pub(crate) fn open(app: &mut PhotocraftApp, ctx: &Context, pos: [f32; 2], mods: egui::Modifiers) { if !pos.iter().all(|v| v.is_finite()) || items(app.ui.tool).is_empty() { return; } + let plain = !is_gesture(app.ui.tool, mods); + ctx.data_mut(|d| d.insert_temp(plain_id(), plain)); // The checked row reads the tool's own brush. crate::paint_mouse::sync_tool_brush(app); app.ui.brush_picker = None; @@ -378,7 +396,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &Context) { crate::paint_mouse::sync_tool_brush(app); let tool = app.ui.tool; let rows: Vec<(Item, bool)> = items(tool).into_iter().map(|i| (i, enabled(app, i))).collect(); - let current = current(app, tool); + let current = checked(app, ctx, tool); let screen = crate::work_area::visible_rect(ctx); let id = menu_id(); let margin = ctx.global_style().spacing.menu_margin.sum() + egui::Vec2::splat(2.0); @@ -424,3 +442,7 @@ mod eraser_block_right_click_tests; #[cfg(test)] #[path = "pattern_stamp_behind_tests.rs"] mod pattern_stamp_behind_tests; + +#[cfg(test)] +#[path = "paint_bucket_right_click_menu_tests.rs"] +mod paint_bucket_right_click_menu_tests; diff --git a/crates/ui-egui/src/brush_refusal_alert_tests.rs b/crates/ui-egui/src/brush_refusal_alert_tests.rs index b24872ca6e..8acfae65e9 100644 --- a/crates/ui-egui/src/brush_refusal_alert_tests.rs +++ b/crates/ui-egui/src/brush_refusal_alert_tests.rs @@ -9,7 +9,7 @@ use super::*; use crate::canvas::{ToolEvent, tool_event}; /// A 64 × 64 document with a painted layer active, black foreground, `tool`. -pub(super) fn app(tool: Tool) -> PhotocraftApp { +pub(in crate::tools) fn app(tool: Tool) -> PhotocraftApp { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); app.run("layer.new.layer", json!({})).unwrap(); @@ -24,22 +24,22 @@ pub(super) fn active(app: &PhotocraftApp) -> u64 { app.session.active().unwrap().active_layer.unwrap().0 } -pub(super) fn steps(app: &PhotocraftApp) -> usize { +pub(in crate::tools) fn steps(app: &PhotocraftApp) -> usize { app.session.active().unwrap().history.past_len() } /// A press, a short drag and the release with the active tool. -pub(super) fn stroke(app: &mut PhotocraftApp) { +pub(in crate::tools) fn stroke(app: &mut PhotocraftApp) { tool_event(app, ToolEvent::Down { x: 20.0, y: 32.0, pressure: 1.0 }, Modifiers::NONE); tool_event(app, ToolEvent::Move { x: 44.0, y: 32.0, pressure: 1.0 }, Modifiers::NONE); tool_event(app, ToolEvent::Up { x: 44.0, y: 32.0 }, Modifiers::NONE); } -pub(super) fn alerts(app: &PhotocraftApp) -> Vec { +pub(in crate::tools) fn alerts(app: &PhotocraftApp) -> Vec { app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message").and_then(Value::as_str).map(str::to_string)).collect() } -pub(super) fn refused(app: &mut PhotocraftApp, want: &str) { +pub(in crate::tools) fn refused(app: &mut PhotocraftApp, want: &str) { let before = steps(app); stroke(app); assert_eq!(alerts(app), [want], "the alert, once"); diff --git a/crates/ui-egui/src/bucket_bitmap_alert_tests.rs b/crates/ui-egui/src/bucket_bitmap_alert_tests.rs new file mode 100644 index 0000000000..e46c60bedb --- /dev/null +++ b/crates/ui-egui/src/bucket_bitmap_alert_tests.rs @@ -0,0 +1,50 @@ +//! #12536: a Paint Bucket click in a Bitmap document opens the reference application's alert with +//! OK and fills nothing; an RGB document still fills. + +use photocraft_engine::paint_cmds::BITMAP_REFUSAL as TEXT; +use serde_json::json; + +use super::brush_refusal_alert_tests::{alerts, app, refused, steps, stroke}; +use super::*; +use crate::control::{ControlRequest, Outcome, handle}; + +fn bitmap() -> PhotocraftApp { + let mut app = app(Tool::PaintBucket); + app.run("image.mode.grayscale", json!({})).unwrap(); + app.run("image.mode.bitmap", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.mode, photocraft_doc::ColorMode::Bitmap); + app +} + +#[test] +fn a_click_in_a_bitmap_document_opens_the_alert() { + let mut app = bitmap(); + refused(&mut app, TEXT); + assert!(!app.ui.status_error, "no status-bar error as well: {:?}", app.ui.status); +} + +#[test] +fn more_clicks_while_it_is_open_keep_one_alert() { + let mut app = bitmap(); + stroke(&mut app); + stroke(&mut app); + assert_eq!(alerts(&app), [TEXT]); +} + +#[test] +fn the_alert_is_listed_in_ui_inspect() { + let mut app = bitmap(); + stroke(&mut app); + let (req, _rx) = ControlRequest::new("ui.inspect", json!({})); + let Outcome::Done(inspect) = handle(&mut app, &egui::Context::default(), &req) else { panic!("ui.inspect: expected an immediate reply") }; + assert_eq!(inspect["result"]["dialogs"][0]["fields"]["message"], TEXT, "{inspect}"); +} + +#[test] +fn an_rgb_document_still_fills() { + let mut app = app(Tool::PaintBucket); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty()); + assert_eq!(steps(&app), before + 1, "the fill was applied"); +} diff --git a/crates/ui-egui/src/burn_bar_tooltips_tests.rs b/crates/ui-egui/src/burn_bar_tooltips_tests.rs index b000418ab3..3bc893fdb2 100644 --- a/crates/ui-egui/src/burn_bar_tooltips_tests.rs +++ b/crates/ui-egui/src/burn_bar_tooltips_tests.rs @@ -17,7 +17,7 @@ const CONTROLS: [(Role, &str, &str); 3] = [ ]; /// Build a settled options-bar fixture with the requested tool, locale, viewport and scale. -fn bar(tool: Tool, lang: Lang, width: f32, scale: f32, narrow: bool) -> Harness<'static, PhotocraftApp> { +pub(super) fn bar(tool: Tool, lang: Lang, width: f32, scale: f32, narrow: bool) -> Harness<'static, PhotocraftApp> { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); app.run("prefs.set", json!({"path": "workspace.enableNarrowOptionsBar", "value": narrow})).unwrap(); @@ -39,7 +39,7 @@ fn bar(tool: Tool, lang: Lang, width: f32, scale: f32, narrow: bool) -> Harness< } /// Find the named control by its accessibility role without matching tooltip labels. -fn control<'a>(h: &'a Harness<'static, PhotocraftApp>, role: Role, label: &str) -> egui_kittest::Node<'a> { +pub(super) fn control<'a>(h: &'a Harness<'static, PhotocraftApp>, role: Role, label: &str) -> egui_kittest::Node<'a> { h.query_all_by_role(role).find(|n| n.accesskit_node().label().as_deref() == Some(label)).unwrap_or_else(|| panic!("missing {role:?} {label:?}")) } @@ -54,7 +54,7 @@ fn control_name(h: &Harness<'static, PhotocraftApp>, lang: Lang, role: Role, lab } /// Scroll a control into view, wait for its hover delay and assert the visible tooltip text. -fn hover(h: &mut Harness<'static, PhotocraftApp>, role: Role, label: &str, tip: &str) { +pub(super) fn hover(h: &mut Harness<'static, PhotocraftApp>, role: Role, label: &str, tip: &str) { control(h, role, label).scroll_to_me(); h.run_steps(4); let rect = control(h, role, label).rect(); diff --git a/crates/ui-egui/src/burn_default_tip_tests.rs b/crates/ui-egui/src/burn_default_tip_tests.rs index a95b0b8b4f..b72a072b55 100644 --- a/crates/ui-egui/src/burn_default_tip_tests.rs +++ b/crates/ui-egui/src/burn_default_tip_tests.rs @@ -43,7 +43,6 @@ fn scramble(app: &mut PhotocraftApp) { } const BURN_TIP: [f64; 5] = [65.0, 0.0, 0.25, 0.0, 1.0]; -const DEFAULT_TIP: [f64; 5] = [20.0, 1.0, 0.1, 0.0, 1.0]; #[test] fn reset_tool_gives_the_burn_tool_a_65_px_soft_tip() { @@ -87,19 +86,3 @@ fn reset_all_tools_gives_it_the_tip_active_or_picked_later() { pick(&mut app, Tool::Burn); assert_eq!(tip(&mut app), BURN_TIP, "picked after the reset"); } - -/// The Dodge tool shares the Burn tool's tip (#12684); the Sponge keeps the default. -#[test] -fn the_sponge_tool_keeps_its_tip() { - let mut a = app(); - pick(&mut a, Tool::Sponge); - scramble(&mut a); - invoke(&mut a, "tool.reset", json!({})); - assert_eq!(tip(&mut a), DEFAULT_TIP); - // A first use still takes the current tip, as before. - let mut a = app(); - pick(&mut a, Tool::Pencil); - scramble(&mut a); - pick(&mut a, Tool::Sponge); - assert_eq!(tip(&mut a)[0], 57.0, "first use"); -} diff --git a/crates/ui-egui/src/cam_reset_tool_mode_tests.rs b/crates/ui-egui/src/cam_reset_tool_mode_tests.rs new file mode 100644 index 0000000000..2cca9c673f --- /dev/null +++ b/crates/ui-egui/src/cam_reset_tool_mode_tests.rs @@ -0,0 +1,55 @@ +//! Reset Tool on the Content-Aware Move tool keeps the Mode (#12183), as the reference app does; +//! Reset All Tools still resets it, and a tool preset still stores it. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::{Tool, ToolOptions}; + +fn app() -> PhotocraftApp { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.ui.tool = Tool::ContentAwareMove; + app +} + +/// Mode Extend, Structure 7, Color 5, Transform On Drop flipped. +fn customize(app: &mut PhotocraftApp) { + let o = &mut app.ui.tool_options; + o.cam_mode = "extend".into(); + o.cam_structure = 7.0; + o.cam_color = 5.0; + o.cam_transform_on_drop = !ToolOptions::default().cam_transform_on_drop; +} + +#[test] +fn reset_tool_keeps_the_mode_and_resets_the_rest() { + let mut app = app(); + customize(&mut app); + app.ui.selection_mode = 2; + crate::menus::invoke(&mut app, &egui::Context::default(), crate::tool_reset::RESET, json!({})).unwrap(); + let (o, d) = (&app.ui.tool_options, ToolOptions::default()); + assert_eq!(o.cam_mode, "extend"); + assert_eq!((o.cam_structure, o.cam_color), (4.0, 0.0)); + assert_eq!(o.cam_transform_on_drop, d.cam_transform_on_drop); + assert_eq!(app.ui.selection_mode, 0); +} + +#[test] +fn reset_all_tools_still_resets_the_mode_to_move() { + let mut app = app(); + customize(&mut app); + crate::menus::invoke(&mut app, &egui::Context::default(), crate::tool_reset::RESET_ALL, json!({"confirmed": true})).unwrap(); + let o = &app.ui.tool_options; + assert_eq!(o.cam_mode, "move"); + assert_eq!((o.cam_structure, o.cam_color), (4.0, 0.0)); +} + +#[test] +fn a_content_aware_move_preset_still_stores_the_mode() { + let keys = crate::tool_reset::option_keys(Tool::ContentAwareMove); + for k in ["cam_mode", "cam_structure", "cam_color", "cam_transform_on_drop"] { + assert!(keys.contains(&k), "{k}"); + } +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 1bf00dd871..240a64f994 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -882,7 +882,7 @@ fn handle_dialog_canvas_input(app: &mut PhotocraftApp, input: DialogCanvasInput< } let b = crate::dialogs::free_buttons(input.ctx, input.rect); let pointer = input.ctx.input(|i| i.pointer.latest_pos()); - crate::zoom_tool::drag(app, input.ctx, input.view, input.xf, &b, pointer); + crate::zoom_tool::drag(app, input.ctx, input.view, input.xf, &b, pointer, &zoom_out); if b.clicked && let Some(p) = pointer { @@ -1001,6 +1001,8 @@ struct CanvasToolInput<'a> { under_dialog: bool, menu_dismiss_press: bool, zoom_out: &'a dyn Fn(bool) -> bool, + /// The Animated Zoom direction for ⌥ held or not: `zoom_out` without the Zoom Out mode. + hold_zoom_out: &'a dyn Fn(bool) -> bool, display_zoom: f32, } @@ -1019,7 +1021,7 @@ fn handle_primary_canvas_input(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: // Tools follow the left button; the right one opens the Brush Preset picker or erases // (Preferences › Tools, `paint_mouse`). crate::paint_mouse::sync_tool_brush(app); - let mut buttons = crate::paint_mouse::canvas_buttons(app, response, tool); + let mut buttons = crate::paint_mouse::canvas_buttons(app, response, tool, xf); if input.menu_dismiss_press { // Navigation and drags read `buttons` directly (zoom holds and drags, Rotate View): // starve them. The release click stays armed, so the click handling below consumes @@ -1043,7 +1045,10 @@ fn handle_primary_canvas_input(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: let capture_press = tool.is_type() || matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::SingleRowMarquee | Tool::SingleColumnMarquee | Tool::ObjectSelection); let tool_press = egui::Id::unique(("tool-pointer-press-modifiers", idx)); + // Read from the raw events, so a dialog's modal layer doesn't block it: gated here, or a ⌘-press + // under a dialog would start a type transform (#12896). if capture_press + && !under_dialog && !input.menu_dismiss_press && let Some((p, press_mods)) = ui.input(|i| { i.events.iter().find_map(|e| match e { @@ -1203,7 +1208,7 @@ fn handle_canvas_tool_navigation( // it owns the press: no scrub, and its release is no click step. A menu-dismissal press // must not arm it: holding the dismissal click would zoom (CodeRabbit, #9841). if tool == Tool::Zoom && !transform_owns_pointer { - let out = zoom_out(ui.input(|i| i.modifiers.alt)); + let out = (input.hold_zoom_out)(ui.input(|i| i.modifiers.alt)); let on_canvas = !input.menu_dismiss_press && !input.under_dialog && !over_compass && response.is_pointer_button_down_on(); let hold = crate::zoom_hold::hold_id(idx, primary, ctx.viewport_id()); if crate::zoom_hold::update(ctx, view, xf, app.session.prefs().general.animated_zoom, out, ppp, on_canvas, hold) { @@ -1212,7 +1217,7 @@ fn handle_canvas_tool_navigation( } // Zoom tool drags: scrubby zoom or a zoom rectangle (zoom_tool.rs); clicks step below. // Like the Hand, the selected Zoom yields to an open Free Transform box (#4799). - if tool == Tool::Zoom && !transform_owns_pointer && crate::zoom_tool::drag(app, ctx, view, xf, buttons, response.interact_pointer_pos()) { + if tool == Tool::Zoom && !transform_owns_pointer && crate::zoom_tool::drag(app, ctx, view, xf, buttons, response.interact_pointer_pos(), zoom_out) { (buttons.started, buttons.dragged, buttons.stopped) = (false, false, false); } } @@ -1271,6 +1276,7 @@ fn handle_canvas_tool_stroke( if press_stroke || (strokes_live(tool) && (app.alt_sampling || app.mixer_sampling)) { buttons.started = false; } + let transform_press = transform_press_moves(app, ui, input, mods, buttons); if buttons.started && !input.menu_dismiss_press && let Some(p) = ui.input(|i| i.pointer.press_origin()).filter(|p| rect.contains(*p)).or(response.interact_pointer_pos()) @@ -1408,6 +1414,90 @@ fn handle_canvas_tool_stroke( if press_stroke && (app.drag.is_none() || !ui.input(|i| i.pointer.primary_down())) { app.press_stroke = false; } + if transform_press { + transform_press_release(app, ui, input, mods, buttons); + } +} + +/// Marks a Free Transform drag started on the press (`transform_press_moves`). +fn transform_press_id(ctx: &egui::Context) -> egui::Id { + egui::Id::unique(("free-transform-press", ctx.viewport_id())) +} + +/// An open Free Transform box follows the pointer from the press (#11103): the press goes to the +/// box at once and every move before egui recognises a drag (past its click distance) moves it, +/// so the box doesn't sit still and then jump to catch up. Warp keeps its own gesture. Returns +/// whether the current press started this way; the drag egui recognises later continues it. +fn transform_press_moves( + app: &mut PhotocraftApp, + ui: &egui::Ui, + input: &CanvasToolInput<'_>, + mods: egui::Modifiers, + buttons: &mut crate::paint_mouse::Buttons, +) -> bool { + let ctx = input.ctx; + let id = transform_press_id(ctx); + let view = Some(tool_input::ToolViewContext::new(input.xf, Some(ctx.viewport_id()))); + let open = input.transform_owns_pointer && app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none()); + if open + && !input.menu_dismiss_press + && !input.under_dialog + && input.response.is_pointer_button_down_on() + && ui.input(|i| i.pointer.primary_pressed()) + && let Some(p) = ui.input(|i| i.pointer.press_origin()).filter(|p| input.rect.contains(*p)) + { + let d = input.xf.to_doc(p); + let press_mods = ui.input(|i| pointer_button_modifiers(&i.events, PointerButton::Primary)).unwrap_or(mods); + tool_input::tool_event_with_view(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, press_mods, view); + ctx.data_mut(|m| m.insert_temp(id, true)); + } + let pressed = ctx.data(|m| m.get_temp::(id)).unwrap_or(false); + if !pressed { + return false; + } + // The press already went to the box: the recognised drag continues it, it doesn't start over. + buttons.started = false; + let moved = ui.input(|i| i.pointer.primary_down() && i.pointer.delta() != egui::Vec2::ZERO); + if moved + && !buttons.dragged + && !buttons.stopped + && let Some(p) = ui.input(|i| i.pointer.latest_pos()) + { + let d = input.xf.to_doc(p); + tool_input::tool_event_with_view(app, ToolEvent::Move { x: d[0], y: d[1], pressure: app.stylus.pressure() }, mods, view); + } + true +} + +/// Ends a Free Transform press that egui never recognised as a drag: its release is the gesture's +/// `Up` (a click outside the box still accepts or keeps it), not a second click-sized `Down`/`Up`. +fn transform_press_release( + app: &mut PhotocraftApp, + ui: &egui::Ui, + input: &CanvasToolInput<'_>, + mods: egui::Modifiers, + buttons: &mut crate::paint_mouse::Buttons, +) { + let ctx = input.ctx; + if !buttons.stopped && ui.input(|i| i.pointer.primary_released()) { + buttons.clicked = false; + if app.ui.transform.is_some() + && let Some(p) = input.response.interact_pointer_pos().or(ui.input(|i| i.pointer.latest_pos())) + { + let d = input.xf.to_doc(p); + tool_input::tool_event_with_view( + app, + ToolEvent::Up { x: d[0], y: d[1] }, + mods, + Some(tool_input::ToolViewContext::new(input.xf, Some(ctx.viewport_id()))), + ); + } + } + if app.ui.transform.is_none() || !ui.input(|i| i.pointer.primary_down()) { + // The id first: reading the viewport inside `data_mut` would wait on its own lock. + let id = transform_press_id(ctx); + ctx.data_mut(|m| m.remove::(id)); + } } /// Dispatches discrete pointer click and release events to active tools with view transform context. @@ -1807,6 +1897,12 @@ fn draw_canvas_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: &C let toward = xf.to_screen((d[0] + k[0] * 16.0) as f32, (d[1] + k[1] * 16.0) as f32) - p; crate::crop_ui::draw_turn_cursor(ctx, p, toward); } + } else if let Some(p) = response.hover_pos() + && let Some(zone) = + crate::perspective_crop_ui::cursor(app, xf.to_doc(p)).filter(|z| tool == Tool::PerspectiveCrop && *z != crate::perspective_crop_ui::Zone::Outside) + { + // What a press there does (#11974); outside the quad the tool's usual crosshair below. + ui.ctx().set_cursor_icon(crate::tool_cursor::perspective_crop(input.painter, zone, p)); } else if let Some(p) = response.hover_pos() && let Some(c) = selection_cursor(app, tool, xf.to_doc(p), crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers))) { @@ -1860,6 +1956,22 @@ fn pencil_outline_cursor(painter: &egui::Painter, xf: &ViewXform, p: Pos2, size: egui::CursorIcon::None } +/// A pen tool's cursor at screen point `p` (document point `doc`): the crosshair for precise Other +/// Cursors (#4639), the black arrow for Add Anchor Point unless a click would split a segment +/// (#12729; ⌘ is Direct Selection's arrow, ⌥ keeps the pen), else the tool's own pen icon. +fn pen_tool_cursor(app: &PhotocraftApp, ui: &egui::Ui, tool: Tool, doc: [f64; 2], p: Pos2) -> egui::CursorIcon { + if precise_other_cursor(app) { + return egui::CursorIcon::Crosshair; + } + if tool == Tool::AddAnchorPoint { + let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); + if !mods.alt && (mods.command || !crate::anchor_tools::adds_anchor_at(app, tool, doc)) { + return crate::tool_cursor::arrow(ui.ctx(), p); + } + } + pen_cursor(ui.ctx(), tool, p) +} + fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: &CanvasOverlayInput<'_>, resizing: bool, p: Pos2) { let painter = input.painter; let xf = input.xf; @@ -1892,15 +2004,10 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & && !app.services.right_button_down.as_ref().is_some_and(|f| f()) && alt_picks(t, crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)))) => { - // While it samples (button held), the comparison ring replaces the cursor (#213). - if let Some(icon) = eyedropper_ring(app, painter, xf, p, response.is_pointer_button_down_on()) { - icon - } else if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise { - egui::CursorIcon::Crosshair - } else { - pipette_cursor(ui.ctx(), p) - } + cursors::alt_pick_cursor(app, painter, xf, p, response.is_pointer_button_down_on(), t) } + // Over a layer it can't paint (Lock All), the Mixer Brush shows a no-entry sign (#11957). + Tool::MixerBrush if cursors::mixer_target_locked(app) => cursors::no_entry_cursor(painter, p), t if t.is_brushlike() || t == Tool::QuickSelection => { // Preferences › Cursors: brush tip outline (normal = the 50% contour, or // full size), precise crosshair, or the standard pointer. @@ -1926,6 +2033,9 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & let size = if block { crate::eraser_ui::block_size(app) } else { brush.size }; pencil_outline_cursor(painter, xf, p, size, block, cur.show_crosshair_in_brush_tip) } + // The Healing Brush's ⌥ (source point): the reference's fixed target at any tip + // size (#12113). Unmeasured cases keep the tip with its centre mark below. + PaintingCursor::NormalTip if tool == Tool::Healing && (alt || app.ui.shell.sticky_alt) => cursors::sample_target_cursor(painter, p), // A shaped tip (sampled bitmap, or a rotated/flattened round tip) // traces its outline, turned and flipped with the view; a plain round // tip keeps the circle. @@ -1957,12 +2067,15 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & } // The Color Sampler (#11744): // - Over a sampler: arrow with the sampler target, or with Alt the arrow with scissors. + // Dragging one keeps the arrow with the sampler target until release, though the stored + // point stays behind, and without scissors: Alt removes only on the press (#13063). // - Off a sampler: eyedropper with the sampler target at its top-left, or the crosshair // for precise Other Cursors. Tool::ColorSampler => { let [x, y] = xf.to_doc(p); - if crate::analysis_ui::sampler_at(app, [x, y]).is_some() { - sampler_hover_cursor(ui.ctx(), p, alt || app.ui.shell.sticky_alt) + let dragging = matches!(app.ui.analysis.drag, Some(crate::analysis_ui::Drag::Sampler(..))); + if dragging || crate::analysis_ui::sampler_at(app, [x, y]).is_some() { + sampler_hover_cursor(ui.ctx(), p, !dragging && (alt || app.ui.shell.sticky_alt)) } else if precise_other_cursor(app) { egui::CursorIcon::Crosshair } else { @@ -1995,14 +2108,16 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & { crate::tool_cursor::continue_path(painter, p) } + // Add Anchor Point: the pen with "+" only over a segment a click would split, else the + // black arrow (#12729); ⌘ is Direct Selection's arrow. ⌥ and Precise stay as they were. // The pen tools: their own icon with its nib on the point, or the crosshair for - // precise Other Cursors (#4639). + // precise Other Cursors (#4639); Add Anchor Point the black arrow off a segment (#12729). Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint => { - if precise_other_cursor(app) { egui::CursorIcon::Crosshair } else { pen_cursor(ui.ctx(), tool, p) } + pen_tool_cursor(app, ui, tool, xf.to_doc(p), p) } // Preferences › Cursors › Other Cursors: Precise shows a crosshair for every tool. Tool::Move if crate::move_mods::copying(app, alt) => egui::CursorIcon::Copy, - Tool::Move | Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask + Tool::Move | Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask | Tool::Ruler if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise => { egui::CursorIcon::Crosshair @@ -2032,6 +2147,11 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & } egui::CursorIcon::None } + // The Ruler tool: its own arrow with a ruler below right of the tip, and that arrow with a + // protractor over the end point an ⌥-drag takes for the protractor arm (#12037). ⌘ is not + // here: it makes the Ruler the temporary Move tool (`hold_keys::cmd_moves`), so this match + // runs with `Tool::Move` and shows its pointer, on the ruler and off it. + Tool::Ruler => crate::tool_cursor::ruler(app, painter, p, xf.to_doc(p), crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers))), _ => egui::CursorIcon::Crosshair, }; let icon = visible_crosshair(icon, painter, p, cfg!(not(target_arch = "wasm32"))); @@ -2117,6 +2237,13 @@ fn finish_canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut Vie if primary { app.perf.span("scrollbars", crate::gpu_canvas::now_ms() - t0); app.hover_doc = response.hover_pos().map(|p| xf.to_doc(p)); + // A focused document window can remain primary after another document becomes active. + if let Some(at) = app.hover_doc + && app.session.active().is_some_and(|st| st.doc.id == doc.id) + && crate::preset_panels::remember_clone_cursor(app, at) + { + ctx.request_repaint(); + } } if primary && app.ui.extras.rulers { let before = app.guide_drag; @@ -2386,10 +2513,20 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: app.tool_override = (temporary == Some(crate::hold_keys::Temporary::Move)).then_some(Tool::Move); // `~` held: a Brush or Pencil stroke that starts now erases (`tool_event`'s `Down`). app.held_erase = crate::hold_keys::erase_held(app, &ctx); - // Zoom direction: the temporary zoom key decides, else ⌥ (Zoom tool), held or latched in - // Window › Modifier Keys (the way around a desktop that takes Alt+click, `alt_grab`). + // Zoom direction: the temporary zoom key decides, else the Zoom tool's Zoom In / Zoom Out + // mode, turned around by ⌥ held or latched in Window › Modifier Keys (the way around a + // desktop that takes Alt+click, `alt_grab`). A held Z is a temporary zoom key too: in, out + // with ⌥, whatever the mode (#12066). let sticky_alt = app.ui.shell.sticky_alt; + let out_mode = !app.ui.tool_options.zoom_in && !crate::spring_tools::holds(app, Tool::Zoom); let zoom_out = |alt: bool| match temporary { + Some(crate::hold_keys::Temporary::ZoomOut) => true, + Some(crate::hold_keys::Temporary::ZoomIn) => false, + _ => (alt || sticky_alt) != out_mode, + }; + // Animated Zoom (press and hold) keeps its direction in either mode: in, out with ⌥. Zoom + // Out mode was not measured for it (#12066). + let hold_zoom_out = |alt: bool| match temporary { Some(crate::hold_keys::Temporary::ZoomOut) => true, Some(crate::hold_keys::Temporary::ZoomIn) => false, _ => alt || sticky_alt, @@ -2508,6 +2645,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: under_dialog, menu_dismiss_press, zoom_out: &zoom_out, + hold_zoom_out: &hold_zoom_out, display_zoom: display_view.zoom, }; handle_primary_canvas_input(app, ui, &mut view, &input); @@ -2621,6 +2759,9 @@ mod pattern_drag_tests; #[cfg(test)] mod tabs_tests; +#[cfg(test)] +mod doc_window_dialog_tests; + #[cfg(test)] mod tests; @@ -3097,6 +3238,9 @@ mod cpu_background_tests; #[path = "canvas/blend_viewport_tests.rs"] mod blend_viewport_regression; +#[cfg(test)] +#[path = "canvas/perspective_crop_cursor_tests.rs"] +mod perspective_crop_cursor_tests; #[cfg(test)] #[path = "canvas/pixel_alignment_tests.rs"] mod pixel_alignment_tests; diff --git a/crates/ui-egui/src/canvas/art_history_shift_click_tests.rs b/crates/ui-egui/src/canvas/art_history_shift_click_tests.rs index 011e4a4cd2..22caf24343 100644 --- a/crates/ui-egui/src/canvas/art_history_shift_click_tests.rs +++ b/crates/ui-egui/src/canvas/art_history_shift_click_tests.rs @@ -105,7 +105,9 @@ fn shift_click_still_connects_brush_pencil_history_brush_and_other_painting_tool tool_event(&mut app, ToolEvent::Up { x: 20.0, y: 40.0 }, none); tool_event(&mut app, ToolEvent::Down { x: 120.0, y: 40.0, pressure: 1.0 }, shift); tool_event(&mut app, ToolEvent::Up { x: 120.0, y: 40.0 }, shift); - assert_eq!(last_points(&app, cmd), vec![[20.0, 40.0], [120.0, 40.0]], "{tool:?}"); + // The Pencil's 1 px tip paints whole pixels, so its points sit on pixel centres (#12200). + let want = if tool == Tool::Pencil { vec![[20.5, 40.5], [120.5, 40.5]] } else { vec![[20.0, 40.0], [120.0, 40.0]] }; + assert_eq!(last_points(&app, cmd), want, "{tool:?}"); assert!(red(&app, 70, 40) > 0.9, "{tool:?} painted the connecting line midpoint"); } } diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index 8917596e4b..b7a9a99cdb 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -8,7 +8,9 @@ use photocraft_engine::prefs::{self, CanvasColor}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use crate::direct_select::PathRef; use crate::{PhotocraftApp, state::Tool}; +use photocraft_vector::edit::Hit; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CanvasToolMenu { @@ -70,6 +72,12 @@ pub struct CanvasToolMenu { /// Opened with the Content-Aware Move tool inside the active selection (#12194). #[serde(default)] pub inside_selection: bool, + /// Opened with the Delete Anchor Point or Convert Point tool over an anchor or a segment of the + /// targeted path (#12771, #12744): the engine command that entry runs and its params. It heads + /// the path menu, above a separator. The third part is the document id and revision it was read + /// from: the knot index means something only there, so the entry expires once either moves on. + #[serde(default)] + pub point: Option<(String, Value, (u64, u64))>, } /// A misspelled word in the type layer being edited (`edit.checkSpelling`'s `list` entry). @@ -382,6 +390,7 @@ pub fn open_crop(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; sampler_at: None, color: None, inside_selection: false, + point: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -458,24 +467,38 @@ pub const HAND_MENU: &[Row] = &[ /// the view itself. pub const FILL_SCREEN: &str = "view.fillScreen"; +/// A selection menu: the rows every selection menu shares, with `$fills` (the rows between +/// Transform Selection and Last Filter) in its own order. +macro_rules! selection_menu { + ($($fills:expr),* $(,)?) => { + &[ + Some(("Deselect", "select.deselect")), + Some(("Select Inverse", "select.inverse")), + Some(("Feather…", "select.modify.feather")), + Some(("Select and Mask…", "select.selectAndMask")), + None, + Some(("Save Selection…", "select.saveSelection")), + Some(("Make Work Path…", "select.toWorkPath")), + None, + Some(("Layer Via Copy", "layer.new.layerViaCopy")), + Some(("Layer Via Cut", "layer.new.layerViaCut")), + Some(("New Layer…", "layer.new.layer")), + None, + Some(("Free Transform", "edit.freeTransform")), + Some(("Transform Selection", "select.transformSelection")), + $($fills,)* + None, + Some(("Last Filter", "filter.lastFilter")), + None, + Some(("Fade…", "edit.fade")), + ] + }; +} + /// Photoshop's selection-tool context menu with an active selection, in its order. Its Generative /// Fill row has no PhotoCraft command and is left out. Rows stay visible and grey out exactly like /// their menu-bar twins. -pub const SELECTION_MENU: &[Row] = &[ - Some(("Deselect", "select.deselect")), - Some(("Select Inverse", "select.inverse")), - Some(("Feather…", "select.modify.feather")), - Some(("Select and Mask…", "select.selectAndMask")), - None, - Some(("Save Selection…", "select.saveSelection")), - Some(("Make Work Path…", "select.toWorkPath")), - None, - Some(("Layer Via Copy", "layer.new.layerViaCopy")), - Some(("Layer Via Cut", "layer.new.layerViaCut")), - Some(("New Layer…", "layer.new.layer")), - None, - Some(("Free Transform", "edit.freeTransform")), - Some(("Transform Selection", "select.transformSelection")), +pub const SELECTION_MENU: &[Row] = selection_menu![ Some(("Distort", "edit.transform.distort")), Some(("Perspective", "edit.transform.perspective")), None, @@ -483,10 +506,6 @@ pub const SELECTION_MENU: &[Row] = &[ Some(("Fill…", "edit.fill")), Some(("Stroke…", "edit.stroke")), Some(("Content-Aware Fill…", "edit.contentAwareFill")), - None, - Some(("Last Filter", "filter.lastFilter")), - None, - Some(("Fade…", "edit.fade")), ]; /// The selection tools' context menu with nothing selected: making a selection. @@ -498,9 +517,44 @@ pub const NO_SELECTION_MENU: &[Row] = &[ Some(("Load Selection…", "select.loadSelection")), ]; +/// Photoshop's generic layer menu, in its order for a pixel layer without a selection: the Count +/// tool's canvas menu on a marker or off one (#11772), and the Red Eye and Object Selection +/// (#12866) tools' without a selection. Each row is enabled as the Layers panel menu enables it +/// for the active layer (`menus::is_enabled`) and runs like the menu item. +pub const COUNT_MENU: &[Row] = &[ + Some(("Blending Options…", "layer.layerStyle.blendingOptions")), + None, + Some(("Duplicate Layer…", "layer.duplicate")), + Some(("Delete Layer", "layer.delete")), + Some(("Group from Layers…", "layer.new.groupFromLayers")), + None, + Some(("Convert to Smart Object", "layer.smartObjects.convertToSmartObject")), + Some(("Convert to Layers", "layer.smartObjects.convertToLayers")), + None, + Some(("Rasterize Layer", "layer.rasterize.layer")), + Some(("Rasterize Layer Style", "layer.rasterize.layerStyle")), + None, + Some(("Free Transform", "edit.freeTransform")), + None, + Some(("Color Range…", "select.colorRange")), + Some(("Load Selection…", "select.loadSelection")), + Some(("Reselect", "select.reselect")), +]; + /// Right-click with the Content-Aware Move tool inside an active selection (#12194). pub const CAM_INSIDE_SELECTION_MENU: &[Row] = &[Some(("Color Range…", "select.colorRange")), Some(("Load Selection…", "select.loadSelection"))]; +/// The selection menu as measured in the reference application with the Red Eye tool (#12577) and +/// the Object Selection tool (#12866): no Distort or Perspective, and Delete and Fill Selection +/// after the fills. +pub const MEASURED_SELECTION_MENU: &[Row] = selection_menu![ + None, + Some(("Fill…", "edit.fill")), + Some(("Stroke…", "edit.stroke")), + Some(("Content-Aware Fill…", "edit.contentAwareFill")), + Some(("Delete and Fill Selection", "edit.deleteAndFillSelection")), +]; + /// The Eyedropper's copy rows (#11747). pub const EYEDROPPER_COPY_HTML: &str = "canvasMenu.eyedropper.copyHtml"; pub const EYEDROPPER_COPY_HEX: &str = "canvasMenu.eyedropper.copyHex"; @@ -651,8 +705,31 @@ fn cam_allowed(app: &PhotocraftApp) -> bool { app.session.active().is_some_and(|s| !matches!(s.doc.mode, ColorMode::Bitmap | ColorMode::Duotone | ColorMode::Multichannel)) } +/// Is document point `d` on the image and inside the active selection? +fn selected_at(app: &PhotocraftApp, d: [f64; 2]) -> bool { + d.iter().all(|v| v.is_finite()) + && d[0] >= 0.0 + && d[1] >= 0.0 + && app.session.active().is_some_and(|s| { + d[0] < f64::from(s.doc.size.width) + && d[1] < f64::from(s.doc.size.height) + && s.doc.selection.as_ref().is_some_and(|sel| sel.sample_channel(d[0].floor() as i32, d[1].floor() as i32, 0) >= 0.5) + }) +} + +/// Does a Red Eye right-click at `doc` open a menu (#12577)? Only where the reference application +/// was measured: an RGB document whose one layer is a pixel layer, with no selection or the pointer +/// inside it. Elsewhere it keeps opening nothing. +fn red_eye_measured(app: &PhotocraftApp, doc: Option<[f64; 2]>) -> bool { + app.session.active().is_some_and(|s| { + s.doc.mode == ColorMode::Rgb + && matches!(s.doc.layers.as_slice(), [l] if matches!(l.content, LayerContent::Raster(_)) && l.frame.is_none()) + && (s.doc.selection.is_none() || doc.is_some_and(|d| selected_at(app, d))) + }) +} + /// Tools whose plain canvas right-click opens a menu: the selection tools' actions, the -/// Content-Aware Move menu, the path menu and the Color Sampler's. +/// Content-Aware Move menu, the path menu, the Color Sampler's and the Red Eye tool's. pub fn applies(tool: Tool) -> bool { matches!( tool, @@ -669,9 +746,13 @@ pub fn applies(tool: Tool) -> bool { // selection menu, as in Photoshop (#7268). | Tool::QuickSelection | Tool::ColorSampler + // The layer menu (#11772). + | Tool::Count // Sample Size and Copy Color (#11747). | Tool::Eyedropper | Tool::ContentAwareMove + // The layer or selection menu, where measured (#12577). + | Tool::RedEye ) || path_menu(tool) } @@ -689,7 +770,54 @@ pub fn magnetic_drawing(app: &PhotocraftApp) -> bool { /// Selection and Direct Selection tools, whose Photoshop menu offers the same whole-path actions /// for the selected path (#1056). pub fn path_menu(tool: Tool) -> bool { - matches!(tool, Tool::Pen | Tool::PathSelection | Tool::DirectSelection) + matches!(tool, Tool::Pen | Tool::PathSelection | Tool::DirectSelection) || point_menu(tool) +} + +/// The anchor tools whose path menu also heads with the entry for the point under the right-click +/// (#12771, #12744). Add Anchor Point (#12710) joins here. +fn point_menu(tool: Tool) -> bool { + matches!(tool, Tool::DeleteAnchorPoint | Tool::ConvertPoint) +} + +/// The anchor or segment of the targeted path under document point `doc`, as the anchor tools hit +/// it (`direct_select::hit_active`): Delete Anchor Point on an anchor, Add Anchor Point on a +/// segment, at the clicked point. `None` on empty canvas, a handle, or the Pen draft, which the +/// engine doesn't edit. +fn point_at(app: &PhotocraftApp, doc: [f64; 2]) -> Option<(String, Value, (u64, u64))> { + let (target, _, hit) = crate::direct_select::hit_active(app, doc)?; + let (command, mut params) = match hit { + Hit::Anchor([subpath, knot]) => (POINT_DELETE, json!({"subpath": subpath, "knot": knot})), + Hit::Segment([subpath, knot], t) => (POINT_ADD, json!({"subpath": subpath, "knot": knot, "t": t})), + Hit::Handle(..) => return None, + }; + if target == PathRef::Pen || crate::anchor_tools::ignores(app, &target) { + return None; + } + if let (Some(o), Some(t)) = (params.as_object_mut(), target.params(app).as_object()) { + o.extend(t.clone()); + } + let stamp = app.session.active().map(|st| (st.doc.id.0, st.revision))?; + Some((command.to_string(), params, stamp)) +} + +const POINT_DELETE: &str = "path.deleteAnchor"; +const POINT_ADD: &str = "path.addAnchor"; + +/// The label of a menu's top point entry, spelled out so `cargo xtask i18n-coverage` lists it. +fn point_label(command: &str) -> String { + if command == POINT_DELETE { tl!("Delete Anchor Point").to_string() } else { tl!("Add Anchor Point").to_string() } +} + +/// Is `command` the open menu's top point entry? +fn is_point(menu: &CanvasToolMenu, command: &str) -> bool { + menu.point.as_ref().is_some_and(|(c, ..)| c == command) +} + +/// Is the open menu's point entry still about the path as it is? The document and its revision are +/// the ones the entry was read from; an edit meanwhile (say a control-channel `path.addAnchor`) +/// shifts the knot indexes, so a stale entry runs nothing. +fn point_current(app: &PhotocraftApp, menu: &CanvasToolMenu) -> bool { + menu.point.as_ref().is_some_and(|(.., stamp)| app.session.active().map(|st| (st.doc.id.0, st.revision)) == Some(*stamp)) } /// Tools whose plain canvas right-click offers the view menu. @@ -723,6 +851,10 @@ pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { PEN_MENU } else if sampler_menu(menu) { SAMPLER_MENU + } else if menu.tool == Tool::Count { + COUNT_MENU + } else if matches!(menu.tool, Tool::RedEye | Tool::ObjectSelection) { + if menu.has_selection { MEASURED_SELECTION_MENU } else { COUNT_MENU } } else if menu.tool == Tool::Eyedropper { EYEDROPPER_MENU } else if inside_selection(menu) { @@ -734,7 +866,9 @@ pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { /// Is `command` one of the open menu's rows, and enabled? pub fn available(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str) -> bool { - (rows(menu).iter().flatten().any(|(_, id)| *id == command) || is_spelling(menu, command) || is_crop(menu, command)) && entry_enabled(app, menu, command) + (is_point(menu, command) && point_current(app, menu)) + || ((rows(menu).iter().flatten().any(|(_, id)| *id == command) || is_spelling(menu, command) || is_crop(menu, command)) + && entry_enabled(app, menu, command)) } /// Is `command` the transform box's current mode (checked in the transform menu)? @@ -903,6 +1037,7 @@ pub fn open_transform(app: &mut PhotocraftApp, ctx: &Context, pos: [f32; 2]) -> sampler_at: None, color: None, inside_selection: false, + point: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -979,7 +1114,9 @@ pub fn open_pasteboard(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: transform: false, pasteboard: true, anchor: None, - under: None, + // Space's Hand keeps the menu over the selected tool (#11271); a held zoom key's goes with + // the key, as before. + under: (tool == Tool::Hand && tool != app.ui.tool).then_some(app.ui.tool), text: false, type_layer: false, type_shape: None, @@ -990,6 +1127,7 @@ pub fn open_pasteboard(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: sampler_at: None, color: None, inside_selection: false, + point: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -1027,6 +1165,7 @@ pub fn open_guide(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, mods: egui sampler_at: None, color: None, inside_selection: false, + point: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -1166,23 +1305,17 @@ pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2] crate::color_hud::release(&mut app.ui); return false; } + if tool == Tool::RedEye && !red_eye_measured(app, doc) { + return false; + } app.ui.brush_picker = None; app.ui.layer_menu = None; let has_selection = app.session.active().is_some_and(|s| s.doc.selection.is_some()); let has_path = crate::vector_ui::active_path_name(app).is_some() || app.ui.pen.as_ref().is_some_and(|p| p.knots.len() >= 2); let path_name = crate::vector_ui::active_path_name(app); let spelling = if text { doc.and_then(|d| spelling_at(app, d)) } else { None }; - let inside_selection = tool == Tool::ContentAwareMove - && doc.is_some_and(|d| { - d.iter().all(|v| v.is_finite()) - && d[0] >= 0.0 - && d[1] >= 0.0 - && app.session.active().is_some_and(|s| { - d[0] < f64::from(s.doc.size.width) - && d[1] < f64::from(s.doc.size.height) - && s.doc.selection.as_ref().is_some_and(|sel| sel.sample_channel(d[0].floor() as i32, d[1].floor() as i32, 0) >= 0.5) - }) - }); + let point = if point_menu(tool) && has_path { doc.filter(|d| d.iter().all(|v| v.is_finite())).and_then(|d| point_at(app, d)) } else { None }; + let inside_selection = tool == Tool::ContentAwareMove && doc.is_some_and(|d| selected_at(app, d)); let sampler = if tool == Tool::ColorSampler { doc.and_then(|d| crate::analysis_ui::sampler_at(app, d)) } else { None }; let sampler_at = sampler.and_then(|i| Some((app.session.active_index()?, *app.session.active()?.color_samplers.get(i)?))); // The Eyedropper reads the colour now, under the right-click: all layers, with the Sample @@ -1208,6 +1341,7 @@ pub fn open_at(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; 2] sampler_at, color, inside_selection, + point, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -1242,6 +1376,7 @@ pub fn open_view(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos: [f32; sampler_at: None, color: None, inside_selection: false, + point: None, }); crate::canvas_popup::mark_open(ctx, menu_id()); true @@ -1284,7 +1419,9 @@ pub fn choose(app: &mut PhotocraftApp, ctx: &Context, command: &str) { if !available(app, &menu, command) { return; } - let result = if menu.crop.is_some() { + let result = if is_point(&menu, command) { + menu.point.as_ref().map_or(Ok(()), |(id, params, _)| app.run(id, params.clone()).map(|_| ())) + } else if menu.crop.is_some() { choose_crop(app, &menu, command) } else if menu.guide { choose_guide(app, ctx, command) @@ -1632,6 +1769,13 @@ pub fn show(app: &mut PhotocraftApp, ctx: &Context) { selected = Some(command); } } + if let Some((command, ..)) = &menu.point { + let item = egui::Button::new(point_label(command)).min_size(egui::vec2(200.0, 20.0)); + if ui.add_enabled(available(app, &menu, command), item).clicked() { + selected = Some(command.clone()); + } + ui.separator(); + } for row in rows(&menu) { let Some((label, command)) = *row else { ui.separator(); @@ -1676,7 +1820,10 @@ pub fn menu_rect_if_open(app: &PhotocraftApp, ctx: &Context) -> Option 3, "every anchor is selected"); + app.ui.tool = Tool::ConvertPoint; + let mut h = harness(app); + assert!(!h.state().ui.direct_selection.anchors.is_empty(), "Convert Point keeps the selection"); + let p = screen_of(h.state(), [300.0, 300.0]); + right_click(&mut h, p, Modifiers::NONE); + // Chosen without a frame after it, which would drop a selection with no owner, as for a click. + let ctx = h.ctx.clone(); + super::choose(h.state_mut(), &ctx, "path.deleteAnchor"); + assert_eq!(saved(h.state()).subpaths[0].knots.len(), 3, "the anchor is gone"); + let ds = &h.state().ui.direct_selection; + assert!(ds.target.is_none_or(|t| t == PathRef::Saved(0)), "the selection is on no other path"); + assert!(ds.anchors.is_empty(), "no stale anchor index: {:?}", ds.anchors); +} diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/count_tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/count_tests.rs new file mode 100644 index 0000000000..ff76f9e7f8 --- /dev/null +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/count_tests.rs @@ -0,0 +1,131 @@ +//! #11772: a right-click on the canvas with the Count tool, on a marker or off one, opens +//! Photoshop's generic layer menu. Its rows are enabled as the Layers panel menu enables them for +//! the active layer, and the right-click itself adds no marker and no history step. + +use serde_json::{Value, json}; + +use super::*; +use crate::control::{ControlRequest, Outcome, handle}; + +/// A 64 × 48 document with a second pixel layer (active) and one count marker at 20,20. +fn app() -> (PhotocraftApp, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.run("layer.new.layer", json!({"name": "Ink"})).unwrap(); + app.run("count.add", json!({"x": 20, "y": 20})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Count; + (app, egui::Context::default()) +} + +pub(crate) fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { + let (req, _rx) = ControlRequest::new(method, params); + match handle(app, ctx, &req) { + Outcome::Done(v) => v, + _ => panic!("{method}: expected an immediate reply"), + } +} + +pub(crate) fn right_click(app: &mut PhotocraftApp, ctx: &egui::Context, x: f64, y: f64) { + let r = call(app, ctx, "ui.pointer", json!({"button": "secondary", "events": [{"kind": "down", "x": x, "y": y}, {"kind": "up", "x": x, "y": y}]})); + assert_eq!(r["ok"], true, "{r}"); +} + +/// The open menu's rows as `ui.inspect` lists them: ids, with "―" for separators. +pub(crate) fn listed(app: &mut PhotocraftApp, ctx: &egui::Context) -> Vec { + let inspected = call(app, ctx, "ui.inspect", json!({})); + let entries = inspected.pointer("/result/canvasToolMenu/entries").and_then(Value::as_array).cloned().unwrap_or_default(); + entries.iter().map(|e| e["id"].as_str().map_or_else(|| "―".to_string(), str::to_string)).collect() +} + +fn markers(app: &PhotocraftApp) -> Vec<[f64; 2]> { + app.session.active().unwrap().doc.measurement.count_groups.iter().flat_map(|g| g.points.clone()).collect() +} + +const WANT: [&str; 17] = [ + "layer.layerStyle.blendingOptions", + "―", + "layer.duplicate", + "layer.delete", + "layer.new.groupFromLayers", + "―", + "layer.smartObjects.convertToSmartObject", + "layer.smartObjects.convertToLayers", + "―", + "layer.rasterize.layer", + "layer.rasterize.layerStyle", + "―", + "edit.freeTransform", + "―", + "select.colorRange", + "select.loadSelection", + "select.reselect", +]; + +#[test] +fn a_right_click_on_or_off_a_marker_opens_the_layer_menu_in_order() { + for (x, y, what) in [(50.0, 40.0, "empty canvas"), (20.0, 20.0, "a marker")] { + let (mut app, ctx) = app(); + right_click(&mut app, &ctx, x, y); + assert_eq!(listed(&mut app, &ctx), WANT, "on {what}"); + let labels: Vec<&str> = rows(app.ui.canvas_tool_menu.as_ref().unwrap()).iter().flatten().map(|(l, _)| *l).collect(); + assert_eq!(labels[..3], ["Blending Options…", "Duplicate Layer…", "Delete Layer"], "on {what}"); + assert_eq!(labels.last(), Some(&"Reselect")); + } +} + +#[test] +fn the_right_click_adds_no_marker_and_no_history_step() { + for (x, y) in [(50.0, 40.0), (20.0, 20.0)] { + let (mut app, ctx) = app(); + let (before, steps) = (markers(&app), app.session.active().unwrap().history.past_len()); + right_click(&mut app, &ctx, x, y); + assert_eq!(markers(&app), before, "({x}, {y}): no marker added or moved"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps, "({x}, {y}): no history step"); + assert!(app.ui.canvas_tool_menu.is_some(), "({x}, {y}): the menu is open"); + } +} + +#[test] +fn rows_are_enabled_as_the_layers_panel_menu_enables_them() { + let (mut app, ctx) = app(); + right_click(&mut app, &ctx, 50.0, 40.0); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + for (_, id) in rows(&menu).iter().flatten() { + assert_eq!(entry_enabled(&app, &menu, id), crate::menus::is_enabled(&app, id), "{id}"); + } + // A pixel layer: Convert to Layers (a smart object's) and Reselect (no earlier selection) are + // greyed; Delete Layer and Free Transform are not. + assert!(!entry_enabled(&app, &menu, "layer.smartObjects.convertToLayers")); + assert!(!entry_enabled(&app, &menu, "select.reselect")); + assert!(entry_enabled(&app, &menu, "layer.delete") && entry_enabled(&app, &menu, "edit.freeTransform")); + // After a selection is made and cleared, Reselect is enabled. + app.ui.canvas_tool_menu = None; + app.run("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + right_click(&mut app, &ctx, 50.0, 40.0); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(entry_enabled(&app, &menu, "select.reselect"), "Reselect after a cleared selection"); +} + +#[test] +fn picking_a_row_runs_it_on_the_active_layer() { + let (mut app, ctx) = app(); + let layers = app.session.active().unwrap().doc.layers.len(); + right_click(&mut app, &ctx, 50.0, 40.0); + assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id": "layer.delete"}))["ok"], true); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers - 1, "Delete Layer deleted the active layer"); + assert!(app.ui.canvas_tool_menu.is_none(), "the pick closes the menu"); + // A row the menu doesn't have is refused. + right_click(&mut app, &ctx, 50.0, 40.0); + assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id": "select.inverse"}))["ok"], false); +} + +#[test] +fn the_other_tools_keep_their_menus() { + let (mut app, ctx) = app(); + app.ui.tool = Tool::RectMarquee; + right_click(&mut app, &ctx, 50.0, 40.0); + assert_ne!(listed(&mut app, &ctx), WANT, "the marquee keeps its selection menu"); + assert!(!applies(Tool::Note), "a tool without a canvas menu still gets none"); +} diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/delete_anchor_menu_tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/delete_anchor_menu_tests.rs new file mode 100644 index 0000000000..7db812349d --- /dev/null +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/delete_anchor_menu_tests.rs @@ -0,0 +1,206 @@ +//! #12771: with the Delete Anchor Point tool a right-click on the canvas opens the Pen's path menu +//! with one entry for what is under the pointer on top: Delete Anchor Point on an anchor, Add +//! Anchor Point on a segment, nothing on empty canvas. Opening it records no history step and +//! leaves the anchor selection alone. The helpers are shared with the Convert Point tests (#12744). + +use egui::Modifiers; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::vector::Path; +use serde_json::json; + +use super::tests::{harness, right_click, screen_of}; +use super::{PEN_MENU, rows}; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// 800 x 600 with a saved, targeted **Path 1**: a closed square (100,300)(300,300)(300,500) +/// (100,500), an open line (400,300)->(700,300) and an open S-curve (400,450)->(700,450). +pub(super) fn setup(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + let path = json!({"subpaths": [ + {"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}, + {"closed": false, "knots": [[400, 300], [700, 300]]}, + {"closed": false, "knots": [ + {"anchor": [400, 450], "in": [400, 450], "out": [500, 350]}, + {"anchor": [700, 450], "in": [600, 550], "out": [700, 450]}, + ]}, + ]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); + app.ui.tool = tool; + app +} + +/// A harness over [`setup`] with the right-click at document point `at` done. +pub(super) fn right_clicked(tool: Tool, at: [f32; 2]) -> Harness<'static, PhotocraftApp> { + let mut h = harness(setup(tool)); + let p = screen_of(h.state(), at); + right_click(&mut h, p, Modifiers::NONE); + h +} + +pub(super) fn saved(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths.iter().find(|p| p.name == "Path 1").unwrap().path.clone() +} + +pub(super) fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.entries().len() +} + +/// The path menu is open and its rows are the Pen's, in the Pen's order. +fn assert_path_menu(h: &Harness<'static, PhotocraftApp>, tool: Tool) { + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.tool == tool && rows(m) == PEN_MENU), "{tool:?}: the path menu is open"); +} + +/// The first entry of the open menu is `label`, above Create Vector Mask, and is the only one of +/// the two Add / Delete Anchor Point entries shown. +pub(super) fn assert_top_entry(h: &Harness<'static, PhotocraftApp>, tool: Tool, label: &str) { + assert_path_menu(h, tool); + let other = if label == "Delete Anchor Point" { "Add Anchor Point" } else { "Delete Anchor Point" }; + assert!(h.query_by_label(other).is_none(), "{other} is not offered"); + assert!(h.get_by_label(label).rect().top() < h.get_by_label("Create Vector Mask").rect().top(), "{label} heads the menu"); +} + +/// The context-menu contract after a menu edit: undo restores the whole original path and redo +/// replays the edit (the path as it was right after the menu choice, `edited`). +fn assert_undo_redo(h: &mut Harness<'static, PhotocraftApp>, original: &Path, edited: &Path) { + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(&saved(h.state()), original, "undo restores the whole path"); + h.state_mut().run("edit.redo", json!({})).unwrap(); + assert_eq!(&saved(h.state()), edited, "redo replays the menu edit"); +} + +/// Right-click the corner (300,300), choose Delete Anchor Point: the square stays closed with +/// three anchors and the history gains one step by that name. +pub(super) fn delete_the_corner(tool: Tool) { + let mut h = right_clicked(tool, [300.0, 300.0]); + assert_top_entry(&h, tool, "Delete Anchor Point"); + let before = steps(h.state()); + let original = saved(h.state()); + h.get_by_label("Delete Anchor Point").click(); + h.run_steps(2); + let path = saved(h.state()); + assert!(path.subpaths[0].closed, "the square stays closed"); + assert_eq!(path.subpaths[0].knots.len(), 3); + assert!(path.subpaths[0].knots.iter().all(|k| (k.anchor.x, k.anchor.y) != (300.0, 300.0)), "(300,300) is gone"); + assert_eq!(steps(h.state()), before + 1); + assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Delete Anchor Point")); + assert_undo_redo(&mut h, &original, &path); +} + +/// Right-click the top edge (200,300): Add Anchor Point heads the menu and adds one there. +pub(super) fn add_on_the_edge(tool: Tool) { + let mut h = right_clicked(tool, [200.0, 300.0]); + assert_top_entry(&h, tool, "Add Anchor Point"); + let before = steps(h.state()); + let original = saved(h.state()); + h.get_by_label("Add Anchor Point").click(); + h.run_steps(2); + let path = saved(h.state()); + assert_eq!(path.subpaths[0].knots.len(), 5); + let added = &path.subpaths[0].knots[1].anchor; + assert!((added.x - 200.0).abs() < 3.0 && (added.y - 300.0).abs() < 3.0, "the anchor lands where it was clicked: {added:?}"); + assert_eq!(steps(h.state()), before + 1); + assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Add Anchor Point")); + assert_undo_redo(&mut h, &original, &path); +} + +/// Right-click empty canvas with the path targeted: the path menu with no top entry. +pub(super) fn empty_canvas(tool: Tool) { + let h = right_clicked(tool, [500.0, 100.0]); + assert_path_menu(&h, tool); + assert!(h.query_by_label("Delete Anchor Point").is_none() && h.query_by_label("Add Anchor Point").is_none(), "no top entry"); + assert!(h.query_by_label("Create Vector Mask").is_some()); +} + +/// Opening the menu on an anchor and on a segment adds no history step, changes no path and +/// leaves the Direct Selection state as it was (here: one anchor selected). +pub(super) fn opening_changes_nothing(tool: Tool) { + for at in [[300.0, 300.0], [200.0, 300.0]] { + let mut app = setup(tool); + // Direct Selection picks the anchor at (100,300); the tool under test takes over. + app.ui.tool = Tool::DirectSelection; + tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 300.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 300.0 }, Modifiers::NONE); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 0]], "an anchor is selected"); + app.ui.tool = tool; + let (path, n) = (saved(&app), steps(&app)); + let mut h = harness(app); + // The selection once the first frames have run: Convert Point keeps Direct Selection's, + // Delete Anchor Point already drops it today, menu or not. + let selection = h.state().ui.direct_selection.clone(); + assert_eq!(!selection.anchors.is_empty(), tool == Tool::ConvertPoint, "{tool:?}: selection before the right-click"); + let p = screen_of(h.state(), at); + right_click(&mut h, p, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_some(), "the menu opened at {at:?}"); + assert_eq!(steps(h.state()), n, "no history step at {at:?}"); + assert_eq!(h.state().ui.direct_selection, selection, "the anchor selection is as it was at {at:?}"); + assert_eq!(saved(h.state()), path, "no path changed at {at:?}"); + } +} + +#[test] +fn right_click_on_an_anchor_offers_delete_anchor_point_on_top_and_it_deletes() { + delete_the_corner(Tool::DeleteAnchorPoint); +} + +#[test] +fn right_click_on_a_segment_offers_add_anchor_point_on_top() { + add_on_the_edge(Tool::DeleteAnchorPoint); +} + +#[test] +fn right_click_on_empty_canvas_opens_the_path_menu_without_a_top_entry() { + empty_canvas(Tool::DeleteAnchorPoint); +} + +#[test] +fn opening_the_menu_adds_no_history_step_and_keeps_the_anchor_selection() { + opening_changes_nothing(Tool::DeleteAnchorPoint); +} + +/// The entry is about the path as it was when the menu opened: an edit meanwhile (a control call +/// inserting an anchor before the corner) shifts the knots, so choosing it deletes nothing. +#[test] +fn a_point_entry_expires_once_the_path_is_edited() { + let mut h = right_clicked(Tool::DeleteAnchorPoint, [300.0, 300.0]); + assert_top_entry(&h, Tool::DeleteAnchorPoint, "Delete Anchor Point"); + h.state_mut().run("path.addAnchor", json!({"name": "Path 1", "subpath": 0, "knot": 0, "t": 0.5})).unwrap(); + let after_add = saved(h.state()); + assert_eq!(after_add.subpaths[0].knots.len(), 5, "the anchor went in"); + let n = steps(h.state()); + let ctx = h.ctx.clone(); + super::choose(h.state_mut(), &ctx, "path.deleteAnchor"); + assert_eq!(saved(h.state()), after_add, "the stale entry deleted nothing"); + assert_eq!(steps(h.state()), n, "and added no history step"); +} + +/// The expired entry is drawn disabled, not just rejected on click (#12771, CodeRabbit). +#[test] +fn an_expired_point_entry_is_drawn_disabled() { + let mut h = right_clicked(Tool::DeleteAnchorPoint, [300.0, 300.0]); + assert!(!h.get_by_label("Delete Anchor Point").accesskit_node().is_disabled(), "enabled while the path is as it was"); + h.state_mut().run("path.addAnchor", json!({"name": "Path 1", "subpath": 0, "knot": 0, "t": 0.5})).unwrap(); + h.run(); + assert!(h.get_by_label("Delete Anchor Point").accesskit_node().is_disabled(), "disabled once the path is edited"); +} + +/// A shape with only its own position lock is ignored by the anchor tools' click (#12730, #12825), +/// so the menu offers no point entry on its corner either: the rest of the menu is as before. +#[test] +fn a_shape_with_only_its_position_lock_gets_no_point_entry() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + let shape = app.run("shape.create", json!({"kind": "rect", "rect": [450, 100, 200, 150], "fill": "#3070c0"})).unwrap()["layer"].as_u64().unwrap(); + app.run("layer.select", json!({"layer": shape})).unwrap(); + app.run("layer.lockLayers", json!({"position": true})).unwrap(); + app.ui.tool = Tool::DeleteAnchorPoint; + let mut h = harness(app); + let p = screen_of(h.state(), [650.0, 250.0]); + right_click(&mut h, p, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.is_some(), "the menu opens"); + assert!(h.query_by_label("Delete Anchor Point").is_none() && h.query_by_label("Add Anchor Point").is_none(), "no point entry on the locked shape"); +} diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/object_selection_menu_tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/object_selection_menu_tests.rs new file mode 100644 index 0000000000..a1f722a626 --- /dev/null +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/object_selection_menu_tests.rs @@ -0,0 +1,192 @@ +//! #12866: the Object Selection tool's canvas menu lists the reference application's rows: with a +//! selection, no Distort or Perspective and Delete and Fill Selection after the fills; with none, +//! the layer menu, its rows greyed as measured over the Background, a type and a shape layer. The +//! marquees', lassos' and Magic Wand's menus are unchanged. + +use egui::{Context, Modifiers}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; + +use super::tests::{app, harness, labels, right_click}; +use super::{COUNT_MENU, NO_SELECTION_MENU, SELECTION_MENU, available, open, rows}; +use crate::PhotocraftApp; +use crate::state::Tool; + +/// A pixel layer filled red, active, with `select` run first when given. +fn pixel_layer(select: &[(&str, Value)]) -> PhotocraftApp { + let mut app = app(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + for (id, params) in select { + app.run(id, params.clone()).unwrap(); + } + app.ui.tool = Tool::ObjectSelection; + app +} + +/// Right-click the middle of the canvas: the open menu's entries as `ui.inspect` lists them. +fn right_click_entries(h: &mut Harness<'static, PhotocraftApp>) -> Vec { + let center = h.state().last_canvas_rect.center(); + right_click(h, center, Modifiers::NONE); + let inspected = crate::control::inspect(h.state(), &h.ctx); + assert_eq!(inspected["canvasToolMenu"]["tool"], json!("ObjectSelection")); + inspected["canvasToolMenu"]["entries"].as_array().cloned().unwrap_or_default() +} + +/// The entries' labels, a separator as `None`. +fn shown(entries: &[Value]) -> Vec> { + entries.iter().map(|e| if e["separator"] == json!(true) { None } else { e["label"].as_str().map(String::from) }).collect() +} + +/// The issue's notation: rows joined by " · ", separators written " ― ". +fn menu(spec: &str) -> Vec> { + spec.split(" ― ") + .enumerate() + .flat_map(|(i, group)| (i > 0).then_some(None).into_iter().chain(group.split(" · ").map(|label| Some(label.to_owned())))) + .collect() +} + +#[test] +fn with_a_selection_the_menu_lists_the_reference_rows() { + let mut h = harness(pixel_layer(&[("select.rect", json!({"x": 4, "y": 4, "width": 24, "height": 24}))])); + let entries = right_click_entries(&mut h); + assert_eq!( + shown(&entries), + menu( + "Deselect · Select Inverse · Feather… · Select and Mask… ― Save Selection… · Make Work Path… ― Layer Via Copy · Layer Via Cut · \ + New Layer… ― Free Transform · Transform Selection ― Fill… · Stroke… · Content-Aware Fill… · Delete and Fill Selection ― \ + Last Filter ― Fade…" + ) + ); + // A row the menu had before runs its command, as before. + let before = h.state().session.journal.len(); + h.get_by_label("Select Inverse").click(); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none()); + assert!(h.state().session.journal[before..].iter().any(|(id, _)| id == "select.inverse")); +} + +#[test] +fn with_no_selection_the_menu_lists_the_layer_rows() { + let mut h = harness(pixel_layer(&[("select.rect", json!({"x": 4, "y": 4, "width": 24, "height": 24})), ("select.deselect", json!({}))])); + let entries = right_click_entries(&mut h); + assert_eq!( + shown(&entries), + menu( + "Blending Options… ― Duplicate Layer… · Delete Layer · Group from Layers… ― Convert to Smart Object · Convert to Layers ― \ + Rasterize Layer · Rasterize Layer Style ― Free Transform ― Color Range… · Load Selection… · Reselect" + ) + ); + // Over a plain pixel layer these have nothing to act on and grey out. + for label in ["Convert to Layers", "Rasterize Layer", "Rasterize Layer Style"] { + let entry = entries.iter().find(|e| e["label"] == json!(label)); + assert_eq!(entry.map(|e| &e["enabled"]), Some(&json!(false)), "{label} is greyed out"); + } + h.get_by_label("Reselect").click(); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none()); + assert!(h.state().session.active().unwrap().doc.selection.is_some(), "Reselect brings the selection back"); + assert_eq!(h.state().session.journal.last().map(|(id, _)| id.as_str()), Some("select.reselect")); +} + +/// The rows greyed without a selection, as measured over each layer kind (#12866). Load +/// Selection… and Reselect follow the document, not the layer, and are left out. +const GREYED: [(&str, &[&str]); 3] = [ + ("Background", &["Blending Options…", "Group from Layers…", "Convert to Layers", "Rasterize Layer", "Rasterize Layer Style", "Free Transform"]), + ("Type", &["Convert to Layers", "Rasterize Layer Style"]), + ("Shape", &["Convert to Layers", "Rasterize Layer Style"]), +]; + +#[test] +fn background_type_and_shape_layers_get_the_layer_menu_greyed_as_measured() { + for (kind, greyed) in GREYED { + let mut app = app(); + // The Background stays active under a second layer, so Delete Layer has one to keep. + let background = app.session.active().and_then(|st| st.active_layer).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + match kind { + "Background" => app.session.set_active_layer(Some(background)), + "Type" => { + app.run("type.create", json!({"x": 4, "y": 20, "text": "A", "size": 12})).unwrap(); + } + _ => { + app.run("shape.create", json!({"kind": "rect", "rect": [4, 4, 20, 20], "fill": "#ff0000"})).unwrap(); + } + } + let st = app.session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert_eq!(if st.doc.is_background(layer.id) { "Background" } else { layer.content.kind_name() }, kind); + app.ui.tool = Tool::ObjectSelection; + assert!(open(&mut app, &Context::default(), Tool::ObjectSelection, [10.0, 10.0]), "{kind}"); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert_eq!(labels(rows(&menu)), labels(COUNT_MENU), "{kind}"); + let wrong: Vec<_> = rows(&menu) + .iter() + .flatten() + .filter(|(label, id)| !matches!(*label, "Load Selection…" | "Reselect") && available(&app, &menu, id) == greyed.contains(label)) + .map(|(label, _)| *label) + .collect(); + assert!(wrong.is_empty(), "{kind}: enabled or greyed unlike the reference: {wrong:?}"); + } +} + +/// The reference application greys Group from Layers… whenever the Background is selected, also +/// beside a pixel layer that is the active one. +#[test] +fn group_from_layers_is_greyed_with_the_background_among_the_selected_layers() { + let mut app = pixel_layer(&[]); + let st = app.session.active().unwrap(); + let pixel = st.active_layer.unwrap(); + let background = st.doc.layers.iter().map(|l| l.id).find(|id| st.doc.is_background(*id)).unwrap(); + assert!(open(&mut app, &Context::default(), Tool::ObjectSelection, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(available(&app, &menu, "layer.new.groupFromLayers"), "a pixel layer alone can be grouped"); + app.run("layer.select", json!({"layer": background.0, "mode": "add"})).unwrap(); + app.session.set_active_layer(Some(pixel)); + assert_eq!(app.session.active().unwrap().selected_layers().len(), 2); + assert!(open(&mut app, &Context::default(), Tool::ObjectSelection, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(!available(&app, &menu, "layer.new.groupFromLayers"), "the Background is selected too"); +} + +#[test] +fn every_object_selection_row_runs_a_known_command() { + let mut app = pixel_layer(&[]); + let items = crate::menus::menu_items(&app); + // Selected first, then deselected. + for id in ["select.all", "select.deselect"] { + app.run(id, json!({})).unwrap(); + assert!(open(&mut app, &Context::default(), Tool::ObjectSelection, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + for (label, id) in rows(&menu).iter().flatten() { + assert!(items.iter().any(|i| i.id == *id) || photocraft_engine::commands::find(id).is_some(), "{label}: unknown command {id}"); + } + } +} + +#[test] +fn the_other_selection_tools_keep_their_menus() { + let tools = [ + Tool::RectMarquee, + Tool::EllipseMarquee, + Tool::SingleRowMarquee, + Tool::SingleColumnMarquee, + Tool::Lasso, + Tool::PolygonLasso, + Tool::MagneticLasso, + Tool::MagicWand, + ]; + for tool in tools { + for (selection, menu) in [(true, SELECTION_MENU), (false, NO_SELECTION_MENU)] { + let mut app = app(); + if selection { + app.run("select.all", json!({})).unwrap(); + } + app.ui.tool = tool; + assert!(open(&mut app, &Context::default(), tool, [10.0, 10.0]), "{tool:?}"); + let open_rows = rows(app.ui.canvas_tool_menu.as_ref().unwrap()); + assert_eq!(labels(open_rows), labels(menu), "{tool:?}, selection {selection}"); + } + } +} diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs index 92b0ab9bc6..debcd8aee4 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs @@ -28,7 +28,7 @@ pub(super) fn choose_open(app: &mut PhotocraftApp, command: &str) { choose(app, &Context::default(), command); } -pub(super) fn harness(mut app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { +pub(crate) fn harness(mut app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { app.sync_views(); let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( |ui, app: &mut PhotocraftApp| { @@ -45,7 +45,7 @@ pub(super) fn harness(mut app: PhotocraftApp) -> Harness<'static, PhotocraftApp> h } -pub(super) fn right_click(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, modifiers: Modifiers) { +pub(crate) fn right_click(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, modifiers: Modifiers) { h.event(egui::Event::ModifiersChanged(modifiers)); h.event(egui::Event::PointerMoved(p)); h.run_steps(1); @@ -387,7 +387,7 @@ fn transform_menu_follows_photoshop_order() { } } -fn labels(rows: &[Row]) -> Vec> { +pub(super) fn labels(rows: &[Row]) -> Vec> { rows.iter().map(|row| row.map(|(label, _)| label)).collect() } @@ -526,7 +526,7 @@ fn zoom_app(w: u32, h: u32) -> PhotocraftApp { app } -fn screen_of(app: &PhotocraftApp, doc: [f32; 2]) -> Pos2 { +pub(super) fn screen_of(app: &PhotocraftApp, doc: [f32; 2]) -> Pos2 { crate::canvas::ViewXform::active(app).unwrap().to_screen(doc[0], doc[1]) } diff --git a/crates/ui-egui/src/canvas/cursors.rs b/crates/ui-egui/src/canvas/cursors.rs index 132fab319f..fd44445a2a 100644 --- a/crates/ui-egui/src/canvas/cursors.rs +++ b/crates/ui-egui/src/canvas/cursors.rs @@ -34,11 +34,13 @@ pub(crate) fn pencil_tip_is_round(size: f32) -> bool { (h - 0.5) * std::f32::consts::SQRT_2 > h } -/// Whether a brush-tip circle draws its centre mark. -/// Clone Stamp and Healing Brush stay an empty circle until Option is held, the source-point -/// cursor. Other brushes follow Preferences › Cursors › Show Crosshair in Brush Tip, as in -/// Photoshop; the Background Eraser always shows its sampling hotspot, and the Remove tool its -/// centre + (#12550). +/// Whether a brush-tip circle draws its centre mark, for Normal and Full Size Brush Tip cursors +/// alike (both draw through this). Quick Selection never draws one. Clone Stamp and Healing Brush +/// stay an empty circle until Option is held, the source-point cursor (the Healing Brush's ⌥ with +/// Normal Brush Tip shows the sample target instead, #12113). Other brushes follow +/// Preferences › Cursors › Show Crosshair in Brush Tip, as in Photoshop; the Background Eraser +/// and the Color Replacement tool (#11934) always show their sampling hotspot, and the Remove +/// tool its centre + (#12550). pub(super) fn brush_tip_centre(tool: Tool, option: bool, show_crosshair: bool) -> bool { if tool == Tool::QuickSelection { return false; @@ -46,7 +48,7 @@ pub(super) fn brush_tip_centre(tool: Tool, option: bool, show_crosshair: bool) - if matches!(tool, Tool::CloneStamp | Tool::Healing) { return option || show_crosshair; } - show_crosshair || matches!(tool, Tool::BackgroundEraser | Tool::Remove) + show_crosshair || matches!(tool, Tool::BackgroundEraser | Tool::ColorReplacement | Tool::Remove) } /// The display colour of an RGB triple (0..1 per channel) as an egui colour. @@ -176,11 +178,9 @@ pub(crate) fn color_sampler_cursor(ctx: &egui::Context, p: Pos2) -> egui::Cursor } /// The sampling cursor: a pipette whose tip is the sampled pixel. Draws it at `p` and returns the -/// OS cursor to set (hidden). +/// OS cursor to set. Native windows use a cached bitmap that moves independently of rendering. pub(crate) fn pipette_cursor(ctx: &egui::Context, p: Pos2) -> egui::CursorIcon { - // The tip of the icon's pipette is at (2, 22) of its 24-unit box. - crate::icons::cursor(ctx, "pipette", p, vec2(2.0, 22.0) / 24.0, 20.0); - egui::CursorIcon::None + crate::tool_cursor::pipette(ctx, p) } /// The filter dialogs' preview locator: a small square centred on `p`, the point a click centres @@ -197,6 +197,58 @@ pub(crate) fn preview_locator_cursor(ctx: &egui::Context, p: Pos2) -> egui::Curs egui::CursorIcon::None } +/// The cursor while ⌥ turns a painting tool into the Eyedropper (`alt_eyedropper`): the pipette, +/// or the comparison ring while it samples with the button `held` (#213), or the precise crosshair +/// with Preferences › Cursors › Other Cursors = Precise. The Mixer Brush's ⌥ loads paint instead: +/// its sample target, with no ring (#11957). +pub(super) fn alt_pick_cursor(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, p: Pos2, held: bool, tool: Tool) -> egui::CursorIcon { + let precise = app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise; + if tool == Tool::MixerBrush && !app.alt_sampling { + return if precise { egui::CursorIcon::Crosshair } else { sample_target_cursor(painter, p) }; + } + if let Some(icon) = eyedropper_ring(app, painter, xf, p, held) { + icon + } else if precise { + egui::CursorIcon::Crosshair + } else { + pipette_cursor(painter.ctx(), p) + } +} + +/// The Mixer Brush's and the Healing Brush's ⌥ cursor, the reference's sample target (#11957, +/// #12113): a small circle with a crosshair through it, centred on the hotspot. Draws it at `p` +/// and returns the OS cursor to set. +pub(crate) fn sample_target_cursor(painter: &egui::Painter, p: Pos2) -> egui::CursorIcon { + let across = vec![vec2(-8.0, 0.0), vec2(8.0, 0.0)]; + let down = vec![vec2(0.0, -8.0), vec2(0.0, 8.0)]; + super::tool_cursor::outline(painter, p, vec![ring(5.0), across, down], false) +} + +/// A no-entry sign, a circle with a diagonal bar centred on the hotspot: the Mixer Brush over a +/// layer it can't paint (Lock All, #11957). Draws it at `p` and returns the OS cursor to set. +pub(crate) fn no_entry_cursor(painter: &egui::Painter, p: Pos2) -> egui::CursorIcon { + let bar = vec![vec2(-4.5, -4.5), vec2(4.5, 4.5)]; + super::tool_cursor::outline(painter, p, vec![ring(6.5), bar], false) +} + +/// A closed circle of `radius` points around the hotspot. +fn ring(radius: f32) -> Vec { + (0..32).map(|i| i as f32 / 32.0 * std::f32::consts::TAU).map(|a| vec2(a.cos(), a.sin()) * radius).collect() +} + +/// Whether the Mixer Brush's target layer has Lock All on, so it shows [`no_entry_cursor`]. +pub(crate) fn mixer_target_locked(app: &PhotocraftApp) -> bool { + app.session.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))).is_some_and(|layer| layer.locks.all) +} + +#[cfg(test)] +#[path = "../mixer_cursor_tests.rs"] +mod mixer_cursor_tests; + +#[cfg(test)] +#[path = "../healing_alt_cursor_tests.rs"] +mod healing_alt_cursor_tests; + /// The Paint Bucket artwork and target share one cached cursor image. Report rasterization /// failures once per distinct message, with the same concise error in the dialog and status bar. pub(crate) fn paint_bucket_cursor(app: &mut PhotocraftApp, painter: &egui::Painter, p: Pos2) -> egui::CursorIcon { @@ -235,20 +287,23 @@ pub(crate) fn paint_bucket_cursor(app: &mut PhotocraftApp, painter: &egui::Paint /// Decided when the press starts, so ⌥ pressed or released mid-stroke never switches between /// painting and sampling. pub(super) fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool { - if matches!(ev, ToolEvent::Down { .. }) { + if let ToolEvent::Down { x, y, .. } = ev { let physical_right = app.services.right_button_down.as_ref().is_some_and(|f| f()); - app.alt_sampling = !physical_right && !app.secondary_erase && alt_samples(app.active_tool(), mods); + app.alt_sampling = !physical_right && !app.secondary_erase && (alt_samples(app.active_tool(), mods) || shape_alt_samples(app, mods, x, y)); } if !app.alt_sampling { return false; } + // The Triangle tool's ⇧⌥ at the press samples as ⌥ does, and the release point's colour is the + // one it keeps (#13364). + let triangle = app.active_tool() == Tool::Triangle; match ev { // ⇧⌥-click adds a colour sampler at the clicked pixel instead, as the Color Sampler tool // places one: no foreground change, nothing painted (#11890). A refused point (the // document's limit) reports in the status bar as that tool's does; off the canvas, as that // tool, it places none and says nothing. A press on an existing point wasn't measured, so // it samples the foreground as before. - ToolEvent::Down { x, y, .. } if mods.shift && !on_sampler(app, x, y) => { + ToolEvent::Down { x, y, .. } if mods.shift && !triangle && !on_sampler(app, x, y) => { let size = app.session.active().map(|d| d.doc.size); let inside = size.is_some_and(|s| (0.0..f64::from(s.width)).contains(&x) && (0.0..f64::from(s.height)).contains(&y)); if inside && let Err(e) = app.run("view.colorSamplers.add", json!({"x": x, "y": y})) { @@ -260,14 +315,42 @@ pub(super) fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui: } } // While ⇧⌥ stay held after that press, moves sample nothing. - ToolEvent::Move { .. } if mods.shift => {} + ToolEvent::Move { .. } if mods.shift && !triangle => {} + ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } if triangle => sample_shape_fill(app, x, y), // Without ⌥: the sample sets the foreground colour, whatever the Eyedropper would do. ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } => sample_eyedropper(app, x, y, egui::Modifiers::NONE), - ToolEvent::Up { .. } => app.alt_sampling = false, + ToolEvent::Up { x, y } => { + if triangle { + sample_shape_fill(app, x, y); + } + app.alt_sampling = false; + } } true } +/// The Triangle tool samples with ⌥ held at the press at (x, y) only in Shape mode and with no +/// shape layer active (#13364): with one, ⌥ subtracts from it. Path or Pixels mode and a press +/// with nothing to sample (off the image, over transparency) weren't measured and keep drawing +/// from the centre. Control+⌥ stays the brush-resize drag, as in [`alt_samples`]. +fn shape_alt_samples(app: &mut PhotocraftApp, mods: egui::Modifiers, x: f64, y: f64) -> bool { + mods.alt + && !mods.ctrl + && app.active_tool() == Tool::Triangle + && app.ui.tool_options.shape_mode == "shape" + && crate::vector_ui::active_shape_path(app).is_none() + && eyedropper_color(app, x, y).is_some() +} + +/// The Triangle tool's ⌥ sample: the colour at (x, y) becomes the foreground and the tool's Fill, a +/// solid fill, which follows the foreground (#13364). Where nothing is sampled, both stay. +fn sample_shape_fill(app: &mut PhotocraftApp, x: f64, y: f64) { + if sampled_eyedropper(app, x, y, egui::Modifiers::NONE) { + app.ui.tool_options.shape_fill = true; + app.ui.tool_options.shape_fill_gradient = None; + } +} + /// Is document point (x, y) on a colour sampler, within the Color Sampler tool's reach of one (7 /// screen pixels)? fn on_sampler(app: &PhotocraftApp, x: f64, y: f64) -> bool { @@ -275,6 +358,10 @@ fn on_sampler(app: &PhotocraftApp, x: f64, y: f64) -> bool { app.session.active().is_some_and(|d| d.color_samplers.iter().any(|q| (q[0] - x).hypot(q[1] - y) <= tol)) } +#[cfg(test)] +#[path = "triangle_alt_eyedropper_tests.rs"] +mod triangle_alt_eyedropper_tests; + #[cfg(test)] #[path = "../brush_shift_alt_sampler_tests.rs"] mod brush_shift_alt_sampler_tests; @@ -282,6 +369,11 @@ mod brush_shift_alt_sampler_tests; /// Sample the image or targeted raster mask at (x, y) using the configured Sample Size. /// Write a valid sample to the foreground swatch, or to the background swatch with Alt. pub(super) fn sample_eyedropper(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) { + sampled_eyedropper(app, x, y, mods); +} + +/// [`sample_eyedropper`], true when it set a swatch. +fn sampled_eyedropper(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) -> bool { let rgb = if let Some((surface, canvas)) = eyedropper_mask_source(app) { sample_layer_mask(surface, canvas, x, y, app.ui.tool_options.eyedropper_size) } else { @@ -289,8 +381,9 @@ pub(super) fn sample_eyedropper(app: &mut PhotocraftApp, x: f64, y: f64, mods: e }; if let Some(rgb) = rgb { let key = if mods.alt { "background" } else { "foreground" }; - let _ = app.run("tools.setColors", json!({ key: [rgb[0],rgb[1],rgb[2],1.0] })); + return app.run("tools.setColors", json!({ key: [rgb[0],rgb[1],rgb[2],1.0] })).is_ok(); } + false } /// Only the Eyedropper's Current Layer and Current & Below modes pick the targeted raster mask. @@ -368,6 +461,10 @@ pub(crate) fn alt_picks(tool: Tool, mods: egui::Modifiers) -> bool { #[path = "../eyedropper_mask_sample_tests.rs"] mod eyedropper_mask_sample_tests; +#[cfg(test)] +#[path = "../color_replacement_cursor_tests.rs"] +mod color_replacement_cursor_tests; + #[cfg(test)] #[path = "../color_replacement_alt_click_tests.rs"] mod color_replacement_alt_click_tests; @@ -379,3 +476,7 @@ mod background_eraser_alt_click_tests; #[cfg(test)] #[path = "remove_cursor_tests.rs"] mod remove_cursor_tests; + +#[cfg(test)] +#[path = "paint_bucket_cursor_tests.rs"] +mod paint_bucket_cursor_tests; diff --git a/crates/ui-egui/src/canvas/doc_window_dialog_tests.rs b/crates/ui-egui/src/canvas/doc_window_dialog_tests.rs new file mode 100644 index 0000000000..9a5bab7400 --- /dev/null +++ b/crates/ui-egui/src/canvas/doc_window_dialog_tests.rs @@ -0,0 +1,150 @@ +//! A Window › New Window document window under an open dialog: its canvas is as inert as the main +//! window's, so a tool drag there adds no History step (the dialog's Cancel would not undo it). + +use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, vec2}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::{DocWindow, Tool, View}; + +use super::tabs::document_window_canvas; + +fn app_with_a_layer() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + // Filled where the drag starts; Auto-Select off, so the press moves the active layer whatever + // lies under it. + app.run("select.rect", json!({"x": 20, "y": 20, "width": 160, "height": 110})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_auto_select = false; + app.ui.extras.rulers = false; + app.ui.extras.snap = false; + app.ui.view.show.smart_guides = false; + app +} + +fn history(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().history.entries().to_vec() +} + +/// A document window's canvas, drawn in its own context as its own viewport is: no dialog is +/// drawn there, only in the main window. 1:1 around the document's centre, at the screen's centre. +struct DocumentWindow { + ctx: egui::Context, + screen: Rect, + window: DocWindow, + view: View, +} + +impl DocumentWindow { + fn new(app: &PhotocraftApp) -> Self { + let window = DocWindow { id: 7, document: 0, view: app.ui.views[0].clone(), open: true, position: None, floating: false, focused: true }; + let mut view = window.view.clone(); + let size = app.session.active().unwrap().doc.size; + view.zoom = 1.0; + view.center = [size.width as f32 / 2.0, size.height as f32 / 2.0]; + view.fit_pending = false; + view.fill_pending = false; + Self { ctx: egui::Context::default(), screen: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), window, view } + } + + fn frame(&mut self, app: &mut PhotocraftApp, events: Vec) { + let input = RawInput { screen_rect: Some(self.screen), events, ..Default::default() }; + let mut out = self.ctx.run_ui(input, |ui| { + self.view = document_window_canvas(app, ui, &self.window, self.view.clone(), true).0; + }); + out.textures_delta.clear(); + } +} + +fn button(pos: Pos2, pressed: bool, modifiers: Modifiers) -> Event { + Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers } +} + +/// Drags across the middle of a document window's canvas. +fn drag_in_document_window(app: &mut PhotocraftApp) { + let mut w = DocumentWindow::new(app); + let start = w.screen.center(); + w.frame(app, vec![]); + w.frame(app, vec![Event::PointerMoved(start)]); + w.frame(app, vec![button(start, true, Modifiers::NONE)]); + let mut at = start; + for _ in 0..6 { + at += vec2(15.0, 10.0); + w.frame(app, vec![Event::PointerMoved(at)]); + } + w.frame(app, vec![button(at, false, Modifiers::NONE)]); + w.frame(app, vec![]); +} + +#[test] +fn a_move_drag_in_a_document_window_adds_a_history_step_without_a_dialog() { + // The control: the same drag does reach the Move tool when no dialog is open. + let mut app = app_with_a_layer(); + let before = history(&app); + drag_in_document_window(&mut app); + let after = history(&app); + assert_eq!(after.len(), before.len() + 1, "{after:?}"); + assert_eq!(after.last().map(String::as_str), Some("Move")); +} + +#[test] +fn a_document_window_canvas_takes_no_tool_drag_under_a_dialog() { + let mut app = app_with_a_layer(); + crate::filter_dialog::open(&mut app, "image.rotation.arbitrary").unwrap(); + assert!(!app.ui.dialogs.is_empty()); + let before = history(&app); + let revision = app.session.active().unwrap().revision; + drag_in_document_window(&mut app); + assert_eq!(history(&app), before, "no History step under the dialog"); + assert_eq!(app.session.active().unwrap().revision, revision, "the document untouched"); + assert!(app.drag.is_none(), "no tool gesture left open"); +} + +/// Text being typed in a paragraph box over the document's centre, with the Type tool. +fn app_typing(dialog: bool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + app.run("type.create", json!({"text": "Hello", "size": 24, "x": 20, "y": 40, "box": [20, 20, 160, 110]})).unwrap(); + app.sync_views(); + app.ui.extras.rulers = false; + app.ui.tool = Tool::Type; + if dialog { + crate::filter_dialog::open(&mut app, "image.rotation.arbitrary").unwrap(); + assert!(!app.ui.dialogs.is_empty()); + } + crate::type_tool::edit_active(&mut app).unwrap(); + assert!(app.ui.text_edit.is_some()); + app +} + +/// A ⌘-press on the text: the type transform reads it from the raw events, which a modal layer +/// doesn't block. Whether a transform started. +fn command_press_on_the_text(app: &mut PhotocraftApp) -> bool { + let command = Modifiers { command: true, ctrl: true, ..Modifiers::NONE }; + let mut w = DocumentWindow::new(app); + let at = w.screen.center(); + w.frame(app, vec![]); + w.frame(app, vec![Event::ModifiersChanged(command), Event::PointerMoved(at)]); + w.frame(app, vec![button(at, true, command)]); + app.ui.type_transform.is_some() +} + +#[test] +fn a_command_press_on_text_in_a_document_window_starts_a_type_transform_without_a_dialog() { + // The control: the press does reach the type transform when no dialog is open. + let mut app = app_typing(false); + assert!(command_press_on_the_text(&mut app)); +} + +#[test] +fn a_command_press_on_text_in_a_document_window_starts_no_type_transform_under_a_dialog() { + let mut app = app_typing(true); + assert!(!command_press_on_the_text(&mut app), "no type transform under the dialog"); +} diff --git a/crates/ui-egui/src/canvas/gesture.rs b/crates/ui-egui/src/canvas/gesture.rs index 1b82804e3d..155ae25ac8 100644 --- a/crates/ui-egui/src/canvas/gesture.rs +++ b/crates/ui-egui/src/canvas/gesture.rs @@ -6,6 +6,10 @@ use super::strokes::{ use super::textures::shown_as_document; use super::{PhotocraftApp, Tool, json}; +#[cfg(test)] +#[path = "rectangle_click_in_shape_tests.rs"] +mod rectangle_click_in_shape_tests; + pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) { finish(app, d, None); } @@ -110,8 +114,10 @@ fn finish(app: &mut PhotocraftApp, mut d: Drag, click: Option) { // mode a click adds nothing: the dialog makes a shape layer, which Path mode never draws, // and the click's few pixels of travel would add a speck of a subpath to the work path. t if crate::vector_ui::is_shape_tool(t) - && crate::shape_dialog::is_click(d.start, &d.points, app.point_zoom()) - && (crate::vector_ui::draws_path(&app.ui.tool_options) || crate::shape_dialog::open(app, t, d.start).is_some()) => {} + && crate::shape_dialog::is_tool_click(t, &app.ui.tool_options, d.start, &d.points, app.point_zoom()) + && (crate::vector_ui::draws_path(&app.ui.tool_options) + || crate::shape_dialog::click_inside_active_rectangle(app, t, d.start) + || crate::shape_dialog::open(app, t, d.start).is_some()) => {} t if crate::vector_ui::is_shape_tool(t) => crate::vector_ui::finish_shape(app, t, d.start, [end[0], end[1]], d.live), Tool::PathSelection => crate::vector_ui::path_selection_finish(app, d.start, [end[0], end[1]]), Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => crate::type_tool::pointer_up(app, d.start, [end[0], end[1]]), @@ -167,7 +173,7 @@ fn finish(app: &mut PhotocraftApp, mut d: Drag, click: Option) { if made.is_ok() && d.tool != Tool::Lasso { crate::retouch_ui::patch_hint(app); } - } else if app.session.is_enabled("select.deselect") { + } else if (d.tool != Tool::Lasso || selection_mode(app, d.modifiers) == "replace") && app.session.is_enabled("select.deselect") { let _ = app.run("select.deselect", json!({})); } } diff --git a/crates/ui-egui/src/canvas/move_ui.rs b/crates/ui-egui/src/canvas/move_ui.rs index f57d71788e..8da97c0a82 100644 --- a/crates/ui-egui/src/canvas/move_ui.rs +++ b/crates/ui-egui/src/canvas/move_ui.rs @@ -298,7 +298,7 @@ fn shape_reach(l: &photocraft_doc::Layer, canvas: Rect) -> Option { } /// `ids` and every layer inside them (groups move their contents). -fn with_descendants(doc: &Document, ids: &[LayerId]) -> Vec { +pub(crate) fn with_descendants(doc: &Document, ids: &[LayerId]) -> Vec { let walk = doc.walk(); let roots: Vec<_> = walk.iter().filter(|(_, _, l)| ids.contains(&l.id)).map(|(p, _, _)| p.as_slice()).collect(); walk.iter().filter(|(p, _, _)| roots.iter().any(|r| p.starts_with(r))).map(|(_, _, l)| l.id).collect() diff --git a/crates/ui-egui/src/canvas/paint_bucket_cursor_tests.rs b/crates/ui-egui/src/canvas/paint_bucket_cursor_tests.rs new file mode 100644 index 0000000000..cff285afc2 --- /dev/null +++ b/crates/ui-egui/src/canvas/paint_bucket_cursor_tests.rs @@ -0,0 +1,103 @@ +//! The Paint Bucket cursor (#12539): with Standard Other Cursors it is the bucket with a small +//! arrow at its top left, the hotspot on the arrow tip, and a click fills the pixel under that tip. +//! Precise Other Cursors and Caps Lock keep the crosshair; ⌥ and ⌘ keep the Eyedropper and Move +//! cursors. Tests drive the real canvas (`document_area`) and read the OS cursor bitmap it sets. + +use egui::{CursorIcon, Modifiers}; +use egui_kittest::Harness; +use serde_json::json; + +use super::remove_cursor_tests::{Cursor, cursor, harness, set_pref}; +use crate::PhotocraftApp; +use crate::state::Tool; + +/// The cursor with `mods` held over the canvas centre. +fn cursor_with(h: &mut Harness<'_, PhotocraftApp>, mods: Modifiers) -> Cursor { + let p = h.state().last_canvas_rect.center(); + h.event(egui::Event::ModifiersChanged(mods)); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(3); + cursor(h) +} + +fn pixel(app: &PhotocraftApp, x: i32, y: i32) -> [u8; 3] { + let st = app.session.active().unwrap(); + let c = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y); + [0, 1, 2].map(|i| (c[i] * 255.0).round() as u8) +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn the_standard_cursor_is_the_bucket_with_the_arrow_tip_on_the_hotspot() { + let h = harness(Tool::PaintBucket); + let (icon, image) = cursor(&h); + assert_eq!(icon, CursorIcon::Crosshair, "the OS bitmap keeps its visible fallback"); + let (size, [x, y], rgba) = image.expect("the Paint Bucket's OS cursor bitmap"); + assert_eq!([x, y], [1, 1], "the hotspot is the arrow tip at the bitmap's top left"); + let at = |x: u16, y: u16| { + let i = (usize::from(y) * usize::from(size[0]) + usize::from(x)) * 4; + [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] + }; + // The tip sits on the hotspot texel's centre, so that pixel is antialiased, not solid. + assert!(at(x, y)[3] > 128, "the tip itself is drawn: no open crosshair centre under the pointer"); + let body = at(x + 1, y + 4); + assert!(body[3] > 230 && body[0] < 40, "a black arrow runs down from the tip: {body:?}"); + let bucket = (0..size[1]).flat_map(|row| (0..size[0]).map(move |col| (col, row))).any(|(col, row)| { + let p = at(col, row); + col > x + 10 && row > y + 10 && p[0] > 200 && p[3] > 200 + }); + assert!(bucket, "the white bucket art sits below right of the arrow"); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn a_click_fills_the_pixel_under_the_arrow_tip() { + let mut h = harness(Tool::PaintBucket); + let p = h.state().last_canvas_rect.center(); + let (x, y) = crate::panels::info::hover_pixel(h.state()).expect("the pointer is over the image"); + // Black left of and above the pointer's pixel: a fill there stops at the edges, a fill one + // pixel off to the left or up would turn the black red. + let app = h.state_mut(); + for rect in [[0, 0, x, 300], [0, 0, 400, y]] { + app.run("select.rect", json!({"x": rect[0], "y": rect[1], "width": rect[2], "height": rect[3]})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap(); + } + app.run("select.deselect", json!({})).unwrap(); + app.run("tools.setColors", json!({"foreground": "#ff0000"})).unwrap(); + h.run_steps(2); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(2); + } + assert_eq!(pixel(h.state(), x, y), [255, 0, 0], "the pixel under the tip is filled"); + assert_eq!(pixel(h.state(), x - 1, y), [0, 0, 0], "the pixel left of it is not"); + assert_eq!(pixel(h.state(), x, y - 1), [0, 0, 0], "the pixel above it is not"); +} + +#[test] +fn precise_other_cursors_and_caps_lock_keep_the_crosshair() { + let mut h = harness(Tool::PaintBucket); + let standard = cursor(&h); + set_pref(&mut h, "cursors.other", json!("precise")); + let precise = cursor(&h); + assert_eq!(precise.0, CursorIcon::Crosshair, "Precise: the crosshair"); + assert_ne!(precise, standard, "Precise: not the bucket"); + set_pref(&mut h, "cursors.other", json!("standard")); + h.state_mut().caps_lock = true; + h.run_steps(2); + assert_eq!(cursor(&h), precise, "Caps Lock: the same crosshair"); +} + +#[test] +fn alt_and_command_keep_the_eyedropper_and_move_cursors() { + let mut bucket = harness(Tool::PaintBucket); + let standard = cursor(&bucket); + let eyedropper = cursor(&harness(Tool::Eyedropper)); + let alt = cursor_with(&mut bucket, Modifiers::ALT); + assert_eq!(alt, eyedropper, "⌥: the Eyedropper cursor"); + assert_ne!(alt, standard); + let mv = cursor_with(&mut harness(Tool::Move), Modifiers::NONE); + let command = cursor_with(&mut bucket, Modifiers::COMMAND); + assert_eq!(command, mv, "⌘: the Move cursor"); + assert_ne!(command, standard); +} diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index 7783aa4d20..c611df6f40 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -40,14 +40,27 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) { // A tool seen for the first time takes what the brush has, at Photoshop's smoothing, but // in Normal mode: each tool's Mode starts at Normal, so a Multiply Brush doesn't make the // first Pattern Stamp stroke multiply (or give Healing a mode its menu doesn't have). - // The Art History Brush also starts at full opacity (#10263): its Opacity is its own. - // The Background Eraser, the Healing Brush, the Burn and Dodge tools and the Clone Stamp - // start with their own measured tips instead, as the whole brush Reset Tool gives them - // (#11911, #12099, #12671, #12684, #12601). - None if matches!(tool, Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::CloneStamp) => fresh_brush(tool, ¤t), + // The Art History Brush also starts at full opacity (#10263), and the Pattern Stamp at full + // opacity and flow (#12616): those fields are their own. + // The Background Eraser, the Healing Brush, the Burn, Dodge and Sponge tools, the Clone + // Stamp and the Smudge tool start with their own measured tips instead, as the whole brush + // Reset Tool gives them (#11911, #12099, #12671, #12684, #13029, #12601, #12964). + None if matches!(tool, Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp | Tool::Smudge) => { + fresh_brush(tool, ¤t) + } + // The Pencil starts with its own 1 px hard round (#12200) regardless of the Brush, keeping + // the outgoing opacity. + None if tool == Tool::Pencil => BrushSettings { opacity: current.opacity, ..fresh_brush(tool, ¤t) }, None => { - let opacity = if tool == Tool::ArtHistoryBrush { BrushSettings::default().opacity } else { current.opacity }; - BrushSettings { smoothing: first_smoothing(), mode: photocraft_color::BlendMode::Normal, opacity, ..current } + let fresh = BrushSettings::default(); + let (opacity, flow) = match tool { + Tool::ArtHistoryBrush => (fresh.opacity, current.flow), + Tool::PatternStamp => (fresh.opacity, fresh.flow), + _ => (current.opacity, current.flow), + }; + // The Remove tool starts at its measured 19 px; the rest is the current brush (#12548). + let size = if tool == Tool::Remove { REMOVE_TOOL_SIZE } else { current.size }; + BrushSettings { smoothing: first_smoothing(), mode: photocraft_color::BlendMode::Normal, opacity, flow, size, ..current } } }; // The picked preset was the outgoing tool's brush: forget it, so Update Brush can't overwrite @@ -78,28 +91,41 @@ const BRUSH_TOOL_TIP: (f32, f32, f32) = (13.0, 0.0, 0.25); const BACKGROUND_ERASER_TIP: (f32, f32, f32) = (13.0, 1.0, 0.25); /// The Healing Brush's tip after Reset Tool (#12099): a 19 px hard round at 25 % spacing. const HEALING_BRUSH_TIP: (f32, f32, f32) = (19.0, 1.0, 0.25); -/// The Burn and Dodge tools' tip after Reset Tool (#12671, #12684): a 65 px soft round at 25 % -/// spacing. +/// The Pencil tool's starting and Reset Tool tip, as the reference measures it (#12200): size, +/// hardness and spacing of a 1 px hard round at 25 % spacing. +const PENCIL_TOOL_TIP: (f32, f32, f32) = (1.0, 1.0, 0.25); +/// The Burn, Dodge and Sponge tools' tip after Reset Tool (#12671, #12684, #13029): a 65 px soft +/// round at 25 % spacing. const TONING_TOOL_TIP: (f32, f32, f32) = (65.0, 0.0, 0.25); /// The Clone Stamp's tip after Reset Tool (#12601): a 21 px soft round at 25 % spacing. const CLONE_STAMP_TIP: (f32, f32, f32) = (21.0, 0.0, 0.25); +/// The Remove tool's size after Reset Tool (#12548): 19 px. Its hardness and spacing are not +/// measured, so they stay the default brush's. +const REMOVE_TOOL_SIZE: f32 = 19.0; +/// The Smudge tool's tip after Reset Tool (#12964): a 13 px soft round at 25 % spacing. +const SMUDGE_TOOL_TIP: (f32, f32, f32) = (13.0, 0.0, 0.25); /// `tool`'s brush as it starts out (Reset Tool, #2825): the default brush at Photoshop's /// smoothing, with the session's own fields of `current`. The Brush tool's tip is /// [`BRUSH_TOOL_TIP`], the Background Eraser's [`BACKGROUND_ERASER_TIP`], the Healing Brush's -/// [`HEALING_BRUSH_TIP`], the Burn and Dodge tools' [`TONING_TOOL_TIP`], the Clone Stamp's -/// [`CLONE_STAMP_TIP`] with no smoothing; the other tools keep the default tip. +/// [`HEALING_BRUSH_TIP`], the Burn, Dodge and Sponge tools' [`TONING_TOOL_TIP`], the Clone Stamp's +/// [`CLONE_STAMP_TIP`] with no smoothing, the Remove tool's size [`REMOVE_TOOL_SIZE`], the Smudge +/// tool's [`SMUDGE_TOOL_TIP`] and the Pencil's [`PENCIL_TOOL_TIP`]; the other tools keep the +/// default tip. pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings { let mut brush = BrushSettings { smoothing: first_smoothing(), ..BrushSettings::default() }; match tool { Tool::Brush => (brush.size, brush.hardness, brush.spacing) = BRUSH_TOOL_TIP, Tool::BackgroundEraser => (brush.size, brush.hardness, brush.spacing) = BACKGROUND_ERASER_TIP, Tool::Healing => (brush.size, brush.hardness, brush.spacing) = HEALING_BRUSH_TIP, - Tool::Burn | Tool::Dodge => (brush.size, brush.hardness, brush.spacing) = TONING_TOOL_TIP, + Tool::Pencil => (brush.size, brush.hardness, brush.spacing) = PENCIL_TOOL_TIP, + Tool::Burn | Tool::Dodge | Tool::Sponge => (brush.size, brush.hardness, brush.spacing) = TONING_TOOL_TIP, + Tool::Smudge => (brush.size, brush.hardness, brush.spacing) = SMUDGE_TOOL_TIP, Tool::CloneStamp => { (brush.size, brush.hardness, brush.spacing) = CLONE_STAMP_TIP; brush.smoothing.amount = 0.0; } + Tool::Remove => brush.size = REMOVE_TOOL_SIZE, _ => {} } session_fields(current, &brush) @@ -341,8 +367,9 @@ pub fn track_right_press_view(response: &Response, view: &crate::state::View, fl /// Route the canvas response's buttons: the left one drives the tool; the right one resizes the /// brush with Alt held (#297), erases (Erase preference) or opens the Brush Preset picker. Arms -/// `secondary_erase` or `brush_resize_armed` for this frame's `Down`. -pub fn canvas_buttons(app: &mut PhotocraftApp, response: &Response, tool: Tool) -> Buttons { +/// `secondary_erase` or `brush_resize_armed` for this frame's `Down`. `xf` is this canvas's view, +/// one cell of a Window › Arrange layout: it places a right-click on the image or the pasteboard. +pub fn canvas_buttons(app: &mut PhotocraftApp, response: &Response, tool: Tool, xf: &crate::canvas::ViewXform) -> Buttons { if crate::brush_mode_menu::blocks_canvas(app, &response.ctx) { app.secondary_erase = false; return Buttons::default(); @@ -371,12 +398,13 @@ pub fn canvas_buttons(app: &mut PhotocraftApp, response: &Response, tool: Tool) // ⌘/Ctrl+right-click lists the layers under the pointer instead (layer_pick_ui.rs, #307). let layer_menu = crate::layer_pick_ui::is_gesture(tool, mods); // Decided by the modifiers held when the button went down, not by those of the release frame that reports the click. - let mode_menu = - crate::brush_mode_menu::opens_on(app, tool, crate::workspace_ui::sticky_mods(app, crate::brush_mode_menu::gesture_mods(&response.ctx, mods))); + let menu_mods = crate::workspace_ui::sticky_mods(app, crate::brush_mode_menu::gesture_mods(&response.ctx, mods)); + let menu_at = right_click_at(response); + let mode_menu = crate::brush_mode_menu::opens_on(app, tool, menu_mods, menu_at.map(|p| xf.to_doc(p))); if mode_menu && !resizing && app.drag.is_none() { app.secondary_erase = false; - if let Some(p) = right_click_at(response) { - crate::brush_mode_menu::open(app, &response.ctx, [p.x, p.y]); + if let Some(p) = menu_at { + crate::brush_mode_menu::open(app, &response.ctx, [p.x, p.y], menu_mods); } return Buttons { started: response.drag_started_by(PointerButton::Primary), @@ -449,10 +477,11 @@ pub fn pointer_secondary(app: &mut PhotocraftApp, ctx: &egui::Context, down: boo app.brush_resize_armed = down && app.drag.is_none(); return true; } - if crate::brush_mode_menu::opens_on(app, tool, mods) && app.drag.is_none() && app.brush_resize.is_none() { + // The control channel opens the pasteboard menu before it gets here (`secondary_canvas_menu_took`). + if crate::brush_mode_menu::opens_on(app, tool, mods, None) && app.drag.is_none() && app.brush_resize.is_none() { app.secondary_erase = false; if down { - crate::brush_mode_menu::open(app, ctx, at); + crate::brush_mode_menu::open(app, ctx, at, mods); } return false; } @@ -553,3 +582,7 @@ pub fn show_picker(app: &mut PhotocraftApp, ctx: &egui::Context) { #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "../pencil_reset_defaults_tests.rs"] +mod pencil_reset_defaults_tests; diff --git a/crates/ui-egui/src/canvas/perspective_crop_cursor_tests.rs b/crates/ui-egui/src/canvas/perspective_crop_cursor_tests.rs new file mode 100644 index 0000000000..f21b29ca49 --- /dev/null +++ b/crates/ui-egui/src/canvas/perspective_crop_cursor_tests.rs @@ -0,0 +1,211 @@ +//! #11974: the Perspective Crop's hover cursor says what a press does. With no quad a small +//! crosshair with the tool's icon (hotspot on the crosshair's centre), our own solid black +//! arrow inside the quad, over a corner the hollow arrowhead; outside the quad (no press there +//! yet) the usual crosshair. + +use egui::epaint::ColorMode; +use egui::{Color32, CursorIcon, Pos2, Shape, pos2}; + +use crate::PhotocraftApp; +use crate::canvas::ToolEvent; +use crate::perspective_crop_ui::{Drag, Zone, cursor, pointer}; +use crate::state::Tool; + +const QUAD: [[f64; 2]; 4] = [[40.0, 30.0], [160.0, 40.0], [150.0, 120.0], [50.0, 110.0]]; + +/// A 200 × 150 document with the Perspective Crop tool. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", serde_json::json!({"width": 200, "height": 150})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::PerspectiveCrop; + app +} + +/// The drag a press at `p` starts, with the quad left as it was. +fn press(app: &mut PhotocraftApp, p: [f64; 2]) -> Option { + let quad = app.ui.perspective_crop; + assert!(pointer(app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, egui::Modifiers::NONE)); + let drag = app.pcrop.drag.take(); + app.ui.perspective_crop = quad; + drag +} + +/// The zone a drag acts on: the cursor has to show the same. +fn acts_on(drag: Option) -> Zone { + match drag { + Some(Drag::New { .. }) => Zone::Idle, + Some(Drag::Corner { index, .. }) => Zone::Corner(index), + Some(Drag::Move { .. }) => Zone::Inside, + None => Zone::Outside, + } +} + +#[test] +fn every_point_shows_what_a_press_there_does() { + let mut app = app(); + let mut seen = Vec::new(); + for quad in [None, Some(QUAD)] { + app.ui.perspective_crop = quad; + for y in (0..=150).step_by(3) { + for x in (0..=200).step_by(3) { + let p = [f64::from(x), f64::from(y)]; + let shown = cursor(&app, p).expect("a cursor over the canvas"); + assert_eq!(shown, acts_on(press(&mut app, p)), "at {p:?} with {quad:?}"); + if !seen.contains(&shown) { + seen.push(shown); + } + } + } + } + for z in [Zone::Idle, Zone::Inside, Zone::Outside, Zone::Corner(0), Zone::Corner(1), Zone::Corner(2), Zone::Corner(3)] { + assert!(seen.contains(&z), "{z:?} was hovered"); + } +} + +#[test] +fn the_corner_tolerance_is_the_press_tolerance() { + let mut app = app(); + app.ui.perspective_crop = Some(QUAD); + let tol = crate::distort_ui::tolerance(&app); + // Just inside the tolerance, inside the quad: the corner wins, as for a press. + let near = [QUAD[2][0] - tol * 0.6, QUAD[2][1] - tol * 0.6]; + assert_eq!(cursor(&app, near), Some(Zone::Corner(2))); + assert_eq!(acts_on(press(&mut app, near)), Zone::Corner(2)); + // Just past it, inside the quad: the arrow, and a press moves the quad. + let past = [QUAD[2][0] - tol * 1.2, QUAD[2][1] - tol * 1.2]; + assert_eq!(cursor(&app, past), Some(Zone::Inside)); + assert_eq!(acts_on(press(&mut app, past)), Zone::Inside); +} + +#[test] +fn a_held_drag_keeps_its_cursor() { + // Not measured: as the Crop tool, the cursor stays the drag's while the button is held. + let mut app = app(); + app.ui.perspective_crop = Some(QUAD); + assert!(pointer(&mut app, ToolEvent::Down { x: 100.0, y: 75.0, pressure: 1.0 }, egui::Modifiers::NONE)); + assert!(pointer(&mut app, ToolEvent::Move { x: 190.0, y: 140.0, pressure: 1.0 }, egui::Modifiers::NONE)); + assert_eq!(cursor(&app, [5.0, 5.0]), Some(Zone::Inside), "moving the quad"); + assert!(pointer(&mut app, ToolEvent::Up { x: 190.0, y: 140.0 }, egui::Modifiers::NONE)); + let corner = app.ui.perspective_crop.unwrap()[0]; + assert!(pointer(&mut app, ToolEvent::Down { x: corner[0], y: corner[1], pressure: 1.0 }, egui::Modifiers::NONE)); + assert_eq!(cursor(&app, [100.0, 75.0]), Some(Zone::Corner(0)), "dragging a corner"); +} + +#[test] +fn only_the_perspective_crop_tool_with_a_document() { + let mut app = app(); + app.ui.tool = Tool::Crop; + assert_eq!(cursor(&app, [100.0, 75.0]), None); + app.ui.tool = Tool::PerspectiveCrop; + assert_eq!(cursor(&app, [f64::NAN, 75.0]), None); + app.run("file.close", serde_json::json!({})).unwrap(); + assert_eq!(cursor(&app, [100.0, 75.0]), None); +} + +/// A cursor bitmap's hotspot and size. +type Bitmap = ([u16; 2], [u16; 2]); + +/// What the cursor for a zone is made of. +struct Drawn { + /// The OS cursor. + icon: CursorIcon, + /// The OS cursor bitmap's hotspot and size, if one is set. + bitmap: Option, + /// Everything painted on top (the badge, the arrowhead, the arrow), flattened. + shapes: Vec, +} + +impl Drawn { + /// The positions of the fully opaque black vertices: a solid black fill (the arrowhead's dark + /// outline is translucent, its fill white). + fn black_fill(&self) -> Vec { + let mut at = Vec::new(); + for shape in &self.shapes { + if let Shape::Mesh(mesh) = shape { + at.extend(mesh.vertices.iter().filter(|v| v.color == Color32::BLACK).map(|v| v.pos)); + } + } + at + } + + /// The closed light outlines. + fn light_outlines(&self) -> Vec<&egui::epaint::PathShape> { + let light = |c: Color32| c.r() > 200 && c.g() > 200 && c.b() > 200 && c.a() > 128; + self.shapes + .iter() + .filter_map(|s| match s { + Shape::Path(p) if p.closed && p.stroke.width > 0.0 && matches!(p.stroke.color, ColorMode::Solid(c) if light(c)) => Some(p), + _ => None, + }) + .collect() + } +} + +fn flatten(shape: Shape, out: &mut Vec) { + match shape { + Shape::Vec(inner) => inner.into_iter().for_each(|s| flatten(s, out)), + s => out.push(s), + } +} + +/// The cursor drawn for `zone` at `at`. +fn drawn(zone: Zone, at: Pos2) -> Drawn { + let ctx = egui::Context::default(); + ctx.add_plugin(crate::tool_cursor::CursorLifecycle); + egui_extras::install_image_loaders(&ctx); + let run = || { + let mut out = ctx.run_ui(Default::default(), |ui| { + let icon = crate::tool_cursor::perspective_crop(ui.painter(), zone, at); + ui.ctx().set_cursor_icon(icon); + }); + out.textures_delta.clear(); + out + }; + // egui's first Area pass measures its content and paints nothing; the icon loads meanwhile. + run(); + run(); + let out = run(); + let mut shapes = Vec::new(); + for clipped in out.shapes { + flatten(clipped.shape, &mut shapes); + } + Drawn { icon: out.platform_output.cursor_icon, bitmap: out.platform_output.cursor_image.map(|i| (i.hotspot, i.size)), shapes } +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn the_zones_draw_distinct_cursors_with_their_hotspots() { + let at = pos2(120.0, 90.0); + let idle = drawn(Zone::Idle, at); + let inside = drawn(Zone::Inside, at); + let corner = drawn(Zone::Corner(1), at); + // No quad: the small crosshair as the OS bitmap, centred on the point, with the + // tool's icon painted beside it. (`CursorLifecycle` leaves the OS crosshair under a bitmap, + // for a backend that can't show one.) + assert_eq!(idle.icon, CursorIcon::Crosshair); + // The bitmap is padded for its outline: the hotspot is its centre, where the arms cross. + let (hot, size) = idle.bitmap.expect("the crosshair bitmap"); + assert_eq!(hot[0], hot[1]); + assert_eq!(hot[0] * 2 + 1, size[0], "the crosshair's centre is the hotspot: {hot:?} in {size:?}"); + assert!(!idle.shapes.is_empty(), "the tool badge"); + // Inside: our own solid black arrow, not the OS one (which is white on Windows and follows the + // theme on Linux), with the OS cursor hidden under it. + assert_eq!(inside.icon, CursorIcon::None, "the OS arrow is not used"); + assert_eq!(inside.bitmap, None, "no crosshair bitmap"); + let fill = inside.black_fill(); + assert!(!fill.is_empty(), "the arrow is filled solid black"); + let (min, max) = fill.iter().fold((pos2(f32::MAX, f32::MAX), pos2(f32::MIN, f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))); + assert_eq!(min, at, "the arrow's tip is the hotspot, on the point"); + assert!(max.x - min.x >= 9.0 && max.y - min.y >= 15.0, "an arrow of the usual size, not a dot: {min:?} to {max:?}"); + let outlines = inside.light_outlines(); + assert!(!outlines.is_empty(), "a thin light outline so it reads on a dark image"); + assert!(outlines.iter().all(|o| o.stroke.width <= 2.0), "thin"); + assert!(outlines.iter().any(|o| o.points.contains(&at)), "the outline passes through the tip too"); + // Corner: the hollow arrowhead, painted with its tip on the point. + assert_eq!(corner.icon, CursorIcon::None); + assert_eq!(corner.bitmap, None, "no crosshair bitmap"); + assert!(!corner.shapes.is_empty(), "the arrowhead"); + assert!(corner.black_fill().is_empty(), "the corner arrowhead is hollow white, not the solid arrow"); + assert!(idle.black_fill().is_empty()); +} diff --git a/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs new file mode 100644 index 0000000000..ec3c180e7f --- /dev/null +++ b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs @@ -0,0 +1,121 @@ +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; +use crate::{PhotocraftApp, Services}; +use serde_json::json; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.ui.tool = Tool::Rectangle; + app.ui.extras.snap = false; + app.sync_views(); + app +} + +fn shape(app: &mut PhotocraftApp, kind: &str, radius: f64) { + let radii = [radius; 4]; + app.run("shape.create", json!({"kind": kind, "rect": [400, 300, 200, 100], "radii": radii, "fill": "#ff0000"})).unwrap(); +} + +fn gesture(app: &mut PhotocraftApp, [x, y]: [f64; 2], [end_x, end_y]: [f64; 2]) { + let mods = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: end_x, y: end_y, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: end_x, y: end_y }, mods); +} + +fn state(app: &PhotocraftApp) -> (usize, usize) { + let active = app.session.active().unwrap(); + (active.doc.layer_count(), active.history.past_len()) +} + +fn assert_create_rectangle(app: &PhotocraftApp) { + let [dialog] = app.ui.dialogs.as_slice() else { panic!("expected one Create Rectangle dialog") }; + assert_eq!(dialog.fields["__label"], "Create Rectangle"); + assert_eq!(dialog.fields["width"], 100.0); + assert_eq!(dialog.fields["height"], 100.0); + assert_eq!(dialog.fields["fromCenter"], false); +} + +#[test] +fn inside_the_active_live_rectangle_is_a_no_op() { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let before = state(&app); + let center = [500.0, 350.0]; + for end in [center, [501.0, 350.0]] { + gesture(&mut app, center, end); + assert!(app.ui.dialogs.is_empty()); + assert_eq!(state(&app), before); + } +} + +#[test] +fn outside_the_rectangle_and_on_the_pasteboard_open_create_rectangle() { + for point in [[100.0, 500.0], [-20.0, 500.0]] { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let before = state(&app); + gesture(&mut app, point, point); + assert_create_rectangle(&app); + assert_eq!(state(&app), before); + } +} + +#[test] +fn a_pixel_layer_or_non_rectangle_shape_leaves_the_dialog_available() { + let point = [500.0, 350.0]; + for other_shape in [false, true] { + let mut app = app(); + shape(&mut app, "rect", 0.0); + if other_shape { + shape(&mut app, "ellipse", 0.0); + } else { + app.run("layer.new.layer", json!({"name": "Pixels"})).unwrap(); + } + let before = state(&app); + gesture(&mut app, point, point); + assert_create_rectangle(&app); + assert_eq!(state(&app), before); + } +} + +#[test] +fn rounded_corners_use_the_outline() { + let mut app = app(); + shape(&mut app, "roundedRect", 30.0); + let before = state(&app); + let center = [500.0, 350.0]; + gesture(&mut app, center, center); + assert!(app.ui.dialogs.is_empty()); + assert_eq!(state(&app), before); + let corner = [401.0, 301.0]; + super::finish_gesture(&mut app, super::Drag::new(Tool::Rectangle, corner, vec![[corner[0], corner[1], 1.0]], egui::Modifiers::NONE, false)); + assert_create_rectangle(&app); +} + +#[test] +fn other_modes_keep_their_click_behavior() { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let before = state(&app); + let center = [500.0, 350.0]; + app.ui.tool_options.shape_mode = "path".into(); + gesture(&mut app, center, center); + assert!(app.ui.dialogs.is_empty()); + assert!(app.session.active().unwrap().doc.work_path.is_none()); + app.ui.tool_options.shape_mode = "pixels".into(); + super::finish_gesture(&mut app, super::Drag::new(Tool::Rectangle, center, vec![[center[0], center[1], 1.0]], egui::Modifiers::NONE, false)); + assert_create_rectangle(&app); + assert_eq!(state(&app), before); +} + +#[test] +fn more_than_one_pixel_of_travel_still_draws_a_shape() { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let (layers, history) = state(&app); + gesture(&mut app, [500.0, 350.0], [502.0, 351.0]); + assert!(app.ui.dialogs.is_empty()); + assert_eq!(state(&app), (layers + 1, history + 1)); +} diff --git a/crates/ui-egui/src/canvas/remove_cursor_tests.rs b/crates/ui-egui/src/canvas/remove_cursor_tests.rs index cc4670e590..d0ddd71c83 100644 --- a/crates/ui-egui/src/canvas/remove_cursor_tests.rs +++ b/crates/ui-egui/src/canvas/remove_cursor_tests.rs @@ -11,10 +11,11 @@ use crate::PhotocraftApp; use crate::state::Tool; /// The canvas at 100 % with `tool` and a 40 px tip, the pointer over its centre. -fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> { +pub(super) fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); app.ui.tool = tool; + crate::paint_mouse::sync_tool_brush(&mut app); app.run("tools.setBrush", json!({"brush": {"size": 40, "hardness": 1.0}})).unwrap(); app.sync_views(); app.ui.extras.rulers = false; @@ -40,7 +41,7 @@ fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> { h } -fn set_pref(h: &mut Harness<'_, PhotocraftApp>, path: &str, value: serde_json::Value) { +pub(super) fn set_pref(h: &mut Harness<'_, PhotocraftApp>, path: &str, value: serde_json::Value) { h.state_mut().run("prefs.set", json!({"path": path, "value": value})).unwrap(); h.run_steps(2); } @@ -65,10 +66,10 @@ fn circle_drawn(h: &Harness<'_, PhotocraftApp>) -> bool { } /// A cursor icon, and its bitmap's size, hotspot and pixels. -type Cursor = (CursorIcon, Option<([u16; 2], [u16; 2], Vec)>); +pub(super) type Cursor = (CursorIcon, Option<([u16; 2], [u16; 2], Vec)>); /// The cursor the canvas asks for this frame. -fn cursor(h: &Harness<'_, PhotocraftApp>) -> Cursor { +pub(super) fn cursor(h: &Harness<'_, PhotocraftApp>) -> Cursor { let out = h.output(); let image = out.platform_output.cursor_image.as_ref().map(|i| (i.size, i.hotspot, i.rgba.to_vec())); (out.platform_output.cursor_icon, image) diff --git a/crates/ui-egui/src/canvas/sampler_cursor_tests.rs b/crates/ui-egui/src/canvas/sampler_cursor_tests.rs index 51dbf22520..52a255103a 100644 --- a/crates/ui-egui/src/canvas/sampler_cursor_tests.rs +++ b/crates/ui-egui/src/canvas/sampler_cursor_tests.rs @@ -65,27 +65,29 @@ fn hover_at(h: &mut Harness<'static, PhotocraftApp>, doc_x: f32, doc_y: f32, m: h.output().platform_output.cursor_icon } +/// The eyedropper's pipette: the OS bitmap where one uploads, else drawn (#12523). +fn pipette_shown(h: &Harness<'static, PhotocraftApp>) -> bool { + crate::tool_cursor::pipette_shown(&h.ctx, &h.output().platform_output) +} + #[test] fn off_sampler_no_key_or_shift_or_alt_shows_eyedropper_with_sampler_target() { let mut h = harness(); // 1. Off a sampler, no key: eyedropper with small sampler target at top-left. - let icon = hover_at(&mut h, 80.0, 80.0, Modifiers::NONE); - assert_eq!(icon, egui::CursorIcon::None, "pipette cursor replaces OS pointer"); - assert!(cursor_area_visible(&h, "pc-icon-cursor"), "pipette icon is drawn"); + hover_at(&mut h, 80.0, 80.0, Modifiers::NONE); + assert!(pipette_shown(&h), "pipette cursor replaces OS pointer"); assert!(cursor_area_visible(&h, "pc-sampler-badge"), "sampler target at top-left is drawn"); assert!(!cursor_badge_visible(&h, "sampler") && !cursor_badge_visible(&h, "scissors"), "arrow badge is not drawn off sampler"); // 2. Off a sampler, Shift held: still eyedropper with sampler target. - let icon_shift = hover_at(&mut h, 80.0, 80.0, Modifiers::SHIFT); - assert_eq!(icon_shift, egui::CursorIcon::None); - assert!(cursor_area_visible(&h, "pc-icon-cursor")); + hover_at(&mut h, 80.0, 80.0, Modifiers::SHIFT); + assert!(pipette_shown(&h)); assert!(cursor_area_visible(&h, "pc-sampler-badge")); // 3. Off a sampler, Alt held: still eyedropper with sampler target. - let icon_alt = hover_at(&mut h, 80.0, 80.0, Modifiers::ALT); - assert_eq!(icon_alt, egui::CursorIcon::None); - assert!(cursor_area_visible(&h, "pc-icon-cursor")); + hover_at(&mut h, 80.0, 80.0, Modifiers::ALT); + assert!(pipette_shown(&h)); assert!(cursor_area_visible(&h, "pc-sampler-badge")); } @@ -96,7 +98,7 @@ fn off_sampler_precise_other_cursors_shows_crosshair() { let icon = hover_at(&mut h, 80.0, 80.0, Modifiers::NONE); assert_eq!(icon, egui::CursorIcon::Crosshair, "Precise Other Cursors shows crosshair off sampler"); - assert!(!cursor_area_visible(&h, "pc-icon-cursor"), "no pipette icon with precise cursor"); + assert!(!pipette_shown(&h), "no pipette with precise cursor"); assert!(!cursor_area_visible(&h, "pc-sampler-badge"), "no sampler badge with precise cursor"); } @@ -111,7 +113,7 @@ fn over_sampler_shows_arrow_with_sampler_target_and_alt_shows_scissors() { assert_eq!(icon, egui::CursorIcon::Default, "over sampler uses standard arrow pointer"); assert!(cursor_badge_visible(&h, "sampler"), "sampler target badge is drawn"); assert!(!cursor_badge_visible(&h, "scissors"), "scissors badge is not drawn without Alt"); - assert!(!cursor_area_visible(&h, "pc-icon-cursor"), "no pipette icon over sampler"); + assert!(!pipette_shown(&h), "no pipette over sampler"); // Even with Precise Other Cursors, over a sampler is the arrow cursor. h.state_mut().run("prefs.set", json!({"values": {"cursors.other": "precise"}})).unwrap(); @@ -159,9 +161,9 @@ fn cursor_follows_sampler_hit_test_tolerance() { assert!(cursor_badge_visible(&h, "sampler")); assert!(!cursor_badge_visible(&h, "scissors")); - // Outside hit square (dx = 8.0 > 7.0): off sampler -> CursorIcon::None (eyedropper). - let icon_out = hover_at(&mut h, 158.0, 150.0, Modifiers::NONE); - assert_eq!(icon_out, egui::CursorIcon::None, "dx = 8 px is outside tolerance"); + // Outside hit square (dx = 8.0 > 7.0): off sampler -> the eyedropper's pipette. + hover_at(&mut h, 158.0, 150.0, Modifiers::NONE); + assert!(pipette_shown(&h), "dx = 8 px is outside tolerance"); assert!(cursor_area_visible(&h, "pc-sampler-badge")); // A press at dx = 6 grabs the existing sampler. @@ -180,3 +182,40 @@ fn cursor_follows_sampler_hit_test_tolerance() { assert_eq!(samplers.len(), 1, "dragging within tolerance moved the existing sampler"); assert!((samplers[0][0] - 170.0).abs() < 1.0, "moved to 170"); } + +#[test] +fn dragging_a_sampler_past_its_tolerance_keeps_the_sampler_cursor_until_release() { + // #13063: the stored point stays where it was until release, so the hit test alone would show + // the placement eyedropper once the pointer leaves the 7 px tolerance mid-drag. + let mut h = harness(); + h.state_mut().run("view.colorSamplers.add", json!({"x": 150.0, "y": 150.0})).unwrap(); + + let p = screen(&h, 150.0, 150.0); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + let q = screen(&h, 200.0, 150.0); + h.event(egui::Event::PointerMoved(q)); + h.run_steps(2); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "the drag keeps the arrow pointer"); + assert!(cursor_badge_visible(&h, "sampler"), "the drag keeps the sampler target badge"); + assert!(!pipette_shown(&h) && !cursor_area_visible(&h, "pc-sampler-badge"), "no placement eyedropper mid-drag"); + + // Alt removes only on the press; the release still moves the point, so no scissors mid-drag. + h.event(egui::Event::ModifiersChanged(Modifiers::ALT)); + h.run_steps(2); + assert!(cursor_badge_visible(&h, "sampler"), "Alt mid-drag keeps the sampler target"); + assert!(!cursor_badge_visible(&h, "scissors"), "Alt mid-drag shows no scissors"); + h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + + h.event(egui::Event::PointerButton { pos: q, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + let samplers = h.state().session.active().unwrap().color_samplers.clone(); + assert!((samplers[0][0] - 200.0).abs() < 1.0, "the release moved the sampler to 200"); + + // After release, off a sampler is the placement eyedropper again. + hover_at(&mut h, 100.0, 100.0, Modifiers::NONE); + assert!(pipette_shown(&h) && cursor_area_visible(&h, "pc-sampler-badge"), "the placement eyedropper returns after release"); + assert!(!cursor_badge_visible(&h, "sampler")); +} diff --git a/crates/ui-egui/src/canvas/snap_ui.rs b/crates/ui-egui/src/canvas/snap_ui.rs index f1a8917b63..e0364d50c3 100644 --- a/crates/ui-egui/src/canvas/snap_ui.rs +++ b/crates/ui-egui/src/canvas/snap_ui.rs @@ -8,6 +8,7 @@ use egui::{Color32, Stroke, pos2}; use photocraft_doc::LayerId; +use photocraft_engine::layer_multi_cmds::move_targets; use photocraft_engine::snap::{SnapKind, SnapLine, SnapOptions, SnapTargets, layer_rect, union}; use crate::PhotocraftApp; @@ -104,7 +105,24 @@ fn moving_rect(app: &PhotocraftApp, tool: Tool) -> Option<[f64; 4]> { if crate::move_ui::moves_selected_pixels_with(app, tool) { return selection_rect(app); } - union(st.selected_layers().into_iter().filter_map(|id| layer_rect(&st.doc, id))) + // What moves, not what is selected: a group carries its layers and linked layers go along. + union(move_targets(&st.doc, &st.selected_layers()).into_iter().filter_map(|id| tree_rect(&st.doc, id))) +} + +/// The bounds of layer `id` as the Move tool moves and snaps it. `snap::layer_rect` skips groups, +/// which hold no pixels of their own: a group is the layers in it, whole even with a selection +/// (it moves them whole, so clipping its pixel layers to the selection would frame less than +/// moves). An artboard is its board, as the snap targets take it, since the whole board moves. +pub(crate) fn tree_rect(doc: &photocraft_doc::Document, id: LayerId) -> Option<[f64; 4]> { + let l = doc.layer(id)?; + let b = if let Some(a) = l.artboard() { + a.rect + } else if l.is_group() { + photocraft_engine::transform_cmds::transform_bounds(doc, l) + } else { + return layer_rect(doc, id); + }; + (!b.is_empty()).then(|| [b.x0, b.y0, b.x1, b.y1].map(f64::from)) } /// The bounds of the pixels a selection moves, where they are shown: its floating piece's outline @@ -231,7 +249,17 @@ fn begin(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) { } else if tool == Tool::Move && crate::rulers::guide_at(app, p[0], p[1]).is_some() { Some((Gesture::Guide, Vec::new())) } else if tool == Tool::Move || moves_layer { - let exclude = app.session.active().map(|s| s.selected_layers()).unwrap_or_default(); + // The targets and everything inside them stay out of the snap targets: a moving group + // must not snap to its own layers' starting edges. Selected pixels float off the active + // layer alone, so its linked layers stay put and stay targets. + let pixels = crate::move_ui::moves_selected_pixels_with(app, tool); + let exclude = app.session.active().map_or_else(Vec::new, |s| { + let mut ids = s.selected_layers(); + if !pixels { + ids.extend(crate::move_ui::with_descendants(&s.doc, &move_targets(&s.doc, &ids))); + } + ids + }); moving_rect(app, tool).map(|rect| (Gesture::Move { rect }, exclude)) } else if straightens { // A straighten line (`crop_straighten::pointer` takes the press before the frame's drags) diff --git a/crates/ui-egui/src/canvas/snap_ui/tests.rs b/crates/ui-egui/src/canvas/snap_ui/tests.rs index bd809a30fc..710373987a 100644 --- a/crates/ui-egui/src/canvas/snap_ui/tests.rs +++ b/crates/ui-egui/src/canvas/snap_ui/tests.rs @@ -984,3 +984,103 @@ fn a_path_box_snaps_to_a_stationary_selection_edge() { crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 143.0, y: 110.0 }, m); assert_eq!(app.ui.transform.as_ref().unwrap().quad[0][0], 123.0); } + +/// A group of two layers (40..90 x 40..80 and 100..140 x 100..130) selected, as one layer. +fn app_with_group() -> PhotocraftApp { + let mut app = app_with_box(); + app.run("layer.new.layer", json!({"name": "second"})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 40, "height": 30})).unwrap(); + app.run("edit.fill", json!({"color": "#00ff00"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.run("layer.select", json!({"name": "mover"})).unwrap(); + app.run("layer.select", json!({"name": "second", "mode": "add"})).unwrap(); + app.run("layer.groupLayers", json!({"name": "G"})).unwrap(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_auto_select = false; + app +} + +fn child_bounds(app: &PhotocraftApp, name: &str) -> photocraft_geom::Rect { + let st = app.session.active().unwrap(); + let (_, _, l) = st.doc.walk().into_iter().find(|(_, _, l)| l.name == name).unwrap(); + l.surface().unwrap().content_bounds() +} + +/// A plain Move drag from `from` to `to`, released there. +fn move_drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + let m = egui::Modifiers::NONE; + crate::canvas::tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, m); + crate::canvas::tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, m); + crate::canvas::tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, m); +} + +/// #13418: a selected group had no Move gesture at all (`layer_rect` skips groups), so no blue box +/// and no Smart Guides; the box is the union of the layers it carries. +#[test] +fn dragging_a_group_frames_the_layers_inside_it() { + for bbox in [false, true] { + let mut app = app_with_group(); + app.session.edit_prefs(|p| p.interface.show_bounding_box_when_dragging_layer = bbox); + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, egui::Modifiers::NONE); + let gesture = app.prefs_rt.snap.as_ref().map(|s| s.gesture.clone()); + assert_eq!(gesture, Some(Gesture::Move { rect: [40.0, 40.0, 140.0, 130.0] }), "bounding box pref {bbox}"); + } +} + +/// #13418: a group moves its layers whole with a selection too, so the box isn't cut to the +/// selection as a pixel layer's is. +#[test] +fn a_group_box_is_not_cut_to_the_selection() { + let mut app = app_with_group(); + app.run("select.rect", json!({"x": 50, "y": 50, "width": 20, "height": 20})).unwrap(); + crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, egui::Modifiers::NONE); + let gesture = app.prefs_rt.snap.as_ref().map(|s| s.gesture.clone()); + assert_eq!(gesture, Some(Gesture::Move { rect: [40.0, 40.0, 140.0, 130.0] })); +} + +/// #13418: the group's edge snaps to another layer's edge as a single layer's does. +#[test] +fn a_dragged_group_snaps_to_other_layers() { + let mut app = app_with_group(); + // 72 px down puts the group's bottom edge (130 -> 202) 2 px past the target's top (200); no + // other edge or centre is within reach. + move_drag(&mut app, [60.0, 60.0], [80.0, 132.0]); + let (m, s) = (child_bounds(&app, "mover"), child_bounds(&app, "second")); + assert_eq!((m.x0, m.y0, s.y0), (60, 110, 170), "snapped 2 px up, the layers kept their spacing"); +} + +/// #13418: a moving group's layers are not snap targets, or it would snap to where it started. +#[test] +fn a_dragged_group_does_not_snap_to_its_own_layers() { + let mut app = app_with_group(); + // +46, +3: the group's left edge (86) is 4 px from where the mover's right edge was (90) and + // its top (43) 3 px from where the mover's top was (40); nothing else is in reach. + move_drag(&mut app, [60.0, 60.0], [106.0, 63.0]); + let b = child_bounds(&app, "mover"); + assert_eq!((b.x0, b.y0), (86, 43), "moved by the raw offset"); +} + +/// Selected pixels float off the active layer alone: a layer linked to it stays put, so the +/// pixels still snap to it. +#[test] +fn moving_selected_pixels_snaps_to_a_linked_layer() { + let mut app = app_with_box(); + app.run("layer.new.layer", json!({"name": "linked"})).unwrap(); + app.run("select.rect", json!({"x": 150, "y": 120, "width": 40, "height": 20})).unwrap(); + app.run("edit.fill", json!({"color": "#00ff00"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.run("layer.select", json!({"name": "mover"})).unwrap(); + app.run("layer.select", json!({"name": "linked", "mode": "add"})).unwrap(); + app.run("layer.linkLayers", json!({"linked": true})).unwrap(); + app.run("layer.select", json!({"name": "mover"})).unwrap(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_auto_select = false; + app.run("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap(); + // 37 px down puts the pixels' bottom edge (80 -> 117) 3 px above the linked layer's top (120); + // no other edge or centre is within reach. + move_drag(&mut app, [60.0, 60.0], [60.0, 97.0]); + app.run("select.drop", json!({})).unwrap(); + let sel = app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds().y0); + assert_eq!(sel, Some(80), "snapped to the linked layer's top"); + assert_eq!(child_bounds(&app, "linked").y0, 120, "the linked layer stayed put"); +} diff --git a/crates/ui-egui/src/canvas/strokes.rs b/crates/ui-egui/src/canvas/strokes.rs index e2eaab80cb..678cb9892f 100644 --- a/crates/ui-egui/src/canvas/strokes.rs +++ b/crates/ui-egui/src/canvas/strokes.rs @@ -7,6 +7,9 @@ use super::{Color32, DRect, PhotocraftApp, Pos2, Stroke, Tool, json, pos2}; pub(crate) struct ClonePreviewCache { pub(super) key: String, + // Reopening a file can retain its document id and revision; distinguish its new snapshot. + // A weak reference detects that replacement without keeping a closed image's pixels alive. + source_document: Option>, /// The brush a clipped overlay took its coverage from: a hardness or tip change redraws it. pub(super) brush: Option, /// The document area the texture covers. @@ -22,8 +25,8 @@ const CLONE_PREVIEW_MAX_PIXELS: u64 = 1800 * 1800; /// the source area it reads (`Mapping::source_rect`: the overlay's, mapped, with a 2 px apron). const CLONE_PREVIEW_MAX_SIDE: u32 = 1024; -/// The coverage of one dab of `brush` at `at`, as the brush engine paints it with opacity and flow -/// at full: its tip, angle, roundness and hardness (a soft tip reaches past its radius). The area +/// The coverage of one dab of `brush` at `at`, including flow, tip, angle, roundness and +/// hardness (a soft tip reaches past its radius). Stroke opacity is applied when drawing. The area /// it covers and its `width × height` coverage values in 0..1. A very large soft tip, or a source /// the Clone Source panel scales down (which reads a larger area than it covers), is cropped /// around `at` to the sampling budget, keeping the middle of the dab. @@ -31,8 +34,9 @@ fn clone_dab_coverage( brush: &photocraft_paint::BrushSettings, at: [f64; 2], map: &photocraft_engine::presets::clone_source::Mapping, + flow: f32, ) -> Option<(DRect, Vec)> { - let brush = photocraft_paint::BrushSettings { opacity: 1.0, flow: 1.0, erase: false, ..brush.clone() }; + let brush = photocraft_paint::BrushSettings { opacity: 1.0, flow, erase: false, ..brush.clone() }; let stroke = photocraft_paint::Stroke { brush, points: vec![photocraft_paint::StrokePoint::new(at[0], at[1], 1.0)] }; let (rect, cov) = photocraft_paint::retouch::stroke_coverage_within(&stroke, CLONE_PREVIEW_MAX_PIXELS)?; let fits = |r: DRect| r.width() <= CLONE_PREVIEW_MAX_SIDE && r.height() <= CLONE_PREVIEW_MAX_SIDE; @@ -70,33 +74,37 @@ fn clone_dab_coverage( /// A transient source image beneath the brush outline; never part of the document render. The /// Clone Source panel drives the Clone Stamp and the Healing Brush alike, so both show it. pub(super) fn draw_clone_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, at: [f64; 2], output: Option) { - use photocraft_engine::presets::clone_source::{Mapping, overlay_blend, transform_matrix}; + use photocraft_engine::presets::clone_source::overlay_blend; let overlay = app.session.presets.clone.overlay.clone(); let tool = app.ui.tool; if !matches!(tool, Tool::CloneStamp | Tool::Healing) || !overlay.show || (overlay.auto_hide && app.drag.is_some()) { return; } let slot = app.session.presets.clone.active().clone(); - let Some(source) = slot.source else { return }; + let Some(map) = crate::preset_panels::clone_mapping_at(app, Some(at)) else { return }; let radius = f64::from(app.session.tools.brush.size) / 2.0; if !radius.is_finite() || radius <= 0.0 || radius > 500.0 || !at.iter().all(|v| v.is_finite() && v.abs() < 1_000_000.0) { return; } - // View › Pattern Preview repeats the source for the Clone Stamp only (`paint.cloneStamp`'s - // `wrap`); the Healing Brush samples it as it is. - let wrap = tool == Tool::CloneStamp && app.ui.view.pattern_preview; - let stroke_start = app.drag.as_ref().map(|d| d.start); - let anchor = if app.ui.tool_options.clone_aligned { slot.anchor.or(stroke_start) } else { stroke_start }.unwrap_or(at); - let map = - Mapping { source: (source[0], source[1]), anchor: (anchor[0], anchor[1]), m: transform_matrix(slot.scale, slot.rotation, slot.flip_h, slot.flip_v) }; + // Both tools repeat source reads in Pattern Preview; this also refreshes a stationary hover. + let wrap = app.ui.view.pattern_preview; let Some(st) = app.session.active() else { return }; + let target = paint_target(app); + if slot.document.is_some_and(|id| id != st.doc.id) && photocraft_engine::channel_cmds::gray_target(&json!({"target": target})).is_some() { + // Strokes reject these cross-document targets, including a mask selected only in the UI. + return; + } + let source_revision = + slot.document.and_then(|id| app.session.documents().iter().find(|st| st.doc.id == id)).map(|st| (st.doc.id, st.revision, st.active_layer)); + let source_document = slot.document.and_then(|id| app.session.documents().iter().find(|st| st.doc.id == id)).map(|st| std::sync::Arc::downgrade(&st.doc)); let (display, display_key) = canvas_display(app, &st.doc, output); let key = format!( - "{:?}:{}:{:?}:{:?}:{map:?}:{}:{}:{}:{}:{wrap}:{}:{}", + "{tool:?}:{source_revision:?}:{:?}:{}:{:?}:{:?}:{map:?}:{:?}:{}:{}:{}:{}:{wrap}:{}:{}", st.doc.id, st.revision, st.active_layer, at.map(f64::to_bits), + slot.layer, app.ui.tool_options.clone_sample, display_key, overlay.invert, @@ -105,12 +113,20 @@ pub(super) fn draw_clone_preview(app: &mut PhotocraftApp, painter: &egui::Painte radius.to_bits() ); let brush = overlay.clipped.then_some(&app.session.tools.brush); - if app.clone_preview.as_ref().is_none_or(|c| c.key != key || c.brush.as_ref() != brush) { + if app.clone_preview.as_ref().is_none_or(|c| { + let same_source = match (&c.source_document, &source_document) { + (Some(a), Some(b)) => std::sync::Weak::ptr_eq(a, b), + (None, None) => true, + _ => false, + }; + c.key != key || c.brush.as_ref() != brush || !same_source + }) { // Clipped (Photoshop's default): the dab the tool paints here, so a soft brush previews // soft and a shaped tip keeps its outline. Unclipped: the brush's whole square. let (rect, coverage) = match brush { Some(b) => { - let Some((rect, coverage)) = clone_dab_coverage(b, at, &map) else { return }; + let flow = if tool == Tool::CloneStamp { b.flow } else { 1.0 }; + let Some((rect, coverage)) = clone_dab_coverage(b, at, &map, flow) else { return }; (rect, Some(coverage)) } None => ( @@ -118,7 +134,12 @@ pub(super) fn draw_clone_preview(app: &mut PhotocraftApp, painter: &egui::Painte None, ), }; - let Ok(mut buf) = photocraft_engine::retouch_cmds::clone_preview_periodic(&app.session, rect, &map, &app.ui.tool_options.clone_sample, wrap) else { + let preview = if tool == Tool::Healing { + photocraft_engine::retouch_cmds::healing_preview_periodic(&app.session, rect, &map, &app.ui.tool_options.clone_sample, wrap) + } else { + photocraft_engine::retouch_cmds::clone_preview_periodic(&app.session, rect, &map, &app.ui.tool_options.clone_sample, wrap) + }; + let Ok(mut buf) = preview else { return; }; if overlay.invert { @@ -131,8 +152,7 @@ pub(super) fn draw_clone_preview(app: &mut PhotocraftApp, painter: &egui::Painte // Darken, Lighten and Difference mix the source with the image under the brush (the // composite, whatever Sample reads), so Difference turns black where they line up. if overlay.blend != "normal" { - let here = Mapping { source: (0.0, 0.0), anchor: (0.0, 0.0), m: [1.0, 0.0, 0.0, 1.0] }; - let Ok(under) = photocraft_engine::retouch_cmds::clone_preview_periodic(&app.session, rect, &here, "all", wrap) else { + let Ok(under) = photocraft_engine::retouch_cmds::clone_destination_preview(&app.session, rect, wrap) else { return; }; for (px, d) in buf.px.iter_mut().zip(&under.px) { @@ -150,18 +170,25 @@ pub(super) fn draw_clone_preview(app: &mut PhotocraftApp, painter: &egui::Painte Some(cache) => { cache.texture.set(image, canvas_texture_options(1)); cache.key = key; + cache.source_document = source_document; cache.brush = brush; cache.rect = rect; } None => { let texture = painter.ctx().load_texture("clone-preview", image, canvas_texture_options(1)); - app.clone_preview = Some(ClonePreviewCache { key, brush, rect, texture }); + app.clone_preview = Some(ClonePreviewCache { key, source_document, brush, rect, texture }); } } } let Some(cache) = &app.clone_preview else { return }; let rect = cache.rect; - let tint = Color32::from_white_alpha((overlay.opacity.clamp(0.0, 100.0) * 2.55).round() as u8); + // Clone Stamp sends its opacity/flow with every stroke; Healing Brush uses full strength. + let brush_alpha = if tool == Tool::CloneStamp { + app.session.tools.brush.opacity.clamp(0.0, 1.0) * if overlay.clipped { 1.0 } else { app.session.tools.brush.flow.clamp(0.0, 1.0) } + } else { + 1.0 + }; + let tint = Color32::from_white_alpha((overlay.opacity.clamp(0.0, 100.0) * brush_alpha * 2.55).round() as u8); // A textured quad over the covered area: its texels carry the clip, in mirrored and rotated // canvas views too. let mut mesh = egui::Mesh::with_texture(cache.texture.id()); @@ -539,6 +566,14 @@ pub(super) fn live_stroke_busy(app: &PhotocraftApp) -> bool { app.live_stroke.as_ref().is_some_and(|l| l.paint.busy()) } +impl PhotocraftApp { + /// Is the live stroke still painting, or holding steps the canvas hasn't shown yet? Lets a + /// test read the canvas only once what it shows is the whole stroke so far (#13477). + pub fn live_stroke_busy(&self) -> bool { + live_stroke_busy(self) + } +} + /// The points the live retouching stroke has rendered. #[cfg(test)] pub(crate) fn live_retouch_points(app: &PhotocraftApp) -> Option> { diff --git a/crates/ui-egui/src/canvas/tabs.rs b/crates/ui-egui/src/canvas/tabs.rs index 40e7f47105..6eafa7b3c1 100644 --- a/crates/ui-egui/src/canvas/tabs.rs +++ b/crates/ui-egui/src/canvas/tabs.rs @@ -837,14 +837,10 @@ pub fn extra_windows(app: &mut PhotocraftApp, ctx: &egui::Context) { if focused && !w.focused && app.session.active_index() != Some(w.document) { app.session.set_active(w.document); } - egui::CentralPanel::default().frame(egui::Frame::NONE.fill(crate::theme::Tokens::get(ui.ctx()).canvas)).show(ui, |ui| { - let rect = ui.available_rect_before_wrap(); - app.drawing_window = Some(w.id); - view = canvas_view(app, ui, w.document, rect, view.clone(), focused); - app.drawing_window = None; - // Preferences › Zoom Resizes Windows: a zoom wraps the window around the image. - crate::zoom_window_fit::follow(app, ui.ctx(), class, vid, &w, &mut view, rect); - }); + let (shown, rect) = document_window_canvas(app, ui, &w, view.clone(), focused); + view = shown; + // Preferences › Zoom Resizes Windows: a zoom wraps the window around the image. + crate::zoom_window_fit::follow(app, ui.ctx(), class, vid, &w, &mut view, rect); }); if shares && let Some(v) = app.ui.views.get_mut(w.document) { *v = view.clone(); @@ -860,6 +856,35 @@ pub fn extra_windows(app: &mut PhotocraftApp, ctx: &egui::Context) { app.ui.windows.retain(|w| w.open); } +/// The canvas of document window `w` (Window › New Window), drawn in its own viewport. Returns the +/// view after this frame's input and the canvas rect. +/// +/// Dialogs are modal, but their `egui::Modal` only blocks the viewport it is drawn in, the main +/// window. Without a modal layer of its own, this window's canvas would take presses and drags +/// under a dialog: a Move drag here committed a History step the dialog's Cancel never undid. +/// So while a dialog is open the window gets an empty, transparent modal of its own, and its +/// canvas is as inert as the main one's; the dialog's own gestures on the image (pan, zoom, +/// eyedroppers) read the raw pointer and still work here, as they do there. +pub(super) fn document_window_canvas( + app: &mut PhotocraftApp, + ui: &mut egui::Ui, + w: &crate::state::DocWindow, + view: crate::state::View, + focused: bool, +) -> (crate::state::View, Rect) { + if !app.ui.dialogs.is_empty() { + egui::Modal::new(egui::Id::unique(("docwin-dialog-block", w.id))).backdrop_color(Color32::TRANSPARENT).frame(egui::Frame::NONE).show(ui.ctx(), |_| {}); + } + let mut out = (view.clone(), Rect::NOTHING); + egui::CentralPanel::default().frame(egui::Frame::NONE.fill(crate::theme::Tokens::get(ui.ctx()).canvas)).show(ui, |ui| { + let rect = ui.available_rect_before_wrap(); + app.drawing_window = Some(w.id); + out = (canvas_view(app, ui, w.document, rect, view, focused), rect); + app.drawing_window = None; + }); + out +} + /// Window › Arrange tiles: each document shown with its tile in `rect`, or `None` when the /// active document fills the area. pub(super) fn docked_document_indices(app: &PhotocraftApp) -> Vec { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 6506b65987..4914e2e1e6 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1474,6 +1474,56 @@ fn clone_overlay_app(size: f32) -> PhotocraftApp { app } +/// A focused canvas can remain primary after another document becomes active. +#[test] +fn clone_cursor_from_an_inactive_document_cannot_replace_the_active_offset_reference() { + let rect = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let ctx = egui::Context::default(); + let frame = |app: &mut PhotocraftApp, idx: usize, primary: bool, at: Option<[f64; 2]>| { + let view = View { zoom: 2.0, center: [32.0, 32.0], doc_size: [64, 64], fit_pending: false, fill_pending: false, ..Default::default() }; + let event = + at.map_or(egui::Event::PointerGone, |at| egui::Event::PointerMoved(rect.center() + vec2((at[0] as f32 - 32.0) * 2.0, (at[1] as f32 - 32.0) * 2.0))); + let input = egui::RawInput { screen_rect: Some(rect), events: vec![event], ..Default::default() }; + let mut output = ctx.run_ui(input, |ui| { + canvas_view(app, ui, idx, rect, view.clone(), primary); + }); + output.textures_delta.clear(); + }; + for tool in [Tool::CloneStamp, Tool::Healing] { + for aligned in [false, true] { + let mut app = clone_overlay_app(12.0); + app.background_jobs = false; + app.ui.extras.rulers = false; + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.ui.tool = tool; + app.ui.tool_options.clone_aligned = aligned; + let document = app.session.active().unwrap().doc.id; + let slots = app.session.presets.clone.clone(); + let revision = app.session.active().unwrap().revision; + // Warm up hover detection, then establish the active document's own reference. + for _ in 0..2 { + frame(&mut app, 1, true, Some([40.0, 30.0])); + } + assert_eq!(app.ui.presets_ui.clone_cursor, Some((document, [40.0, 30.0]))); + assert_eq!(crate::preset_panels::clone_offset_readout(&app), Some([-24.0, -14.0])); + // A different, still-focused window draws as primary without activating its document. + frame(&mut app, 0, true, Some([12.0, 24.0])); + assert_eq!(app.session.active_index(), Some(1)); + assert!(app.hover_doc.is_some(), "the inactive canvas really received hover input"); + assert_eq!(app.ui.presets_ui.clone_cursor, Some((document, [40.0, 30.0])), "{tool:?}/{aligned}: retain the active document's reference"); + assert_eq!(crate::preset_panels::clone_offset_readout(&app), Some([-24.0, -14.0])); + assert_eq!(crate::preset_panels::clone_offset_edit(&app, [-20.0, -10.0]).unwrap()["anchor"], json!([40.0, 30.0])); + frame(&mut app, 1, true, Some([44.0, 34.0])); + assert_eq!(app.ui.presets_ui.clone_cursor, Some((document, [44.0, 34.0])), "the active canvas still updates normally"); + frame(&mut app, 0, false, Some([8.0, 12.0])); + frame(&mut app, 1, true, None); + assert_eq!(app.ui.presets_ui.clone_cursor, Some((document, [44.0, 34.0])), "secondary views and leaving the canvas retain the reference"); + assert_eq!(app.session.presets.clone, slots, "hover does not establish a source anchor"); + assert_eq!(app.session.active().unwrap().revision, revision, "hover does not paint"); + } + } +} + /// One frame of the overlay at (32, 32): its shapes and texture uploads. fn clone_overlay_frame(ctx: &egui::Context, app: &mut PhotocraftApp, xf: &ViewXform) -> egui::FullOutput { ctx.run_ui(Default::default(), |ui| { @@ -1563,6 +1613,181 @@ fn clone_overlay_follows_the_brush_hardness() { assert_eq!(clone_overlay_alpha(&big, &mut output)(32, 32), 255, "a 1000 px soft brush previews too"); } +#[test] +fn clone_overlay_opacity_and_flow_match_a_stamp_on_another_layer() { + let ctx = egui::Context::default(); + let xf = clone_overlay_view(100.0, 1.0); + for depth in [8, 16, 32] { + for clipped in [true, false] { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64, "depth": depth})).unwrap(); + crate::retouch_ui::set_source(&mut app, 16.0, 16.0); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = Tool::CloneStamp; + app.ui.tool_options.clone_sample = "all".into(); + app.session.tools.brush.size = 20.0; + app.session.presets.clone.overlay.clipped = clipped; + // Settings change under a stationary cursor, including after a cached full-strength preview. + for (opacity, flow) in [(1.0, 1.0), (0.5, 1.0), (1.0, 0.25), (0.5, 0.4)] { + let mut cached = clone_overlay_frame(&ctx, &mut app, &xf); + cached.textures_delta.clear(); + app.run("tools.setBrush", json!({"size": 20, "hardness": 1.0, "opacity": opacity, "flow": flow})).unwrap(); + let revision = app.session.active().unwrap().revision; + let mut output = clone_overlay_frame(&ctx, &mut app, &xf); + let tint = output + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Mesh(mesh) => mesh.vertices.first().map(|v| v.color.a()), + _ => None, + }) + .expect("the overlay mesh"); + // An unclipped preview may reuse its texture when only tint changes. + if output.textures_delta.set.is_empty() { + app.clone_preview = None; + output = clone_overlay_frame(&ctx, &mut app, &xf); + } + let alpha = clone_overlay_alpha(&app, &mut output)(32, 32) as f32 / 255.0 * tint as f32 / 255.0; + assert_eq!(app.session.active().unwrap().revision, revision, "hovering is read-only"); + let mut params = crate::retouch_ui::clone_params(&app).unwrap(); + params["points"] = json!([[32, 32]]); + app.run("paint.cloneStamp", params).unwrap(); + let st = app.session.active().unwrap(); + let printed = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(32, 32)[3]; + assert!((printed - opacity * flow).abs() < 0.01, "opacity={opacity} flow={flow}: printed {printed}"); + assert!((alpha - printed).abs() < 0.01, "{depth} clipped={clipped} opacity={opacity} flow={flow}: preview {alpha}, print {printed}"); + assert!(app.session.undo()); + } + } + } +} + +#[test] +fn clone_overlay_separate_opacity_setting_still_multiplies_the_brush_opacity() { + let ctx = egui::Context::default(); + let mut app = clone_overlay_app(20.0); + app.session.tools.brush.opacity = 0.5; + app.session.presets.clone.overlay.opacity = 40.0; + let mut output = clone_overlay_frame(&ctx, &mut app, &clone_overlay_view(100.0, 1.0)); + let alpha = output + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Mesh(mesh) => mesh.vertices.first().map(|v| v.color.a()), + _ => None, + }) + .unwrap(); + output.textures_delta.clear(); + assert_eq!(alpha, 51, "50% brush opacity times 40% overlay opacity"); +} + +#[test] +fn clone_overlay_refreshes_when_the_source_layer_changes_at_the_same_coordinates() { + let ctx = egui::Context::default(); + let mut app = clone_overlay_app(20.0); + app.run("layer.new.layer", json!({})).unwrap(); + let xf = clone_overlay_view(100.0, 1.0); + let mut output = clone_overlay_frame(&ctx, &mut app, &xf); + assert_eq!(clone_overlay_alpha(&app, &mut output)(32, 32), 255, "the picked white source survives the layer switch"); + crate::retouch_ui::set_source(&mut app, 16.0, 16.0); + let mut output = clone_overlay_frame(&ctx, &mut app, &xf); + assert_eq!(clone_overlay_alpha(&app, &mut output)(32, 32), 0, "picking the transparent layer refreshes the cached overlay"); +} + +#[test] +fn clone_overlay_strength_changes_leave_the_healing_preview_at_full_strength() { + let ctx = egui::Context::default(); + let mut app = clone_overlay_app(20.0); + app.session.tools.brush.opacity = 0.5; + app.session.tools.brush.flow = 0.4; + let xf = clone_overlay_view(100.0, 1.0); + let mut output = clone_overlay_frame(&ctx, &mut app, &xf); + assert!((i32::from(clone_overlay_alpha(&app, &mut output)(32, 32)) - 102).abs() <= 1); + app.ui.tool = Tool::Healing; + let mut output = clone_overlay_frame(&ctx, &mut app, &xf); + assert_eq!(clone_overlay_alpha(&app, &mut output)(32, 32), 255, "Healing Brush still previews its full-strength texture"); +} + +fn clone_overlay_center(app: &PhotocraftApp, output: &mut egui::FullOutput) -> Color32 { + let cache = app.clone_preview.as_ref().unwrap(); + let upload = output.textures_delta.set.get(&cache.texture.id()).and_then(|d| d.last()).expect("the source preview was refreshed"); + let egui::ImageData::Color(image) = &upload.image; + let pixel = image.pixels[(32 - cache.rect.y0) as usize * image.width() + (32 - cache.rect.x0) as usize]; + output.textures_delta.clear(); + pixel +} + +#[test] +fn clone_overlay_repicking_on_the_original_layer_updates_preview_and_both_layers() { + let ctx = egui::Context::default(); + let mut app = clone_overlay_app(12.0); + let source = app.session.active().unwrap().active_layer.unwrap(); + for (point, color) in [([16, 16], "#ff0000"), ([8, 8], "#0000ff")] { + app.run("paint.pencil", json!({"points": [point], "size": 6, "color": color})).unwrap(); + } + crate::retouch_ui::set_source(&mut app, 16.0, 16.0); + app.run("layer.new.layer", json!({})).unwrap(); + let target = app.session.active().unwrap().active_layer.unwrap(); + app.run("tools.setBrush", json!({"size": 6, "hardness": 1, "opacity": 1, "flow": 1})).unwrap(); + let xf = clone_overlay_view(100.0, 1.0); + let mut output = clone_overlay_frame(&ctx, &mut app, &xf); + assert_eq!(clone_overlay_center(&app, &mut output), Color32::RED); + let stamp = |app: &mut PhotocraftApp| { + let mut params = crate::retouch_ui::clone_params(app).unwrap(); + params["points"] = json!([[32, 32]]); + app.run("paint.cloneStamp", params).unwrap(); + }; + stamp(&mut app); + app.run("layer.select", json!({"layer": source.0})).unwrap(); + crate::retouch_ui::set_source(&mut app, 8.0, 8.0); + stamp(&mut app); + assert_eq!(app.session.active().unwrap().doc.layer(source).unwrap().surface().unwrap().rgba(32, 32), [0.0, 0.0, 1.0, 1.0]); + app.run("layer.select", json!({"layer": target.0})).unwrap(); + let mut output = clone_overlay_frame(&ctx, &mut app, &xf); + assert_eq!(clone_overlay_center(&app, &mut output), Color32::BLUE); + stamp(&mut app); + assert_eq!(app.session.active().unwrap().doc.layer(target).unwrap().surface().unwrap().rgba(32, 32), [0.0, 0.0, 1.0, 1.0]); +} + +#[test] +fn clone_overlay_between_documents_updates_after_source_edits_and_blends_with_the_destination() { + let ctx = egui::Context::default(); + let mut app = clone_overlay_app(12.0); + crate::paint_mouse::sync_tool_brush(&mut app); + app.run("paint.pencil", json!({"points": [[16,16]], "size": 8, "color": "#ff0000"})).unwrap(); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("paint.pencil", json!({"points": [[32,32]], "size": 16, "color": "#000000"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("tools.setBrush", json!({"size": 8, "hardness": 1, "opacity": 1, "flow": 1})).unwrap(); + let xf = clone_overlay_view(100.0, 1.0); + let mut output = clone_overlay_frame(&ctx, &mut app, &xf); + assert_eq!(clone_overlay_center(&app, &mut output), Color32::RED); + app.run("cloneSource.overlay", json!({"blend": "difference"})).unwrap(); + let mut output = clone_overlay_frame(&ctx, &mut app, &xf); + assert_eq!(clone_overlay_center(&app, &mut output), Color32::RED, "Difference uses the black destination, not the white source document"); + let revision = app.session.active().unwrap().revision; + assert!(app.session.set_active(0)); + app.run("paint.pencil", json!({"points": [[16,16]], "size": 8, "color": "#00ff00"})).unwrap(); + assert!(app.session.set_active(1)); + assert_eq!(app.session.active().unwrap().revision, revision); + let mut output = clone_overlay_frame(&ctx, &mut app, &xf); + assert_eq!(clone_overlay_center(&app, &mut output), Color32::GREEN, "editing another document invalidates the cached source"); + let mods = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 32.0, y: 32.0, pressure: 1.0 }, mods); + assert!(crate::retouch_ui::source_marker_point(&app).is_none(), "the source crosshair belongs to the other document"); + tool_event(&mut app, ToolEvent::Up { x: 32.0, y: 32.0 }, mods); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(32, 32), [0.0, 1.0, 0.0, 1.0]); + app.run("cloneSource.select", json!({"index": 1})).unwrap(); + assert!(crate::retouch_ui::clone_params(&app).is_none(), "an empty slot cannot reuse coordinates from another document"); + let before = app.session.active().unwrap().doc.clone(); + let revision = app.session.active().unwrap().revision; + tool_event(&mut app, ToolEvent::Down { x: 48.0, y: 48.0, pressure: 1.0 }, mods); + tool_event(&mut app, ToolEvent::Up { x: 48.0, y: 48.0 }, mods); + assert_eq!(app.session.active().unwrap().doc, before, "painting with an empty slot cannot sample stale coordinates"); + assert_eq!(app.session.active().unwrap().revision, revision, "the refused gesture does not create a history edit"); +} + /// A scaled Clone Source reads a larger source area than the overlay covers: a large brush's /// overlay shrinks around the pointer until that area fits the sampling budget, rather than /// vanishing. @@ -1597,6 +1822,73 @@ fn clone_overlay_shows_for_the_healing_brush_too() { } } +/// Pattern Preview changes the Healing Brush source overlay at a stationary cursor. +#[test] +fn clone_healing_overlay_wraps_with_the_live_texture_at_source_edges() { + let ctx = egui::Context::default(); + let xf = clone_overlay_view(100.0, 1.0); + let mut app = clone_overlay_app(12.0); + app.ui.tool = Tool::Healing; + app.run("cloneSource.set", json!({"source": [0,0]})).unwrap(); + app.run("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap(); + let mut output = clone_overlay_frame(&ctx, &mut app, &xf); + assert_eq!(clone_overlay_alpha(&app, &mut output)(30, 32), 0); + app.ui.view.pattern_preview = true; + assert_eq!(crate::retouch_ui::clone_params(&app).unwrap()["wrap"], true); + let mut output = clone_overlay_frame(&ctx, &mut app, &xf); + assert_eq!(clone_overlay_alpha(&app, &mut output)(30, 32), 255, "the repeated source is visible before painting"); + let live = photocraft_engine::retouch_cmds::LiveRetouch::begin( + &app.session, + "paint.healingBrush", + &json!({"points": [[32,32]], "size": 12, "hardness": 100, "wrap": true}), + ) + .unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(live.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(30, 32), [1.0; 4]); + app.ui.view.pattern_preview = false; + let mut output = clone_overlay_frame(&ctx, &mut app, &xf); + assert_eq!(clone_overlay_alpha(&app, &mut output)(30, 32), 0); +} + +/// Unsupported cross-document targets never reuse a cached pixel-layer source overlay. +#[test] +fn clone_overlay_suppresses_cross_document_masks_and_channels() { + for tool in [Tool::CloneStamp, Tool::Healing] { + for mask in [false, true] { + let ctx = egui::Context::default(); + let xf = clone_overlay_view(100.0, 1.0); + let mut app = clone_overlay_app(12.0); + app.ui.tool = tool; + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + if mask { + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + } else { + app.run("channel.new", json!({"fill": "white"})).unwrap(); + } + app.run("channel.target", json!({"channel": "composite"})).unwrap(); + app.ui.mask_target = false; + let mut output = clone_overlay_frame(&ctx, &mut app, &xf); + assert!(output.shapes.iter().any(|s| matches!(s.shape, egui::Shape::Mesh(_)))); + output.textures_delta.clear(); + let revision = app.session.active().unwrap().revision; + if mask { + app.ui.mask_target = true; + } else { + app.session.active_mut().unwrap().channel_view.target = photocraft_engine::channel_cmds::ChannelTarget::Alpha(0); + } + assert_eq!(app.session.active().unwrap().revision, revision, "only the target changed"); + let mut output = clone_overlay_frame(&ctx, &mut app, &xf); + assert!(!output.shapes.iter().any(|s| matches!(s.shape, egui::Shape::Mesh(_))), "{tool:?}, mask={mask}: the gesture has no supported source"); + output.textures_delta.clear(); + app.ui.mask_target = false; + app.run("channel.target", json!({"channel": "composite"})).unwrap(); + let mut output = clone_overlay_frame(&ctx, &mut app, &xf); + assert!(output.shapes.iter().any(|s| matches!(s.shape, egui::Shape::Mesh(_))), "returning to pixels restores the source overlay"); + output.textures_delta.clear(); + } + } +} + #[test] fn clone_overlay_keeps_magnified_pixels_crisp_on_upload_and_refresh() { let ctx = egui::Context::default(); @@ -3141,8 +3433,9 @@ fn retouch_drags_show_the_footprint_without_wedges() { let ctx = egui::Context::default(); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); app.run("file.new", json!({"width": 120, "height": 60})).unwrap(); - app.run("tools.setBrush", json!({"brush": {"size": 30, "hardness": hardness}})).unwrap(); app.ui.tool = Tool::Remove; + crate::paint_mouse::sync_tool_brush(&mut app); + app.run("tools.setBrush", json!({"brush": {"size": 30, "hardness": hardness}})).unwrap(); tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE); for i in 1..80 { let t = f64::from(i) * 0.5; diff --git a/crates/ui-egui/src/canvas/tool_cursor.rs b/crates/ui-egui/src/canvas/tool_cursor.rs index 238a966eb2..400346ceb7 100644 --- a/crates/ui-egui/src/canvas/tool_cursor.rs +++ b/crates/ui-egui/src/canvas/tool_cursor.rs @@ -12,6 +12,7 @@ use egui::{CursorIcon, CustomCursorImage, Painter, Pos2, Stroke, Vec2, vec2}; use crate::canvas::ViewXform; use crate::state::Tool; +mod arrow; mod bucket; mod hand; mod pen; @@ -30,13 +31,16 @@ const MAX_SIDE: u16 = if cfg!(any(target_os = "windows", target_os = "macos")) { /// What a bitmap cursor shows. `Hand` is the Hand tool's open hand, or its fist while it drags; /// `Zoom` is the Zoom tool's magnifier, with a minus when it zooms out. `Outline` is a brush tip -/// outline: closed rings of logical-point offsets from the hotspot. +/// outline: closed rings of logical-point offsets from the hotspot. `Arrow` is the black arrow +/// pointer, its tip on the hotspot. #[derive(Clone, Debug, PartialEq)] enum Shape { + Arrow, Circle { radius: f32, centre: bool }, Crosshair { length: f32, gap: f32 }, Hand { closed: bool }, Zoom { out: bool }, + Pipette, Outline { rings: Arc<[Vec]>, centre: bool }, } @@ -50,6 +54,24 @@ struct Cached { image: CustomCursorImage, } +/// Root and child viewports may use different bitmap units at the same time (points vs Retina +/// pixels on macOS). Retain a small number of densities, including failed loads, without letting +/// arbitrary zoom values accumulate unbounded images or retry a broken SVG every frame. +#[derive(Clone)] +struct CachedPipette { + scale: f32, + painted: bool, + image: Option, + texture: Option, +} + +const PIPETTE_CACHE_CAPACITY: usize = 4; + +/// GPU textures are not subject to the OS cursor limit. Bound their density independently; +/// beyond 8x the GPU scales the same artwork, keeping its logical size and hotspot intact. +const PAINTED_PIPETTE_MAX_SCALE: f32 = 8.0; +const PAINTED_PIPETTE_MAX_SIDE: u16 = 511; + /// Pen variants retain at most one bitmap each; large brush bitmaps stay in the single-entry cache. #[derive(Clone, Default)] struct PenCache { @@ -130,7 +152,7 @@ pub(crate) fn count(ctx: &egui::Context, at: Pos2, kind: CountCursor) -> CursorI CursorIcon::Default } -/// The bucket artwork and its exact fill crosshair move as one native cursor or painted image. +/// The bucket artwork and the arrow on its fill target move as one native cursor or painted image. pub(crate) fn bucket(painter: &Painter, at: Pos2) -> Result { bucket::show(painter, at) } @@ -143,10 +165,54 @@ pub(crate) fn crosshair(painter: &Painter, at: Pos2, length: f32, gap: f32) -> C show(painter, at, Shape::Crosshair { length, gap }) } +/// The Perspective Crop's pointer for what a press at `at` does (#11974): with no quad a small +/// crosshair centred on the point with the tool's icon below right; inside the quad the solid +/// black arrow; over a corner the hollow white arrowhead with its tip on the point. Both are drawn +/// by us (the OS arrow is white on Windows and follows the theme on Linux). +pub(crate) fn perspective_crop(painter: &Painter, zone: crate::perspective_crop_ui::Zone, at: Pos2) -> CursorIcon { + use crate::perspective_crop_ui::Zone; + match zone { + Zone::Idle => { + crate::icons::crosshair_badge(painter.ctx(), crate::icons::tool_icon(Tool::PerspectiveCrop), at); + crosshair(painter, at, 5.0, 0.0) + } + Zone::Inside => { + // Our own solid black arrow, the same on every system; the OS cursor is hidden. + crate::icons::cursor_arrow(painter.ctx(), at); + CursorIcon::None + } + Zone::Corner(_) => { + // The tip of the arrowhead is at (4, 4) of its 24-unit box. + crate::icons::cursor(painter.ctx(), "mouse-pointer-2", at, vec2(4.0, 4.0) / 24.0, 18.0); + CursorIcon::None + } + // A press there does nothing yet (#11801): the tool's usual crosshair. + Zone::Outside => standard_crosshair(painter, at), + } +} + pub(crate) fn standard_crosshair(painter: &Painter, at: Pos2) -> CursorIcon { show(painter, at, STANDARD_CROSSHAIR.clone()) } +/// The tip stays on the sampled pixel. Native root viewports upload the bitmap; web and +/// immediate viewports draw the same geometry without an interactive overlay widget. +pub(crate) fn pipette(ctx: &egui::Context, at: Pos2) -> CursorIcon { + let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("pc-tool-pointer"))); + show(&painter, at, Shape::Pipette) +} + +/// Whether the pass whose output is `out` shows the sampling pipette: the OS bitmap and its +/// visible-fallback crosshair where a bitmap can be uploaded, the drawn pipette elsewhere. +#[cfg(test)] +pub(crate) fn pipette_shown(ctx: &egui::Context, out: &egui::PlatformOutput) -> bool { + if !native(ctx) { + return out.cursor_icon == CursorIcon::None; + } + let expected = cached_pipette(ctx, native_scale(ctx), false).image; + out.cursor_icon == CursorIcon::Crosshair && expected.is_some() && out.cursor_image == expected +} + pub(crate) fn outline(painter: &Painter, at: Pos2, rings: Vec>, centre: bool) -> CursorIcon { show(painter, at, Shape::Outline { rings: rings.into(), centre }) } @@ -208,6 +274,68 @@ pub(crate) fn path_type(painter: &Painter, at: Pos2) -> CursorIcon { outline(painter, at, path_type_rings(), false) } +/// The Ruler tool's pointer (#12037). A small arrow with a ruler below right of its tip, and the +/// same arrow with a protractor's angle mark over an end point with ⌥ — the same hit test a press +/// makes its decision with (`analysis_ui::ruler_end_at`), so the angle mark shows exactly where an +/// ⌥-drag starts the protractor arm. The hotspot is the arrow's tip, so the point a press takes is +/// the pointer itself. `CursorIcon::None` with the shape painted where a backend takes no bitmap, +/// as for the other tool pointers. +pub(crate) fn ruler(app: &crate::PhotocraftApp, painter: &Painter, at: Pos2, doc: [f64; 2], mods: egui::Modifiers) -> CursorIcon { + outline(painter, at, ruler_rings(mods.alt && crate::analysis_ui::ruler_end_at(app, doc)), false) +} + +/// The Ruler cursors' geometry, in points round the hotspot on the arrow's tip: the arrowhead, +/// then the glyph below right of it. Our own artwork, in the same outlined pair the other tool +/// pointers use. +fn ruler_rings(protractor: bool) -> Vec> { + let mut rings = vec![ruler_arrow()]; + rings.extend(if protractor { protractor_glyph() } else { straightedge_glyph() }); + rings +} + +/// The arrowhead: tip on the hotspot, body towards the lower right as a plain pointer's sits, with +/// the notch in its back. +fn ruler_arrow() -> Vec { + let d = std::f32::consts::FRAC_1_SQRT_2; + let (along, side) = (vec2(d, d), vec2(-d, d)); + let (base, notch, half) = (along * 11.5, along * 4.6, 3.6); + vec![Vec2::ZERO, base + side * half, notch, base - side * half] +} + +/// A ticked straightedge below right of the arrow's tip: the bar and three ticks off its upper edge. +fn straightedge_glyph() -> Vec> { + let (along, side) = (vec2(0.948_7, 0.316_2), vec2(-0.316_2, 0.948_7)); + let (from, len, half) = (vec2(10.5, 12.5), 12.0, 2.4); + let to = from + along * len; + let mut rings = vec![vec![from + side * half, to + side * half, to - side * half, from - side * half]]; + for t in [0.3, 0.55, 0.8] { + let edge = from + along * (len * t) - side * half; + rings.push(open_ring(&[edge, edge + side * 1.7])); + } + rings +} + +/// A protractor's angle mark below right of the arrow's tip: two arms out of one vertex and the arc +/// between them. +fn protractor_glyph() -> Vec> { + let vertex = vec2(9.0, 19.5); + let arc: Vec = (0..=6) + .map(|i| { + let a = i as f32 * std::f32::consts::FRAC_PI_4 / 6.0; + vertex + vec2(a.cos(), -a.sin()) * 4.5 + }) + .collect(); + vec![open_ring(&[vertex, vertex + vec2(11.0, 0.0)]), open_ring(&[vertex, vertex + vec2(7.8, -7.8)]), open_ring(&arc)] +} + +/// A ring through `pts` and back again: [`Shape::Outline`] closes its rings, so an open line has to +/// list its points both ways instead of gaining the chord back to its start. +fn open_ring(pts: &[Vec2]) -> Vec { + let mut ring = pts.to_vec(); + ring.extend(pts.get(1..pts.len().saturating_sub(1)).unwrap_or(&[]).iter().rev().copied()); + ring +} + /// Can this pass show an OS cursor bitmap? eframe's immediate viewports and its web integration /// don't upload cursor images; every desktop root viewport does (winit custom cursors). Wayland at /// any scale but 1 doesn't either: winit sizes the bitmap there with a `wp_viewport` destination @@ -342,6 +470,20 @@ fn hand_with(ctx: &egui::Context, closed: bool, bitmap: bool) -> CursorIcon { if closed { CursorIcon::Grabbing } else { CursorIcon::Grab } } +/// The black arrow pointer, its tip on the pointer (`_at`): an OS cursor bitmap on every platform +/// that takes one, the system arrow where none can be set. +pub(crate) fn arrow(ctx: &egui::Context, _at: Pos2) -> CursorIcon { + arrow_with(ctx, native(ctx)) +} + +fn arrow_with(ctx: &egui::Context, bitmap: bool) -> CursorIcon { + if bitmap && let Some(image) = cached_image(ctx, &Shape::Arrow, native_scale(ctx)) { + ctx.set_cursor_image(Some(image)); + return CursorIcon::None; + } + CursorIcon::Default +} + /// The bitmap [`hand`] hands Windows, for tests that check the Hand's pointer on every platform. #[cfg(test)] pub(crate) fn hand_bitmap(ctx: &egui::Context, closed: bool) -> Option { @@ -405,6 +547,7 @@ fn cached_pen_image(ctx: &egui::Context, variant: PenVariant, scale: f32) -> Opt Some(image) } +/// Prefer OS-owned motion; paint only on backends without bitmap cursors or for oversized tips. fn show(painter: &Painter, at: Pos2, shape: Shape) -> CursorIcon { let ctx = painter.ctx(); // Where cursor images can't be uploaded (immediate viewports, the web), paint the shape. @@ -422,11 +565,14 @@ fn show(painter: &Painter, at: Pos2, shape: Shape) -> CursorIcon { } return CursorIcon::None; } - paint(painter, at, &shape); - CursorIcon::None + if paint(painter, at, &shape) { CursorIcon::None } else { CursorIcon::Crosshair } } +/// Large, variable brush outlines share one entry; pipettes retain each active density separately. fn cached_image(ctx: &egui::Context, shape: &Shape, scale: f32) -> Option { + if matches!(shape, Shape::Pipette) { + return cached_pipette(ctx, scale, false).image; + } let id = egui::Id::unique("photocraft-tool-cursor"); if let Some(cached) = ctx.data(|d| d.get_temp::(id)) && cached.shape == *shape @@ -439,9 +585,66 @@ fn cached_image(ctx: &egui::Context, shape: &Shape, scale: f32) -> Option CachedPipette { + let scale = if painted && scale.is_finite() && scale > 0.0 { scale.clamp(0.5, PAINTED_PIPETTE_MAX_SCALE) } else { scale }; + let id = egui::Id::unique("photocraft-pipette-cache"); + let mut entries = ctx.data(|d| d.get_temp::>(id)).unwrap_or_default(); + // A rejected native bitmap must not poison a valid texture at the same density, nor may + // a cached GPU texture bypass the native size check when the pointer returns to the root. + let matches = |entry: &CachedPipette| entry.scale.to_bits() == scale.to_bits() && entry.painted == painted; + let mut cached = entries.iter().find(|entry| matches(entry)).cloned().unwrap_or_else(|| CachedPipette { + scale, + painted, + image: if painted { + extent(&Shape::Pipette) + .and_then(|extent| bitmap_dimensions(extent, scale, PAINTED_PIPETTE_MAX_SIDE)) + .and_then(|(side, hot)| rasterize_pipette(scale, side, hot)) + } else { + rasterize(&Shape::Pipette, scale) + }, + texture: None, + }); + if painted + && cached.texture.is_none() + && let Some(image) = &cached.image + { + let pixels = egui::ColorImage::from_rgba_unmultiplied(image.size.map(usize::from), &image.rgba); + cached.texture = Some(ctx.load_texture("pc-pipette-icon", pixels, egui::TextureOptions::LINEAR)); + } + entries.retain(|entry| !matches(entry)); + if entries.len() >= PIPETTE_CACHE_CAPACITY { + entries.remove(0); + } + entries.push(cached.clone()); + ctx.data_mut(|d| d.insert_temp(id, entries)); + cached +} + +/// Draw the fallback in logical points; report failure so a visible system crosshair can remain. +fn paint(painter: &Painter, at: Pos2, shape: &Shape) -> bool { if extent(shape).is_none() { - return; + return false; + } + if matches!(shape, Shape::Pipette) { + let scale = painter.ctx().pixels_per_point(); + let cached = cached_pipette(painter.ctx(), scale, true); + let (Some(image), Some(texture)) = (cached.image, cached.texture) else { + return false; + }; + // Divide by the raster density, which is capped independently of the display density. + let scale = cached.scale; + // Match the native hotspot's texel centre, not the top-left corner of its pixel cell. + let hot = (vec2(f32::from(image.hotspot[0]), f32::from(image.hotspot[1])) + Vec2::splat(0.5)) / scale; + let size = vec2(f32::from(image.size[0]), f32::from(image.size[1])) / scale; + painter.image( + texture.id(), + egui::Rect::from_min_size(at - hot, size), + egui::Rect::from_min_max(Pos2::ZERO, egui::pos2(1.0, 1.0)), + egui::Color32::WHITE, + ); + return true; } let [dark, light] = crate::theme::Tokens::cursor_outline(); for (width, color) in [(3.0, dark), (1.0, light)] { @@ -465,9 +668,10 @@ fn paint(painter: &Painter, at: Pos2, shape: &Shape) { } } // Only ever a bitmap: without one the OS draws its own grab cursors. - Shape::Hand { .. } | Shape::Zoom { .. } => {} + Shape::Arrow | Shape::Hand { .. } | Shape::Zoom { .. } | Shape::Pipette => {} } } + true } fn paint_crosshair(painter: &Painter, at: Pos2, length: f32, gap: f32, stroke: Stroke) { @@ -483,6 +687,7 @@ fn cross_distance(x: f32, y: f32, length: f32, gap: f32) -> f32 { horizontal.min(vertical) } +/// Logical reach from the hotspot, before rasterize adds stroke and antialiasing padding. fn extent(shape: &Shape) -> Option { Some(match shape { Shape::Circle { radius, centre } => { @@ -512,8 +717,12 @@ fn extent(shape: &Shape) -> Option { } if *centre { e.max(3.0) } else { e } } + Shape::Arrow => arrow::REACH, Shape::Hand { .. } => hand::HALF, Shape::Zoom { .. } => zoom::HALF, + // The 24-unit SVG extends at most 22 units from (2, 22). This extra unit plus + // rasterize's 1.5-unit stroke padding covers the 3.75-wide halo (radius 1.875). + Shape::Pipette => 23.0, }) } @@ -527,6 +736,7 @@ fn seg_distance(x: f32, y: f32, a: Vec2, b: Vec2) -> f32 { /// How much of the pixel at `(dx, dy)` physical pixels from the hotspot the light fill covers and /// how much the dark outline around it does, each 0 to 1. A dark crease inside the hand takes /// from the fill, so the fill never covers it. +/// Pipette pixels never pass here: rasterize dispatches that shape to its SVG renderer first. fn coverage(shape: &Shape, dx: f32, dy: f32, scale: f32) -> (f32, f32) { let (x, y) = (dx.abs(), dy.abs()); match shape { @@ -561,6 +771,11 @@ fn coverage(shape: &Shape, dx: f32, dy: f32, scale: f32) -> (f32, f32) { let (lx, ly) = (dx / scale, dy / scale); silhouette(zoom::shape(lx, ly), zoom::glyph(*out, lx, ly), 0.75, scale) } + Shape::Arrow => { + let (lx, ly) = (dx / scale, dy / scale); + silhouette(arrow::shape(lx, ly), f32::MAX, 0.0, scale) + } + Shape::Pipette => (0.0, 0.0), // SVG rasterization supplies these pixels. } } @@ -643,29 +858,37 @@ fn ring_spans(dy: f32, r: f32, reach: f32) -> Option<[(f32, f32); 2]> { Some([(-xo, -xi), (xi, xo)]) } -fn rasterize(shape: &Shape, scale: f32) -> Option { - if !scale.is_finite() || scale <= 0.0 { +/// Odd bitmap dimensions keep the hotspot central; stroke and AA padding fit within the limit. +fn bitmap_dimensions(extent: f32, scale: f32, max_side: u16) -> Option<(u16, u16)> { + if !scale.is_finite() || scale <= 0.0 || max_side < 3 { return None; } - let extent = extent(shape)?; // Odd dimensions put the hotspot on the centre pixel at every DPI. Include the outline // and its antialiasing fringe, then check before converting or allocating. let half = ((extent + 1.5) * scale + 1.0).ceil(); - if !half.is_finite() || half > f32::from((MAX_SIDE - 1) / 2) { + if !half.is_finite() || half > f32::from((max_side - 1) / 2) { return None; } let hot = half as u16; let side = hot * 2 + 1; + Some((side, hot)) +} + +/// Produce bounded straight-RGBA cursor pixels. Pipette SVGs bypass the distance-coverage loop. +fn rasterize(shape: &Shape, scale: f32) -> Option { + let (side, hot) = bitmap_dimensions(extent(shape)?, scale, MAX_SIDE)?; let bytes = usize::from(side).checked_mul(usize::from(side))?.checked_mul(4)?; - // Transparent to start; only pixels a shape can reach are evaluated below (a big tip's - // outline is a thin ring in a large square, #1343). + if matches!(shape, Shape::Pipette) { + return rasterize_pipette(scale, side, hot); + } + // Transparent to start; evaluate only pixels the shape can reach. let mut rgba = vec![0u8; bytes]; let [dark, light] = crate::theme::Tokens::cursor_outline(); let n = usize::from(side); let hotf = f32::from(hot); let mut put = |col: usize, row: usize, cov: (f32, f32)| { if let Some(px) = row.checked_mul(n).and_then(|i| i.checked_add(col)).and_then(|i| rgba.get_mut(i * 4..i * 4 + 4)) { - px.copy_from_slice(&stroke_pixel(cov, dark, light)); + px.copy_from_slice(&if matches!(shape, Shape::Arrow) { arrow::pixel(cov) } else { stroke_pixel(cov, dark, light) }); } }; if let Shape::Outline { rings, centre } = shape { @@ -717,11 +940,52 @@ fn rasterize(shape: &Shape, scale: f32) -> Option { } } } - Some(CustomCursorImage { rgba: Arc::from(rgba), size: [side, side], hotspot: [hot, hot] }) + let image = CustomCursorImage { rgba: Arc::from(rgba), size: [side, side], hotspot: [hot, hot] }; + if matches!(shape, Shape::Arrow) { arrow::crop(image) } else { Some(image) } } +/// Use the toolbar's actual SVG, with its lower-left tip (2, 22) at the hotspot. +/// Both native and painted cursors share these pixels; only the contrast halo is added. +fn rasterize_pipette(scale: f32, side: u16, hot: u16) -> Option { + let icon = include_str!("../../../../assets/icons/pipette.svg"); + rasterize_pipette_svg(icon, scale, side, hot).inspect_err(|error| log::error!("Could not rasterize pipette cursor: {error}")).ok() +} + +/// The embedded artwork has a deliberate styling contract. Reject unexpected source changes +/// explicitly instead of silently losing the halo; a declaration/DOCTYPE before the root is not +/// part of the nested SVG. Loader failures reach the log, and the cached failure keeps a crosshair. +fn rasterize_pipette_svg(icon: &str, scale: f32, side: u16, hot: u16) -> Result { + let start = icon.find("{dark}{light}"); + let image = egui_extras::image::load_svg_bytes_with_size( + svg.as_bytes(), + egui::load::SizeHint::Size { width: u32::from(side), height: u32::from(side), maintain_aspect_ratio: false }, + &Default::default(), + ) + .map_err(|error| format!("invalid pipette SVG: {error}"))?; + let rgba: Vec = image.pixels.iter().flat_map(|pixel| pixel.to_srgba_unmultiplied()).collect(); + Ok(CustomCursorImage { rgba: Arc::from(rgba), size: [side, side], hotspot: [hot, hot] }) +} + +#[cfg(test)] +mod ruler_tests; + #[cfg(test)] mod tests; #[cfg(test)] mod count_tests; + +#[cfg(test)] +mod add_anchor_cursor_tests; diff --git a/crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs b/crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs new file mode 100644 index 0000000000..27b746d7c8 --- /dev/null +++ b/crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs @@ -0,0 +1,158 @@ +//! #12729: Add Anchor Point's cursor says what a click would do. Over a segment of the targeted path +//! it is the pen with "+"; over an anchor, a handle end, empty canvas, with no path targeted and +//! over a locked shape layer's segments it is the black arrow. ⌘ keeps Direct Selection's arrow, +//! ⌥ and the Precise "Other Cursors" crosshair stay as they were. The tests drive the real canvas +//! (`document_area`) and compare the OS cursor bitmap it hands the platform with the arrow's and +//! the pen's. + +use egui::{CursorIcon, Modifiers, Pos2, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +use super::{PenVariant, Shape, rasterize}; +use crate::PhotocraftApp; +use crate::anchor_tools::delete_anchor_targeted_path_tests::{select_layer, select_saved_path, setup}; +use crate::state::Tool; + +/// Path 1 is the square (50,450)-(150,550); the shape layer is the rectangle (450,100)-(650,250). +const SQUARE_TOP: [f32; 2] = [100.0, 450.0]; +const SQUARE_CORNER: [f32; 2] = [50.0, 450.0]; +const SQUARE_MIDDLE: [f32; 2] = [100.0, 500.0]; +const SHAPE_TOP: [f32; 2] = [550.0, 100.0]; + +/// The canvas at 100 % over `app`, the view centred on `view` (a document point). +fn harness(app: PhotocraftApp, view: [f32; 2]) -> Harness<'static, PhotocraftApp> { + let mut app = app; + app.sync_views(); + app.ui.extras.rulers = false; + let mut h = Harness::builder().with_size(vec2(900.0, 600.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + v.zoom = 1.0; + v.center = view; + v.fit_pending = false; + h.run_steps(2); + h +} + +/// Hover the document point `at` with `mods` held. +fn hover(h: &mut Harness<'static, PhotocraftApp>, at: [f32; 2], view: [f32; 2], mods: Modifiers) { + h.event(egui::Event::ModifiersChanged(mods)); + let p: Pos2 = h.state().last_canvas_rect.center() + vec2(at[0] - view[0], at[1] - view[1]); + h.hover_at(p); + h.run_steps(3); +} + +#[derive(Debug, PartialEq)] +enum Shown { + Arrow, + Pen, + Crosshair, + Other, +} + +/// Which cursor the last frame asked the platform for. +fn shown(h: &Harness<'static, PhotocraftApp>) -> Shown { + let out = &h.output().platform_output; + let scale = super::native_scale(&h.ctx); + let same = + |a: &egui::CustomCursorImage, b: Option| b.is_some_and(|b| a.size == b.size && a.hotspot == b.hotspot && a.rgba == b.rgba); + match &out.cursor_image { + Some(i) if same(i, rasterize(&Shape::Arrow, scale)) => Shown::Arrow, + Some(i) if same(i, PenVariant::from_tool(Tool::AddAnchorPoint).and_then(|v| super::pen::rasterize(v, scale))) => Shown::Pen, + Some(i) if same(i, rasterize(&super::STANDARD_CROSSHAIR, scale)) => Shown::Crosshair, + _ => Shown::Other, + } +} + +/// The square's Path 1 targeted, the pointer at `at` on it. +fn on_path_one(at: [f32; 2], mods: Modifiers) -> Shown { + let (mut app, _) = setup(Tool::AddAnchorPoint); + select_saved_path(&mut app); + let mut h = harness(app, SQUARE_MIDDLE); + hover(&mut h, at, SQUARE_MIDDLE, mods); + shown(&h) +} + +#[test] +fn over_a_segment_of_the_targeted_path_it_is_the_pen_with_plus() { + assert_eq!(on_path_one(SQUARE_TOP, Modifiers::NONE), Shown::Pen); +} + +#[test] +fn over_an_anchor_a_handle_end_or_empty_canvas_it_is_the_black_arrow() { + assert_eq!(on_path_one(SQUARE_CORNER, Modifiers::NONE), Shown::Arrow); + assert_eq!(on_path_one(SQUARE_MIDDLE, Modifiers::NONE), Shown::Arrow); + // A handle end: a curved top edge's out-handle ends in empty canvas, off every segment. + let (mut app, _) = setup(Tool::AddAnchorPoint); + let path = json!({"subpaths": [{"closed": true, "knots": [{"anchor": [50, 450], "in": [50, 450], "out": [50, 400]}, [150, 450], [150, 550], [50, 550]]}]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); + let mut h = harness(app, SQUARE_MIDDLE); + hover(&mut h, [50.0, 400.0], SQUARE_MIDDLE, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Arrow); +} + +#[test] +fn with_no_path_targeted_it_is_the_black_arrow_everywhere() { + // The active layer is the pixel layer "Red": no path is targeted, whatever lies under the pointer. + for at in [SHAPE_TOP, [450.0, 100.0], [550.0, 175.0], [300.0, 150.0]] { + let (app, _) = setup(Tool::AddAnchorPoint); + let mut h = harness(app, SHAPE_TOP); + hover(&mut h, at, SHAPE_TOP, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Arrow, "{at:?}"); + } +} + +#[test] +fn over_a_segment_of_a_locked_shape_layers_mask_it_is_the_black_arrow() { + let (mut app, shape) = setup(Tool::AddAnchorPoint); + select_layer(&mut app, shape); + let mut h = harness(app, SHAPE_TOP); + hover(&mut h, SHAPE_TOP, SHAPE_TOP, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Pen, "unlocked, the same point is a segment"); + h.state_mut().run("layer.lockLayers", json!({"position": true})).unwrap(); + hover(&mut h, SHAPE_TOP, SHAPE_TOP, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Arrow); +} + +#[test] +fn with_ctrl_held_it_is_the_black_arrow_even_over_a_segment() { + assert_eq!(on_path_one(SQUARE_TOP, Modifiers::COMMAND), Shown::Arrow); +} + +#[test] +fn with_alt_held_it_stays_the_pen_over_empty_canvas() { + assert_eq!(on_path_one(SQUARE_MIDDLE, Modifiers::ALT), Shown::Pen); +} + +#[test] +fn the_precise_other_cursors_crosshair_keeps_working() { + for at in [SQUARE_TOP, SQUARE_MIDDLE] { + let (mut app, _) = setup(Tool::AddAnchorPoint); + select_saved_path(&mut app); + app.run("prefs.set", json!({"path": "cursors.other", "value": "precise"})).unwrap(); + let mut h = harness(app, SQUARE_MIDDLE); + hover(&mut h, at, SQUARE_MIDDLE, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Crosshair, "{at:?}"); + } +} + +#[test] +fn the_arrow_bitmap_is_not_empty_and_its_hotspot_is_the_tip_at_1_1() { + let image = rasterize(&Shape::Arrow, 1.0).unwrap(); + assert_eq!(image.hotspot, [1, 1]); + let alpha = |x: usize, y: usize| image.rgba[(y * usize::from(image.size[0]) + x) * 4 + 3]; + assert!(image.rgba.chunks(4).any(|p| p[3] == 255 && p[0] == 0), "a solid black body"); + assert!(image.rgba.chunks(4).any(|p| p[3] > 0 && p[0] == 255), "a white edge"); + assert!(alpha(1, 1) > 0, "the tip pixel is covered"); + assert_eq!(super::arrow_with(&egui::Context::default(), false), CursorIcon::Default); +} diff --git a/crates/ui-egui/src/canvas/tool_cursor/arrow.rs b/crates/ui-egui/src/canvas/tool_cursor/arrow.rs new file mode 100644 index 0000000000..b99cd20886 --- /dev/null +++ b/crates/ui-egui/src/canvas/tool_cursor/arrow.rs @@ -0,0 +1,60 @@ +//! The black arrow pointer: a filled black arrow with a white edge, PhotoCraft's own drawing from +//! one polygon (tip at the top left, body down to the right, a short tail), as a signed distance +//! field (negative inside) in logical pixels from the tip with y pointing down. The hotspot is the +//! tip; the bitmap is cropped to the arrow so the tip sits one pixel in from its top left corner, +//! at (1, 1) at 100 %. Windows' stock arrow is white, so every platform gets this bitmap. + +use std::sync::Arc; + +use egui::CustomCursorImage; + +use super::hand::capsule; + +/// How far the polygon reaches from the tip, outline excluded. +pub(super) const REACH: f32 = 20.0; + +/// The arrow's corners, clockwise from the tip. +const OUTLINE: [[f32; 2]; 7] = [[0.0, 0.0], [11.5, 11.8], [6.7, 11.8], [9.2, 17.4], [6.6, 18.6], [4.0, 12.8], [0.0, 16.5]]; + +/// The arrow's silhouette: negative inside it. +pub(super) fn shape(x: f32, y: f32) -> f32 { + let mut distance = f32::MAX; + let mut inside = false; + for (&a, &b) in OUTLINE.iter().zip(OUTLINE.iter().cycle().skip(1)) { + distance = distance.min(capsule(x, y, a, b, 0.0)); + // Even-odd rule: a ray towards +x crossing this edge flips the answer. + if (a[1] > y) != (b[1] > y) && x < a[0] + (y - a[1]) * (b[0] - a[0]) / (b[1] - a[1]) { + inside = !inside; + } + } + if inside { -distance } else { distance } +} + +/// One bitmap pixel in straight RGBA: black `fill` over a white edge, `outline` being the coverage +/// of the whole arrow (edge included), each 0 to 1. No coverage is `[0; 4]`. +pub(super) fn pixel((fill, outline): (f32, f32)) -> [u8; 4] { + let edge = outline * (1.0 - fill); + let alpha = fill + edge; + let white = if alpha > 0.0 { (255.0 * edge / alpha).round() as u8 } else { 0 }; + [white, white, white, (255.0 * alpha).round() as u8] +} + +/// Crop `image` (the arrow centred on its hotspot) to the pixels it covers, the hotspot moving +/// with them. `None` when nothing is covered. +pub(super) fn crop(image: CustomCursorImage) -> Option { + let [w, h] = image.size.map(usize::from); + let covered = |col: usize, row: usize| image.rgba.get((row * w + col) * 4 + 3).is_some_and(|&a| a > 0); + let cols: Vec = (0..w).filter(|&c| (0..h).any(|r| covered(c, r))).collect(); + let rows: Vec = (0..h).filter(|&r| (0..w).any(|c| covered(c, r))).collect(); + let (&c0, &c1) = (cols.first()?, cols.last()?); + let (&r0, &r1) = (rows.first()?, rows.last()?); + let mut rgba = Vec::with_capacity((c1 - c0 + 1) * (r1 - r0 + 1) * 4); + for row in r0..=r1 { + rgba.extend_from_slice(image.rgba.get((row * w + c0) * 4..(row * w + c1 + 1) * 4)?); + } + Some(CustomCursorImage { + rgba: Arc::from(rgba), + size: [u16::try_from(c1 - c0 + 1).ok()?, u16::try_from(r1 - r0 + 1).ok()?], + hotspot: [image.hotspot[0].checked_sub(u16::try_from(c0).ok()?)?, image.hotspot[1].checked_sub(u16::try_from(r0).ok()?)?], + }) +} diff --git a/crates/ui-egui/src/canvas/tool_cursor/bucket.rs b/crates/ui-egui/src/canvas/tool_cursor/bucket.rs index 41d37ea1f3..091326303b 100644 --- a/crates/ui-egui/src/canvas/tool_cursor/bucket.rs +++ b/crates/ui-egui/src/canvas/tool_cursor/bucket.rs @@ -1,11 +1,23 @@ -//! One image owns the bucket artwork and its lower-right fill target. Splitting those between -//! the frame and the OS pointer lets them drift apart whenever a frame arrives after the pointer. +//! One image owns the bucket artwork and the arrow at its top left whose tip is the fill target +//! (#12539). Splitting those between the frame and the OS pointer lets them drift apart whenever a +//! frame arrives after the pointer. use super::{CursorIcon, CustomCursorImage, Painter, Pos2, native, native_scale}; use std::sync::Arc; const SIZE: f32 = 22.0; -const HOT: egui::Vec2 = egui::vec2(26.0 / 24.0 * SIZE, 25.0 / 24.0 * SIZE); +/// The bucket icon's top-left corner, in points from the arrow tip. +const ICON: egui::Vec2 = egui::vec2(6.0, 6.0); +/// Our own small arrow, in points from its tip: the hotspot, so a click fills the pixel under it. +const ARROW: [egui::Vec2; 7] = [ + egui::vec2(0.0, 0.0), + egui::vec2(0.0, 10.5), + egui::vec2(2.6, 8.2), + egui::vec2(4.3, 11.8), + egui::vec2(5.9, 11.1), + egui::vec2(4.2, 7.5), + egui::vec2(7.5, 7.5), +]; #[derive(Clone)] struct Cached { @@ -58,40 +70,75 @@ pub(super) fn rasterize(scale: f32) -> Result { if !scale.is_finite() || scale <= 0.0 { return Err(format!("Invalid Paint Bucket cursor scale: {scale}")); } - // Round the hotspot itself, rather than the box, so it always lands on an exact bitmap pixel. - // Keep one logical pixel of the existing icon halo and its antialiasing fringe inside the box. - let margin = (scale + 1.0).ceil(); - let hot = [(HOT.x * scale).round() + margin, (HOT.y * scale).round() + margin]; - let cross = super::rasterize(&super::STANDARD_CROSSHAIR, scale).ok_or_else(|| format!("Paint Bucket crosshair does not fit a cursor at scale {scale}"))?; - let size = [hot[0] + f32::from(cross.size[0] - cross.hotspot[0]), hot[1] + f32::from(cross.size[1] - cross.hotspot[1])]; + // The arrow's halo reaches one halo width above and left of its tip, so the tip lands on + // (1, 1) at 1x, as in the reference cursor. The bucket's halo and fringe get room below right. + let halo = scale.round(); + let side = (SIZE * scale).round(); + let icon_at = (ICON * scale).round() + egui::Vec2::splat(halo); + let size = [icon_at.x + side + halo + 1.0, icon_at.y + side + halo + 1.0]; if size.iter().any(|side| !side.is_finite() || *side > f32::from(super::MAX_SIDE)) { return Err(format!("Paint Bucket cursor does not fit the platform bitmap limit at scale {scale}")); } let size = size.map(|side| side as u16); - let hotspot = hot.map(|coord| coord as u16); + let hotspot = [halo as u16; 2]; let mut pixels = vec![egui::Color32::TRANSPARENT; usize::from(size[0]) * usize::from(size[1])]; - let icon = crate::icons::rasterize("paint-bucket", (SIZE * scale).round() as u32)?; - let margin = margin as i32; - let halo = scale.round() as i32; - // The same eight dark halo offsets and white SVG as icons::cursor, now in the image that - // also owns the crosshair. Color32 keeps composition premultiplied until the final upload. - for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (1, 1), (-1, 1), (1, -1), (0, 0)] { + let icon = crate::icons::rasterize("paint-bucket", side as u32)?; + let halo = halo as i32; + let (arrow_width, arrow) = arrow_mask(scale); + // The same eight dark halo offsets and white SVG as icons::cursor, then the arrow on top of + // the bucket: black on a white halo. Color32 keeps composition premultiplied until the upload. + const OFFSETS: [(i32, i32); 9] = [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (1, 1), (-1, 1), (1, -1), (0, 0)]; + for (dx, dy) in OFFSETS { for (i, pixel) in icon.pixels.iter().enumerate() { - let x = (i % icon.size[0]) as i32 + margin + dx * halo; - let y = (i / icon.size[0]) as i32 + margin + dy * halo; + let x = (i % icon.size[0]) as i32 + icon_at.x as i32 + dx * halo; + let y = (i / icon.size[0]) as i32 + icon_at.y as i32 + dy * halo; let color = if dx == 0 && dy == 0 { *pixel } else { egui::Color32::from_black_alpha((f32::from(pixel.a()) * 200.0 / 255.0).round() as u8) }; over(&mut pixels, size, x, y, color); } } - for (i, pixel) in cross.rgba.as_chunks::<4>().0.iter().enumerate() { - let x = (i % usize::from(cross.size[0])) as i32 + i32::from(hotspot[0]) - i32::from(cross.hotspot[0]); - let y = (i / usize::from(cross.size[0])) as i32 + i32::from(hotspot[1]) - i32::from(cross.hotspot[1]); - over(&mut pixels, size, x, y, egui::Color32::from_rgba_unmultiplied(pixel[0], pixel[1], pixel[2], pixel[3])); + for (dx, dy) in OFFSETS { + for (i, alpha) in arrow.iter().enumerate() { + let x = (i % arrow_width) as i32 + i32::from(hotspot[0]) + dx * halo; + let y = (i / arrow_width) as i32 + i32::from(hotspot[1]) + dy * halo; + let color = if dx == 0 && dy == 0 { egui::Color32::from_black_alpha(*alpha) } else { egui::Color32::from_white_alpha(*alpha) }; + over(&mut pixels, size, x, y, color); + } } let rgba = pixels.into_iter().flat_map(|pixel| pixel.to_srgba_unmultiplied()).collect::>(); Ok(CustomCursorImage { rgba: Arc::from(rgba), size, hotspot }) } +/// The arrow's coverage per physical pixel, its tip at the centre of pixel (0, 0), the texel +/// centre the painted fallback puts on the pointer: the mask's width and its alpha values, row by row. +fn arrow_mask(scale: f32) -> (usize, Vec) { + const SAMPLES: u16 = 4; + let extent = ARROW.iter().fold(egui::Vec2::ZERO, |extent, point| extent.max(*point)) * scale + egui::Vec2::splat(0.5); + let (width, height) = (extent.x.ceil() as usize, extent.y.ceil() as usize); + let mut mask = Vec::with_capacity(width * height); + for y in 0..height { + for x in 0..width { + let mut hits = 0_u16; + for sy in 0..SAMPLES { + for sx in 0..SAMPLES { + let sample = egui::vec2(x as f32 + (f32::from(sx) + 0.5) / f32::from(SAMPLES), y as f32 + (f32::from(sy) + 0.5) / f32::from(SAMPLES)); + hits += u16::from(inside((sample - egui::Vec2::splat(0.5)) / scale, &ARROW)); + } + } + mask.push((f32::from(hits) * 255.0 / f32::from(SAMPLES * SAMPLES)).round() as u8); + } + } + (width, mask) +} + +/// Even-odd point in polygon. +fn inside(point: egui::Vec2, polygon: &[egui::Vec2]) -> bool { + let next = polygon.iter().skip(1).chain(polygon.first()); + polygon.iter().zip(next).fold(false, |inside, (a, b)| { + let crosses = (a.y > point.y) != (b.y > point.y) && point.x < (b.x - a.x) * (point.y - a.y) / (b.y - a.y) + a.x; + inside != crosses + }) +} + fn over(pixels: &mut [egui::Color32], size: [u16; 2], x: i32, y: i32, foreground: egui::Color32) { if x < 0 || y < 0 || x >= i32::from(size[0]) || y >= i32::from(size[1]) { return; diff --git a/crates/ui-egui/src/canvas/tool_cursor/ruler_tests.rs b/crates/ui-egui/src/canvas/tool_cursor/ruler_tests.rs new file mode 100644 index 0000000000..94f45f9b5d --- /dev/null +++ b/crates/ui-egui/src/canvas/tool_cursor/ruler_tests.rs @@ -0,0 +1,298 @@ +//! The Ruler tool's own pointers (#12037). Away from the ruler, over its line or one of its end +//! points without ⌥, and with ⇧: a small arrow with a ruler below right of its tip. Over an end +//! point with ⌥ — where an ⌥-drag starts the protractor arm: the same arrow with a protractor's +//! angle mark, from the very hit test a press uses. ⌘ turns the Ruler into the temporary Move tool +//! (`hold_keys::cmd_moves`), so it keeps the Move pointer on and off the ruler. The hotspot is the +//! arrow's tip; the artwork is our own geometry, an OS cursor bitmap that is painted where a +//! backend takes no bitmap. + +use egui::{CursorIcon, CustomCursorImage, Modifiers, Shape as EShape, Vec2, vec2}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::analysis_ui::Drag; +use crate::canvas::ToolEvent; +use crate::state::Tool; + +use super::{CursorLifecycle, Shape, native_scale, rasterize, ruler_arrow, ruler_rings}; + +/// The document's ruler, and a point well clear of it. +const START: [f64; 2] = [80.0, 120.0]; +const END: [f64; 2] = [260.0, 220.0]; +const AWAY: [f64; 2] = [340.0, 60.0]; +/// The point the pointer sits on in a bare frame. +const ON: egui::Pos2 = egui::Pos2::new(100.0, 80.0); + +/// A document with the Ruler tool and one ruler drawn in it, at `zoom`. +fn ruler_app(zoom: f32) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("image.analysis.rulerTool", json!({"start": START, "end": END, "protractor": null})).unwrap(); + app.ui.views[0].zoom = zoom; + app.ui.tool = Tool::Ruler; + app.sync_views(); + app +} + +/// One cursor pass with no renderer: the pointer the app asks for, and what it drew. +fn cursor_frame(app: &PhotocraftApp, doc: [f64; 2], mods: Modifiers) -> egui::FullOutput { + let ctx = egui::Context::default(); + ctx.add_plugin(CursorLifecycle); + let mut output = ctx.run_ui(Default::default(), |ui| { + let icon = super::ruler(app, ui.painter(), ON, doc, mods); + ui.ctx().set_cursor_icon(icon); + }); + // These tests read the cursor output, never a renderer. + output.textures_delta.clear(); + output +} + +fn alpha(image: &CustomCursorImage, x: u16, y: u16) -> u8 { + image.rgba[(usize::from(y) * usize::from(image.size[0]) + usize::from(x)) * 4 + 3] +} + +/// The Ruler tool's pointer as its bitmap: `protractor` is the angle mark over an end point. +fn bitmap(protractor: bool, scale: f32) -> CustomCursorImage { + let shape = Shape::Outline { rings: ruler_rings(protractor).into(), centre: false }; + rasterize(&shape, scale).expect("the ruler cursor rasterizes") +} + +/// The inked pixels of a bitmap as points round its hotspot, so a claim about the artwork does not +/// depend on the display scale. +fn ink(image: &CustomCursorImage, scale: f32) -> Vec { + let side = usize::from(image.size[0]); + let hot = f32::from(image.hotspot[0]); + image + .rgba + .as_chunks::<4>() + .0 + .iter() + .enumerate() + .filter(|(_, p)| p[3] > 0) + .map(|(i, _)| vec2((i % side) as f32 - hot, (i / side) as f32 - hot) / scale) + .collect() +} + +/// The ink within 8 pt of the hotspot: the arrowhead alone, wherever the glyph is. +fn arrow_ink(image: &CustomCursorImage) -> Vec<(i32, i32)> { + ink(image, 1.0).into_iter().filter(|p| p.length() <= 8.0).map(|p| (p.x.round() as i32, p.y.round() as i32)).collect() +} + +/// Assert two bitmaps are the same picture, reporting the difference in words rather than in +/// thousands of bytes. +fn assert_same_bitmap(got: &CustomCursorImage, want: &CustomCursorImage, what: &str) { + assert_eq!(got.size, want.size, "{what}: the bitmap size"); + assert_eq!(got.hotspot, want.hotspot, "{what}: the hotspot"); + let differs = got.rgba.iter().zip(want.rgba.iter()).filter(|(a, b)| a != b).count(); + assert_eq!(differs, 0, "{what}: {differs} of {} bytes differ from the pointer module's own picture", got.rgba.len()); +} + +#[test] +fn ruler_bitmaps_put_the_arrow_tip_on_the_hotspot_at_each_scale() { + for scale in [1.0, 1.25, 2.0] { + for protractor in [false, true] { + let image = bitmap(protractor, scale); + let [x, y] = image.hotspot; + assert_eq!(image.size, [2 * x + 1, 2 * y + 1]); + assert!(alpha(&image, x, y) > 100, "{protractor}: the arrow's tip is on the hotspot"); + let painted = ink(&image, scale); + let reach = painted.iter().fold(0.0f32, |m, p| m.max(p.length())); + assert!(reach <= 30.0, "{protractor} at {scale}: nothing reaches further than 30 pt from the tip, {reach} does"); + // Above and left of the tip there is nothing to show: that is where the pointer is. + let stray: Vec<_> = painted.iter().filter(|p| p.x + p.y <= -3.0).copied().collect(); + assert!(stray.is_empty(), "{protractor} at {scale}: the glyph stays below right of the tip, {stray:?}"); + assert!(painted.iter().any(|p| p.x > 12.0 && p.y > 12.0), "{protractor}: a glyph below right of the arrow"); + let pixels = image.rgba.as_chunks::<4>().0; + assert!(pixels.iter().any(|p| p[3] > 230 && p[0] > 230), "a light cursor"); + assert!(pixels.iter().any(|p| p[3] > 100 && p[0] < 25), "with a dark outline, readable on white"); + } + } +} + +#[test] +fn the_protractor_cursor_is_the_same_arrow_with_a_different_glyph() { + let ruler = bitmap(false, 1.0); + let protractor = bitmap(true, 1.0); + assert_ne!(ruler.rgba, protractor.rgba, "the angle mark is not the ruler"); + let alone = rasterize(&Shape::Outline { rings: vec![ruler_arrow()].into(), centre: false }, 1.0).expect("the arrowhead alone rasterizes"); + let want = arrow_ink(&alone); + assert!(!want.is_empty(), "the arrowhead is inked by its tip"); + for (image, what) in [(&ruler, "the ruler"), (&protractor, "the protractor")] { + assert_eq!(arrow_ink(image), want, "{what}: the same arrowhead round the tip"); + } +} + +/// Where a backend takes no cursor bitmap the shape is painted at the pointer, its tip on it. +#[test] +fn the_ruler_pointer_is_painted_at_the_pointer_without_a_bitmap() { + let ctx = egui::Context::default(); + for protractor in [false, true] { + let mut output = ctx.run_ui(Default::default(), |ui| { + super::paint(ui.painter(), ON, &Shape::Outline { rings: ruler_rings(protractor).into(), centre: false }); + }); + output.textures_delta.clear(); + let paths: Vec<_> = output.shapes.iter().filter_map(|s| if let EShape::Path(p) = &s.shape { Some(p) } else { None }).collect(); + assert!(paths.len() >= 4, "{protractor}: the arrow and its glyph are drawn, got {}", paths.len()); + assert!(paths.iter().any(|p| p.closed && p.points.first().is_some_and(|q| *q == ON)), "{protractor}: an arrowhead with its tip on the pointer"); + assert!(paths.iter().any(|p| p.points.iter().all(|q| (*q - ON).length() > 11.0)), "{protractor}: and a glyph clear of it"); + } +} + +/// The state table, as the canvas match asks for it: the arrow with its ruler everywhere but over +/// an end point with ⌥, where the angle mark takes the ruler's place. The hotspot of both is the +/// arrow's tip, which is what the pointer sits on. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn every_ruler_state_gets_its_pointer() { + let app = ruler_app(1.0); + let scale = native_scale(&egui::Context::default()); + let mid = [(START[0] + END[0]) / 2.0, (START[1] + END[1]) / 2.0]; + for (doc, mods, protractor, what) in [ + (AWAY, Modifiers::NONE, false, "away from the ruler"), + (mid, Modifiers::NONE, false, "over the line"), + (END, Modifiers::NONE, false, "over an end"), + (START, Modifiers::NONE, false, "over the other end"), + (AWAY, Modifiers::SHIFT, false, "with ⇧"), + (mid, Modifiers::SHIFT, false, "over the line with ⇧"), + (mid, Modifiers::ALT, false, "over the line with ⌥"), + (AWAY, Modifiers::ALT, false, "away from the ruler with ⌥"), + (END, Modifiers::ALT, true, "over an end with ⌥"), + (START, Modifiers::ALT, true, "over the other end with ⌥"), + ] { + let out = cursor_frame(&app, doc, mods); + let image = out.platform_output.cursor_image.unwrap_or_else(|| panic!("{what}: the Ruler's own pointer is a bitmap cursor")); + assert_same_bitmap(&image, &bitmap(protractor, scale), what); + assert_eq!(out.platform_output.cursor_icon, CursorIcon::Crosshair, "{what}: a bitmap marks itself None, with a visible fallback"); + } +} + +/// ⌘ makes the Ruler the temporary Move tool, so the canvas' cursor match runs with `Tool::Move` +/// and shows the Move pointer — held on the ruler and off it (#12037; #9933 draws the four-way +/// cross Photoshop shows for it). +#[test] +fn ctrl_handed_to_the_ruler_is_the_move_tool() { + let app = ruler_app(1.0); + assert!(crate::hold_keys::cmd_moves(Tool::Ruler), "⌘ is the Move tool with the Ruler"); + let ctx = egui::Context::default(); + let mut input = egui::RawInput::default(); + input.events.push(egui::Event::ModifiersChanged(Modifiers::COMMAND)); + let mut out = ctx.run_ui(input, |_| {}); + out.textures_delta.clear(); + assert_eq!(crate::hold_keys::held_tool(&app, &ctx), Some(crate::hold_keys::Temporary::Move), "⌘ held over the canvas"); + assert_eq!(crate::hold_keys::Temporary::Move.tool(), Tool::Move, "and the cursor match runs with the Move tool's own arm"); +} + +/// The ⌥ pointer shows exactly where an ⌥-drag starts the protractor arm: the cursor's hit test and +/// a press agree at every zoom, because they are the same `dist` with the same grab radius, in +/// screen points. +#[test] +fn the_protractor_pointer_marks_exactly_where_an_alt_press_takes_the_end() { + for zoom in [0.5f32, 1.0, 2.0] { + // Past the end along its own line, in screen points: the grab radius is 7 of them. + for (reach, takes_the_end) in [(3.0, true), (12.0, false)] { + let app = ruler_app(zoom); + let mut pressed = ruler_app(zoom); + let p = [END[0] + reach / f64::from(app.point_zoom().max(0.01)), END[1]]; + crate::analysis_ui::pointer(&mut pressed, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, Modifiers::ALT); + assert_eq!(crate::analysis_ui::ruler_end_at(&app, p), takes_the_end, "{reach} pt past the end at {zoom}: the cursor"); + assert_eq!(pressed.ui.analysis.drag == Some(Drag::RulerHandle(2)), takes_the_end, "{reach} pt past the end at {zoom}: an ⌥-press"); + } + } +} + +/// Without a ruler there is no end point to mark, and an ⌥-press starts a new ruler. +#[test] +fn an_empty_document_has_no_end_to_mark() { + let mut app = ruler_app(1.0); + app.run("image.analysis.rulerTool", json!({"clear": true})).unwrap(); + assert!(app.session.active().is_some_and(|d| d.doc.measurement.ruler.is_none())); + assert!(!crate::analysis_ui::ruler_end_at(&app, START), "no ruler, no end point"); + crate::analysis_ui::pointer(&mut app, ToolEvent::Down { x: START[0], y: START[1], pressure: 1.0 }, Modifiers::ALT); + assert!(matches!(app.ui.analysis.drag, Some(Drag::RulerNew(_))), "and a press there starts a new ruler"); +} + +/// Over an end point without ⌥ the press grabs that end, so the plain ruler pointer stays. +#[test] +fn over_an_end_without_alt_the_press_grabs_the_end() { + let mut app = ruler_app(1.0); + assert!(crate::analysis_ui::ruler_end_at(&app, END), "the end is a grab target"); + crate::analysis_ui::pointer(&mut app, ToolEvent::Down { x: END[0], y: END[1], pressure: 1.0 }, Modifiers::NONE); + assert_eq!(app.ui.analysis.drag, Some(Drag::RulerHandle(1)), "and a press there drags it"); +} + +/// The live canvas: with the Ruler tool it hands the OS the arrow-and-ruler bitmap, the angle mark +/// over an end with ⌥, and the Move tool's pointer under ⌘. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn the_canvas_gives_the_ruler_tool_its_own_pointer() { + use egui::{Event, vec2}; + use egui_kittest::Harness; + + let mut h = Harness::builder().with_size(vec2(900.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + // Nothing to lay out before the font stack is in: an early pass draws no label at all. + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + ruler_app(1.0), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + if !h.ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + eprintln!("skipped: no font stack, so the canvas cannot be laid out here"); + return; + } + let scale = native_scale(&h.ctx); + let at = |h: &Harness<'static, PhotocraftApp>, doc: [f64; 2]| { + crate::canvas::ViewXform::active(h.state()).expect("a document with a view").to_screen(doc[0] as f32, doc[1] as f32) + }; + let hover = |h: &mut Harness<'static, PhotocraftApp>, doc: [f64; 2], mods: Modifiers| { + h.event(Event::ModifiersChanged(mods)); + h.event(Event::PointerMoved(at(h, doc))); + h.run_steps(2); + h.output().platform_output.cursor_image.clone() + }; + for (doc, mods, protractor, what) in [ + (AWAY, Modifiers::NONE, false, "away from the ruler"), + (END, Modifiers::ALT, true, "over an end with ⌥"), + (AWAY, Modifiers::NONE, false, "back away from it"), + ] { + let image = hover(&mut h, doc, mods).unwrap_or_else(|| panic!("{what}: the canvas shows the Ruler's own pointer")); + assert_same_bitmap(&image, &bitmap(protractor, scale), what); + } + for doc in [AWAY, END] { + h.event(Event::ModifiersChanged(Modifiers::COMMAND)); + h.event(Event::PointerMoved(at(&h, doc))); + h.run_steps(2); + assert!(h.output().platform_output.cursor_image.is_none(), "{doc:?}: ⌘ shows no Ruler bitmap"); + assert_eq!(h.output().platform_output.cursor_icon, CursorIcon::Default, "{doc:?}: the Move tool's pointer"); + } + // Preferences › Cursors › Other Cursors = Precise: the Ruler keeps the plain crosshair, as + // the Move and Type tools do; its own arrow is a nice-to-have, not a precise pointer (#12037 review). + let mut app = ruler_app(1.0); + app.run("prefs.set", json!({"values": {"cursors.other": "precise"}})).unwrap(); + let mut hp = Harness::builder().with_size(vec2(900.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&hp.ctx, crate::theme::ThemeKind::ALL[0]); + hp.run_steps(4); + for doc in [AWAY, END] { + hp.event(Event::ModifiersChanged(Modifiers::NONE)); + hp.event(Event::PointerMoved(crate::canvas::ViewXform::active(hp.state()).expect("a view").to_screen(doc[0] as f32, doc[1] as f32))); + hp.run_steps(2); + // The icon is the point: Precise asks for the plain crosshair, exactly as the Move and + // Type arms do; the small bitmap that rides with it on native is the cursor pipeline's + // visible crosshair fallback, not the Ruler's arrow-and-ruler art of the phases above. + assert_eq!(hp.output().platform_output.cursor_icon, CursorIcon::Crosshair, "{doc:?}: Precise keeps the crosshair"); + } +} diff --git a/crates/ui-egui/src/canvas/tool_cursor/tests.rs b/crates/ui-egui/src/canvas/tool_cursor/tests.rs index ec003d4845..5246cbe1bc 100644 --- a/crates/ui-egui/src/canvas/tool_cursor/tests.rs +++ b/crates/ui-egui/src/canvas/tool_cursor/tests.rs @@ -10,11 +10,6 @@ fn alpha(image: &CustomCursorImage, x: u16, y: u16) -> u8 { image.rgba[(usize::from(y) * usize::from(image.size[0]) + usize::from(x)) * 4 + 3] } -fn rgba_at(image: &CustomCursorImage, x: u16, y: u16) -> [u8; 4] { - let offset = (usize::from(y) * usize::from(image.size[0]) + usize::from(x)) * 4; - image.rgba[offset..offset + 4].try_into().unwrap() -} - fn frame(ctx: &egui::Context, draw: impl FnMut(&mut egui::Ui)) -> egui::FullOutput { let mut output = ctx.run_ui(Default::default(), draw); // These tests inspect cursor output without a renderer. @@ -22,7 +17,6 @@ fn frame(ctx: &egui::Context, draw: impl FnMut(&mut egui::Ui)) -> egui::FullOutp output } -#[cfg(target_os = "linux")] fn collect_meshes(shape: &egui::Shape, meshes: &mut Vec<(egui::TextureId, egui::Rect)>) { match shape { egui::Shape::Mesh(mesh) => meshes.push((mesh.texture_id, mesh.calc_bounds())), @@ -68,36 +62,19 @@ fn precise_and_tip_centre_crosshairs_have_distinct_hotspots() { } #[test] -fn bucket_bitmap_keeps_the_svg_above_left_of_its_exact_crosshair_hotspot() { - for scale in [1.0, 1.25, 2.0] { +fn bucket_bitmap_keeps_the_svg_below_right_of_its_arrow_tip_hotspot() { + for (scale, hotspot) in [(1.0, [1, 1]), (1.25, [1, 1]), (2.0, [2, 2])] { let image = super::bucket::rasterize(scale).unwrap(); - let expected_x = (26.0 / 24.0 * 22.0 * scale).round() + (scale + 1.0).ceil(); - let expected_y = (25.0 / 24.0 * 22.0 * scale).round() + (scale + 1.0).ceil(); - assert_eq!(image.hotspot, [expected_x as u16, expected_y as u16], "bucket box target at {scale}x"); - let gradient_cross = rasterize(&STANDARD_CROSSHAIR, scale).unwrap(); - assert_eq!(alpha(&image, image.hotspot[0], image.hotspot[1]), 0, "Gradient-style open center at {scale}x"); + assert_eq!(image.hotspot, hotspot, "the arrow tip sits one halo in from the top left at {scale}x"); + assert!(alpha(&image, image.hotspot[0], image.hotspot[1]) > 128, "the antialiased tip itself is drawn at {scale}x"); let side = usize::from(image.size[0]); let has_bucket_art = image.rgba.as_chunks::<4>().0.iter().enumerate().any(|(i, p)| { let x = (i % side) as u16; let y = (i / side) as u16; - p[3] > 200 && x + 2 < image.hotspot[0] && y + 2 < image.hotspot[1] + p[0] > 200 && p[3] > 200 && x > image.hotspot[0] + 10 && y > image.hotspot[1] + 10 }); - assert!(has_bucket_art, "opaque bucket art remains above-left of the hotspot at {scale}x"); - - for arm in [1, 5, 8] { - let arm = (arm as f32 * scale).round() as u16; - assert_eq!( - rgba_at(&image, image.hotspot[0] + arm, image.hotspot[1]), - rgba_at(&gradient_cross, gradient_cross.hotspot[0] + arm, gradient_cross.hotspot[1]), - "right arm matches the Gradient crosshair at {scale}x" - ); - assert_eq!( - rgba_at(&image, image.hotspot[0], image.hotspot[1] + arm), - rgba_at(&gradient_cross, gradient_cross.hotspot[0], gradient_cross.hotspot[1] + arm), - "lower arm matches the Gradient crosshair at {scale}x" - ); - } + assert!(has_bucket_art, "opaque white bucket art below-right of the hotspot at {scale}x"); } } @@ -197,7 +174,7 @@ fn scaled_wayland_bucket_uses_one_cached_image_area_without_a_split_crosshair() let (first, first_images) = run(1.25, first_at); assert!(first.platform_output.cursor_image.is_none(), "scaled Wayland does not send a bitmap to winit"); assert_eq!(first.platform_output.cursor_icon, CursorIcon::None, "the image replaces the system arrow"); - assert_eq!(first_images.len(), 1, "bucket and fill crosshair are one Image primitive"); + assert_eq!(first_images.len(), 1, "bucket and arrow are one Image primitive"); let image = super::bucket::rasterize(1.25).unwrap(); let image_bounds = first_images[0].1; let image_hotspot = image_bounds.min + egui::vec2((f32::from(image.hotspot[0]) + 0.5) / 1.25, (f32::from(image.hotspot[1]) + 0.5) / 1.25); @@ -497,6 +474,8 @@ fn write_cursor_preview() { (Shape::Zoom { out: false }, 1.0), (Shape::Zoom { out: true }, 1.0), (Shape::Zoom { out: false }, 2.0), + (Shape::Pipette, 1.0), + (Shape::Pipette, 1.5), ]; let (width, height) = (600_usize, cases.len() * 100); let mut rgba = vec![255; width * height * 4]; @@ -524,6 +503,37 @@ fn write_cursor_preview() { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/tool-cursor-preview.png"); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(path, png).unwrap(); + write_painted_pipette_preview(); +} + +/// The first row is 6x; the second uses a 64x display with the bounded 8x texture. +fn write_painted_pipette_preview() { + let ctx = egui::Context::default(); + let (width, height) = (1200_usize, 800_usize); + let mut rgba = vec![255; width * height * 4]; + for (col, background) in [0_u8, 128, 255].into_iter().enumerate() { + for y in 0..height { + for x in col * 400..(col + 1) * 400 { + rgba[(y * width + x) * 4..(y * width + x) * 4 + 3].fill(background); + } + } + for (row, scale) in [6.0, 64.0].into_iter().enumerate() { + let image = cached_pipette(&ctx, scale, true).image.unwrap(); + let side = usize::from(image.size[0]); + let x0 = col * 400 + 200 - usize::from(image.hotspot[0]); + let y0 = row * 400 + 200 - usize::from(image.hotspot[1]); + for (i, pixel) in image.rgba.as_chunks::<4>().0.iter().enumerate() { + let at = ((y0 + i / side) * width + x0 + i % side) * 4; + let alpha = f32::from(pixel[3]) / 255.0; + let value = (f32::from(pixel[0]) * alpha + f32::from(background) * (1.0 - alpha)).round() as u8; + rgba[at..at + 3].fill(value); + } + } + } + let image = photocraft_codecs::Image::from_u8(width as u32, height as u32, photocraft_codecs::ChannelLayout::Rgba, rgba).unwrap(); + let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/painted-pipette-preview.png"); + std::fs::write(path, png).unwrap(); } /// Run explicitly to inspect the unified bucket bitmap at 1× and 2× against three backgrounds. @@ -1153,3 +1163,202 @@ fn continue_path_bitmap_has_the_centre_cross_and_a_slash_beside_it() { assert_eq!(at(0.0, 9.0), 0, "apart from the cross"); } } + +#[test] +fn pipette_bitmaps_are_readable_at_each_dpi_and_bound_allocations() { + for (scale, side, hot) in [(1.0, 53, 26), (1.25, 65, 32), (1.5, 77, 38), (2.0, 101, 50), (3.0, 151, 75)] { + let image = rasterize(&Shape::Pipette, scale).unwrap(); + assert_eq!(image.size, [side; 2], "bitmap bounds at {scale}x"); + assert_eq!(image.hotspot, [hot; 2], "SVG tip (2, 22) is placed at the bitmap centre"); + assert!(image.rgba.as_chunks::<4>().0.iter().any(|p| p[0] > 230 && p[3] > 230)); + let halo_pixels = image.rgba.as_chunks::<4>().0.iter().filter(|p| p[0] < 25 && p[3] > 100).count(); + assert!(halo_pixels > (35.0 * scale * scale) as usize, "a substantial dark halo at {scale}x: {halo_pixels}"); + for p in 0..side { + assert_eq!( + [alpha(&image, p, 0), alpha(&image, p, side - 1), alpha(&image, 0, p), alpha(&image, side - 1, p)], + [0; 4], + "no clipped halo at {scale}x" + ); + } + assert!(alpha(&image, image.hotspot[0], image.hotspot[1]) > 230); + } + for scale in [f32::NAN, f32::INFINITY, -1.0, 0.0, f32::MAX, 500.0] { + assert!(rasterize(&Shape::Pipette, scale).is_none()); + } +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn pipette_bitmap_uses_the_platform_cursor_units_at_high_dpi() { + let ctx = egui::Context::default(); + ctx.add_plugin(CursorLifecycle); + for (native_ppp, zoom, mac_size, mac_hot, other_size, other_hot) in [(2.0, 1.0, 53, 26, 101, 50), (2.0, 1.5, 77, 38, 151, 75)] { + ctx.set_zoom_factor(zoom); + let mut input = egui::RawInput::default(); + input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(native_ppp); + let mut output = ctx.run_ui(input, |ui| { + let icon = pipette(ui.ctx(), egui::pos2(100.0, 100.0)); + ui.ctx().set_cursor_icon(icon); + }); + assert_eq!(ctx.pixels_per_point(), native_ppp * zoom); + let image = output.platform_output.cursor_image.unwrap(); + let (side, hot) = if cfg!(target_os = "macos") { (mac_size, mac_hot) } else { (other_size, other_hot) }; + assert_eq!(image.size, [side; 2]); + assert_eq!(image.hotspot, [hot; 2]); + assert!(alpha(&image, hot, hot) > 230); + // No renderer consumes font/texture uploads in this output-only test. + output.textures_delta.clear(); + } +} + +/// A Retina child viewport must not evict the root viewport's point-sized native bitmap. +#[test] +fn pipette_bitmap_cache_reuses_each_scale_when_viewports_alternate() { + let ctx = egui::Context::default(); + let first = cached_image(&ctx, &Shape::Pipette, 1.0).unwrap(); + let retina = cached_image(&ctx, &Shape::Pipette, 2.0).unwrap(); + for _ in 0..3 { + assert!(Arc::ptr_eq(&first.rgba, &cached_image(&ctx, &Shape::Pipette, 1.0).unwrap().rgba)); + assert!(Arc::ptr_eq(&retina.rgba, &cached_image(&ctx, &Shape::Pipette, 2.0).unwrap().rgba)); + } + for scale in [1.25, 1.5, 3.0, 4.0, 5.0] { + cached_image(&ctx, &Shape::Pipette, scale).unwrap(); + } + let entries = ctx.data(|d| d.get_temp::>(egui::Id::unique("photocraft-pipette-cache"))).unwrap(); + assert_eq!(entries.len(), 4, "repeated UI zoom changes cannot grow the cache indefinitely"); +} + +/// Declarations are valid XML but cannot be nested inside the composed cursor's SVG root. +#[test] +fn pipette_svg_accepts_a_preamble_and_reports_broken_styling_or_xml() { + let icon = include_str!("../../../../../assets/icons/pipette.svg"); + let original = rasterize_pipette_svg(icon, 1.0, 53, 26).unwrap(); + let prefixed = format!("\n\n{icon}"); + assert_eq!(rasterize_pipette_svg(&prefixed, 1.0, 53, 26).unwrap().rgba, original.rgba); + for (bad, expected) in [ + (icon.replace("currentColor", "black"), "currentColor"), + (icon.replace("stroke-width=\"2\"", "stroke-width='2'"), "stroke-width"), + (icon.replace("0 0 24 24", "0 0 32 32"), "viewBox"), + (icon.replace("", ""), "invalid pipette SVG"), + ] { + assert!(rasterize_pipette_svg(&bad, 1.0, 53, 26).unwrap_err().contains(expected)); + } +} + +/// A load failure must not leave an invisible pointer on the painted-only path. +#[test] +fn pipette_failed_bitmap_keeps_a_visible_fallback() { + let ctx = egui::Context::default(); + let child = egui::ViewportId::from_hash_of("pipette-failed-child"); + ctx.data_mut(|d| { + d.insert_temp(egui::Id::unique("photocraft-pipette-cache"), vec![CachedPipette { scale: 1.0, painted: true, image: None, texture: None }]) + }); + let mut input = egui::RawInput { viewport_id: child, ..Default::default() }; + input.viewports.entry(child).or_default(); + let mut output = ctx.run_ui(input, |ui| { + let icon = pipette(ui.ctx(), egui::pos2(100.0, 100.0)); + ui.ctx().set_cursor_icon(icon); + }); + assert!(output.platform_output.cursor_image.is_none()); + assert_eq!(output.platform_output.cursor_icon, CursorIcon::Crosshair); + output.textures_delta.clear(); +} + +/// Exercise the same painted path used on the web and in immediate child viewports. +#[test] +fn pipette_painted_fallback_keeps_its_hotspot_and_reuses_textures_across_frames_and_scales() { + let ctx = egui::Context::default(); + ctx.add_plugin(CursorLifecycle); + let child = egui::ViewportId::from_hash_of("pipette-test-child"); + let draw = |scale: f32, at: Pos2, side: f32, hot: f32| { + let mut input = egui::RawInput { viewport_id: child, ..Default::default() }; + input.viewports.entry(child).or_default().native_pixels_per_point = Some(scale); + let output = ctx.run_ui(input, |ui| { + assert!(!native(ui.ctx())); + let icon = pipette(ui.ctx(), at); + ui.ctx().set_cursor_icon(icon); + }); + assert!(output.platform_output.cursor_image.is_none()); + assert_eq!(output.platform_output.cursor_icon, CursorIcon::None); + let mut meshes = Vec::new(); + for shape in &output.shapes { + collect_meshes(&shape.shape, &mut meshes); + } + assert_eq!(meshes.len(), 1); + let (texture, rect) = meshes[0]; + assert_eq!(rect.size(), Vec2::splat(side / scale)); + assert_eq!(rect.min + Vec2::splat((hot + 0.5) / scale), at, "centre of hotspot texel follows the pointer"); + (texture, output.textures_delta) + }; + let (first, mut delta) = draw(1.0, egui::pos2(100.0, 100.0), 53.0, 26.0); + // This headless test checks upload reuse without a renderer. Acknowledge every delta, + // including the initial upload and the new-density upload, before dropping it. + delta.clear(); + let (moved, mut delta) = draw(1.0, egui::pos2(120.0, 140.0), 53.0, 26.0); + assert_eq!(first, moved); + assert!(!delta.set.iter().any(|(id, _)| *id == first), "no repeated upload on movement"); + assert!(!delta.free.contains(&first), "context retains the texture handle between frames"); + delta.clear(); + let (retina, mut delta) = draw(2.0, egui::pos2(120.0, 140.0), 101.0, 50.0); + assert_ne!(first, retina, "different density uses a different texture"); + delta.clear(); + let (back, mut delta) = draw(1.0, egui::pos2(140.0, 160.0), 53.0, 26.0); + assert_eq!(back, first, "alternating viewport densities retain both textures"); + assert!(!delta.set.iter().any(|(id, _)| *id == first)); + assert!(!delta.free.contains(&retina)); + delta.clear(); +} + +/// Painted viewports must keep the artwork even above every platform's native cursor limit. +#[test] +fn pipette_painted_fallback_survives_high_display_scales() { + let ctx = egui::Context::default(); + ctx.add_plugin(CursorLifecycle); + let child = egui::ViewportId::from_hash_of("pipette-high-dpi-child"); + for display_scale in [6.0, 64.0] { + let at = egui::pos2(100.0, 100.0); + let mut input = egui::RawInput { viewport_id: child, ..Default::default() }; + input.viewports.entry(child).or_default().native_pixels_per_point = Some(display_scale); + let mut output = ctx.run_ui(input, |ui| { + let icon = pipette(ui.ctx(), at); + ui.ctx().set_cursor_icon(icon); + }); + assert_eq!(output.platform_output.cursor_icon, CursorIcon::None, "{display_scale}x must paint the pipette"); + assert!(output.platform_output.cursor_image.is_none()); + let mut meshes = Vec::new(); + for shape in &output.shapes { + collect_meshes(&shape.shape, &mut meshes); + } + assert_eq!(meshes.len(), 1, "the sampling cursor still has artwork at {display_scale}x"); + let texture = meshes[0].0; + let upload = output.textures_delta.set.get(&texture).unwrap().first().unwrap(); + let (side, hot, raster_scale) = if display_scale == 6.0 { (297, 148.0, 6.0) } else { (395, 197.0, 8.0) }; + assert_eq!(upload.image.size(), [side; 2], "bounded texture even with excessive display scaling"); + let expected = egui::Rect::from_min_size(at - Vec2::splat((hot + 0.5) / raster_scale), Vec2::splat(side as f32 / raster_scale)); + assert!(meshes[0].1.min.distance(expected.min) < 0.001); + assert!(meshes[0].1.max.distance(expected.max) < 0.001); + // Inspect the upload above, then discard it intentionally: no GPU renderer is attached. + output.textures_delta.clear(); + } +} + +/// The native cursor cap and the independent GPU cap must not leak through the shared cache. +#[test] +fn pipette_native_and_painted_limits_are_independent_and_bounded() { + let ctx = egui::Context::default(); + for scale in [6.0, 64.0] { + let native = cached_pipette(&ctx, scale, false); + let painted = cached_pipette(&ctx, scale, true); + let image = painted.image.unwrap(); + assert!(image.size.into_iter().all(|side| side <= 395)); + assert!(painted.texture.is_some()); + assert_eq!(native.image.is_some(), scale == 6.0 && MAX_SIDE >= 297); + assert_eq!(cached_pipette(&ctx, scale, false).image, native.image, "painted texture cannot bypass the native cap"); + assert!(Arc::ptr_eq(&image.rgba, &cached_pipette(&ctx, scale, true).image.unwrap().rgba)); + } + let capped = cached_pipette(&ctx, f32::MAX, true); + assert_eq!(capped.image.unwrap().size, [395; 2]); + for scale in [0.0, -1.0, f32::NAN, f32::INFINITY] { + assert!(cached_pipette(&ctx, scale, true).image.is_none()); + } +} diff --git a/crates/ui-egui/src/canvas/tool_feedback.rs b/crates/ui-egui/src/canvas/tool_feedback.rs index 88aec042e5..d25f587c0d 100644 --- a/crates/ui-egui/src/canvas/tool_feedback.rs +++ b/crates/ui-egui/src/canvas/tool_feedback.rs @@ -64,16 +64,8 @@ pub fn selection_mode(tool: Tool, bar: u8, m: egui::Modifiers) -> &'static str { "add" } } - // Object Selection: ⌥ subtracts, ⇧ adds (see `retouch_ui::finish_object_selection`). - Tool::ObjectSelection => { - if m.alt { - "subtract" - } else if m.shift { - "add" - } else { - "replace" - } - } + // Every other selection tool, Object Selection included: ⇧⌥ intersects, ⇧ adds, ⌥ + // subtracts, otherwise the options-bar mode (`retouch_ui::finish_object_selection`). _ => { if m.shift && m.alt { "intersect" @@ -109,7 +101,14 @@ pub fn badge(app: &PhotocraftApp, tool: Tool, m: egui::Modifiers) -> Option { - let o = app.ui.tool_options.clone(); - let contents = if o.bucket_fill_pattern { "pattern" } else { "foreground" }; - let mode = if o.bucket_clear { "clear" } else { o.bucket_blend_mode.label() }; - let _ = app.run("paint.bucket", json!({"x": x.floor(), "y": y.floor(), "tolerance": o.tolerance, "contiguous": o.contiguous, "antiAlias": o.anti_alias, "sampleAllLayers": o.sample_all.paint_bucket, "opacity": o.fill_opacity, "contents": contents, "mode": mode, "target": paint_target(app)})); + bucket_click(app, x, y); return; } Tool::RedEye => { @@ -800,9 +822,10 @@ fn hidden_target(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { photocraft_engine::hidden_target::refusal(&app.session, cmd, &json!({})) } -/// The press-time refusals: a hidden target layer (#571), and for the Brush a locked layer or a -/// group's pixels. The Brush says why in an alert, as in Photoshop (#11898); the other tools say -/// a hidden target in the status bar. True when the press is refused. +/// The press-time refusals: a hidden target layer (#571), and for the tools with an alert in +/// `brush_refusal` (the Brush, #11898, and others) a locked layer or a group's pixels. Those tools +/// say why in an alert, as in Photoshop; the other tools say a hidden target in the status bar +/// (the Remove tool mostly says nothing: [`quiet_hidden_refusal`]). True when the press is refused. fn press_refused(app: &mut PhotocraftApp, tool: Tool) -> bool { let hidden = hidden_target(app, tool); if let Some(message) = crate::brush_refusal::alert(app, tool, hidden.is_some()) { @@ -810,8 +833,10 @@ fn press_refused(app: &mut PhotocraftApp, tool: Tool) -> bool { return true; } if let Some(why) = hidden { - app.ui.status = why.into(); - app.ui.status_error = true; + if !quiet_hidden_refusal(app, tool) { + app.ui.status = why.into(); + app.ui.status_error = true; + } return true; } false @@ -832,6 +857,22 @@ fn refuse_group(app: &mut PhotocraftApp, tool: Tool) -> bool { group } +/// A Remove press on a hidden active pixel layer does nothing and says nothing, as in Photoshop +/// (#12554). Only that case was measured: a layer inside a hidden group, a targeted mask, Sample +/// All Layers and the other layer kinds keep the status-bar error. Hidden is checked before the +/// lock, so a hidden layer with Lock All is quiet too. +fn quiet_hidden_refusal(app: &PhotocraftApp, tool: Tool) -> bool { + if tool != Tool::Remove || app.ui.tool_options.sample_all.remove || paint_target(app) != json!("pixels") { + return false; + } + let Some(st) = app.session.active() else { return false }; + let Some(id) = st.active_layer.filter(|&id| st.doc.layer(id).is_some_and(|l| matches!(l.content, photocraft_doc::LayerContent::Raster(_)))) else { + return false; + }; + let Some(path) = st.doc.path_of(id) else { return false }; + (1..path.len()).all(|n| path.get(..n).and_then(|p| st.doc.layer_at(p)).is_some_and(|l| l.visible)) +} + /// Is document point `p` inside the active document's selection? fn inside_selection(app: &PhotocraftApp, p: [f64; 2]) -> bool { app.session.active().and_then(|st| st.doc.selection.as_ref()).is_some_and(|sel| covers(sel, p)) @@ -869,7 +910,21 @@ pub fn selection_drag_kind(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: e // Click-driven selection tools (a press places a point or samples): only ⌘ drags the // selection, and not while a polygon is being drawn. let clicky = matches!(tool, Tool::PolygonLasso | Tool::MagicWand); - let marquee = matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::SingleRowMarquee | Tool::SingleColumnMarquee); + // Object Selection with Object Finder on drags the outline like a marquee in New mode (#12853). + // With Object Finder off a press stays a Quick Selection dab or a rectangle, as before (the + // issue measured only Finder on). Unlike the marquees, ⌘ with it is the Move tool + // (`hold_keys::cmd_moves`), which moves the pixels itself: a ⌘ press must not start a cut here + // first. + let marquee = matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::SingleRowMarquee | Tool::SingleColumnMarquee) + || (tool == Tool::ObjectSelection && app.ui.tool_options.object_finder); + if tool == Tool::ObjectSelection && mods.command { + return None; + } + // In Indexed Color and Bitmap the press must reach `finish_object_selection` for the tool's + // alert (#12867) rather than deselect or move the outline. + if tool == Tool::ObjectSelection && app.session.active().is_some_and(|st| photocraft_engine::smartselect_cmds::object_mode_refusal(st.doc.mode).is_some()) { + return None; + } if !(clicky || marquee || tool == Tool::Lasso) || (clicky && !app.ui.polygon.is_empty()) { return None; } diff --git a/crates/ui-egui/src/canvas/triangle_alt_eyedropper_tests.rs b/crates/ui-egui/src/canvas/triangle_alt_eyedropper_tests.rs new file mode 100644 index 0000000000..97e36ed232 --- /dev/null +++ b/crates/ui-egui/src/canvas/triangle_alt_eyedropper_tests.rs @@ -0,0 +1,175 @@ +//! #13364: with the Triangle tool, ⌥ (Alt) held at the press with no shape layer active picks the +//! colour under the pointer as the foreground and the tool's Fill instead of drawing or opening +//! Create Triangle; ⇧⌥ does the same. ⌥ pressed only after the drag started still draws from the +//! centre, and with a shape layer active ⌥ at the press does not sample. + +use egui::Modifiers; +use photocraft_doc::{Color, Fill, LayerContent}; +use serde_json::json; + +use super::shape_alt_samples; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +const RED: [u8; 3] = [220, 30, 30]; +const BLACK: [u8; 3] = [0, 0, 0]; +const WHITE: [u8; 3] = [255, 255, 255]; +/// A point on the red layer, and one on the white Background only. +const ON_RED: [f64; 2] = [200.0, 175.0]; +const ON_WHITE: [f64; 2] = [500.0, 350.0]; + +/// The issue's test document: 800 × 600, white Background, a red (220,30,30) pixel layer at +/// 100,100 to 300,250 (active), black foreground, the Triangle tool in Shape mode. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 200, "height": 150})).unwrap(); + app.run("edit.fill", json!({"color": "#dc1e1e"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.run("tools.setColors", json!({"foreground": "#000000"})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Triangle; + app +} + +/// What a press could change: history states, layers, open dialogs and colour samplers. +fn document_state(app: &PhotocraftApp) -> (usize, usize, usize, usize) { + let st = app.session.active().unwrap(); + (st.history.past_len(), st.doc.layers.len(), app.ui.dialogs.len(), st.color_samplers.len()) +} + +/// The foreground colour in 8-bit RGB. +fn foreground(app: &PhotocraftApp) -> [u8; 3] { + let c = app.session.tools.foreground; + [0, 1, 2].map(|i| (c[i] * 255.0).round() as u8) +} + +/// The tool's Fill colour: a solid Fill follows the foreground (`vector_ui::shapes::tool_paint`). +fn tool_fill(app: &PhotocraftApp) -> [u8; 3] { + let o = &app.ui.tool_options; + assert!(o.shape_fill && o.shape_fill_gradient.is_none(), "a solid Fill"); + foreground(app) +} + +/// Press at `from` with `press` held, move to `to` with `rest`, release there with `rest`. +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], press: Modifiers, rest: Modifiers) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, press); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, rest); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, rest); +} + +/// The active layer's Fill colour in 8-bit RGB, which must be a shape layer with a solid Fill. +fn active_shape_fill(app: &PhotocraftApp) -> [u8; 3] { + let st = app.session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + let LayerContent::Shape(shape) = &layer.content else { panic!("a shape layer, not {:?}", layer.name) }; + let Some(Fill::Solid(c)) = &shape.fill else { panic!("a solid Fill, not {:?}", shape.fill) }; + let [r, g, b, _] = c.to_rgba8(); + [r, g, b] +} + +#[test] +fn alt_click_on_the_red_layer_picks_it_as_foreground_and_fill() { + for press in [Modifiers::ALT, Modifiers::SHIFT | Modifiers::ALT] { + let mut app = app(); + let before = document_state(&app); + drag(&mut app, ON_RED, ON_RED, press, press); + assert_eq!(foreground(&app), RED, "{press:?}: foreground #DC1E1E"); + assert_eq!(tool_fill(&app), RED, "{press:?}: Fill 220,30,30"); + assert_eq!(document_state(&app), before, "{press:?}: no History state, layer, dialog or colour sampler"); + assert!(!app.alt_sampling, "{press:?}: the release ends the sampling"); + // The next triangle is drawn in that Fill. + drag(&mut app, [400.0, 300.0], [600.0, 400.0], Modifiers::NONE, Modifiers::NONE); + assert_eq!(active_shape_fill(&app), RED, "{press:?}: the next triangle's Fill"); + } +} + +#[test] +fn an_alt_drag_keeps_the_colour_under_the_release_point() { + for press in [Modifiers::ALT, Modifiers::SHIFT | Modifiers::ALT] { + let mut app = app(); + let before = document_state(&app); + // The last move is still on red; the release is on white. + tool_event(&mut app, ToolEvent::Down { x: ON_RED[0], y: ON_RED[1], pressure: 1.0 }, press); + tool_event(&mut app, ToolEvent::Move { x: 250.0, y: 200.0, pressure: 1.0 }, press); + assert_eq!(foreground(&app), RED, "{press:?}: the drag samples as it goes"); + tool_event(&mut app, ToolEvent::Up { x: ON_WHITE[0], y: ON_WHITE[1] }, press); + assert_eq!(foreground(&app), WHITE, "{press:?}: foreground"); + assert_eq!(tool_fill(&app), WHITE, "{press:?}: Fill"); + assert_eq!(document_state(&app), before, "{press:?}: no shape and no History state"); + } +} + +#[test] +fn a_gradient_or_no_fill_becomes_the_sampled_solid_fill() { + let gradient = Fill::Gradient { + stops: vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], + angle: 90.0, + scale: 1.0, + style: Default::default(), + reverse: false, + opacity_stops: Vec::new(), + midpoints: Vec::new(), + offset: (0.0, 0.0), + dither: false, + align: true, + }; + for (fill, fill_gradient) in [(true, Some(gradient)), (false, None)] { + let mut app = app(); + app.ui.tool_options.shape_fill = fill; + app.ui.tool_options.shape_fill_gradient = fill_gradient; + drag(&mut app, ON_RED, ON_RED, Modifiers::ALT, Modifiers::ALT); + assert_eq!(tool_fill(&app), RED, "fill {fill}"); + } +} + +#[test] +fn alt_pressed_after_the_drag_started_still_draws_from_the_centre() { + let mut app = app(); + let layers = document_state(&app).1; + drag(&mut app, [400.0, 300.0], [500.0, 350.0], Modifiers::NONE, Modifiers::ALT); + assert_eq!(foreground(&app), BLACK, "nothing sampled"); + assert_eq!(document_state(&app).1, layers + 1, "a triangle was drawn"); + let st = app.session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + let LayerContent::Shape(shape) = &layer.content else { panic!("a shape layer") }; + let anchors: Vec<[f64; 2]> = shape.path.subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); + assert_eq!(anchors, [[400.0, 250.0], [500.0, 350.0], [300.0, 350.0]], "centred on the press"); +} + +#[test] +fn a_shape_layer_active_does_not_sample() { + let mut app = app(); + drag(&mut app, [400.0, 300.0], [600.0, 400.0], Modifiers::NONE, Modifiers::NONE); + app.run("tools.setColors", json!({"foreground": "#000000"})).unwrap(); + assert!(!shape_alt_samples(&mut app, Modifiers::ALT, ON_RED[0], ON_RED[1]), "⌥ is left to the subtract"); + tool_event(&mut app, ToolEvent::Down { x: ON_RED[0], y: ON_RED[1], pressure: 1.0 }, Modifiers::ALT); + assert!(!app.alt_sampling); + tool_event(&mut app, ToolEvent::Up { x: ON_RED[0], y: ON_RED[1] }, Modifiers::ALT); + assert_eq!(foreground(&app), BLACK); +} + +#[test] +fn unmeasured_cases_keep_drawing() { + let mut app = app(); + assert!(shape_alt_samples(&mut app, Modifiers::ALT, ON_RED[0], ON_RED[1])); + assert!(shape_alt_samples(&mut app, Modifiers::SHIFT | Modifiers::ALT, ON_RED[0], ON_RED[1])); + assert!(!shape_alt_samples(&mut app, Modifiers::NONE, ON_RED[0], ON_RED[1])); + assert!(!shape_alt_samples(&mut app, Modifiers::ALT | Modifiers::CTRL, ON_RED[0], ON_RED[1]), "Control+⌥ is the brush resize"); + assert!(!shape_alt_samples(&mut app, Modifiers::ALT, -40.0, -40.0), "nothing to sample off the image"); + for mode in ["path", "pixels"] { + app.ui.tool_options.shape_mode = mode.into(); + assert!(!shape_alt_samples(&mut app, Modifiers::ALT, ON_RED[0], ON_RED[1]), "{mode} mode wasn't measured"); + } + app.ui.tool_options.shape_mode = "shape".into(); + app.ui.tool = Tool::Rectangle; + assert!(!shape_alt_samples(&mut app, Modifiers::ALT, ON_RED[0], ON_RED[1]), "the other shape tools are their own items"); + // Off the image the press draws from the centre, as before. + app.ui.tool = Tool::Triangle; + let layers = document_state(&app).1; + drag(&mut app, [-40.0, -40.0], [60.0, 60.0], Modifiers::ALT, Modifiers::ALT); + assert_eq!(foreground(&app), BLACK, "nothing sampled"); + assert_eq!(document_state(&app).1, layers + 1, "a triangle was drawn"); +} diff --git a/crates/ui-egui/src/canvas/wheel_nav.rs b/crates/ui-egui/src/canvas/wheel_nav.rs index 13847d0d88..cf8a42d347 100644 --- a/crates/ui-egui/src/canvas/wheel_nav.rs +++ b/crates/ui-egui/src/canvas/wheel_nav.rs @@ -88,6 +88,10 @@ pub struct Input { pub notch: f32, } +/// Screen points one wheel notch (a line) pans the canvas: Photoshop's 16 px (#12028). Panels and +/// other scroll areas keep egui's `line_scroll_speed`, and so does the wheel zoom's notch. +pub const CANVAS_PAN_PER_LINE: f32 = 16.0; + /// The view change for one frame of wheel input, if any. pub fn classify(i: Input) -> Option { if i.pinch_zooms && i.zoom_delta.is_finite() && i.zoom_delta > 0.0 && i.zoom_delta != 1.0 { @@ -410,7 +414,9 @@ pub fn read_with( } None => ctx.data(|d| d.get_temp::(shift_id())).unwrap_or(false), }; - let scroll = if smooth { smoothed } else { unsmoothed_scroll(&wheel, (alt, shift), &options, page) }; + let scroll = if smooth { smoothed } else { unsmoothed_scroll(&wheel, (alt, shift), &options, page, options.line_scroll_speed) }; + // The canvas pans [`CANVAS_PAN_PER_LINE`] points per notch; zoom steps keep egui's notch. + let pan = (!smooth).then(|| unsmoothed_scroll(&wheel, (alt, shift), &options, page, CANVAS_PAN_PER_LINE)); let wheel = mark_unsmoothed(ctx, wheel); if !hovered { @@ -521,7 +527,15 @@ pub fn read_with( // Unsmoothed, a scroll pans by this frame's own wheel events (none: no tail). scroll }; - classify(Input { scroll, raw, zoom_delta, alt, shift, zoom_with_wheel, pinch_zooms, animated_zoom, notch }) + match (classify(Input { scroll, raw, zoom_delta, alt, shift, zoom_with_wheel, pinch_zooms, animated_zoom, notch }), pan) { + // The canvas notch only along the axes egui's pan moves: a zoom's wheel delta never + // leaks into it, and a pan that cancels out at the canvas notch stays still. + (Some(Wheel::Pan(s)), Some(p)) => { + let p = Vec2::new(if s.x != 0.0 { p.x } else { 0.0 }, if s.y != 0.0 { p.y } else { 0.0 }); + (p != Vec2::ZERO).then_some(Wheel::Pan(p)) + } + (wheel, _) => wheel, + } } } @@ -536,7 +550,7 @@ fn gesture_mode(m: &Modifiers) -> (bool, bool) { /// it sideways as egui does ([`configure`]), so every pan, plain or sideways, moves at once. /// Only the wheel events of the gesture in progress (`mode`, the ⌥ and ⇧ of [`gesture_mode`]) /// count: a ⌥ zoom notch in the same frame as a plain pan notch doesn't pan too. -fn unsmoothed_scroll(wheel: &[(MouseWheelUnit, Vec2, Modifiers, TouchPhase)], mode: (bool, bool), options: &egui::InputOptions, page: f32) -> Vec2 { +fn unsmoothed_scroll(wheel: &[(MouseWheelUnit, Vec2, Modifiers, TouchPhase)], mode: (bool, bool), options: &egui::InputOptions, page: f32, line: f32) -> Vec2 { wheel.iter().fold(Vec2::ZERO, |sum, (unit, delta, modifiers, phase)| { // egui scrolls only by `Move` events; a trackpad's `Start`, `End` or `Cancel` delta // (`WheelState::on_wheel_event`) is not a scroll. @@ -550,7 +564,7 @@ fn unsmoothed_scroll(wheel: &[(MouseWheelUnit, Vec2, Modifiers, TouchPhase)], mo let d = *delta * match unit { MouseWheelUnit::Point => 1.0, - MouseWheelUnit::Line => options.line_scroll_speed, + MouseWheelUnit::Line => line, MouseWheelUnit::Page => page, }; let sideways = modifiers.matches_any(options.horizontal_scroll_modifier); @@ -612,5 +626,7 @@ pub fn pinch_factor(i: &InputState, touch_gestures: bool) -> f32 { .product() } +#[cfg(test)] +mod scroll_step_tests; #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/canvas/wheel_nav/scroll_step_tests.rs b/crates/ui-egui/src/canvas/wheel_nav/scroll_step_tests.rs new file mode 100644 index 0000000000..8eced69211 --- /dev/null +++ b/crates/ui-egui/src/canvas/wheel_nav/scroll_step_tests.rs @@ -0,0 +1,100 @@ +//! #12028: one wheel notch over the canvas pans 16 screen points, as in Photoshop (egui's notch is +//! 40): down, and sideways with Ctrl, at any zoom. Trackpad point deltas, the Alt and Shift+Alt +//! zooms, Zoom with Scroll Wheel and panels keep their notch. + +use egui::{Context, Event, Id, Modifiers, MouseWheelUnit, RawInput, TouchPhase, Vec2}; + +use super::{CANVAS_PAN_PER_LINE, Wheel, configure, read_with}; + +fn event(unit: MouseWheelUnit, delta: Vec2, modifiers: Modifiers) -> Event { + Event::MouseWheel { source: egui::MouseWheelSource::Unknown, unit, delta, phase: TouchPhase::Move, modifiers } +} + +/// What the canvas reads (unsmoothed) for one frame holding `events`; `zoom_with_wheel` and +/// `animated` are the preferences. +fn canvas_reads(events: Vec, zoom_with_wheel: bool, animated: bool) -> Option { + let ctx = Context::default(); + configure(&ctx); + let owner = Id::unique("scroll-step-test"); + let modifiers = events.iter().find_map(|e| if let Event::MouseWheel { modifiers, .. } = e { Some(*modifiers) } else { None }).unwrap_or_default(); + let events = std::iter::once(Event::ModifiersChanged(modifiers)).chain(events).collect(); + let raw = RawInput { time: Some(0.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut got = None; + let mut out = ctx.run_ui(raw, |ui| got = read_with(ui.ctx(), zoom_with_wheel, true, animated, owner, true, false, true)); + out.textures_delta.clear(); + got +} + +fn pan(w: Option) -> Vec2 { + match w { + Some(Wheel::Pan(d)) => d, + other => panic!("not a pan: {other:?}"), + } +} + +#[test] +fn one_notch_pans_sixteen_points() { + assert_eq!(pan(canvas_reads(vec![event(MouseWheelUnit::Line, Vec2::new(0.0, -1.0), Modifiers::NONE)], false, false)), Vec2::new(0.0, -16.0)); + assert_eq!(pan(canvas_reads(vec![event(MouseWheelUnit::Line, Vec2::new(0.0, 3.0), Modifiers::NONE)], false, true)), Vec2::new(0.0, 48.0)); + assert_eq!(CANVAS_PAN_PER_LINE, 16.0); +} + +#[test] +fn ctrl_wheel_pans_sixteen_points_sideways() { + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + assert_eq!(pan(canvas_reads(vec![event(MouseWheelUnit::Line, Vec2::new(0.0, -1.0), ctrl)], false, false)), Vec2::new(-16.0, 0.0)); +} + +#[test] +fn trackpad_points_pan_as_before() { + assert_eq!(pan(canvas_reads(vec![event(MouseWheelUnit::Point, Vec2::new(0.0, -30.0), Modifiers::NONE)], false, false)), Vec2::new(0.0, -30.0)); +} + +#[test] +fn the_wheel_zooms_keep_their_notch() { + let notch = |ctx: &Context| ctx.options(|o| o.input_options.line_scroll_speed); + let egui_notch = { + let ctx = Context::default(); + configure(&ctx); + notch(&ctx) + }; + assert!(egui_notch > CANVAS_PAN_PER_LINE, "egui's notch: {egui_notch}"); + // Alt + one notch up: one ×1.1 step, instant with Animated Zoom off. + match canvas_reads(vec![event(MouseWheelUnit::Line, Vec2::new(0.0, 1.0), Modifiers::ALT)], false, false) { + Some(Wheel::Zoom(f)) => assert!((f - 1.1).abs() < 1e-4, "{f}"), + other => panic!("{other:?}"), + } + // Zoom with Scroll Wheel: the plain notch is a ×1.1 step too. + match canvas_reads(vec![event(MouseWheelUnit::Line, Vec2::new(0.0, 1.0), Modifiers::NONE)], true, false) { + Some(Wheel::Zoom(f)) => assert!((f - 1.1).abs() < 1e-4, "{f}"), + other => panic!("{other:?}"), + } + // Shift + Alt: one snap step. + assert_eq!( + canvas_reads(vec![event(MouseWheelUnit::Line, Vec2::new(0.0, 1.0), Modifiers { alt: true, shift: true, ..Modifiers::NONE })], false, false), + Some(Wheel::SnapZoom(1)) + ); +} + +/// Line and point deltas that cancel out at the canvas notch pan nothing, even where they would +/// not cancel at egui's notch (Alt with Zoom with Scroll Wheel pans). +#[test] +fn a_pan_that_cancels_at_the_canvas_notch_stays_still() { + let events = vec![event(MouseWheelUnit::Line, Vec2::new(0.0, 1.0), Modifiers::ALT), event(MouseWheelUnit::Point, Vec2::new(0.0, -16.0), Modifiers::ALT)]; + assert_eq!(canvas_reads(events, true, false), None); +} + +/// A sideways Ctrl pan in the same frame as plain zoom deltas that cancel at egui's notch (Zoom +/// with Scroll Wheel, Animated Zoom) stays sideways: the zoom's deltas never reach the pan. +#[test] +fn zoom_deltas_stay_out_of_a_sideways_pan() { + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + let events = vec![ + event(MouseWheelUnit::Line, Vec2::new(0.0, -1.0), ctrl), + event(MouseWheelUnit::Line, Vec2::new(0.0, 1.0), ctrl), + event(MouseWheelUnit::Point, Vec2::new(0.0, -40.0), ctrl), + event(MouseWheelUnit::Line, Vec2::new(0.0, -1.0), ctrl), + ]; + let p = pan(canvas_reads(events, true, true)); + assert_eq!(p.y, 0.0, "{p:?}"); +} diff --git a/crates/ui-egui/src/canvas/wheel_nav/tests.rs b/crates/ui-egui/src/canvas/wheel_nav/tests.rs index a7b2d9f58d..bb6067799b 100644 --- a/crates/ui-egui/src/canvas/wheel_nav/tests.rs +++ b/crates/ui-egui/src/canvas/wheel_nav/tests.rs @@ -80,7 +80,8 @@ fn unsmoothed_wheel_pans_at_once_without_a_glide() { ctx.options(|o| o.input_options.line_scroll_speed) }; let direct = pans(false); - assert!(near(direct[0], Vec2::new(0.0, -notch)), "the whole notch at once: {:?}", direct[0]); + // The canvas pans Photoshop's 16 points per notch (#12028), all of it at once. + assert!(near(direct[0], Vec2::new(0.0, -CANVAS_PAN_PER_LINE)), "the whole notch at once: {:?}", direct[0]); assert!(direct[1..].iter().all(|p| *p == Vec2::ZERO), "no glide after it"); let smooth = pans(true); assert!(smooth[0].y.abs() < notch - 0.5, "smoothed, the first frame moves only part of it: {:?}", smooth[0]); @@ -427,7 +428,7 @@ fn animated_zoom_keeps_the_sideways_wheel_unsmoothed_with_animations_off() { pan }) .collect(); - assert!(near(pans[0], Vec2::new(40.0, 0.0)), "the whole notch at once: {:?}", &pans[..4]); + assert!(near(pans[0], Vec2::new(16.0, 0.0)), "the whole notch at once: {:?}", &pans[..4]); assert!(pans[1..].iter().all(|p| *p == Vec2::ZERO), "no glide after it: {pans:?}"); } @@ -450,23 +451,23 @@ fn unsmoothed_pan_takes_only_the_wheel_events_of_the_gesture_in_progress() { let down = Vec2::new(0.0, -1.0); // ⌥ zooms, then a plain notch pans: one notch, not two. let pan = unsmoothed_frame(vec![wheel(down, Modifiers::ALT), wheel(down, Modifiers::NONE)], false); - assert_eq!(pan, Some(Wheel::Pan(Vec2::new(0.0, -40.0))), "only the plain notch pans"); + assert_eq!(pan, Some(Wheel::Pan(Vec2::new(0.0, -16.0))), "only the plain notch pans"); // ⇧ + wheel pans sideways: a plain notch before it in the frame is not part of that. let pan = unsmoothed_frame(vec![wheel(down, Modifiers::NONE), wheel(down, Modifiers::SHIFT)], false); - assert_eq!(pan, Some(Wheel::Pan(Vec2::new(-40.0, 0.0))), "only the ⇧ notch pans, sideways"); + assert_eq!(pan, Some(Wheel::Pan(Vec2::new(-16.0, 0.0))), "only the ⇧ notch pans, sideways"); // Zoom with Scroll Wheel: ⌥ + wheel pans; the plain notch before it zooms and doesn't pan. let pan = unsmoothed_frame(vec![wheel(down, Modifiers::NONE), wheel(down, Modifiers::ALT)], true); - assert_eq!(pan, Some(Wheel::Pan(Vec2::new(0.0, -40.0))), "only the ⌥ notch pans"); + assert_eq!(pan, Some(Wheel::Pan(Vec2::new(0.0, -16.0))), "only the ⌥ notch pans"); // ...and with the plain wheel zooming, a ⇧ snap notch earlier in the frame doesn't pan sideways. let zoom = unsmoothed_frame(vec![wheel(Vec2::new(0.0, 1.0), Modifiers::SHIFT), wheel(down, Modifiers::NONE)], true); assert!(matches!(zoom, Some(Wheel::Zoom(f)) if f < 1.0), "the plain notch zooms, nothing pans: {zoom:?}"); // ⌘/Ctrl + wheel is part of the plain gesture: it pans sideways alongside a plain notch. let pan = unsmoothed_frame(vec![wheel(down, CTRL), wheel(down, Modifiers::NONE)], false); - assert_eq!(pan, Some(Wheel::Pan(Vec2::new(-40.0, -40.0))), "⌘/Ctrl + wheel and a plain notch both pan"); + assert_eq!(pan, Some(Wheel::Pan(Vec2::new(-16.0, -16.0))), "⌘/Ctrl + wheel and a plain notch both pan"); // A held ⌥ the wheel event itself misses (#8049) still makes it the ⌥ gesture's. let alt_key = |pressed: bool| Event::Key { key: Key::AltLeft, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; let pan = unsmoothed_frame(vec![wheel(down, Modifiers::NONE), alt_key(true), wheel(down, Modifiers::NONE), alt_key(false)], true); - assert_eq!(pan, Some(Wheel::Pan(Vec2::new(0.0, -40.0))), "only the notch under the held ⌥ pans"); + assert_eq!(pan, Some(Wheel::Pan(Vec2::new(0.0, -16.0))), "only the notch under the held ⌥ pans"); } /// A diagonal point step with ⌥ is measured as egui measures it, folded onto one axis: (5, 5) diff --git a/crates/ui-egui/src/canvas/zoom_hold.rs b/crates/ui-egui/src/canvas/zoom_hold.rs index 8da4535e01..852e0a6776 100644 --- a/crates/ui-egui/src/canvas/zoom_hold.rs +++ b/crates/ui-egui/src/canvas/zoom_hold.rs @@ -249,6 +249,23 @@ mod tests { assert!(xf(&h).to_screen(doc[0] as f32, doc[1] as f32).distance(p) < 0.5); } + #[test] + fn zoom_out_mode_leaves_the_hold_direction_alone() { + // Zoom Out mode was not measured for Animated Zoom (#12066): a hold still zooms in, and + // out with ⌥, as in Zoom In mode. + for alt in [false, true] { + let held = |zoom_in: bool| { + let mut h = harness(true); + h.state_mut().ui.tool_options.zoom_in = zoom_in; + let p = h.state().last_canvas_rect.center() + vec2(50.0, -30.0); + hold(&mut h, p, 8, alt) + }; + let (zoom_in, zoom_out) = (held(true), held(false)); + assert_eq!(zoom_out, zoom_in, "alt {alt}"); + assert!(zoom_out[4..=8].windows(2).all(|w| (w[1] < w[0]) == alt), "alt {alt}: {zoom_out:?}"); + } + } + #[test] fn a_hold_at_the_zoom_limit_leaves_the_view_alone() { // Zoom Resizes Windows centres the image in a window wrapped around it diff --git a/crates/ui-egui/src/caps_lock_tests.rs b/crates/ui-egui/src/caps_lock_tests.rs index a74c9d59f4..bfc959398e 100644 --- a/crates/ui-egui/src/caps_lock_tests.rs +++ b/crates/ui-egui/src/caps_lock_tests.rs @@ -74,6 +74,11 @@ fn fp(h: &Harness<'_, PhotocraftApp>) -> CursorFp { } } +/// The eyedropper's pipette: the OS bitmap where one uploads, else drawn (#12523). +fn pipette_shown(h: &Harness<'_, PhotocraftApp>) -> bool { + crate::tool_cursor::pipette_shown(&h.ctx, &h.output().platform_output) +} + fn painting(h: &mut Harness<'_, PhotocraftApp>, value: &str) { h.state_mut().run("prefs.set", json!({"path": "cursors.painting", "value": value})).unwrap(); h.run_steps(2); @@ -143,7 +148,7 @@ fn caps_lock_swaps_the_other_cursors_between_their_icon_and_the_crosshair() { Tool::Pen, Tool::FreeformPen, Tool::CurvaturePen, - Tool::AddAnchorPoint, + // Add Anchor Point shows the pen only over a segment (#12729): `add_anchor_cursor_tests`. Tool::DeleteAnchorPoint, Tool::ConvertPoint, Tool::Eyedropper, @@ -164,9 +169,9 @@ fn caps_lock_swaps_the_other_cursors_between_their_icon_and_the_crosshair() { assert_eq!(img.size, expected.size, "{tool:?}: bitmap dimensions match rasterized variant"); assert_eq!(img.hotspot, expected.hotspot, "{tool:?}: hotspot matches variant"); assert_eq!(img.rgba, expected.rgba, "{tool:?}: RGBA bitmap matches variant rasterization"); - } else if tool == Tool::PaintBucket && cfg!(not(target_arch = "wasm32")) { - assert_eq!(standard.icon, CursorIcon::Crosshair, "PaintBucket: the OS bitmap has a visible fallback"); - assert!(standard.image.is_some(), "PaintBucket: the standard cursor is the unified OS bitmap"); + } else if matches!(tool, Tool::PaintBucket | Tool::Eyedropper | Tool::ColorSampler) && cfg!(not(target_arch = "wasm32")) { + assert_eq!(standard.icon, CursorIcon::Crosshair, "{tool:?}: the OS bitmap has a visible fallback"); + assert!(standard.image.is_some(), "{tool:?}: the standard cursor is the OS bitmap"); } else { assert_eq!(standard.icon, CursorIcon::None, "{tool:?}: the standard cursor is the tool's own icon, drawn"); assert!(standard.image.is_none(), "{tool:?}: painted fallback has no native cursor bitmap"); @@ -204,13 +209,12 @@ fn caps_lock_gives_the_curves_eyedroppers_the_precise_crosshair() { h.run_steps(3); other(&mut h, "standard"); let standard = fp(&h); - assert_eq!(standard.icon, CursorIcon::None, "the drawn pipette, not the Move tool's arrow over it"); + assert!(pipette_shown(&h), "the pipette, not the Move tool's arrow over it"); other(&mut h, "precise"); let precise = fp(&h); assert_eq!(precise.icon, CursorIcon::Crosshair, "Precise: the crosshair"); - // CodeRabbit on #10406: the pipette is painted, not only the icon hidden. - assert_ne!(standard.shapes, precise.shapes, "Standard paints a cursor of its own where Precise shows the crosshair"); - assert_ne!(standard, precise, "Standard: the pipette"); + // CodeRabbit on #10406: the pipette is shown (drawn, or the OS bitmap), not only the icon hidden. + assert_ne!(standard, precise, "Standard shows a cursor of its own where Precise shows the crosshair"); other(&mut h, "standard"); caps(&mut h, true); assert_eq!(fp(&h), precise, "caps lock turns the pipette into the precise crosshair"); @@ -232,12 +236,12 @@ fn caps_lock_gives_the_properties_eyedroppers_the_precise_crosshair() { h.run_steps(3); other(&mut h, "standard"); let standard = fp(&h); - assert_eq!(standard.icon, CursorIcon::None, "the drawn pipette, not the Move tool's arrow over it"); + assert!(pipette_shown(&h), "the pipette, not the Move tool's arrow over it"); other(&mut h, "precise"); let precise = fp(&h); assert_eq!(precise.icon, CursorIcon::Crosshair, "Precise: the crosshair"); - // CodeRabbit on #10406: the pipette is painted, not only the icon hidden. - assert_ne!(standard.shapes, precise.shapes, "Standard paints a cursor of its own where Precise shows the crosshair"); + // CodeRabbit on #10406: the pipette is shown (drawn, or the OS bitmap), not only the icon hidden. + assert_ne!(standard, precise, "Standard shows a cursor of its own where Precise shows the crosshair"); other(&mut h, "standard"); caps(&mut h, true); assert_eq!(fp(&h), precise, "caps lock turns the pipette into the precise crosshair"); @@ -257,13 +261,12 @@ fn caps_lock_gives_the_color_pickers_eyedropper_the_precise_crosshair() { h.run_steps(3); other(&mut h, "standard"); let standard = fp(&h); - assert_eq!(standard.icon, CursorIcon::None, "the drawn pipette, not the Move tool's arrow over it"); + assert!(pipette_shown(&h), "the pipette, not the Move tool's arrow over it"); other(&mut h, "precise"); let precise = fp(&h); assert_eq!(precise.icon, CursorIcon::Crosshair, "Precise: the crosshair"); - // CodeRabbit on #10406: the pipette is painted, not only the icon hidden. - assert_ne!(standard.shapes, precise.shapes, "Standard paints a cursor of its own where Precise shows the crosshair"); - assert_ne!(standard, precise); + // CodeRabbit on #10406: the pipette is shown (drawn, or the OS bitmap), not only the icon hidden. + assert_ne!(standard, precise, "Standard shows a cursor of its own where Precise shows the crosshair"); other(&mut h, "standard"); caps(&mut h, true); assert_eq!(fp(&h), precise, "caps lock turns the pipette into the precise crosshair"); @@ -283,7 +286,7 @@ fn a_lent_hand_shows_its_cursor_over_an_eyedropper_when_it_is_also_selected() { assert!(crate::color_picker_ui::top(h.state()).is_some(), "the Color Picker owns the image"); other(&mut h, "standard"); let pipette = fp(&h); - assert_eq!(pipette.icon, CursorIcon::None, "the eyedropper's drawn pipette"); + assert!(pipette_shown(&h), "the eyedropper's pipette"); let p = h.state().last_canvas_rect.center(); let middle = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Middle, pressed, modifiers: egui::Modifiers::NONE }; h.event(middle(true)); diff --git a/crates/ui-egui/src/clone_stamp_indexed_bar_tests.rs b/crates/ui-egui/src/clone_stamp_indexed_bar_tests.rs new file mode 100644 index 0000000000..22d9591b89 --- /dev/null +++ b/crates/ui-egui/src/clone_stamp_indexed_bar_tests.rs @@ -0,0 +1,129 @@ +//! In an Indexed Color document the Clone Stamp's Sample is greyed at Current Layer and a stroke +//! samples the current layer, whatever Sample held; the Normal Mode reads "Threshold". Opacity, +//! Flow and Aligned stay enabled, and RGB documents keep the list, the label and the Sample choice. + +use egui::Modifiers; +use egui::accesskit::Role; +use egui_kittest::kittest::{NodeT, Queryable}; +use egui_kittest::{Harness, Node}; +use photocraft_doc::BlendMode; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::options_bar_mode_wheel_tests::{brush_mode, harness, mode_dropdown, wheel}; +use crate::state::Tool; + +/// The Clone Stamp in a new document, Sample set to All Layers; `indexed` converts it first. +fn bar(indexed: bool) -> Harness<'static, PhotocraftApp> { + let mut h = harness(Tool::CloneStamp); + let app = h.state_mut(); + if indexed { + app.run("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none"})).unwrap(); + } + app.ui.tool_options.clone_sample = "all".into(); + h.run_steps(4); + h +} + +/// The Sample dropdown: the one showing one of its choices. +fn sample<'a>(h: &'a Harness<'_, PhotocraftApp>) -> Node<'a> { + let choices = ["Current Layer", "Current & Below", "All Layers"]; + h.query_all_by_role(Role::ComboBox).find(|n| n.value().is_some_and(|v| choices.contains(&v.as_str()))).expect("the Sample dropdown") +} + +/// The options bar's field or checkbox named `name` ("Opacity:" in the Photoshop-look themes). +fn control<'a>(h: &'a Harness<'_, PhotocraftApp>, role: Role, name: &str) -> Node<'a> { + h.query_all_by_role(role).find(|n| n.accesskit_node().label().is_some_and(|l| l.trim_end_matches(':') == name)).unwrap_or_else(|| panic!("{name}")) +} + +/// An Alt-click for the source, then a drag, through the canvas: the committed stroke's params. +fn clone_stroke(h: &mut Harness<'_, PhotocraftApp>) -> Value { + let app = h.state_mut(); + tool_event(app, ToolEvent::Down { x: 40.0, y: 20.0, pressure: 1.0 }, Modifiers::ALT); + tool_event(app, ToolEvent::Up { x: 40.0, y: 20.0 }, Modifiers::ALT); + tool_event(app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: 30.0, y: 30.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: 30.0, y: 30.0 }, Modifiers::NONE); + let (id, params) = app.session.journal.last().unwrap(); + assert_eq!(id, "paint.cloneStamp", "{}", app.ui.status); + params.clone() +} + +#[test] +fn in_an_indexed_document_sample_is_greyed_at_current_layer() { + let h = bar(true); + let node = sample(&h); + assert_eq!(node.value().as_deref(), Some("Current Layer")); + assert!(node.accesskit_node().is_disabled()); + assert_eq!(h.state().ui.tool_options.clone_sample, "all", "the stored choice is kept"); +} + +#[test] +fn a_stroke_in_an_indexed_document_samples_the_current_layer() { + let mut h = bar(true); + let steps = h.state().session.active().unwrap().history.past_len(); + assert_eq!(clone_stroke(&mut h)["sampleLayer"], "current"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1, "one Clone Stamp state"); +} + +fn shows(h: &Harness<'_, PhotocraftApp>, value: &str) -> bool { + h.query_all_by_role(Role::ComboBox).any(|n| n.value().as_deref() == Some(value)) +} + +#[test] +fn in_an_indexed_document_normal_reads_threshold_in_the_same_list() { + let mut h = bar(true); + assert_eq!(brush_mode(&h), BlendMode::Normal); + assert!(shows(&h, "Threshold")); + // The list itself is today's: the wheel steps on to Dissolve and back. + let at = h.query_all_by_role(Role::ComboBox).find(|n| n.value().as_deref() == Some("Threshold")).unwrap().rect().center(); + wheel(&mut h, at, -1.0); + assert_eq!(brush_mode(&h), BlendMode::Dissolve); + assert!(shows(&h, "Dissolve")); + wheel(&mut h, at, 1.0); + assert_eq!(brush_mode(&h), BlendMode::Normal); + assert!(shows(&h, "Threshold")); +} + +/// Other modes in Indexed Color weren't measured: they keep today's list. +#[test] +fn in_an_indexed_document_another_mode_keeps_the_list() { + let mut h = bar(true); + h.state_mut().session.tools.brush.mode = BlendMode::Dissolve; + h.run_steps(4); + assert!(shows(&h, "Dissolve")); + assert!(!shows(&h, "Threshold")); +} + +#[test] +fn back_in_rgb_sample_shows_and_sends_the_stored_choice() { + let mut h = bar(true); + h.state_mut().run("image.mode.rgb", json!({})).unwrap(); + h.run_steps(4); + let node = sample(&h); + assert_eq!(node.value().as_deref(), Some("All Layers")); + assert!(!node.accesskit_node().is_disabled()); + assert_eq!(clone_stroke(&mut h)["sampleLayer"], "all"); +} + +#[test] +fn opacity_flow_and_aligned_stay_enabled_in_an_indexed_document() { + let h = bar(true); + for (role, name) in [(Role::SpinButton, "Opacity"), (Role::SpinButton, "Flow"), (Role::CheckBox, "Aligned")] { + assert!(!control(&h, role, name).accesskit_node().is_disabled(), "{name}"); + } +} + +#[test] +fn rgb_documents_keep_the_mode_list_and_the_sample_choice() { + let mut h = bar(false); + let node = sample(&h); + assert_eq!(node.value().as_deref(), Some("All Layers")); + assert!(!node.accesskit_node().is_disabled()); + assert!(!shows(&h, "Threshold")); + let at = mode_dropdown(&h).center(); + wheel(&mut h, at, -1.0); + assert_eq!(brush_mode(&h), BlendMode::Dissolve); + assert_eq!(clone_stroke(&mut h)["sampleLayer"], "all"); +} diff --git a/crates/ui-egui/src/clone_stamp_no_source_alert_tests.rs b/crates/ui-egui/src/clone_stamp_no_source_alert_tests.rs new file mode 100644 index 0000000000..f4d1bd29d9 --- /dev/null +++ b/crates/ui-egui/src/clone_stamp_no_source_alert_tests.rs @@ -0,0 +1,95 @@ +//! #12609: a Clone Stamp press before any Alt-click opens the reference application's alert with +//! OK at the press, instead of a status-bar line, and paints nothing. The Healing Brush keeps its +//! own behaviour. + +use egui::Modifiers; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::control::{ControlRequest, Outcome, handle}; +use crate::state::{DialogKind, Tool}; +use crate::tools::brush_refusal::brush_refusal_alert_tests::{alerts, app, refused, steps, stroke}; + +const MESSAGE: &str = if cfg!(target_os = "macos") { + "Could not use the clone stamp tool because the area to clone has not been defined (Option-click to define a source point)." +} else { + "Could not use the clone stamp tool because the area to clone has not been defined (Alt-click to define a source point)." +}; + +/// The active layer's pixels. +fn pixels(app: &PhotocraftApp) -> Vec { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().read_region(st.doc.bounds()) +} + +#[test] +fn a_stroke_without_a_source_alerts_once_and_paints_nothing() { + let mut app = app(Tool::CloneStamp); + let before = pixels(&app); + refused(&mut app, MESSAGE); + assert!(!app.ui.status_error, "no status-bar error as well: {}", app.ui.status); + assert!(pixels(&app) == before, "after OK the document is unchanged"); +} + +#[test] +fn the_alert_opens_at_the_press_and_the_drag_and_release_add_none() { + let mut app = app(Tool::CloneStamp); + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 32.0, pressure: 1.0 }, Modifiers::NONE); + assert_eq!(alerts(&app), [MESSAGE], "at the press, before any move"); + assert!(app.drag.is_none() && app.live_stroke.is_none(), "the press starts no stroke"); + // Closed before the drag, so an alert from the move or the release would show. + let id = app.ui.dialogs.iter().find(|d| d.kind == DialogKind::Error).map(|d| d.id).unwrap(); + crate::dialogs::confirm(&mut app, id).unwrap(); + tool_event(&mut app, ToolEvent::Move { x: 44.0, y: 32.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 44.0, y: 32.0 }, Modifiers::NONE); + assert!(alerts(&app).is_empty(), "neither the drag nor the release alerts"); +} + +#[test] +fn a_second_press_while_the_alert_is_up_adds_none() { + let mut app = app(Tool::CloneStamp); + stroke(&mut app); + stroke(&mut app); + assert_eq!(alerts(&app), [MESSAGE]); +} + +#[test] +fn the_alert_is_listed_and_confirmed_over_the_control_channel() { + let ctx = egui::Context::default(); + let mut app = app(Tool::CloneStamp); + stroke(&mut app); + let (inspect, _rx) = ControlRequest::new("ui.inspect", json!({})); + let Outcome::Done(inspect) = handle(&mut app, &ctx, &inspect) else { panic!("ui.inspect replies at once") }; + let dialog = &inspect["result"]["dialogs"][0]; + assert_eq!(dialog["fields"]["message"], MESSAGE, "{inspect}"); + let (confirm, _rx) = ControlRequest::new("ui.dialog.confirm", json!({"dialog": dialog["id"]})); + assert!(matches!(handle(&mut app, &ctx, &confirm), Outcome::Done(v) if v["ok"] == true)); + assert!(alerts(&app).is_empty()); +} + +#[test] +fn after_an_alt_click_the_clone_stamp_paints_without_an_alert() { + let mut app = app(Tool::CloneStamp); + // A white band around the source on the red layer, so the clone has something to copy. + app.run("select.rect", json!({"x": 0, "y": 0, "width": 64, "height": 20})).unwrap(); + app.run("edit.fill", json!({"color": "#ffffff"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, Modifiers::ALT); + tool_event(&mut app, ToolEvent::Up { x: 10.0, y: 10.0 }, Modifiers::ALT); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty()); + assert_eq!(steps(&app), before + 1, "one Clone Stamp state"); + let st = app.session.active().unwrap(); + let on_stroke = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(32, 32); + assert!(on_stroke[1] > 0.5, "the stroke copies the white source onto the red: {on_stroke:?}"); +} + +#[test] +fn the_healing_brush_keeps_its_status_line() { + let mut app = app(Tool::Healing); + stroke(&mut app); + assert!(alerts(&app).is_empty()); + assert!(app.ui.status_error && app.ui.status.contains("source point to clone from"), "{}", app.ui.status); +} diff --git a/crates/ui-egui/src/color_replacement_blend_keys_tests.rs b/crates/ui-egui/src/color_replacement_blend_keys_tests.rs new file mode 100644 index 0000000000..3acfeca7af --- /dev/null +++ b/crates/ui-egui/src/color_replacement_blend_keys_tests.rs @@ -0,0 +1,101 @@ +//! #11928: with the Color Replacement tool, Shift+Alt+letter sets the active layer's blend mode +//! (one History step each) and the tool's own Mode stays. Its Shift+plus/minus and the other tools +//! that ignore the keys keep today's behaviour. + +use egui::{Key, Modifiers}; +use serde_json::json; + +use super::*; + +const SHIFT_ALT: Modifiers = Modifiers { alt: true, ctrl: false, shift: true, mac_cmd: false, command: false }; + +fn app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 32, "height": 32})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = tool; + app +} + +fn key(app: &mut PhotocraftApp, ctx: &egui::Context, key: Key, modifiers: Modifiers) { + let raw = egui::RawInput { + events: vec![egui::Event::ModifiersChanged(modifiers), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }], + ..Default::default() + }; + ctx.begin_pass(raw); + crate::shortcuts::handle(app, ctx); + ctx.end_pass().textures_delta.clear(); +} + +fn layer_blend(app: &PhotocraftApp) -> BlendMode { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().blend +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +#[test] +fn shift_alt_letters_set_the_active_layer() { + let ctx = egui::Context::default(); + let mut app = app(Tool::ColorReplacement); + let tool_options = app.ui.tool_options.clone(); + for (letter, mode) in [(Key::M, BlendMode::Multiply), (Key::N, BlendMode::Normal), (Key::Y, BlendMode::Luminosity), (Key::U, BlendMode::Hue)] { + let n = steps(&app); + key(&mut app, &ctx, letter, SHIFT_ALT); + assert_eq!(layer_blend(&app), mode, "{letter:?}"); + assert_eq!(steps(&app), n + 1, "{letter:?}: one History step"); + } + assert_eq!(app.ui.tool_options, tool_options, "the tool's own Mode and options stay"); +} + +#[test] +fn shift_plus_minus_with_color_replacement_still_do_nothing() { + let ctx = egui::Context::default(); + let mut app = app(Tool::ColorReplacement); + let n = steps(&app); + for k in [Key::Plus, Key::Minus] { + key(&mut app, &ctx, k, Modifiers::SHIFT); + } + assert_eq!((layer_blend(&app), steps(&app)), (BlendMode::Normal, n), "not measured: today's behaviour"); +} + +#[test] +fn the_other_tools_that_ignore_the_keys_still_do() { + let ctx = egui::Context::default(); + for tool in [Tool::SpotHealing, Tool::Blur, Tool::Sharpen, Tool::Smudge, Tool::ArtHistoryBrush, Tool::Dodge, Tool::Burn, Tool::Sponge] { + let mut app = app(tool); + let n = steps(&app); + key(&mut app, &ctx, Key::M, SHIFT_ALT); + assert_eq!((layer_blend(&app), steps(&app)), (BlendMode::Normal, n), "{tool:?}"); + } +} + +#[test] +fn letters_outside_the_measured_four_still_do_nothing() { + // Not measured: Shift+Alt+S (Screen), C (Color), O (Overlay) keep today's behaviour. + let ctx = egui::Context::default(); + let mut app = app(Tool::ColorReplacement); + let n = steps(&app); + for letter in [Key::S, Key::C, Key::O] { + key(&mut app, &ctx, letter, SHIFT_ALT); + assert_eq!((layer_blend(&app), steps(&app)), (BlendMode::Normal, n), "{letter:?}"); + } +} + +#[test] +fn several_selected_layers_still_do_nothing() { + // Not measured: with more than one layer selected the letters keep today's behaviour. + let ctx = egui::Context::default(); + let mut app = app(Tool::ColorReplacement); + let first = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("layer.select", json!({"layer": first.0, "mode": "add"})).unwrap(); + assert_eq!(app.session.active().unwrap().selected_layers().len(), 2); + let n = steps(&app); + key(&mut app, &ctx, Key::M, SHIFT_ALT); + let st = app.session.active().unwrap(); + let blends: Vec = st.selected_layers().into_iter().map(|id| st.doc.layer(id).unwrap().blend).collect(); + assert_eq!((blends, steps(&app)), (vec![BlendMode::Normal; 2], n)); +} diff --git a/crates/ui-egui/src/color_replacement_cursor_tests.rs b/crates/ui-egui/src/color_replacement_cursor_tests.rs new file mode 100644 index 0000000000..e2ed2b1859 --- /dev/null +++ b/crates/ui-egui/src/color_replacement_cursor_tests.rs @@ -0,0 +1,40 @@ +//! #11934: with Normal and Full Size Brush Tip cursors the Color Replacement cursor always draws +//! the centre +, its sampling hotspot, whatever Show Crosshair in Brush Tip says. Other brush +//! tools follow the preference, and Clone Stamp / Healing Brush keep their Alt behaviour. + +use super::*; + +#[test] +fn color_replacement_always_shows_its_centre() { + for show_crosshair in [false, true] { + for option in [false, true] { + assert!(brush_tip_centre(Tool::ColorReplacement, option, show_crosshair), "crosshair pref {show_crosshair}, Alt {option}"); + } + } +} + +#[test] +fn other_brush_tools_follow_the_preference() { + for tool in [Tool::Brush, Tool::Eraser, Tool::PatternStamp, Tool::Dodge, Tool::Pencil, Tool::Smudge] { + for option in [false, true] { + assert!(!brush_tip_centre(tool, option, false), "{tool:?} off, Alt {option}"); + assert!(brush_tip_centre(tool, option, true), "{tool:?} on, Alt {option}"); + } + } + for show_crosshair in [false, true] { + for option in [false, true] { + // The Background Eraser keeps its hotspot, as before; Quick Selection never has one. + assert!(brush_tip_centre(Tool::BackgroundEraser, option, show_crosshair)); + assert!(!brush_tip_centre(Tool::QuickSelection, option, show_crosshair)); + } + } +} + +#[test] +fn clone_stamp_and_healing_keep_their_alt_behaviour() { + for tool in [Tool::CloneStamp, Tool::Healing] { + assert!(!brush_tip_centre(tool, false, false), "{tool:?}"); + assert!(brush_tip_centre(tool, true, false), "{tool:?} with Alt"); + assert!(brush_tip_centre(tool, false, true), "{tool:?} with the preference"); + } +} diff --git a/crates/ui-egui/src/color_swatch_tests.rs b/crates/ui-egui/src/color_swatch_tests.rs index 6a88301859..89ef2514e7 100644 --- a/crates/ui-egui/src/color_swatch_tests.rs +++ b/crates/ui-egui/src/color_swatch_tests.rs @@ -94,7 +94,8 @@ fn note_and_count_colours_open_the_color_picker() { app.ui.tool = Tool::Count; app.run("count.newGroup", json!({})).unwrap(); }); - pick(&mut h, "Color"); + // The Count swatch is "Count group color", its picker "Color Picker (Count Color)" (#11765). + assert_eq!(pick(&mut h, "Count group color"), crate::color_picker_ui::title_for("Count Color")); let st = h.state().session.active().unwrap(); let m = &st.doc.measurement; let g = &m.count_groups[m.active_count_group]; diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index d4e90ff90c..2aa71a6915 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -1273,6 +1273,9 @@ fn pointer(app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> Outcome { }; if let Some(t) = parsed.tool { crate::tool_memory::select(app, t); + // The tool's own brush now, not at the next frame, so a paint command right after uses + // it (the Pencil's 1 px tip, #12200; any tool's remembered brush). + crate::paint_mouse::sync_tool_brush(app); } // Space held: the Crop tool moves the frame being drawn, a marquee, lasso or shape // being drawn moves instead of growing (hold_keys.rs). Like a modifier flag, it may be diff --git a/crates/ui-egui/src/control/inspect.rs b/crates/ui-egui/src/control/inspect.rs index 5d73b0018d..62821fe1cf 100644 --- a/crates/ui-egui/src/control/inspect.rs +++ b/crates/ui-egui/src/control/inspect.rs @@ -57,13 +57,14 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { use crate::brush_mode_menu as m; let tool = app.ui.tool; let current = m::current(app, tool); + let checked = m::checked(app, ctx, tool); json!({ "pos": pos, "tool": tool, "mode": current.and_then(m::Item::label), "choices": m::labels(tool), "items": m::items(tool).into_iter().map(|i| match i.label() { - Some(label) => json!({"label": label, "enabled": m::enabled(app, i), "checked": Some(i) == current}), + Some(label) => json!({"label": label, "enabled": m::enabled(app, i), "checked": Some(i) == checked}), None => json!({"separator": true}), }).collect::>(), }) @@ -134,6 +135,7 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { "brush": {"size": app.session.tools.brush.size, "hardness": app.session.tools.brush.hardness, "opacity": app.session.tools.brush.opacity}, "distort": app.distort.describe(), "jobs": crate::jobs_ui::inspect(app), + "agentLink": app.agent_link, "histogram": crate::histogram_panel::inspect(app), "cameraRaw": app.camera_raw.as_ref().map(|d| d.describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview)), }) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 164d6de995..17b8b99580 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -286,7 +286,10 @@ pub(crate) fn close_box(ui: &mut egui::Ui, rect: egui::Rect) -> bool { /// The delete confirmations: a layer from the Layers panel's trash, a note (#11788), or all notes /// (#11791). fn delete_prompt(fields: &Fields) -> bool { - crate::delete_layer_prompt::owns(fields) || crate::analysis_ui::owns_delete_note(fields) || crate::analysis_ui::owns_clear_notes(fields) + crate::delete_layer_prompt::owns(fields) + || crate::analysis_ui::owns_delete_note(fields) + || crate::analysis_ui::owns_clear_notes(fields) + || live_shape_prompt::owns(fields) } fn delete_prompt_body(ui: &mut egui::Ui, fields: &mut Fields) { @@ -294,6 +297,8 @@ fn delete_prompt_body(ui: &mut egui::Ui, fields: &mut Fields) { crate::analysis_ui::clear_notes_body(ui); } else if crate::analysis_ui::owns_delete_note(fields) { crate::analysis_ui::delete_note_body(ui, fields); + } else if live_shape_prompt::owns(fields) { + live_shape_prompt::body(ui, fields); } else { crate::delete_layer_prompt::body(ui, fields); } @@ -350,7 +355,7 @@ fn command_body_more(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fie } } _ if crate::color_range_ui::owns(fields) => crate::color_range_ui::body(app, ui, fields), - _ if crate::prefs_ui::owns(fields) => crate::prefs_ui::body(app, ui, fields), + _ if crate::prefs_ui::owns(fields) => crate::prefs_ui::body(app, ui, fields, d.id), _ if fields.contains_key("__export") => crate::export_dialog::body(app, ui, fields), // Image Size and Canvas Size open on Width, selected (#2329). _ if fields.contains_key("__sizing") => first_field_focused(ui, id, |ui| crate::sizing::body(ui, fields)), @@ -493,7 +498,7 @@ fn button_row( tl!("Reset") } else if d.kind == DialogKind::NewDocument { tl!("Close") - } else if crate::analysis_ui::owns_delete_note(fields) { + } else if crate::analysis_ui::owns_delete_note(fields) || live_shape_prompt::owns(fields) { tl!("No") } else { tl!("Cancel") @@ -542,12 +547,14 @@ fn button_row( } else { dialog_buttons(ui, &[ok, cancel]) }; + // Enter is the default button, except where a popup takes it or Export As waits for a click. + let enter_confirms = can_ok && !popup_blocks_enter && crate::export_dialog::enter_confirms(fields); match clicked { Some(ButtonRole::Cancel) if reset => crate::dialog_alt_reset::apply(app, ui.ctx(), fields), Some(ButtonRole::Cancel) => outcome = Some(false), Some(ButtonRole::Apply) => apply_requested = true, Some(_) => outcome = Some(true), - None if interactive && can_ok && !popup_blocks_enter && ui.input(|i| i.key_pressed(egui::Key::Enter)) => outcome = Some(true), + None if interactive && enter_confirms && ui.input(|i| i.key_pressed(egui::Key::Enter)) => outcome = Some(true), None => {} } } @@ -564,7 +571,7 @@ fn ok_label(d: &Dialog) -> &'static str { tl!("Continue") } else if crate::delete_layer_prompt::owns(&d.fields) { tl!("Delete") - } else if crate::analysis_ui::owns_delete_note(&d.fields) { + } else if crate::analysis_ui::owns_delete_note(&d.fields) || live_shape_prompt::owns(&d.fields) { tl!("Yes") } else if crate::disk_change_prompt::owns(&d.fields) || crate::replace_prompt::owns(&d.fields) { tl!("Replace") @@ -625,6 +632,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { let mut drag = egui::Vec2::ZERO; let mut close_clicked = false; let mut sizing = false; + let mut fit_image_alert = None; let area = match start { Some(offset) => egui::Modal::default_area(id).anchor(egui::Align2::LEFT_TOP, offset), None => egui::Modal::default_area(id), @@ -717,8 +725,10 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { crate::widgets::hairline(ui); ui.add_space(8.0); crate::field_tab::begin(ui.ctx()); - if let Some(done) = dialog_body(app, ui, &d, &mut fields, id, interactive) { - outcome = Some(done); + if fit_image_range::owns(&fields) { + fit_image_alert = fit_image_range::body(ui, &mut fields); + } else { + outcome = dialog_body(app, ui, &d, &mut fields, id, interactive); } crate::field_tab::end(ui.ctx(), tab); if let Some(Value::String(key)) = fields.remove(BROWSE_FIELD) { @@ -784,6 +794,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { { outcome = Some(false); } + outcome = fit_image_range::finish(&mut app.ui, interactive, fit_image_alert, outcome); if let Some(dm) = app.ui.dialog_mut(d.id) { dm.fields = fields; } @@ -899,6 +910,7 @@ const ROUTES: &[fn(&Fields) -> bool] = &[ crate::delete_layer_prompt::owns, crate::analysis_ui::owns_delete_note, crate::analysis_ui::owns_clear_notes, + live_shape_prompt::owns, crate::disk_change_prompt::owns, crate::actions::owns_stop_message, crate::actions::owns_insert_stop, @@ -1146,6 +1158,7 @@ fn confirm_command_more(app: &mut PhotocraftApp, d: Dialog) -> Result merge_channels_ui::confirm(app, &d.fields), _ if crate::analysis_ui::owns_delete_note(&d.fields) => crate::analysis_ui::confirm_delete_note(app, &d.fields), _ if crate::analysis_ui::owns_clear_notes(&d.fields) => crate::analysis_ui::confirm_clear_notes(app, &d.fields), + _ if live_shape_prompt::owns(&d.fields) => live_shape_prompt::confirm(app, &d.fields), _ if crate::file_ui::owns(&d.fields) => crate::file_ui::confirm(app, &d.fields), _ if crate::new_guide_ui::owns(&d.fields) => crate::new_guide_ui::confirm(app, &d.fields), _ if crate::color_picker_ui::owns(&d.fields) => { @@ -1162,6 +1175,7 @@ fn confirm_command_more(app: &mut PhotocraftApp, d: Dialog) -> Result Result { confirm_preflight(app, id)?; + fit_image_range::preflight(&mut app.ui, id)?; let d = app.ui.close_dialog(id).ok_or_else(|| format!("no dialog {id}"))?; match d.kind { DialogKind::NewDocument => { @@ -1303,12 +1317,16 @@ pub mod duplicate_layer_ui; pub mod edit_history; pub mod equalize_ui; pub mod export_dialog; +pub(crate) mod fade_modes; pub mod file_ui; pub mod fill_ui; pub mod filter_dialog; pub(super) mod filter_preview_ui; #[cfg(not(target_arch = "wasm32"))] pub(super) mod filter_preview_worker; +mod fit_image_range; +#[cfg(test)] +mod fit_image_range_tests; pub mod gallery_ui; pub(crate) mod guide_edit; pub mod guide_layout_ui; @@ -1319,6 +1337,7 @@ mod label_column_tests; pub mod layer_picker; pub mod layer_style; pub mod liquify_ui; +pub mod live_shape_prompt; pub mod mask_trash_prompt; pub mod merge_channels_ui; pub mod new_doc_ui; @@ -1327,6 +1346,8 @@ pub mod new_guide_ui; pub mod new_layer_ui; pub mod open_prompt; pub mod palette; +#[cfg(test)] +mod paths_export_default_tests; pub(crate) mod pattern_fill_ui; pub mod preset_group_prompt; pub mod rasterize_prompt; diff --git a/crates/ui-egui/src/dialogs/adjust_dialog.rs b/crates/ui-egui/src/dialogs/adjust_dialog.rs index e2044f01bc..ac11967b8c 100644 --- a/crates/ui-egui/src/dialogs/adjust_dialog.rs +++ b/crates/ui-egui/src/dialogs/adjust_dialog.rs @@ -664,10 +664,15 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map 0); } @@ -1007,7 +1007,7 @@ fn curves_on_a_targeted_filter_mask_is_a_gray_plane() { app.run("paint.stroke", json!({"points": [[8, 0], [8, 31]], "size": 16, "hardness": 1, "color": "#000000", "target": "filterMask"})).unwrap(); let surface = photocraft_engine::channel_cmds::GraySurface::FilterMask; let st = app.session.active().unwrap(); - let h = tone::compute_histograms(&st.doc, HistSource::Channel { layer: id, surface }, photocraft_doc::adjust::ToneSpace::Rgb); + let h = tone::compute_histograms(&st.doc, HistSource::Channel { layer: id, surface }, photocraft_doc::adjust::ToneSpace::Rgb, tone::HistScope::WholeInput); assert!(h.ch[0][0] > 0 && h.ch[0][255] > 0, "black and white levels"); assert_eq!(curve_mode(&app, "curves", &Map::new()), photocraft_doc::ColorMode::Grayscale); } diff --git a/crates/ui-egui/src/dialogs/adjust_editors.rs b/crates/ui-egui/src/dialogs/adjust_editors.rs index ba176d7ec7..12f479192f 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors.rs @@ -36,8 +36,8 @@ pub(crate) use basic::PHOTO_FILTER_MODE; pub(crate) use basic::row_value; #[cfg(test)] use basic::track_stops; +pub use basic::{apply_auto, reset_adjustment_editor, reset_color_balance}; use basic::{black_white, brightness_contrast, channel_mixer, color_balance, photo_filter, sliders, threshold}; -pub use basic::{reset_adjustment_editor, reset_color_balance}; use curves::curves; #[cfg(test)] use curves::{CURVE_HANDLE_SIZE, curve_graph}; @@ -96,6 +96,8 @@ pub struct Edit { pub commit: bool, /// Open the host's gradient-file dialog without changing adjustment parameters. pub import_gradients: bool, + /// Black & White's Auto: the host fills in the weights for its image ([`apply_auto`]). + pub auto: bool, } impl Edit { @@ -103,6 +105,7 @@ impl Edit { self.changed |= o.changed; self.commit |= o.commit; self.import_gradients |= o.import_gradients; + self.auto |= o.auto; } fn discrete(changed: bool) -> Self { Edit { changed, commit: changed, ..Default::default() } diff --git a/crates/ui-egui/src/dialogs/adjust_editors/basic.rs b/crates/ui-egui/src/dialogs/adjust_editors/basic.rs index e10d32652b..38018b6e8b 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/basic.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/basic.rs @@ -181,6 +181,9 @@ pub(super) fn black_white(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Ed v["tintColor"] = json!(adjust_params::hex(c)); } e.add(r); + if widgets::secondary_button(ui, tl!("Auto"), 0.0).on_hover_text(tl!("A grey mix that spreads the image's tones")).clicked() { + e.auto = true; + } if widgets::secondary_button(ui, tl!("Default"), 0.0).clicked() { for (i, key) in HUE_RANGES.iter().enumerate() { v[*key] = json!(adjust_params::BW_DEFAULTS[i]); @@ -191,6 +194,27 @@ pub(super) fn black_white(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Ed e } +/// Black & White's Auto (#9269): the weights `image.adjustments.blackWhite.auto` finds for +/// `layer` (an adjustment layer: the image under it; a pixel layer: its pixels; with `filter`, the +/// smart object's pixels below that smart filter) into `v`, as +/// one discrete edit of `e`. +pub fn apply_auto(app: &mut crate::PhotocraftApp, v: &mut Value, layer: Option, filter: Option, e: &mut Edit) { + let mut p = layer.map_or(json!({}), |id| json!({"layer": id.0})); + if let Some(i) = filter { + p["filter"] = json!(i); + } + match app.run("image.adjustments.blackWhite.auto", p) { + Ok(Value::Object(w)) => { + for (k, x) in w { + v[k] = x; + } + e.add(Edit::discrete(true)); + } + Ok(_) => {} + Err(err) => app.ui.status = err, + } +} + // --------------------------------------------------------------------------------------------- // Photo Filter diff --git a/crates/ui-egui/src/dialogs/adjust_editors/curves.rs b/crates/ui-egui/src/dialogs/adjust_editors/curves.rs index d50fc9ab9b..c57c285f61 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/curves.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/curves.rs @@ -603,7 +603,12 @@ mod multi_channel_tests { for kind in ["levels", "curves"] { let base = adjust_params::to_params(&adjust_params::default_for(kind, st.doc.mode).unwrap()); let space = space_of(&base); - let hist = Arc::new(tone::compute_histograms(&st.doc, HistSource::Colors { layer: st.active_layer.unwrap(), colors }, space)); + let hist = Arc::new(tone::compute_histograms( + &st.doc, + HistSource::Colors { layer: st.active_layer.unwrap(), colors }, + space, + tone::HistScope::WholeInput, + )); // Native subset histograms have their own combined slot even in Lab, whose // ordinary composite histograms instead start with Lightness at slot 0. assert_eq!(hist.ch.len(), 1 + st.doc.pixel_format().mode.color_channels()); diff --git a/crates/ui-egui/src/dialogs/adjust_editors/session.rs b/crates/ui-egui/src/dialogs/adjust_editors/session.rs index d254b49bba..4ac5181246 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/session.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/session.rs @@ -1,4 +1,4 @@ -use super::basic::reset_color_balance; +use super::basic::{apply_auto, reset_color_balance}; use super::gradient_map::{gradient_presets, is_gray, swatches}; use super::{Adjustment, EditorCx, HistSource, LayerId, PhotocraftApp, RichText, Tokens, Value, adjust_params, editor, json, needs_histogram, space_of, tone}; @@ -121,10 +121,13 @@ pub fn layer_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: LayerId, adj if matches!(kind, "levels" | "curves") { crate::layer_picker::controls(app, ui, id); } - let e = editor(ui, kind, &mut values, &cx); + let mut e = editor(ui, kind, &mut values, &cx); if e.import_gradients { crate::preset_files_ui::import_gradients_dialog(app); } + if e.auto { + apply_auto(app, &mut values, Some(id), None, &mut e); + } if e.changed { app.live_adjust = Some((id, values.clone())); } diff --git a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs index 81b5dba8cb..ec386a7e9a 100644 --- a/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs +++ b/crates/ui-egui/src/dialogs/adjust_editors/ui_tests.rs @@ -809,13 +809,13 @@ fn import_gradients_from_picker(h: &mut Harness<'_, PhotocraftApp>) { #[test] fn gradient_map_picker_imports_grd_without_editing_the_map() { - use photocraft_psd::grd::{GrdColor, GrdGradient, GrdStop}; + use craft_psd::grd::{GrdColor, GrdGradient, GrdStop}; let mut h = app_harness("gradientMap", "rgb", 16); h.state_mut().session.presets.gradients.truncate(1); let before = layer(&h); let history = h.state().session.active().unwrap().history.past_len(); let tool = h.state().session.presets.gradient.clone(); - let bytes = photocraft_psd::grd::write(&[GrdGradient { + let bytes = craft_psd::grd::write(&[GrdGradient { name: "Imported Teal".into(), stops: vec![ GrdStop { location: 0.0, midpoint: 0.5, color: GrdColor::Rgb([0.0, 0.5, 0.5]) }, @@ -851,10 +851,7 @@ fn gradient_map_picker_import_cancel_and_errors_preserve_state() { None, Some(FileDialogAnswer::Contents("broken.grd".into(), b"invalid".to_vec())), Some(FileDialogAnswer::Contents("old.grd".into(), b"8BGR\0\x03".to_vec())), - Some(FileDialogAnswer::Contents( - "noise.grd".into(), - photocraft_psd::grd::write(&[photocraft_psd::grd::GrdGradient { noise: true, ..Default::default() }]), - )), + Some(FileDialogAnswer::Contents("noise.grd".into(), craft_psd::grd::write(&[craft_psd::grd::GrdGradient { noise: true, ..Default::default() }]))), Some(FileDialogAnswer::Contents("wrong.abr".into(), Vec::new())), Some(FileDialogAnswer::Paths(vec!["/nonexistent/photocraft-gradients.grd".into()])), Some(FileDialogAnswer::Unavailable("dialog unavailable".into())), @@ -1351,3 +1348,41 @@ fn selective_color_properties_method_radios_commit() { assert!(matches!(layer(&h).1, Adjustment::SelectiveColor { relative: true, .. })); assert_eq!(steps(&h), start + 2); } + +/// #9269: Black & White's Auto button sets the layer's weights from the image under it, as one +/// history step. +#[test] +fn black_white_auto_button_sets_the_weights() { + let mut h = app_harness("blackWhite", "rgb", 8); + // A red and a blue the default mix turns into the same grey, under the adjustment layer. + h.state_mut() + .session + .edit("setup", |doc, _| { + let b = doc.bounds(); + let bg = doc.layers.first_mut().and_then(|l| l.surface_mut()).unwrap(); + let fmt = bg.format(); + let mut data = Vec::new(); + for _ in b.y0..b.y1 { + for x in b.x0..b.x1 { + let c = if x < b.x1 / 2 { [0.776, 0.2, 0.2, 1.0] } else { [0.29, 0.29, 1.0, 1.0] }; + data.extend(photocraft_raster::from_rgba(&fmt, c)); + } + } + bg.write_region(b, &data); + Ok(()) + }) + .unwrap(); + h.run_steps(2); + let (_, before) = layer(&h); + let steps = h.state().session.active().unwrap().history.past_len(); + let auto = h.query_all_by_label("Auto").last().map(|n| n.rect().center()).expect("an Auto button"); + click(&mut h, auto); + let (_, after) = layer(&h); + let Adjustment::BlackWhite { weights, .. } = &after else { panic!("{after:?}") }; + let id = layer(&h).0; + let expected = h.state_mut().run("image.adjustments.blackWhite.auto", json!({"layer": id.0})).unwrap(); + let want: Vec = photocraft_engine::adjust_params::HUE_RANGES.iter().map(|k| expected[*k].as_f64().unwrap() as f32).collect(); + assert_eq!(weights.to_vec(), want); + assert_ne!(after, before, "the red and blue are told apart"); + assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1); +} diff --git a/crates/ui-egui/src/dialogs/arbitrary_ruler_prefill_tests.rs b/crates/ui-egui/src/dialogs/arbitrary_ruler_prefill_tests.rs index c139a4e1e5..9d221f836f 100644 --- a/crates/ui-egui/src/dialogs/arbitrary_ruler_prefill_tests.rs +++ b/crates/ui-egui/src/dialogs/arbitrary_ruler_prefill_tests.rs @@ -5,14 +5,27 @@ //! round. The Angle range is -359.99..359.99, wide, so today's wide-range rounding to one //! decimal decided the dialog's value; only this field now keeps hundredths. -use super::filter_dialog::{body, open, params_of}; +use super::filter_dialog::{body, open, params_of, reset_fields}; use crate::PhotocraftApp; use serde_json::{Map, Value, json}; /// Draw a dialog body once, as a live dialog does every frame: the drawn fields are what /// the dialog shows and what OK sends. fn drawn(f: &mut Map) { - egui::Context::default().run_ui(Default::default(), |ui| body(ui, f)).textures_delta.clear(); + drawn_texts(f); +} + +/// [`drawn`], returning the text the frame painted. +fn drawn_texts(f: &mut Map) -> Vec { + let mut out = egui::Context::default().run_ui(Default::default(), |ui| body(ui, f)); + out.textures_delta.clear(); + out.shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Text(t) => Some(t.galley.text().to_string()), + _ => None, + }) + .collect() } /// A 318 px square document (the size `ok_runs_the_two_decimal_angle` measures on), a ruler @@ -83,6 +96,29 @@ fn the_ruler_angle_rounds_at_full_precision_before_the_field_narrows() { assert_eq!(f["direction"], json!("ccw")); } +/// #13067: the 43x27 ruler's first drawn frame, after opening and again after Alt+Reset, +/// shows the 32.12 the dialog stores (the unrounded pre-fill narrowed to exactly 32.125 +/// and drew 32.13 until the next repaint), and the dialog keeps that 32.12 as the exact +/// f64 OK sends, not the 32.1199989 an f32 field value widens to. +#[test] +fn the_ruler_angle_shows_and_sends_the_exact_rounded_value() { + let (mut app, id, mut f) = ruler_dialog([143, 127]); + let check = |f: &mut Map, when: &str| { + let shown = drawn_texts(f); + assert!(shown.iter().any(|t| t == "32.12"), "{when}: the Angle field shows 32.12, drew {shown:?}"); + assert!(!shown.iter().any(|t| t == "32.13"), "{when}: the Angle field must not show 32.13, drew {shown:?}"); + assert_eq!(f["angle"].as_f64(), Some(32.12), "{when}: the dialog keeps the exact rounded angle"); + assert_eq!(params_of(f)["angle"].as_f64(), Some(32.12), "{when}: OK sends the exact rounded angle"); + }; + // `ruler_dialog` drew one frame already: the first frame draws the fields as opened. + check(&mut app.ui.dialog_mut(id).unwrap().fields.clone(), "after opening"); + check(&mut f, "on the next frame"); + // Move off the pre-fill first, so only the reset can bring 32.12 back. + f.insert("angle".into(), json!(5.0)); + reset_fields(&app, &mut f); + check(&mut f, "after Alt+Reset"); +} + /// The fix is per-field: unrelated number fields keep the precision they have today — /// wide ranges round to one decimal (in another dialog, and under the same key name), /// small ranges keep their two. @@ -111,3 +147,19 @@ fn other_number_fields_keep_their_precision() { let x = f["centerX"].as_f64().unwrap(); assert!((x - 0.12).abs() < 1e-5, "the Radial Blur centre {x} keeps its two decimals"); } + +/// The pre-fill is rounded before any frame draws: `ui.dialog.open` then `ui.dialog.confirm` +/// can run without a draw between them, and the 43x27 ruler's raw 32.1249984 must not reach +/// the command, after opening or after Alt+Reset. +#[test] +fn the_ruler_angle_is_rounded_before_the_first_frame() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 318, "height": 318})).unwrap(); + app.run("image.analysis.rulerTool", json!({"start": [100, 100], "end": [143, 127]})).unwrap(); + let id = open(&mut app, "image.rotation.arbitrary").unwrap(); + let mut f = app.ui.dialog_mut(id).unwrap().fields.clone(); + assert_eq!(params_of(&f)["angle"].as_f64(), Some(32.12), "undrawn, OK sends the rounded angle"); + f.insert("angle".into(), json!(5.0)); + reset_fields(&app, &mut f); + assert_eq!(params_of(&f)["angle"].as_f64(), Some(32.12), "undrawn after Alt+Reset, OK sends the rounded angle"); +} diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs index fb1739b161..6b8a468e93 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/controls.rs @@ -197,14 +197,13 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { app.ui.status_error = true; } let Some(d) = app.camera_raw.as_ref() else { return }; - // Where the platform has no extra windows (the web build), draw over the main window. - if ctx.embed_viewports() { + if draws_over_main_window(ctx, app.services.is_wayland) { draw(app, ctx, false); return; } let window_title = d.window_title(); // Camera Raw is modal, as in Photoshop: the main window is dimmed and takes no input while it - // is open (in a separate window, or drawn over it where there are no extra windows). + // is open (in a separate window, or drawn over it: see `draws_over_main_window`). let main = ctx.content_rect(); let scrim = egui::Area::new(egui::Id::unique("camera-raw-modal")).order(egui::Order::Foreground).fixed_pos(main.min).show(ctx, |ui| { let (r, response) = ui.allocate_exact_size(main.size(), Sense::click_and_drag()); @@ -238,6 +237,21 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { } } +/// Whether the dialog is drawn over the main window instead of in a window of its own: where the +/// platform has no extra windows (the web build), while the main window is full screen, and on +/// Wayland while it is maximized. +/// +/// The dialog's window is an immediate viewport, so it takes input and redraws only while the +/// main window draws a frame. A window opened over a full-screen or maximized one can cover it +/// (Hyprland hands the new window the full screen or the maximized state), the compositor then +/// sends the hidden main window no frame callbacks, and the dialog freezes: its sliders don't +/// move and nothing else responds. Elsewhere a maximized main window keeps Camera Raw in its own +/// window, as in Photoshop. +fn draws_over_main_window(ctx: &egui::Context, wayland: bool) -> bool { + let (fullscreen, maximized) = ctx.input(|i| (i.viewport().fullscreen == Some(true), i.viewport().maximized == Some(true))); + ctx.embed_viewports() || fullscreen || (wayland && maximized) +} + /// Whether to bring Camera Raw's window to the front: when the main window has just gained focus /// (it came forward over Camera Raw's) or is clicked. fn raise_camera_raw(was_focused: bool, focused: bool, clicked: bool) -> bool { diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs index 4fd1852aae..f61c57e27d 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs @@ -48,6 +48,37 @@ pub(super) fn apply_raw_conversions(app: &mut PhotocraftApp, index: usize, d: &p Ok(()) } +/// `area` of `surf` averaged over `k`×`k` blocks, row-major (`ceil(w/k)` × `ceil(h/k)`). A block +/// past the last row repeats that row, as a clamped edge; each source row is still read once, +/// weighted by the block rows it stands for (a one-row domain read the same row `k` times, which +/// is quadratic in its width). +fn box_average(surf: &photocraft_raster::Surface, area: Rect, k: usize) -> Vec<[f32; 4]> { + let (w, h) = (area.width() as usize, area.height() as usize); + let (pw, ph) = (w.div_ceil(k), h.div_ceil(k)); + let mut proxy = vec![[0.0f32; 4]; pw * ph]; + let mut row = vec![[0.0f32; 4]; w]; + for py in 0..ph { + // f64: a weighted f32 sample near f32::MAX would overflow to infinity. + let mut acc = vec![[0.0f64; 5]; pw]; + for sy in py * k..((py + 1) * k).min(h) { + let weight = if sy == h - 1 { ((py + 1) * k - sy) as f64 } else { 1.0 }; + let y = area.y0 + sy as i32; + surf.read_rgba_into(Rect::new(area.x0, y, area.x1, y + 1), &mut row); + for (x, q) in row.iter().enumerate() { + let a = &mut acc[x / k]; + for c in 0..4 { + a[c] += f64::from(q[c]) * weight; + } + a[4] += weight; + } + } + for (x, a) in acc.iter().enumerate() { + proxy[py * pw + x] = [0, 1, 2, 3].map(|c| (a[c] / a[4]) as f32); + } + } + proxy +} + /// What the preview develops, and its size: the engine filter domain, including pixels outside the /// canvas, since spatial Camera Raw stages (vignette, grain, local contrast) must agree with the /// committed result. @@ -70,26 +101,7 @@ pub(super) fn preview_area(canvas: Rect, surf: &photocraft_raster::Surface) -> R pub(super) fn box_proxy(surf: &photocraft_raster::Surface, area: Rect, w: usize, h: usize) -> (Vec<[f32; 4]>, usize, usize, usize) { let k = w.max(h).div_ceil(PROXY_SIDE).max(1); let (pw, ph) = (w.div_ceil(k), h.div_ceil(k)); - let mut proxy = vec![[0.0f32; 4]; pw * ph]; - let mut row = vec![[0.0f32; 4]; w]; - for py in 0..ph { - // Box-average k×k blocks. - let mut acc = vec![[0.0f32; 5]; pw]; - for dy in 0..k { - let y = area.y0 + (py * k + dy).min(h - 1) as i32; - surf.read_rgba_into(Rect::new(area.x0, y, area.x1, y + 1), &mut row); - for (x, q) in row.iter().enumerate() { - let a = &mut acc[x / k]; - for c in 0..4 { - a[c] += q[c]; - } - a[4] += 1.0; - } - } - for (x, a) in acc.iter().enumerate() { - proxy[py * pw + x] = [a[0] / a[4], a[1] / a[4], a[2] / a[4], a[3] / a[4]]; - } - } + let proxy = box_average(surf, area, k); (proxy, pw, ph, k) } @@ -204,3 +216,60 @@ pub(super) fn open_pixels( app.camera_raw = Some(d); Ok(()) } + +#[cfg(test)] +mod box_average_tests { + use super::{Rect, box_average}; + use photocraft_color::PixelFormat; + use photocraft_raster::Surface; + + /// The clamped reference: every block row read, past the last row the last row again. + fn reference(surf: &Surface, area: Rect, k: usize) -> Vec<[f32; 4]> { + let (w, h) = (area.width() as usize, area.height() as usize); + let (pw, ph) = (w.div_ceil(k), h.div_ceil(k)); + let mut out = Vec::new(); + let mut row = vec![[0.0f32; 4]; w]; + for py in 0..ph { + let mut acc = vec![[0.0f32; 5]; pw]; + for dy in 0..k { + let y = area.y0 + (py * k + dy).min(h - 1) as i32; + surf.read_rgba_into(Rect::new(area.x0, y, area.x1, y + 1), &mut row); + for (x, q) in row.iter().enumerate() { + for c in 0..4 { + acc[x / k][c] += q[c]; + } + acc[x / k][4] += 1.0; + } + } + out.extend(acc.iter().map(|a| [a[0] / a[4], a[1] / a[4], a[2] / a[4], a[3] / a[4]])); + } + out + } + + #[test] + fn blocks_past_the_last_row_match_the_clamped_average() { + let mut surf = Surface::new(PixelFormat::RGBA32F); + for x in 0..37 { + for y in 0..5 { + surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[x as f32 / 37.0, y as f32 / 5.0, 0.5, 1.0]); + } + } + for (area, k) in [(Rect::new(0, 0, 37, 5), 2), (Rect::new(0, 0, 37, 5), 4), (Rect::new(0, 2, 37, 3), 16), (Rect::new(3, 0, 37, 5), 7)] { + let (got, want) = (box_average(&surf, area, k), reference(&surf, area, k)); + assert_eq!(got.len(), want.len()); + for (g, w) in got.iter().zip(&want) { + assert!(g.iter().zip(w).all(|(a, b)| (a - b).abs() < 1e-5), "{area:?} k={k}: {g:?} vs {w:?}"); + } + } + } + + /// Samples near f32::MAX stay finite: the weighted sums are held in f64. + #[test] + fn huge_samples_do_not_overflow() { + let mut surf = Surface::new(PixelFormat::RGBA32F); + let big = f32::MAX / 2.0; + surf.fill_rect(Rect::new(0, 0, 2, 1), &[big, -big, big, 1.0]); + let got = box_average(&surf, Rect::new(0, 0, 2, 1), 4); + assert!(got.iter().flatten().all(|v| v.is_finite()), "{got:?}"); + } +} diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/identity_tests.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/identity_tests.rs index 968112d5f5..dee1cd8905 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/identity_tests.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/identity_tests.rs @@ -54,6 +54,7 @@ fn identity_app() -> (PhotocraftApp, RawOpen, Control) { bytes: Some(bytes), developed_with: Default::default(), demosaic: Default::default(), + decoded: None, crop: None, }; let mut app = PhotocraftApp::new(session, crate::Services::default()); @@ -149,7 +150,7 @@ fn queue_identity_targets_an_inactive_raw_without_changing_the_active_document() let (mut app, raw, control) = identity_app(); app.session.set_active(0); assert_eq!(app.session.active().unwrap().doc.id, control.doc.id); - queue_open_dialog(&mut app, raw.document, &raw.name, raw.path.as_deref(), raw.bytes.as_deref().map(Vec::as_slice), &[]).unwrap(); + queue_open_dialog(&mut app, raw.document, &raw.name, raw.path.as_deref(), raw.bytes.as_ref(), &[]).unwrap(); let queued = app.raw_shelf.first().map(|h| &h.raw).expect("the explicitly named RAW was queued"); assert_eq!(queued.document, raw.document); assert_eq!((&queued.name, &queued.path, &queued.bytes), (&raw.name, &raw.path, &raw.bytes)); @@ -160,12 +161,12 @@ fn queue_identity_targets_an_inactive_raw_without_changing_the_active_document() #[test] fn queue_identity_rejects_a_missing_document_without_replacing_the_pending_review() { let (mut app, raw, control) = identity_app(); - queue_open_dialog(&mut app, raw.document, &raw.name, raw.path.as_deref(), raw.bytes.as_deref().map(Vec::as_slice), &[]).unwrap(); + queue_open_dialog(&mut app, raw.document, &raw.name, raw.path.as_deref(), raw.bytes.as_ref(), &[]).unwrap(); let pending = app.raw_shelf.first().map(|h| &h.raw).unwrap().clone(); app.session.set_active(0); let missing = photocraft_doc::DocId::fresh(); assert!(!app.session.documents().iter().any(|state| state.doc.id == missing)); - assert!(queue_open_dialog(&mut app, missing, "missing.dng", Some("missing.dng"), Some(&[1, 2, 3]), &[]).is_err()); + assert!(queue_open_dialog(&mut app, missing, "missing.dng", Some("missing.dng"), Some(&std::sync::Arc::new(vec![1, 2, 3])), &[]).is_err()); let queued = app.raw_shelf.first().map(|h| &h.raw).expect("the existing review is preserved"); assert_eq!(queued.document, pending.document); assert_eq!((&queued.name, &queued.path, &queued.bytes), (&pending.name, &pending.path, &pending.bytes)); diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs index 12e168bd7b..5b6721d069 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs @@ -30,6 +30,9 @@ pub struct RawOpen { pub developed_with: photocraft_io::raw::Demosaic, /// The method chosen in the dialog: Open re-develops when it differs from `developed_with`. pub demosaic: photocraft_io::raw::Demosaic, + /// The file decoded once for the dialog's preview and for Open's re-develop (the sensor data + /// is 2 bytes per pixel): freed with the last copy of this, when the dialog closes. + pub decoded: Option>, /// The crop of the file's sidecar (in the raw's stored orientation): Open re-develops and /// crops to it. The settings have no crop, so the dialog previews the whole frame. pub crop: Option, @@ -56,7 +59,7 @@ pub fn queue_open_dialog( document: photocraft_doc::DocId, name: &str, path: Option<&str>, - bytes: Option<&[u8]>, + bytes: Option<&std::sync::Arc>>, warnings: &[String], ) -> Result<(), String> { if document_index(app, document).is_none() { @@ -72,9 +75,10 @@ pub fn queue_open_dialog( document, name: name.to_string(), path: path.map(str::to_string), - bytes: bytes.map(|b| std::sync::Arc::new(b.to_vec())), + bytes: bytes.cloned(), developed_with: method, demosaic: method, + decoded: None, // Read now: a filmstrip raw that is never shown still opens with its sidecar's crop. crop: path.and_then(read_sidecar).and_then(|(_, report, _)| report.crop), }; @@ -134,14 +138,23 @@ pub(super) fn open_raw_with(app: &mut PhotocraftApp, ctx: &egui::Context, mut ra Ok(()) } -/// Gives the open dialog its raw: the file name, and the camera tone curve it was developed with. -fn attach_raw(app: &mut PhotocraftApp, raw: RawOpen) { - let curve = match (&raw.bytes, &raw.path) { - (Some(b), _) => Some(photocraft_io::raw::tone_curve(b)), +/// Gives the open dialog its raw: the file name, the camera tone curve it was developed with, and +/// the decode (the open's kept one, else one made now) the preview and Open's re-develop share. +fn attach_raw(app: &mut PhotocraftApp, mut raw: RawOpen) { + let file = match (&raw.bytes, &raw.path) { + _ if raw.decoded.is_some() => None, + (Some(b), _) => Some(std::borrow::Cow::Borrowed(b.as_slice())), #[cfg(not(target_arch = "wasm32"))] - (None, Some(p)) => std::fs::read(p).ok().map(|b| photocraft_io::raw::tone_curve(&b)), + (None, Some(p)) => std::fs::read(p).ok().map(std::borrow::Cow::Owned), _ => None, }; + let curve = match file { + Some(b) => { + raw.decoded = photocraft_io::raw::take_kept_decode(&b).or_else(|| photocraft_io::raw::RawDecode::new(&b).ok().map(std::sync::Arc::new)); + Some(raw.decoded.as_ref().map(|d| d.tone_curve().to_vec()).unwrap_or_default()) + } + None => raw.decoded.as_ref().map(|d| d.tone_curve().to_vec()), + }; if let Some(d) = app.camera_raw.as_mut() { d.layer_name = raw.name.clone(); // The full-size preview retones the whole frame with it, as Open will. @@ -232,21 +245,25 @@ pub(super) fn commit_open_raw(app: &mut PhotocraftApp, params: &CameraRaw, raw: return finish_open_raw(app, index, params.clone(), None, raw, &defaults); }; app.session.set_active(index); - let (name, doc_id) = (raw.name.clone(), raw.document); + let (name, doc_id, decoded) = (raw.name.clone(), raw.document, raw.decoded.clone()); let work = move |ctx: &photocraft_engine::jobs::JobCtx| -> photocraft_engine::Result<(photocraft_io::ImportResult, bool)> { ctx.progress(0.0, "Reading"); let bytes = match source { photocraft_engine::jobs::OpenSource::Bytes(b) => b, #[cfg(not(target_arch = "wasm32"))] photocraft_engine::jobs::OpenSource::Path(p) => { - std::sync::Arc::new(std::fs::read(&p).map_err(|e| photocraft_engine::EngineError::Other(format!("{p}: {e}")))?) + std::sync::Arc::new(read_raw_file(&p).map_err(|e| photocraft_engine::EngineError::Other(format!("{p}: {e}")))?) } #[cfg(target_arch = "wasm32")] photocraft_engine::jobs::OpenSource::Path(p) => return Err(photocraft_engine::EngineError::Other(format!("{p}: cannot read files here"))), }; ctx.check()?; ctx.progress(0.05, "Developing"); - photocraft_io::raw::import_raw_tuned(&name, &bytes, &tuning).map_err(|e| photocraft_engine::EngineError::Other(e.to_string())) + match &decoded { + Some(d) => photocraft_io::raw::import_raw_tuned_from(&name, &bytes, &tuning, d), + None => photocraft_io::raw::import_raw_tuned(&name, &bytes, &tuning), + } + .map_err(|e| photocraft_engine::EngineError::Other(e.to_string())) }; let apply = move |s: &mut photocraft_engine::Session, (r, wb): (photocraft_io::ImportResult, bool)| replace_raw_document(s, doc_id, r, wb); let label = crate::i18n::fmt(tl!("Developing {name}"), &[("name", &raw.name)]); @@ -396,8 +413,16 @@ pub fn opened_without_dialog(app: &mut PhotocraftApp, index: usize, name: &str, } let Some(document) = app.session.documents().get(index).map(|st| st.doc.id) else { return }; let method = photocraft_io::raw::developed_demosaic(warnings).unwrap_or_else(|| app.session.prefs().raw_defaults.demosaic.method()); - let mut raw = - RawOpen { document, name: name.to_string(), path: path.map(str::to_string), bytes: None, developed_with: method, demosaic: method, crop: None }; + let mut raw = RawOpen { + document, + name: name.to_string(), + path: path.map(str::to_string), + bytes: None, + decoded: None, + developed_with: method, + demosaic: method, + crop: None, + }; let mut params = CameraRaw::default(); let sidecar = path.and_then(read_sidecar).map(|(loaded, report, _)| { raw.crop = report.crop; @@ -561,3 +586,57 @@ pub fn open_smart_filter(app: &mut PhotocraftApp, ctx: &egui::Context, layer: La let coverage = sm.filter_mask.clone().filter(|m| m.enabled).map_or(Coverage::None, Coverage::Mask); open_pixels(app, ctx, layer, surf, params, coverage, Target::SmartFilter(index)) } + +/// Largest RAW file re-read for a tuned develop: the RAW decoder's default allocation ceiling +/// (`photocraft_raw::Limits::default().max_alloc`, 2 GiB), which the decode's buffers exceed for any file this large. +#[cfg(not(target_arch = "wasm32"))] +const MAX_RAW_REREAD_BYTES: u64 = 2 << 30; + +/// The bytes of the regular file at `path`, at most [`MAX_RAW_REREAD_BYTES`]: the opened handle +/// must be a regular file, so a pathname swapped for a never-ending device is refused, and reading +/// stops one byte past the cap. +#[cfg(not(target_arch = "wasm32"))] +fn read_raw_file(path: &str) -> std::io::Result> { + use std::io::{Error, ErrorKind, Read}; + let file = std::fs::File::open(path)?; + let metadata = file.metadata()?; + if !metadata.is_file() { + return Err(Error::new(ErrorKind::InvalidInput, "not a regular file")); + } + if metadata.len() > MAX_RAW_REREAD_BYTES { + return Err(Error::new(ErrorKind::InvalidData, "file is too large")); + } + let expected = usize::try_from(metadata.len()).map_err(|_| Error::new(ErrorKind::InvalidData, "file is too large"))?; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(expected).map_err(|_| Error::new(ErrorKind::OutOfMemory, "cannot reserve RAW read buffer"))?; + file.take(MAX_RAW_REREAD_BYTES + 1).read_to_end(&mut bytes)?; + if bytes.len() as u64 > MAX_RAW_REREAD_BYTES { + return Err(Error::new(ErrorKind::InvalidData, "file is too large")); + } + Ok(bytes) +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod read_tests { + use super::*; + + #[test] + fn an_oversized_raw_file_is_refused_from_its_length_without_reading_it() { + let path = std::env::temp_dir().join(format!("pc-raw-reread-{}", std::process::id())); + let file = std::fs::File::create(&path).unwrap(); + // Sparse: one byte past the cap, never stored or read. + file.set_len(MAX_RAW_REREAD_BYTES + 1).unwrap(); + let e = read_raw_file(path.to_str().unwrap()).unwrap_err(); + std::fs::remove_file(&path).unwrap(); + assert_eq!(e.kind(), std::io::ErrorKind::InvalidData); + } + + #[test] + fn a_small_raw_file_reads_back() { + let path = std::env::temp_dir().join(format!("pc-raw-reread-small-{}", std::process::id())); + std::fs::write(&path, [5u8; 6]).unwrap(); + let bytes = read_raw_file(path.to_str().unwrap()); + std::fs::remove_file(&path).unwrap(); + assert_eq!(bytes.unwrap(), vec![5u8; 6]); + } +} diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs index 34d8bacb91..eb8d75e860 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs @@ -91,6 +91,56 @@ fn closing_the_camera_raw_window_cancels() { assert_eq!(app.session.active().unwrap().history.past_len(), steps); } +/// Over a full-screen main window (or a maximized one on Wayland) the dialog is drawn in that +/// window, not in a window of its own: a separate window would cover the main one, which then +/// draws no frames, and the dialog drawn inside those frames would freeze. +#[test] +fn camera_raw_stays_in_a_full_screen_or_wayland_maximized_window() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::Pro); + ctx.set_embed_viewports(false); + // Stands in for the desktop backend: records each window the dialog asks for and draws it, + // as eframe does, in a frame of its own. + let windows = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let seen = std::rc::Rc::clone(&windows); + egui::Context::set_immediate_viewport_renderer(move |ctx, mut viewport| { + seen.borrow_mut().push(viewport.ids.this); + let mut input = egui::RawInput { viewport_id: viewport.ids.this, ..Default::default() }; + input.viewports.insert(viewport.ids.this, egui::ViewportInfo::default()); + ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui)).textures_delta.clear(); + }); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + open(&mut app, &ctx).unwrap(); + let window = egui::ViewportId::from_hash_of("camera-raw-window"); + + // (Wayland, full screen, maximized, a window of its own) + for (wayland, fullscreen, maximized, own_window) in [ + (false, false, false, true), + (true, false, false, true), + (false, true, false, false), + (true, true, false, false), + (false, false, true, true), + (true, false, true, false), + ] { + app.services.is_wayland = wayland; + windows.borrow_mut().clear(); + app.camera_raw.as_mut().unwrap().viewport = None; + let mut input = egui::RawInput::default(); + let root = input.viewports.entry(egui::ViewportId::ROOT).or_default(); + (root.fullscreen, root.maximized) = (Some(fullscreen), Some(maximized)); + ctx.run_ui(input, |ui| show(&mut app, ui.ctx())).textures_delta.clear(); + let case = format!("wayland {wayland}, full screen {fullscreen}, maximized {maximized}"); + if own_window { + assert_eq!(*windows.borrow(), [window], "a window of its own ({case})"); + } else { + assert!(windows.borrow().is_empty(), "no window of its own ({case})"); + } + assert!(app.camera_raw.as_ref().unwrap().viewport.is_some(), "the dialog is drawn ({case})"); + } +} + /// Coming back to PhotoCraft (⌘Tab, the Dock) can put the main window over Camera Raw's, or /// leave Camera Raw minimized: the main window gaining focus, or a click on its dimmed surface, /// restores Camera Raw's window and focuses it, once per activation. @@ -378,9 +428,26 @@ fn dialog_drives_the_engine() { assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": "x"}}})).unwrap().is_err()); } +std::thread_local! { + /// Held by a test's thread from its first `raw_app` to the test's end. + static RAW_OPEN_TURN: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + /// An app whose importer is the real one, opening a synthetic DNG. +/// +/// Raw opens keep their decode in one process-wide list of two (`photocraft_io::raw`), so tests +/// that open raws take turns: a parallel test's open would otherwise evict the decode another +/// test is about to take. The turn is held until the test's thread ends (nextest runs each test +/// in its own process, where this costs nothing). fn raw_app() -> (PhotocraftApp, Vec) { use photocraft_raw::testgen::{DngSpec, mosaic, scene}; + static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + RAW_OPEN_TURN.with(|held| { + let mut held = held.borrow_mut(); + if held.is_none() { + *held = Some(TURN.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); + } + }); let services = crate::Services { import: Some(Box::new(|name: &str, b: &[u8], opts: &photocraft_io::ImportOptions| { photocraft_io::import_with_options(name, b, opts).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string()) @@ -436,6 +503,41 @@ fn pixels(app: &PhotocraftApp) -> Vec { (0..32).flat_map(|y| (0..48).map(move |x| (x, y))).flat_map(|(x, y)| s.rgba(x, y)).collect() } +/// #9432: a raw open decodes the file once. The dialog's preview curve and Open's re-develop +/// reuse the open's sensor data and look, give the pixels of decoding again, and let go of +/// the sensor data when the dialog closes. +#[test] +fn a_raw_open_decodes_the_file_once_and_frees_it_with_the_dialog() { + use photocraft_io::raw::decodes_on_this_thread; + let ctx = egui::Context::default(); + let develop = |reuse: bool, commit: bool| { + let (mut app, mut dng) = raw_app(); + // Kept decodes are found by file contents: other tests open the same synthetic DNG. + dng.extend_from_slice(b"a_raw_open_decodes_the_file_once"); + let before = decodes_on_this_thread(); + app.open_bytes("IMG_0007.dng", &dng).unwrap(); + let raw = take_queued(&mut app).unwrap(); + open_raw(&mut app, &ctx, raw).unwrap(); + let raw_open = app.camera_raw.as_mut().unwrap().raw_open.as_mut().unwrap(); + let sensor = raw_open.decoded.as_ref().map(std::sync::Arc::downgrade).expect("the dialog holds the open's decode"); + if !reuse { + raw_open.decoded = None; + } + assert!(sensor.upgrade().is_some() || !reuse); + let ui = if commit { json!({"set": {"exposure": 1.0, "temperature": 30}, "commit": true}) } else { json!({"cancel": true}) }; + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": ui})).unwrap().unwrap(); + assert!(app.camera_raw.is_none()); + assert!(sensor.upgrade().is_none(), "the sensor data is freed when the dialog is closed"); + (decodes_on_this_thread() - before, if commit { pixels(&app) } else { Vec::new() }) + }; + let (decodes, reused) = develop(true, true); + assert_eq!(decodes, 1, "open, dialog and commit share one decode"); + let (decodes, again) = develop(false, true); + assert_eq!(decodes, 2, "without the kept decode the commit decodes again"); + assert_eq!(reused, again, "the same pixels either way"); + assert_eq!(develop(true, false).0, 1, "Cancel decodes nothing more"); +} + #[test] fn the_demosaic_method_is_chosen_at_open() { let (mut app, dng) = raw_app(); @@ -476,7 +578,7 @@ fn the_demosaic_method_is_chosen_at_open() { take_queued(&mut app); app.run("prefs.set", json!({"path": "rawDefaults.demosaic", "value": "ahd"})).unwrap(); let document = app.session.active().unwrap().doc.id; - queue_open_dialog(&mut app, document, "IMG_0004.dng", None, Some(&dng), &warnings).unwrap(); + queue_open_dialog(&mut app, document, "IMG_0004.dng", None, Some(&std::sync::Arc::new(dng.clone())), &warnings).unwrap(); let raw = take_queued(&mut app).unwrap(); use photocraft_io::raw::Demosaic; assert_eq!((raw.developed_with, raw.demosaic), (Demosaic::Bilinear, Demosaic::Bilinear)); @@ -754,7 +856,7 @@ fn auto_tone_of_a_never_shown_raw_matches_the_dialogs() { } } let method = photocraft_io::raw::Demosaic::Ahd; - let raw = RawOpen { document, name: "pattern.dng".into(), path: None, bytes: None, developed_with: method, demosaic: method, crop: None }; + let raw = RawOpen { document, name: "pattern.dng".into(), path: None, bytes: None, decoded: None, developed_with: method, demosaic: method, crop: None }; let (unshown, _) = filmstrip::first_settings(&app, &raw); open_raw(&mut app, &ctx, raw).unwrap(); let shown = &app.camera_raw.as_ref().unwrap().params; @@ -795,6 +897,7 @@ fn cancel_closes_the_raw_and_the_preference_skips_the_dialog() { bytes: None, developed_with: Default::default(), demosaic: Default::default(), + decoded: None, crop: None } ) diff --git a/crates/ui-egui/src/dialogs/dont_show_again.rs b/crates/ui-egui/src/dialogs/dont_show_again.rs index da21ce4087..ab6bd25bf9 100644 --- a/crates/ui-egui/src/dialogs/dont_show_again.rs +++ b/crates/ui-egui/src/dialogs/dont_show_again.rs @@ -47,6 +47,11 @@ pub fn closed(app: &mut PhotocraftApp, d: &Dialog) { if d.fields.get("skip").and_then(Value::as_bool) != Some(true) { return; } + remember(app, pref); +} + +/// Keep "Don't show again" for the question remembered as `pref`, with the other dialog preferences. +pub fn remember(app: &mut PhotocraftApp, pref: &str) { app.session.edit_prefs(|prefs| { prefs.dialogs.insert(pref.into(), json!({"skip": true})); }); diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index e8bc29f831..3da56a5860 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -112,7 +112,7 @@ fn open_sized(app: &mut PhotocraftApp, src_w: u32, src_h: u32) -> Result, src_w: f64, src_h: f64) { } } +/// Whether Enter answers the dialog with `f` as its fields the way its default button does. Export +/// As starts only from a click on Export, as in Photoshop: Enter, with no text field taking it, +/// leaves the dialog open (#13740). Every other dialog keeps Enter = OK. +pub(crate) fn enter_confirms(f: &Map) -> bool { + !f.contains_key("__export") +} + /// Layer › Export As…: the same dialog for just the active layer (trimmed to its pixels). pub fn open_layer(app: &mut PhotocraftApp, layer: photocraft_doc::LayerId) -> Result { let st = app.session.active().ok_or("no document")?; @@ -257,7 +264,9 @@ fn batch_paths(path: &str, docs: &[Document]) -> Vec { let candidate = { let mut candidate = candidate; let mut suffix = 1u64; - while candidate.exists() { + // A name any entry occupies is taken, a symlink (even a dangling one) included: the writer + // follows links, so one planted here would redirect the export. + while candidate.symlink_metadata().is_ok() { candidate = parent.join(format!("{stem}-{}-{name}-{suffix}.{ext}", i + 1)); suffix = suffix.saturating_add(1); } @@ -473,6 +482,9 @@ fn settings(f: &Map) -> ExportSettings { // Metadata: None drops EXIF and resolution as well as XMP. A missing key keeps them, // which is what Export As wrote before the choice existed. embed_metadata: metadata != "none", + // Export As's JPGs are progressive (SOF2) in the reference application, measured at its + // default quality; the scan layout is one setting for the whole dialog. + jpeg_format: photocraft_codecs::JpegFormat::Progressive, ..Default::default() } } @@ -944,17 +956,12 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map = vec![("document".into(), tl!("Document Profile")), ("srgb".into(), tl!("Convert to sRGB"))]; - if crate::widgets::dropdown(ui, "export-profile", tl!("Color Profile"), &mut profile, &opts, 130.0) { - f.insert("profile".into(), json!(profile)); - } - }); + ui.add_space(8.0); + ui.label(egui::RichText::new(tl!("Color Space")).font(crate::theme::semibold(12.0)).color(t.text)); + let mut srgb = s(f, "profile") == "srgb"; + if crate::widgets::checkbox(ui, &mut srgb, tl!("Convert to sRGB")).changed() { + f.insert("profile".into(), json!(if srgb { "srgb" } else { "document" })); + } let mut embed = f.get("embedProfile").and_then(Value::as_bool).unwrap_or(true); crate::widgets::checkbox(ui, &mut embed, tl!("Embed Color Profile")); f.insert("embedProfile".into(), json!(embed)); @@ -1173,5 +1180,33 @@ fn quick_export(app: &mut PhotocraftApp, p: Value) -> Result { Ok(r) } +#[cfg(test)] +mod srgb_default_tests; #[cfg(test)] mod tests; + +#[cfg(test)] +mod enter_key_tests; + +#[cfg(test)] +mod jpg_progressive_tests; + +#[cfg(all(test, unix))] +mod batch_name_tests { + use super::*; + use photocraft_doc::{ColorMode, SampleType, Size}; + + #[test] + fn a_planted_symlink_makes_a_batch_name_taken() { + let dir = std::env::temp_dir().join(format!("pc-batch-names-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + // Dangling: `exists()` follows it and reports the name free; the writer would follow it too. + let planted = dir.join("x-2-a.png"); + let _ = std::fs::remove_file(&planted); + std::os::unix::fs::symlink(dir.join("victim"), &planted).unwrap(); + let doc = Document::new("a", Size::new(2, 2), ColorMode::Rgb, SampleType::U8); + let paths = batch_paths(dir.join("x.png").to_str().unwrap(), &[doc.clone(), doc]); + assert_ne!(paths[1], planted.to_str().unwrap()); + std::fs::remove_file(&planted).unwrap(); + } +} diff --git a/crates/ui-egui/src/dialogs/export_dialog/enter_key_tests.rs b/crates/ui-egui/src/dialogs/export_dialog/enter_key_tests.rs new file mode 100644 index 0000000000..7ff2143581 --- /dev/null +++ b/crates/ui-egui/src/dialogs/export_dialog/enter_key_tests.rs @@ -0,0 +1,106 @@ +//! Export As starts only from its Export button, as in Photoshop (#13740): Enter, with no text field +//! taking it, leaves the dialog open and asks for no file; Enter in a size field commits the value +//! typed there; Escape still cancels. Other dialogs keep Enter = OK. +use super::*; +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use std::{cell::RefCell, rc::Rc}; + +/// Every save dialog the export asked for. +type Asked = Rc>>; + +/// A 200 × 150 document with Export As open, in a harness that draws the dialogs and answers the +/// save dialog with Cancel. Returns the dialog's id and the log of save dialogs asked for, which +/// grows by one when the export starts. +fn export_as_open() -> (Harness<'static, PhotocraftApp>, u64, Asked) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + let (show, asked) = crate::file_dialog::fake(vec![None]); + app.services.file_dialog = Some(show); + let mut h = Harness::builder().with_size(egui::vec2(1000.0, 800.0)).build_ui_state( + |ui, app| { + crate::dialogs::show(app, ui.ctx()); + app.poll_file_dialog(ui.ctx(), None); + }, + app, + ); + // The dialog opens once the app's fonts are in: the harness draws a first frame as it is built. + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let id = open(h.state_mut()).unwrap(); + h.run_steps(4); + (h, id, asked) +} + +/// Whether the dialog `id` is still open. +fn is_open(h: &Harness<'_, PhotocraftApp>, id: u64) -> bool { + h.state().ui.dialogs.iter().any(|d| d.id == id) +} + +/// The dialog's stored export size: scale (percent), width and height (pixels). +fn size(h: &Harness<'_, PhotocraftApp>, id: u64) -> (f64, f64, f64) { + let f = &h.state().ui.dialogs.iter().find(|d| d.id == id).expect("Export As is open").fields; + (n(f, "scale", -1.0), n(f, "width", -1.0), n(f, "height", -1.0)) +} + +/// Enter with no field being edited does nothing: the dialog stays open with its size, no save +/// dialog is asked for, and a second Enter changes nothing either. A click on Export then starts +/// the export (the save dialog is asked for once) and closes the dialog, so the harness would +/// have seen an export that Enter started. +#[test] +fn enter_leaves_export_as_open_and_exports_nothing() { + let (mut h, id, asked) = export_as_open(); + assert!(h.query_by_role_and_label(Role::Button, "Export").is_some(), "the default button is Export"); + assert_eq!(size(&h, id), (100.0, 200.0, 150.0)); + for _ in 0..2 { + h.key_press(egui::Key::Enter); + h.run_steps(4); + assert!(is_open(&h, id), "Enter keeps Export As open"); + assert!(asked.borrow().is_empty(), "Enter starts no export"); + assert_eq!(size(&h, id), (100.0, 200.0, 150.0)); + } + h.get_by_role_and_label(Role::Button, "Export").click(); + h.run_steps(4); + assert!(!is_open(&h, id), "Export closes the dialog"); + assert_eq!(asked.borrow().len(), 1, "Export asks where to save, once"); +} + +/// Enter in the Scale field commits the typed percent there (50 % of 200 × 150 is 100 × 75) and +/// leaves the dialog open with nothing exported. +#[test] +fn enter_in_the_scale_field_commits_it_and_keeps_the_dialog() { + let (mut h, id, asked) = export_as_open(); + h.get_by_role_and_label(Role::SpinButton, "Scale").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + for ch in "50".chars() { + h.event(egui::Event::Text(ch.to_string())); + h.run_steps(1); + } + h.key_press(egui::Key::Enter); + h.run_steps(4); + assert!(is_open(&h, id), "Enter in a field keeps Export As open"); + assert!(asked.borrow().is_empty(), "Enter in a field starts no export"); + assert_eq!(size(&h, id), (50.0, 100.0, 75.0)); + assert_eq!(h.get_by_role_and_label(Role::SpinButton, "Scale").accesskit_node().numeric_value(), Some(50.0)); +} + +/// Escape still cancels Export As: the dialog closes and nothing is exported. +#[test] +fn escape_cancels_export_as() { + let (mut h, id, asked) = export_as_open(); + h.key_press(egui::Key::Escape); + h.run_steps(4); + assert!(!is_open(&h, id), "Escape closes Export As"); + assert!(asked.borrow().is_empty(), "Escape starts no export"); +} + +/// Only Export As opts out of Enter = OK. +#[test] +fn only_export_as_opts_out_of_enter() { + let mut f = Map::new(); + assert!(enter_confirms(&f), "a dialog without the Export As marker keeps Enter = OK"); + f.insert("__export".into(), json!(true)); + assert!(!enter_confirms(&f)); +} diff --git a/crates/ui-egui/src/dialogs/export_dialog/jpg_progressive_tests.rs b/crates/ui-egui/src/dialogs/export_dialog/jpg_progressive_tests.rs new file mode 100644 index 0000000000..1ec9a486fa --- /dev/null +++ b/crates/ui-egui/src/dialogs/export_dialog/jpg_progressive_tests.rs @@ -0,0 +1,82 @@ +//! #13724: Export As writes JPGs with a progressive scan layout (SOF2) at every quality. + +use super::*; + +/// A 32 x 24 document of solid colour blocks, so JPEG error stays small away from the edges. +fn blocks_doc() -> Document { + use photocraft_doc::{Color, ColorMode, SampleType, Size}; + use photocraft_geom::Rect; + let mut doc = Document::with_background("blocks", Size::new(32, 24), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let surf = doc.layers[0].surface_mut().unwrap(); + surf.fill_rect(Rect::new(0, 0, 16, 16), &[1.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(16, 0, 32, 16), &[0.0, 1.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(0, 16, 16, 24), &[0.0, 0.0, 1.0, 1.0]); + doc +} + +fn export_jpg(doc: &Document, quality: u32) -> Vec { + let f = json!({"format": "jpg", "quality": quality, "scale": 100, "embedProfile": false}).as_object().unwrap().clone(); + let out = super::export_document(doc, &f, None, &photocraft_engine::color_cmds::document_profile(doc)).unwrap(); + photocraft_io::export(&out, "x.jpg", &settings(&f).io_options()).unwrap().bytes +} + +/// The main frame's marker and component sampling factors, skipping whole segments. +fn frame(bytes: &[u8]) -> (u8, [u8; 3]) { + assert_eq!(bytes.get(..2), Some([0xff, 0xd8].as_slice()), "JPEG SOI"); + let mut offset = 2; + loop { + assert_eq!(bytes.get(offset), Some(&0xff), "marker prefix"); + while bytes.get(offset) == Some(&0xff) { + offset += 1; + } + let marker = *bytes.get(offset).expect("marker"); + offset += 1; + assert!(!matches!(marker, 0xd9 | 0xda), "no frame before scan"); + let len = usize::from(u16::from_be_bytes([bytes[offset], bytes[offset + 1]])); + let segment = &bytes[offset + 2..offset + len]; + if matches!(marker, 0xc0..=0xc3) { + assert_eq!(segment[5], 3, "three components"); + return (marker, std::array::from_fn(|i| segment[6 + 3 * i + 1])); + } + offset += len; + } +} + +#[test] +fn export_as_jpg_is_progressive_at_every_quality() { + let doc = blocks_doc(); + for (quality, sampling) in [(85, [0x11; 3]), (20, [0x22, 0x11, 0x11])] { + let bytes = export_jpg(&doc, quality); + let (marker, factors) = frame(&bytes); + assert_eq!(marker, 0xc2, "quality {quality}: SOF2 (progressive), not SOF0"); + assert_eq!(factors, sampling, "quality {quality}: chroma sampling"); + } +} + +#[test] +fn progressive_export_decodes_back_to_the_source() { + let doc = blocks_doc(); + // Every pixel within 2 levels at the dialog default. Quality 20 quantises saturated flat + // colours and their edges coarsely, so there only the block centres are held to the colour. + for (quality, tolerance) in [(85, 2), (20, 64)] { + let decoded = + photocraft_codecs::decode(&export_jpg(&doc, quality)).unwrap().convert(photocraft_codecs::ChannelLayout::Rgb, photocraft_codecs::SampleType::U8); + assert_eq!(decoded.dimensions(), (32, 24)); + for (i, px) in decoded.data().as_chunks::<3>().0.iter().enumerate() { + let (x, y) = (i % 32, i / 32); + if quality == 20 && !matches!((x, y), (7 | 23, 7) | (7, 20) | (23, 20)) { + continue; + } + let want: [u8; 3] = match (x < 16, y < 16) { + (true, true) => [255, 0, 0], + (false, true) => [0, 255, 0], + (true, false) => [0, 0, 255], + (false, false) => [255, 255, 255], + }; + // The block interiors; the colour edges fall on 16 x 16 MCU boundaries. + for (a, b) in px.iter().zip(want) { + assert!(a.abs_diff(b) <= tolerance, "quality {quality}, pixel ({x}, {y}): {px:?} vs {want:?}"); + } + } + } +} diff --git a/crates/ui-egui/src/dialogs/export_dialog/srgb_default_tests.rs b/crates/ui-egui/src/dialogs/export_dialog/srgb_default_tests.rs new file mode 100644 index 0000000000..2fe9a5e2b6 --- /dev/null +++ b/crates/ui-egui/src/dialogs/export_dialog/srgb_default_tests.rs @@ -0,0 +1,138 @@ +use super::*; +use egui::accesskit::{Role, Toggled}; +use egui_kittest::{ + Harness, + kittest::{NodeT, Queryable}, +}; +use photocraft_cms::Builtin; +use photocraft_doc::{Color, SampleType, Size}; +use std::{cell::RefCell, path::Path, rc::Rc}; + +const CONVERT: &str = "Convert to sRGB"; +const EMBED: &str = "Embed Color Profile"; +type Writes = Rc>>>; + +fn harness(gpu: bool) -> (Harness<'static, PhotocraftApp>, Writes) { + let writes = Writes::default(); + let captured = writes.clone(); + let builder = Harness::builder().with_size(egui::vec2(1100.0, 800.0)).with_max_steps(64); + let builder = if gpu { builder.wgpu() } else { builder }; + let h = builder.build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let (picker, _) = crate::file_dialog::fake(vec![ + Some(crate::FileDialogAnswer::SaveTo("converted.png".into())), + Some(crate::FileDialogAnswer::SaveTo("original.png".into())), + ]); + let services = crate::Services { + file_dialog: Some(picker), + export: Some(Box::new(|doc, path, settings| { + photocraft_io::export(doc, path, &settings.io_options()).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()) + })), + write: Some(Box::new(move |_, bytes| { + captured.borrow_mut().push(bytes.to_vec()); + Ok(()) + })), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let mut doc = Document::with_background("Wide gamut", Size::new(200, 150), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let blue = [30.0 / 255.0, 30.0 / 255.0, 200.0 / 255.0, 1.0]; + let surface = doc.layers[0].surface_mut().unwrap(); + surface.fill_rect(photocraft_geom::Rect::new(50, 25, 150, 125), &photocraft_raster::from_rgba(&surface.format(), blue)); + doc.icc_profile = Some(Builtin::AdobeRgbCompat.profile().to_bytes()); + app.session.add_document(doc, None); + app + }); + (h, writes) +} + +fn checkbox(h: &Harness<'_, PhotocraftApp>, label: &str) -> Toggled { + h.get_by_role_and_label(Role::CheckBox, label).accesskit_node().toggled().unwrap() +} + +fn click(h: &mut Harness<'_, PhotocraftApp>, role: Role, label: &str) { + h.get_by_role_and_label(role, label).click(); + h.run_steps(6); +} + +fn open_dialog(h: &mut Harness<'_, PhotocraftApp>) { + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({})).unwrap(); + h.run_steps(6); +} + +fn snapshot(h: &mut Harness<'_, PhotocraftApp>, dir: Option<&Path>, file: &str) { + if let Some(dir) = dir { + h.render().unwrap().save(dir.join(file)).unwrap(); + } +} + +fn verify_png(bytes: &[u8], want: [u8; 3], tolerance: u8, embedded: bool) { + let doc = photocraft_io::import("out.png", bytes).unwrap().document; + let pixel = doc.layers[0].surface().unwrap().rgba(100, 75); + for (channel, (got, want)) in pixel.into_iter().zip(want).enumerate() { + let got = (got * 255.0).round() as u8; + assert!(got.abs_diff(want) <= tolerance, "channel {channel}: expected {want} ± {tolerance}, got {got}"); + } + assert_eq!(doc.icc_profile.is_some(), embedded); + if let Some(icc) = doc.icc_profile.as_deref() { + assert!(Profile::parse(icc).unwrap().same_colors(Builtin::AdobeRgbCompat.profile())); + } +} + +fn export_both_ways(snapshots: Option<&Path>) { + let (mut h, writes) = harness(snapshots.is_some()); + let source = h.state().session.active().unwrap().doc.clone(); + open_dialog(&mut h); + h.get_by_label("Color Space"); + assert_eq!(checkbox(&h, CONVERT), Toggled::True); + assert_eq!(checkbox(&h, EMBED), Toggled::True); + snapshot(&mut h, snapshots, "export-as-default.png"); + + click(&mut h, Role::CheckBox, EMBED); + click(&mut h, Role::Button, "Export"); + verify_png(&writes.borrow()[0], [24, 24, 205], 1, false); + + open_dialog(&mut h); + assert_eq!(checkbox(&h, CONVERT), Toggled::True); + assert_eq!(checkbox(&h, EMBED), Toggled::False); + click(&mut h, Role::CheckBox, CONVERT); + click(&mut h, Role::CheckBox, EMBED); + snapshot(&mut h, snapshots, "export-as-document-profile.png"); + click(&mut h, Role::Button, "Export"); + verify_png(&writes.borrow()[1], [30, 30, 200], 0, true); + + assert!(Arc::ptr_eq(&source, &h.state().session.active().unwrap().doc)); + open_dialog(&mut h); + assert_eq!(checkbox(&h, CONVERT), Toggled::False, "remembered document-profile choice"); + assert_eq!(checkbox(&h, EMBED), Toggled::True); +} + +#[test] +fn checkbox_defaults_on_and_controls_png_pixels_and_embedding() { + export_both_ways(None); +} + +#[test] +fn existing_document_profile_preset_and_recorded_export_keep_source_colors() { + let (mut h, writes) = harness(false); + h.state_mut().run("file.export.presets.save", json!({"name": "Original colors", "settings": {"profile": "document", "format": "jpg"}})).unwrap(); + open_dialog(&mut h); + click(&mut h, Role::ComboBox, "Preset"); + h.get_by_label("Original colors").click(); + h.run_steps(4); + assert_eq!(checkbox(&h, CONVERT), Toggled::False, "existing JPEG preset"); + assert_eq!(checkbox(&h, EMBED), Toggled::True); + + replay(h.state_mut(), &json!({"path": "recorded.png", "format": "png", "profile": "document", "embedProfile": true})).unwrap(); + verify_png(&writes.borrow()[0], [30, 30, 200], 0, true); +} + +#[test] +fn export_as_color_space_gpu_snapshots() { + let Some(dir) = std::env::var_os("PHOTOCRAFT_SRGB_SNAPSHOTS") else { return }; + let dir = std::path::PathBuf::from(dir); + let _gpu = photocraft_testkit::gpu_lock(); + std::fs::create_dir_all(&dir).unwrap(); + export_both_ways(Some(&dir)); +} diff --git a/crates/ui-egui/src/dialogs/fade_mode_list_tests.rs b/crates/ui-egui/src/dialogs/fade_mode_list_tests.rs new file mode 100644 index 0000000000..ceba62232f --- /dev/null +++ b/crates/ui-egui/src/dialogs/fade_mode_list_tests.rs @@ -0,0 +1,168 @@ +//! #13806: Edit › Fade's Mode list holds the 27 layer blend modes in the reference order, in six +//! groups, and greys the modes a Grayscale 8-bit, Lab 8-bit or RGB 32-bit document can't fade with. + +use photocraft_color::{BlendMode, ColorMode, SampleType}; +use serde_json::{Value, json}; + +use super::{COMMAND, greyed, step_past}; +use crate::PhotocraftApp; +use crate::dialogs::dialog_blend_ui::mode_key; +use crate::filter_dialog::{Kind, parse_spec}; + +/// The reference application's Fade Mode list, a group per row. +const GROUPS: [&[&str]; 6] = [ + &["Normal", "Dissolve"], + &["Darken", "Multiply", "Color Burn", "Linear Burn", "Darker Color"], + &["Lighten", "Screen", "Color Dodge", "Linear Dodge (Add)", "Lighter Color"], + &["Overlay", "Soft Light", "Hard Light", "Vivid Light", "Linear Light", "Pin Light", "Hard Mix"], + &["Difference", "Exclusion", "Subtract", "Divide"], + &["Hue", "Saturation", "Color", "Luminosity"], +]; + +fn app(mode: &str, depth: u32) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 12, "mode": mode, "depth": depth})).unwrap(); + app +} + +fn labels(modes: &[BlendMode]) -> Vec<&'static str> { + modes.iter().map(|m| m.label()).collect() +} + +fn mode_options() -> Vec { + let spec = photocraft_engine::commands::find(COMMAND).unwrap(); + let p = parse_spec(spec.params).into_iter().find(|p| p.key == "mode").unwrap(); + let Kind::Choice { options, .. } = p.kind else { panic!("mode is not a choice") }; + options +} + +#[test] +fn the_list_is_the_27_modes_in_six_groups() { + let shown = labels(&BlendMode::LAYER_MODES); + assert_eq!(shown, GROUPS.concat()); + // A line above the first mode of every group but the first. + let mut groups: Vec> = Vec::new(); + for m in BlendMode::LAYER_MODES { + match groups.last_mut() { + Some(g) if !crate::panels::starts_blend_group(m) => g.push(m.label()), + _ => groups.push(vec![m.label()]), + } + } + assert_eq!(groups, GROUPS.map(<[&str]>::to_vec)); +} + +#[test] +fn the_params_doc_lists_all_27_modes_and_the_old_names_still_work() { + let options = mode_options(); + let modes: Vec> = options.iter().map(|o| photocraft_engine::commands::blend_from_str(o)).collect(); + assert_eq!(modes, BlendMode::LAYER_MODES.map(Some).to_vec()); + assert_eq!(options, BlendMode::LAYER_MODES.map(mode_key).to_vec(), "the keys the dialog writes"); + for old in ["normal", "multiply", "screen", "overlay", "softLight", "hardLight", "darken", "lighten", "difference", "color", "luminosity"] { + assert!(options.iter().any(|o| o == old), "{old} is still listed"); + } +} + +#[test] +fn every_listed_mode_fades() { + for key in mode_options() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + s.execute("edit.fill", json!({"color": "#336699"})).unwrap(); + let out = s.execute(COMMAND, json!({"opacity": 50, "mode": key})).unwrap(); + assert_eq!(out["mode"], json!(photocraft_engine::commands::blend_from_str(&key).unwrap().label()), "{key}"); + } +} + +#[test] +fn greyed_modes_follow_the_measured_colour_modes_and_depths() { + use SampleType::*; + assert_eq!(labels(greyed(ColorMode::Grayscale, U8)), ["Darker Color", "Lighter Color", "Hue", "Saturation", "Color", "Luminosity"]); + assert_eq!(labels(greyed(ColorMode::Lab, U8)), ["Darken", "Color Burn", "Lighten", "Color Dodge", "Difference", "Exclusion", "Subtract", "Divide"]); + assert_eq!( + labels(greyed(ColorMode::Rgb, F32)), + [ + "Color Burn", + "Linear Burn", + "Screen", + "Color Dodge", + "Overlay", + "Soft Light", + "Hard Light", + "Vivid Light", + "Linear Light", + "Pin Light", + "Hard Mix", + "Exclusion" + ] + ); + // Measured with none greyed, and the cases not measured keep the old list (none greyed). + for (mode, depth) in + [(ColorMode::Rgb, U16), (ColorMode::Cmyk, U8), (ColorMode::Rgb, U8), (ColorMode::Grayscale, U16), (ColorMode::Lab, U16), (ColorMode::Cmyk, U16)] + { + assert!(greyed(mode, depth).is_empty(), "{mode:?} {depth:?}"); + } +} + +#[test] +fn opening_the_dialog_notes_the_documents_greyed_modes() { + for (mode, depth, want) in [("lab", 8, greyed(ColorMode::Lab, SampleType::U8)), ("rgb", 32, greyed(ColorMode::Rgb, SampleType::F32)), ("rgb", 16, &[][..])] + { + let mut app = app(mode, depth); + let id = crate::filter_dialog::open(&mut app, COMMAND).unwrap(); + let fields = &app.ui.dialog_mut(id).unwrap().fields; + let noted: Vec<&str> = fields["__fadeGreyed"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!(noted, want.iter().map(|m| mode_key(*m)).collect::>(), "{mode} {depth}"); + assert_eq!(fields["mode"], json!("normal")); + } +} + +#[test] +fn a_remembered_mode_the_document_greys_opens_as_normal() { + let mut app = app("lab", 8); + app.session.prefs.edit(|p| p.dialogs.insert(COMMAND.into(), json!({"mode": "darken", "opacity": 40}))); + let id = crate::filter_dialog::open(&mut app, COMMAND).unwrap(); + let fields = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!((fields["mode"].clone(), fields["opacity"].clone()), (json!("normal"), json!(40))); + + // In a document that can fade with it, the remembered mode stays. + let mut app = self::app("rgb", 8); + app.session.prefs.edit(|p| p.dialogs.insert(COMMAND.into(), json!({"mode": "darken"}))); + let id = crate::filter_dialog::open(&mut app, COMMAND).unwrap(); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields["mode"], json!("darken")); +} + +#[test] +fn the_keys_step_past_greyed_modes() { + use BlendMode::*; + let lab = greyed(ColorMode::Lab, SampleType::U8); + assert_eq!(step_past(Normal, Multiply, lab), Multiply, "not greyed"); + // Down from Dissolve lands on Darken, greyed: Multiply is the next one. + assert_eq!(step_past(Dissolve, Darken, lab), Multiply); + // Up from Multiply: Dissolve. + assert_eq!(step_past(Multiply, Darken, lab), Dissolve); + // Down from Hard Mix past Difference, Exclusion, Subtract and Divide. + assert_eq!(step_past(HardMix, Difference, lab), Hue); + // Nothing open past it: stay. + let all = BlendMode::LAYER_MODES; + assert_eq!(step_past(Normal, Dissolve, &all[1..]), Normal); +} + +#[test] +fn the_row_keeps_an_open_mode_and_writes_its_key() { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + let mut app = app("rgb", 32); + let id = crate::filter_dialog::open(&mut app, COMMAND).unwrap(); + let mut fields = app.ui.dialog_mut(id).unwrap().fields.clone(); + fields.insert("mode".into(), json!("Linear Dodge (Add)")); + ctx.run_ui(egui::RawInput::default(), |ui| crate::filter_dialog::body(ui, &mut fields)).drop_without_applying_deltas(); + assert_eq!(fields["mode"], json!("linearDodge")); + // A greyed mode an agent wrote isn't chosen from the list: the row leaves it to the command. + fields.insert("mode".into(), json!("screen")); + ctx.run_ui(egui::RawInput::default(), |ui| crate::filter_dialog::body(ui, &mut fields)).drop_without_applying_deltas(); + assert_eq!(fields["mode"], json!("screen")); + // Nor is a mode no list names: OK reports it instead of fading in Normal. + fields.insert("mode".into(), json!("nonsense")); + ctx.run_ui(egui::RawInput::default(), |ui| crate::filter_dialog::body(ui, &mut fields)).drop_without_applying_deltas(); + assert_eq!(fields["mode"], json!("nonsense")); +} diff --git a/crates/ui-egui/src/dialogs/fade_modes.rs b/crates/ui-egui/src/dialogs/fade_modes.rs new file mode 100644 index 0000000000..0caeefae46 --- /dev/null +++ b/crates/ui-egui/src/dialogs/fade_modes.rs @@ -0,0 +1,100 @@ +//! Edit › Fade's Mode list (#13806): the 27 layer blend modes in the reference application's order +//! and groups, a line between the groups, with the modes the document's colour mode and depth can't +//! fade with greyed (listed, never chosen). + +use photocraft_color::{BlendMode, ColorMode, SampleType}; +use serde_json::{Map, Value, json}; + +use super::dialog_blend_ui::mode_key; +use crate::PhotocraftApp; + +pub(crate) const COMMAND: &str = "edit.fade"; +/// The `mode` keys greyed for the document the dialog opened on. +const GREYED: &str = "__fadeGreyed"; + +/// The modes the reference application greys in its Fade dialog for a document of `mode` at +/// `depth`. Combinations it wasn't measured in (Grayscale 16/32, Lab 16, CMYK 16, Multichannel, +/// Duotone…) grey none, as before. +pub(crate) fn greyed(mode: ColorMode, depth: SampleType) -> &'static [BlendMode] { + use BlendMode::*; + match (mode, depth) { + (ColorMode::Grayscale, SampleType::U8) => &[DarkerColor, LighterColor, Hue, Saturation, Color, Luminosity], + (ColorMode::Lab, SampleType::U8) => &[Darken, ColorBurn, Lighten, ColorDodge, Difference, Exclusion, Subtract, Divide], + (ColorMode::Rgb, SampleType::F32) => { + &[ColorBurn, LinearBurn, Screen, ColorDodge, Overlay, SoftLight, HardLight, VividLight, LinearLight, PinLight, HardMix, Exclusion] + } + _ => &[], + } +} + +/// Opening (and Alt+Reset): note the active document's greyed modes for the list. A remembered +/// mode this document greys starts the dialog at Normal instead, since it can't be chosen. +pub(crate) fn defaults(app: &PhotocraftApp, fields: &mut Map) { + let greyed = app.session.active().map_or(&[][..], |st| greyed(st.doc.mode, st.doc.depth)); + if mode_of(fields).is_some_and(|m| greyed.contains(&m)) { + fields.insert("mode".into(), json!(mode_key(BlendMode::Normal))); + } + fields.insert(GREYED.into(), json!(greyed.iter().map(|m| mode_key(*m)).collect::>())); +} + +fn mode_of(fields: &Map) -> Option { + fields.get("mode").and_then(Value::as_str).and_then(photocraft_engine::commands::blend_from_str) +} + +fn greyed_of(fields: &Map) -> Vec { + fields + .get(GREYED) + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .filter_map(photocraft_engine::commands::blend_from_str) + .collect() +} + +/// The mode to keep after the list's keys or type-ahead moved from `from` to `to`: `to` unless it +/// is greyed, else the next mode past it the same way that isn't, else `from`. A greyed mode the +/// list didn't move to (written by an agent) stays: the command decides about it. +pub(crate) fn step_past(from: BlendMode, to: BlendMode, greyed: &[BlendMode]) -> BlendMode { + if to == from || !greyed.contains(&to) { + return to; + } + let list = BlendMode::LAYER_MODES; + let at = |m: BlendMode| list.iter().position(|l| *l == m); + let (Some(a), Some(b)) = (at(from), at(to)) else { return from }; + let open = |m: &&BlendMode| !greyed.contains(m); + let next = if b < a { list.get(..b).and_then(|l| l.iter().rev().find(open)) } else { list.get(b + 1..).and_then(|l| l.iter().find(open)) }; + next.copied().unwrap_or(from) +} + +/// The Mode row of the Fade dialog, its label `label` in the schema dialog's style. +pub(crate) fn row(ui: &mut egui::Ui, f: &mut Map, label: &str) { + let t = crate::theme::Tokens::get(ui.ctx()); + let greyed = greyed_of(f); + let known = mode_of(f); + let before = known.unwrap_or(BlendMode::Normal); + let mut mode = before; + let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect(); + ui.horizontal(|ui| { + ui.label(egui::RichText::new(label).color(t.text_dim)); + crate::widgets::dropdown_wheel_grouped_enabled( + ui, + "flt-edit.fade-mode", + label, + &mut mode, + &opts, + 170.0, + |m| crate::panels::starts_blend_group(*m), + |m| !greyed.contains(m), + ); + }); + let mode = step_past(before, mode, &greyed); + // A mode no list names (an agent's typo) stays until one is picked: the command reports it. + if known.is_some() || mode != before { + f.insert("mode".into(), json!(mode_key(mode))); + } +} + +#[cfg(test)] +#[path = "fade_mode_list_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/dialogs/file_ui.rs b/crates/ui-egui/src/dialogs/file_ui.rs index a04e070a79..ab8213265c 100644 --- a/crates/ui-egui/src/dialogs/file_ui.rs +++ b/crates/ui-egui/src/dialogs/file_ui.rs @@ -143,7 +143,11 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &V } names.extend(d.doc.paths.iter().map(|p| p.name.clone())); } - form(app, id, "Export Paths to File", json!({"path": format!("{dir}/{stem}.ai"), "paths": "all"}), json!({"paths": names})) + // Opens on the Paths panel's selected row, as the reference application does (#13777). + // A shape layer's path ("layer") is not an entry yet, and a row the document no longer + // has falls back to All Paths. + let paths = app.ui.selected_path.as_deref().filter(|s| *s != "layer" && names.iter().any(|n| n == s)).unwrap_or("all").to_string(); + form(app, id, "Export Paths to File", json!({"path": format!("{dir}/{stem}.ai"), "paths": paths}), json!({"paths": names})) } _ => return None, })) diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index b46087452c..e69ba917e1 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -469,6 +469,9 @@ fn apply_command_defaults(app: &PhotocraftApp, command: &str, fields: &mut Map) { if !rot.is_finite() { return; } - fields.insert("angle".into(), json!(rot.abs())); + // Rounded here, in f64, to the field's two decimals: `ui.dialog.open` then `ui.dialog.confirm` + // can run with no frame drawn between them, and only a drawn frame rounds (#13067). + let scale = 10f64.powi(wide_field_decimals("image.rotation.arbitrary", "angle").unwrap_or(2).min(6) as i32); + fields.insert("angle".into(), json!((rot.abs() * scale).round() / scale)); fields.insert("direction".into(), json!(if rot < 0.0 { "ccw" } else { "cw" })); } @@ -1150,6 +1156,10 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { indexed_matte_row(ui, f); continue; } + if cmd == super::fade_modes::COMMAND && p.key == "mode" { + super::fade_modes::row(ui, f, &label(&p.key)); + continue; + } if zoom_center::owns(&cmd, f) && matches!(p.key.as_str(), "centerX" | "centerY") { if p.key == "centerX" { zoom_center::row(ui, f); @@ -1158,7 +1168,16 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { } match p.kind { Kind::Range { min, max, default } => { - let src = f.get(&p.key).and_then(Value::as_f64); + // The field's shown precision: small ranges keep their two decimals, and so + // does the Arbitrary angle; the other wide fields round to one (#12035). + let scale = field_scale(&cmd, &p.key, min, max); + let wide_decimals = wide_field_decimals(&cmd, &p.key).is_some(); + let round64 = |x: f64| (x * f64::from(scale)).round() / f64::from(scale); + // A wide field showing two decimals rounds while the value is still f64, before + // the widget narrows it: a 43x27 ruler is 32.1249984°, whose f32 cast lands + // exactly on 32.125, and the field drew that half-away as 32.13 on the first + // frame after opening or Alt+Reset, over the 32.12 it stored (#13067). + let src = f.get(&p.key).and_then(Value::as_f64).map(|x| if wide_decimals { round64(x) } else { x }); let mut v = src.unwrap_or(default as f64) as f32; // A widget edit this frame makes the field's f32 value authoritative (#12035). let mut edited = false; @@ -1209,18 +1228,15 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { .changed(); } }); - // The field's shown precision: small ranges keep their two decimals, and so - // does the Arbitrary angle; the other wide fields round to one (#12035). - let scale = field_scale(&cmd, &p.key, min, max); - // A field showing two decimals rounds while the value is still f64: a 43x27 - // ruler is 32.1249984°, whose f32 cast lands exactly on 32.125, and rounding - // that widened value half-away shows 32.13 where the pre-fill says 32.12. - // Values the user typed or dragged are f32 already, so they round as before. - let w = match (wide_field_decimals(&cmd, &p.key), src) { - (Some(_), Some(raw)) if !edited => ((raw * f64::from(scale)).round() / f64::from(scale)) as f32, - _ => (v * scale).round() / scale, + // Such a field also keeps its rounded value as f64: stored as f32, 32.12 widens to + // 32.1199989 and OK sends that to the command (#13067). A value the user typed or + // dragged this frame is the widget's f32, so it rounds from that. + let w = match (wide_decimals, src) { + (true, Some(rounded)) if !edited => json!(rounded), + (true, _) => json!(round64(f64::from(v))), + (false, _) => json!((v * scale).round() / scale), }; - f.insert(p.key, json!(w)); + f.insert(p.key, w); } Kind::Choice { options, default } => { ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/dialogs/fit_image_range.rs b/crates/ui-egui/src/dialogs/fit_image_range.rs new file mode 100644 index 0000000000..087bd8c55e --- /dev/null +++ b/crates/ui-egui/src/dialogs/fit_image_range.rs @@ -0,0 +1,133 @@ +//! Fit Image's bounds belong to its dialog. The engine still accepts an unconstrained side. + +use std::cell::Cell; + +use serde_json::{Value, json}; + +use super::Fields; +use crate::panels::options_bar::range_alert; +use crate::state::UiState; + +const COMMAND: &str = "file.automate.fitImage"; +const RANGE: std::ops::RangeInclusive = 1.0..=300_000.0; +const WIDTH: (&str, &str) = ("width", "__fitImageWidth"); +const HEIGHT: (&str, &str) = ("height", "__fitImageHeight"); +const SIDES: [(&str, &str); 2] = [WIDTH, HEIGHT]; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum Alert { + Closest, + Invalid, +} + +impl Alert { + pub(super) fn message(self) -> &'static str { + match self { + Self::Closest => "A value between 1 and 300000 is required. Closest value inserted.", + Self::Invalid => "Invalid numeric entry. A value between 1 and 300000 is required. Previous value inserted.", + } + } +} + +pub(super) fn owns(fields: &Fields) -> bool { + fields.contains_key("__form") && fields.get("__command").and_then(Value::as_str) == Some(COMMAND) +} + +fn bounded(number: Option, alert: &Cell>) -> Option { + let Some(number) = number.filter(|value| value.is_finite()) else { + alert.set(Some(Alert::Invalid)); + return None; + }; + if !RANGE.contains(&number) { + alert.set(Some(Alert::Closest)); + } + Some(number.clamp(*RANGE.start(), *RANGE.end())) +} + +/// Covers dialog confirmation when automation supplies values without rendering the fields. +pub(super) fn preflight(ui: &mut UiState, id: u64) -> Result<(), String> { + if let Some(dialog) = ui.dialog_mut(id).filter(|dialog| owns(&dialog.fields)) + && let Some(alert) = validate(&mut dialog.fields) + { + range_alert(ui, alert.message()); + if alert == Alert::Invalid { + return Err(tl!(alert.message()).into()); + } + } + Ok(()) +} + +fn validate(fields: &mut Fields) -> Option { + let mut result = None; + for (key, accepted) in SIDES { + let alert = Cell::new(None); + let number = fields.get(key).and_then(|value| value.as_f64().or_else(|| value.as_str().and_then(crate::widgets::parse_num))); + let value = bounded(number, &alert) + .or_else(|| fields.get(accepted).and_then(Value::as_f64)) + .or_else(|| fields.get("__formOrig")?.get(key)?.as_f64()) + .unwrap_or(*RANGE.start()) + .clamp(*RANGE.start(), *RANGE.end()) as i64; + fields.insert(key.into(), json!(value)); + fields.insert(accepted.into(), json!(value)); + // An invalid entry needs acknowledgment before the dialog can run. + if result != Some(Alert::Invalid) { + result = alert.get().or(result); + } + } + result +} + +pub(super) fn finish(ui: &mut UiState, interactive: bool, alert: Option, outcome: Option) -> Option { + if interactive + && outcome != Some(false) + && let Some(alert) = alert + { + range_alert(ui, alert.message()); + if alert == Alert::Invalid { + return None; + } + } + outcome +} + +pub(super) fn body(ui: &mut egui::Ui, fields: &mut Fields) -> Option { + let mut alert = None; + egui::Grid::new("form-dialog").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| { + for key in crate::view_cmds::form_keys(fields) { + match key.as_str() { + "width" => alert = side(ui, fields, WIDTH, tl!("Width")).or(alert), + "height" => alert = side(ui, fields, HEIGHT, tl!("Height")).or(alert), + "dontEnlarge" => { + ui.label(""); + let mut enabled = fields.get(&key).and_then(Value::as_bool).unwrap_or(false); + ui.checkbox(&mut enabled, tl!("Dont enlarge")); + fields.insert(key, json!(enabled)); + } + _ => continue, + } + ui.end_row(); + } + }); + alert +} + +fn side(ui: &mut egui::Ui, fields: &mut Fields, (key, accepted): (&str, &str), label: &str) -> Option { + let input = fields.get(key).and_then(Value::as_i64); + let mut value = input.or_else(|| fields.get(accepted).and_then(Value::as_i64)).or_else(|| fields.get("__formOrig")?.get(key)?.as_i64()).unwrap_or(1); + let alert = Cell::new(None); + let parsed = Cell::new(false); + ui.label(label); + crate::field_tab::register(ui.ctx(), ui.next_auto_id()); + let response = ui + .add(egui::DragValue::new(&mut value).range(RANGE).clamp_existing_to_range(false).update_while_editing(false).custom_parser(|text| { + parsed.set(true); + bounded(crate::widgets::parse_num(text), &alert) + })) + .accessible_name(label); + if response.changed() || parsed.get() || input.is_some_and(|input| RANGE.contains(&(input as f64))) { + let value = value.clamp(*RANGE.start() as i64, *RANGE.end() as i64); + fields.insert(key.into(), json!(value)); + fields.insert(accepted.into(), json!(value)); + } + alert.get() +} diff --git a/crates/ui-egui/src/dialogs/fit_image_range_tests.rs b/crates/ui-egui/src/dialogs/fit_image_range_tests.rs new file mode 100644 index 0000000000..7e582361b6 --- /dev/null +++ b/crates/ui-egui/src/dialogs/fit_image_range_tests.rs @@ -0,0 +1,176 @@ +use egui::{Event, Key, Modifiers, accesskit::Role}; +use egui_kittest::{ + Harness, + kittest::{NodeT, Queryable}, +}; +use serde_json::{Value, json}; + +use super::{fit_image_range::Alert, show}; +use crate::{PhotocraftApp, Services, state::DialogKind}; + +const FIT_IMAGE: &str = "file.automate.fitImage"; + +fn open() -> (Harness<'static, PhotocraftApp>, u64) { + open_with_renderer(false) +} + +fn open_with_renderer(gpu: bool) -> (Harness<'static, PhotocraftApp>, u64) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let builder = Harness::builder().with_size(egui::vec2(1000.0, 700.0)); + let builder = if gpu { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state(|ui, app| show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let ctx = h.ctx.clone(); + let id = crate::menus::invoke(h.state_mut(), &ctx, FIT_IMAGE, json!({})).unwrap()["dialog"].as_u64().unwrap(); + h.run_steps(4); + (h, id) +} + +fn type_side(h: &mut Harness<'static, PhotocraftApp>, label: &str, input: &str) { + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().label().as_deref() == Some(label)).unwrap(); + field.click(); + h.run_steps(2); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + if input.is_empty() { + h.key_press(Key::Backspace); + } else { + h.event(Event::Text(input.into())); + } + h.run_steps(1); +} + +fn field(h: &Harness<'_, PhotocraftApp>, id: u64, key: &str) -> Value { + h.state().ui.dialogs.iter().find(|dialog| dialog.id == id).unwrap().fields[key].clone() +} + +fn alert(h: &Harness<'_, PhotocraftApp>, expected: Alert) { + let top = h.state().ui.dialogs.last().unwrap(); + assert_eq!(top.kind, DialogKind::Error); + assert_eq!(top.fields["message"], expected.message()); +} + +fn dimensions(h: &Harness<'_, PhotocraftApp>) -> (u32, u32) { + let size = h.state().session.active().unwrap().doc.size; + (size.width, size.height) +} + +#[test] +fn tab_clamps_both_sides_and_the_next_tab_accepts_each_boundary() { + let (mut h, id) = open(); + for (label, key, input, boundary) in [("Width", "width", "-50", 1), ("Height", "height", "300001", 300_000)] { + type_side(&mut h, label, input); + h.key_press(Key::Tab); + h.run_steps(4); + alert(&h, Alert::Closest); + assert_eq!(field(&h, id, key), boundary); + h.key_press(Key::Enter); + h.run_steps(3); + + type_side(&mut h, label, &boundary.to_string()); + h.key_press(Key::Tab); + h.run_steps(4); + assert_eq!(h.state().ui.dialogs.len(), 1); + assert_eq!(field(&h, id, key), boundary); + } + assert_eq!(dimensions(&h), (400, 300)); +} + +#[test] +fn invalid_and_empty_entries_restore_the_last_accepted_value() { + let (mut h, id) = open(); + type_side(&mut h, "Width", "600/2"); + h.key_press(Key::Tab); + h.run_steps(4); + assert_eq!(field(&h, id, "width"), 300); + for input in ["abc", "", "NaN", "1/0", "1e999", &"9".repeat(1100)] { + type_side(&mut h, "Width", input); + h.key_press(Key::Tab); + h.run_steps(4); + alert(&h, Alert::Invalid); + assert_eq!(field(&h, id, "width"), 300, "{input}"); + assert_eq!(field(&h, id, "height"), 300); + h.key_press(Key::Enter); + h.run_steps(3); + } +} + +#[test] +fn zero_on_submit_resizes_once_using_one_pixel() { + for click in [false, true] { + let (mut h, id) = open(); + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("height".into(), json!(1000)); + h.run_steps(2); + let past = h.state().session.active().unwrap().history.past_len(); + type_side(&mut h, "Width", "0"); + if click { + h.get_by_label("OK").click(); + } else { + h.key_press(Key::Enter); + } + h.run_steps(4); + assert_eq!(dimensions(&h), (1, 1)); + let history = &h.state().session.active().unwrap().history; + assert_eq!(history.past_len(), past + 1); + assert_eq!(history.entries().last().map(String::as_str), Some("Image Size")); + assert!(h.state().ui.dialogs.iter().all(|dialog| dialog.id != id)); + alert(&h, Alert::Closest); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(dimensions(&h), (400, 300)); + } +} + +#[test] +fn invalid_submit_keeps_the_dialog_open_without_resizing() { + let (mut h, id) = open(); + type_side(&mut h, "Width", "abc"); + h.key_press(Key::Enter); + h.run_steps(4); + alert(&h, Alert::Invalid); + assert_eq!(field(&h, id, "width"), 400); + assert_eq!(dimensions(&h), (400, 300)); +} + +#[test] +fn programmatic_dialog_confirmation_validates_both_sides() { + let (mut h, id) = open(); + type_side(&mut h, "Width", "350"); + h.key_press(Key::Tab); + h.run_steps(4); + let fields = &mut h.state_mut().ui.dialog_mut(id).unwrap().fields; + fields.insert("width".into(), json!("abc")); + fields.insert("height".into(), json!(-1)); + assert!(super::confirm(h.state_mut(), id).is_err()); + alert(&h, Alert::Invalid); + assert_eq!(field(&h, id, "width"), 350); + assert_eq!(field(&h, id, "height"), 1); + assert_eq!(dimensions(&h), (400, 300)); +} + +#[test] +fn cancel_discards_an_uncommitted_entry() { + let (mut h, _) = open(); + type_side(&mut h, "Width", "abc"); + h.get_by_label("Cancel").click(); + h.run_steps(4); + assert!(h.state().ui.dialogs.is_empty()); + assert_eq!(dimensions(&h), (400, 300)); +} + +#[test] +fn fit_image_range_gpu_snapshots() { + let Some(directory) = std::env::var_os("PHOTOCRAFT_FIT_IMAGE_SNAPSHOTS") else { return }; + let directory = std::path::PathBuf::from(directory); + let _gpu = photocraft_testkit::gpu_lock(); + let (mut h, _) = open_with_renderer(true); + h.render().unwrap().save(directory.join("dialog.png")).unwrap(); + for (input, expected, name) in [("-50", Alert::Closest, "range"), ("abc", Alert::Invalid, "invalid")] { + type_side(&mut h, "Width", input); + h.key_press(Key::Tab); + h.run_steps(4); + alert(&h, expected); + h.render().unwrap().save(directory.join(format!("{name}.png"))).unwrap(); + h.key_press(Key::Enter); + h.run_steps(3); + } +} diff --git a/crates/ui-egui/src/dialogs/jpeg_options_ui.rs b/crates/ui-egui/src/dialogs/jpeg_options_ui.rs index e610ac2d6d..d5740d51ab 100644 --- a/crates/ui-egui/src/dialogs/jpeg_options_ui.rs +++ b/crates/ui-egui/src/dialogs/jpeg_options_ui.rs @@ -2,10 +2,10 @@ //! a JPEG, as Photoshop's JPEG Options does. Quality is Photoshop's 0–12 scale (Low 0–4, Medium //! 5–7, High 8–9, Maximum 10–12), mapped to the encoder's 1–100 by //! `photocraft_engine::file_cmds::jpeg_quality`; Format Options are Baseline ("Standard"), Baseline -//! Optimized and Progressive. Matte, Scans and the size preview aren't offered yet. Re-saving an -//! opened JPEG starts at the file's own quality, as File › Save keeps it (#4032). Otherwise the -//! dialog starts at the quality and format it was last answered with, also after a restart, as -//! Photoshop's does (see [`Start::for_active`]). +//! Optimized and Progressive, and the dialog shows the size the file will have. Matte and Scans +//! aren't offered yet. Re-saving an opened JPEG starts at the file's own quality, as File › Save +//! keeps it (#4032). Otherwise the dialog starts at the quality and format it was last answered +//! with, also after a restart, as Photoshop's does (see [`Start::for_active`]). //! //! The save is parked in [`Prompt`] while the modal is up (egui is immediate-mode) and written //! once answered. Cancel drops the save. Scripts skip the prompt by passing `quality` or @@ -24,6 +24,8 @@ use serde_json::Value; use crate::{ExportSettings, PhotocraftApp}; +mod size_readout; + /// The highest quality on Photoshop's JPEG scale. pub const MAX_QUALITY: u8 = 12; @@ -240,6 +242,7 @@ pub fn park_at(app: &mut PhotocraftApp, path: String, copy: bool, record: &'stat } pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { + let size_source = size_readout::Source::of(app); let Some(p) = &mut app.jpeg_options else { return }; let (mut ok, mut cancel) = (false, false); let (mut quality, mut format) = (p.quality, p.format); @@ -274,6 +277,8 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { ui.spacing_mut().item_spacing.x = 10.0; ok = crate::widgets::primary_button(ui, tl!("OK"), 84.0).clicked(); cancel = crate::widgets::secondary_button(ui, tl!("Cancel"), 84.0).clicked(); + // How big the file will be with these options, at the left of the buttons. + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| size_readout::show(ui, size_source.as_ref(), quality, format)); }); }); cancel |= modal.should_close(); diff --git a/crates/ui-egui/src/dialogs/jpeg_options_ui/size_readout.rs b/crates/ui-egui/src/dialogs/jpeg_options_ui/size_readout.rs new file mode 100644 index 0000000000..46346075fd --- /dev/null +++ b/crates/ui-egui/src/dialogs/jpeg_options_ui/size_readout.rs @@ -0,0 +1,213 @@ +//! JPEG Options' file size: while choosing a quality, the dialog shows how big the JPEG will be +//! ("152.3K"), and updates it as Quality and Format Options change. The dialog's document is +//! encoded in memory with the settings OK would write it with (the same encoder and +//! [`ExportSettings`] as the save, so the size is the file's, metadata and profile included). +//! +//! The encode runs on a worker thread in the native app, so the dialog never waits for it; the web +//! build has no threads and encodes in the frame, so its limit is lower. One encode runs at a time, +//! and the last few answers are kept for their settings: a frame that changes nothing encodes +//! nothing, and going back to settings already worked out shows their size at once. While a new +//! size is worked out, the last one for the same document stays up marked as pending ("152.3K…"). +//! Documents over [`MAX_PX`] aren't encoded and read "—". + +use std::collections::VecDeque; + +use std::sync::{Arc, Mutex, PoisonError}; + +use photocraft_codecs::JpegFormat; +use photocraft_doc::{DocId, Document}; + +use crate::{ExportSettings, PhotocraftApp}; + +/// The largest document, in pixels, whose size is worked out. Flattening and encoding 40 MP takes +/// a second or two on a worker and about 160 MB at 8 bits, as Export As's exact size does (#6595). +#[cfg(not(target_arch = "wasm32"))] +const MAX_PX: u64 = 40_000_000; +/// The web build encodes in the frame: up to 4 MP keeps a settings change under a frame or so. +#[cfg(target_arch = "wasm32")] +const MAX_PX: u64 = 4_000_000; + +/// Whether a document of `size` gets a size readout (see [`MAX_PX`]). +pub(super) fn estimable(size: photocraft_doc::Size) -> bool { + size.area() <= MAX_PX +} + +/// A size as the readout shows it: kilobytes with one decimal under a megabyte +/// ("152.3K"), megabytes above ("1.5M"), in units of 1024. +pub(super) fn size_label(bytes: u64) -> String { + const K: f64 = 1024.0; + let kilo = (bytes as f64 / K * 10.0).round() / 10.0; + if kilo < K { format!("{kilo:.1}K") } else { format!("{:.1}M", bytes as f64 / (K * K)) } +} + +/// The bytes `doc` takes written as a JPEG with `settings`, as the save writes it; `None` when it +/// can't be encoded. +pub(super) fn encoded_size(doc: &Document, settings: &ExportSettings) -> Option { + let bytes = photocraft_io::export(doc, "size.jpg", &settings.io_options()).ok()?.bytes; + u64::try_from(bytes.len()).ok() +} + +/// What one size is for: the document as it is, and the encoder quality (1–100) and format. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Key { + doc: DocId, + revision: u64, + quality: u8, + format: JpegFormat, +} + +/// How many worked-out sizes are kept, so stepping between a few qualities and formats doesn't +/// encode again. +const KEPT: usize = 8; + +/// What the readout says for one set of settings. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Estimate { + /// The size for these settings (`None`: they couldn't be encoded). + Known(Option), + /// Still being worked out, with the last size of the same document as it is now, if any. + Pending(Option), +} + +impl Estimate { + /// "152.3K" when known, "152.3K…" while the last size stands in, "…" with none yet, and "—" + /// when the settings couldn't be encoded. + pub(super) fn label(self) -> String { + match self { + Estimate::Known(Some(bytes)) => size_label(bytes), + Estimate::Known(None) => "—".into(), + Estimate::Pending(Some(bytes)) => format!("{}…", size_label(bytes)), + Estimate::Pending(None) => "…".into(), + } + } +} + +/// Where a worker leaves its answer: `Some` once done (`Some(None)`: couldn't be encoded). +type Slot = Arc>>>; + +/// The readout between frames (kept in egui's temporary data). +#[derive(Default)] +pub(super) struct Readout { + /// The last [`KEPT`] sizes worked out and what each is for, newest last. + known: VecDeque<(Key, Option)>, + /// The encode running, and what it is for. + running: Option<(Key, Slot)>, +} + +impl Readout { + /// What to show for `key`. Unless `key`'s size is known or being worked out, starts the job + /// `make` returns, which calls `done` when it finishes; a change made while another encode + /// runs starts once that one is done. + pub(super) fn update(&mut self, key: Key, make: impl FnOnce() -> J, done: impl FnOnce() + Send + 'static) -> Estimate + where + J: FnOnce() -> Option + Send + 'static, + { + self.collect(); + if self.running.is_none() && self.size_of(key).is_none() { + let slot = Slot::default(); + run(make(), Arc::clone(&slot), done); + self.running = Some((key, slot)); + // The web build encodes in the frame: its answer is already there. + self.collect(); + } + if let Some(size) = self.size_of(key) { + return Estimate::Known(size); + } + let same_doc = self.known.iter().rev().find(|(k, _)| k.doc == key.doc && k.revision == key.revision); + Estimate::Pending(same_doc.and_then(|&(_, size)| size)) + } + + /// `key`'s size if it has been worked out (`Some(None)`: it couldn't be). + fn size_of(&self, key: Key) -> Option> { + self.known.iter().find(|(k, _)| *k == key).map(|&(_, size)| size) + } + + /// Takes a finished encode's answer. + fn collect(&mut self) { + let Some((key, slot)) = &self.running else { return }; + let Some(size) = slot.lock().unwrap_or_else(PoisonError::into_inner).take() else { return }; + let key = *key; + self.running = None; + self.known.retain(|(k, _)| *k != key); + if self.known.len() == KEPT { + self.known.pop_front(); + } + self.known.push_back((key, size)); + } +} + +/// Runs `job` on a worker (in the web build, right here), leaves its answer in `slot`, then calls +/// `done`. A job that panics answers `None`. +fn run(job: impl FnOnce() -> Option + Send + 'static, slot: Slot, done: impl FnOnce() + Send + 'static) { + let answer = Arc::clone(&slot); + let work = move || { + let size = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)).unwrap_or(None); + *answer.lock().unwrap_or_else(PoisonError::into_inner) = Some(size); + done(); + }; + #[cfg(not(target_arch = "wasm32"))] + if std::thread::Builder::new().name("jpeg-options-size".into()).spawn(work).is_err() { + *slot.lock().unwrap_or_else(PoisonError::into_inner) = Some(None); + } + #[cfg(target_arch = "wasm32")] + { + let _ = slot; + work(); + } +} + +/// What the readout encodes: the waiting save's document, with the settings its save starts from. +/// Taken before the dialog is drawn, which borrows the prompt. +pub(super) struct Source { + doc: Arc, + revision: u64, + base: ExportSettings, + own_quality: Option, +} + +impl Source { + /// For the JPEG Options prompt waiting, if any. + pub(super) fn of(app: &PhotocraftApp) -> Option { + let p = app.jpeg_options.as_ref()?; + let st = app.session.documents().iter().find(|st| st.doc.id == p.doc)?; + Some(Source { doc: Arc::clone(&st.doc), revision: st.revision, base: app.save_settings(), own_quality: p.own_quality }) + } + + /// The encoder quality (1–100) OK writes for `quality` (0–12): the opened file's own when left + /// on its step, as `confirm` keeps it. + fn encoder_quality(&self, quality: u8) -> u8 { + let own = self.own_quality.filter(|&q| super::quality_from_percent(u32::from(q)) == quality); + own.unwrap_or_else(|| photocraft_engine::file_cmds::jpeg_quality(f64::from(quality))) + } + + /// The settings OK writes with for `quality` (0–12) and `format`. + fn settings(&self, quality: u8, format: JpegFormat) -> ExportSettings { + ExportSettings { jpeg_quality: Some(self.encoder_quality(quality)), jpeg_format: format, ..self.base.clone() } + } + + /// The readout for `quality` (0–12) and `format` (see [`Estimate::label`]). + fn text(&self, ctx: &egui::Context, quality: u8, format: JpegFormat) -> String { + if !estimable(self.doc.size) { + return "—".into(); + } + let key = Key { doc: self.doc.id, revision: self.revision, quality: self.encoder_quality(quality), format }; + let state = ctx.data_mut(|d| Arc::clone(d.get_temp_mut_or_default::>>(egui::Id::unique("jpeg-options-size")))); + let mut readout = state.lock().unwrap_or_else(PoisonError::into_inner); + let make = || { + let (doc, settings) = (Arc::clone(&self.doc), self.settings(quality, format)); + move || encoded_size(&doc, &settings) + }; + let repaint = ctx.clone(); + readout.update(key, make, move || repaint.request_repaint()).label() + } +} + +/// Draws the readout for the dialog's current `quality` (0–12) and `format`. +pub(super) fn show(ui: &mut egui::Ui, source: Option<&Source>, quality: u8, format: JpegFormat) { + let text = source.map_or_else(|| "—".into(), |s| s.text(ui.ctx(), quality, format)); + let weak = ui.visuals().weak_text_color(); + ui.label(egui::RichText::new(text).color(weak)).on_hover_text(tl!("Estimated file size")); +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/jpeg_options_ui/size_readout/tests.rs b/crates/ui-egui/src/dialogs/jpeg_options_ui/size_readout/tests.rs new file mode 100644 index 0000000000..f5cce74ce9 --- /dev/null +++ b/crates/ui-egui/src/dialogs/jpeg_options_ui/size_readout/tests.rs @@ -0,0 +1,192 @@ +use super::*; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::time::{Duration, Instant}; + +/// A 96 × 64 RGB document of 2 × 2 noise and gradients: detail a JPEG's quality shows in its size. +fn detailed() -> Arc { + let mut doc = Document::with_background( + "x", + photocraft_doc::Size::new(96, 64), + photocraft_doc::ColorMode::Rgb, + photocraft_doc::SampleType::U8, + photocraft_doc::Color::WHITE, + ); + let id = doc.layers[0].id; + let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + let mut seed = 12345u32; + for y in (0..64).step_by(2) { + for x in (0..96).step_by(2) { + seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); + let v = (seed >> 24) as f32 / 255.0; + surf.fill_rect(photocraft_geom::Rect::new(x, y, x + 2, y + 2), &[v, x as f32 / 96.0, y as f32 / 64.0, 1.0]); + } + } + Arc::new(doc) +} + +fn source(own_quality: Option) -> Source { + Source { doc: detailed(), revision: 1, base: ExportSettings::default(), own_quality } +} + +/// The readout: kilobytes with one decimal under a megabyte, then megabytes. +#[test] +fn sizes_read_in_kilobytes_then_megabytes() { + assert_eq!(size_label(0), "0.0K"); + assert_eq!(size_label(155_955), "152.3K"); + assert_eq!(size_label(1023 * 1024), "1023.0K"); + assert_eq!(size_label(1024 * 1024 - 1), "1.0M", "1024.0K would round up past a megabyte"); + assert_eq!(size_label(1024 * 1024), "1.0M"); + assert_eq!(size_label(3 * 1024 * 1024 / 2), "1.5M"); + assert_eq!(size_label(8_703_181), "8.3M"); +} + +/// The readout is the size of the file the save writes: Maximum (12) is larger than Low (0), and +/// each matches the bytes written with the settings OK would use. +#[test] +fn quality_12_reads_larger_than_quality_0() { + let src = source(None); + let (low, high) = (src.settings(0, JpegFormat::Baseline), src.settings(12, JpegFormat::Baseline)); + let size = |s: &ExportSettings| photocraft_io::export(&src.doc, "a.jpg", &s.io_options()).unwrap().bytes.len() as u64; + assert_eq!(encoded_size(&src.doc, &low), Some(size(&low))); + assert_eq!(encoded_size(&src.doc, &high), Some(size(&high))); + assert!(size(&high) > size(&low), "quality 12: {} bytes, quality 0: {} bytes", size(&high), size(&low)); + assert!(size(&high) > 2 * size(&low), "the quality is what is encoded, not a default"); +} + +/// Left on an opened JPEG's own quality, OK writes that quality exactly, so the readout encodes +/// it too; another step encodes the step's quality. +#[test] +fn the_files_own_quality_is_what_is_estimated() { + let src = source(Some(95)); + assert_eq!(src.settings(11, JpegFormat::Progressive).jpeg_quality, Some(95)); + assert_eq!(src.settings(11, JpegFormat::Progressive).jpeg_format, JpegFormat::Progressive); + assert_eq!(src.settings(10, JpegFormat::Baseline).jpeg_quality, Some(photocraft_engine::file_cmds::jpeg_quality(10.0))); +} + +/// Waits for `readout` to answer `key`, encoding with `job`. +fn answer(readout: &mut Readout, key: Key, job: impl Fn() -> Option + Send + Sync + Clone + 'static) -> Option { + let deadline = Instant::now() + Duration::from_secs(20); + loop { + if let Estimate::Known(size) = readout.update(key, || job.clone(), || {}) { + return size; + } + assert!(Instant::now() < deadline, "no size arrived for {key:?}"); + std::thread::sleep(Duration::from_millis(2)); + } +} + +/// A frame that changes nothing encodes nothing: the size is kept per settings. A change encodes +/// once, showing the earlier size marked as pending until the new one is ready, and only one +/// encode runs at a time. +#[test] +fn unchanged_settings_are_not_encoded_again() { + let encodes = Arc::new(AtomicU32::new(0)); + let counted = |size: u64| { + let encodes = encodes.clone(); + move || { + encodes.fetch_add(1, Ordering::SeqCst); + Some(size) + } + }; + let key = Key { doc: photocraft_doc::DocId(1), revision: 3, quality: 84, format: JpegFormat::Baseline }; + let mut readout = Readout::default(); + assert_eq!(answer(&mut readout, key, counted(1000)), Some(1000)); + for _ in 0..10 { + assert_eq!(readout.update(key, || counted(1), || {}), Estimate::Known(Some(1000))); + } + assert_eq!(encodes.load(Ordering::SeqCst), 1, "the same settings are encoded once"); + + let progressive = Key { format: JpegFormat::Progressive, ..key }; + let (gate, wait) = std::sync::mpsc::channel::<()>(); + let wait = Arc::new(Mutex::new(wait)); + let slow = { + let encodes = encodes.clone(); + move || { + let _ = wait.lock().unwrap().recv(); + encodes.fetch_add(1, Ordering::SeqCst); + Some(2000) + } + }; + assert_eq!(readout.update(progressive, || slow.clone(), || {}), Estimate::Pending(Some(1000)), "the earlier size stands in, pending"); + let other = Key { quality: 92, ..key }; + assert_eq!(readout.update(other, || counted(3), || {}), Estimate::Pending(Some(1000)), "a second encode waits for the first"); + gate.send(()).unwrap(); + assert_eq!(answer(&mut readout, progressive, slow), Some(2000)); + assert_eq!(answer(&mut readout, other, counted(3)), Some(3), "the waiting change encodes next"); + assert_eq!(encodes.load(Ordering::SeqCst), 3); + + let edited = Key { revision: 4, ..key }; + assert_eq!(readout.update(edited, || || None, || {}), Estimate::Pending(None), "an edited document shows no size of the old one"); +} + +/// Going back to settings already worked out shows their size at once, without encoding again; +/// only the last [`KEPT`] are kept. +#[test] +fn earlier_settings_are_not_encoded_again() { + let encodes = Arc::new(AtomicU32::new(0)); + let counted = |size: u64| { + let encodes = encodes.clone(); + move || { + encodes.fetch_add(1, Ordering::SeqCst); + Some(size) + } + }; + let at = |quality: u8| Key { doc: photocraft_doc::DocId(1), revision: 3, quality, format: JpegFormat::Baseline }; + let mut readout = Readout::default(); + assert_eq!(answer(&mut readout, at(84), counted(1000)), Some(1000)); + assert_eq!(answer(&mut readout, at(92), counted(2000)), Some(2000)); + assert_eq!(readout.update(at(84), || counted(1), || {}), Estimate::Known(Some(1000)), "back to 84: its size, at once"); + assert_eq!(readout.update(at(92), || counted(1), || {}), Estimate::Known(Some(2000))); + assert_eq!(encodes.load(Ordering::SeqCst), 2); + + for q in 1..=KEPT as u8 { + assert_eq!(answer(&mut readout, at(q), counted(u64::from(q))), Some(u64::from(q))); + } + assert_eq!(encodes.load(Ordering::SeqCst), 2 + KEPT as u32); + assert_eq!(answer(&mut readout, at(84), counted(1000)), Some(1000), "the oldest sizes make room"); + assert_eq!(encodes.load(Ordering::SeqCst), 3 + KEPT as u32); +} + +/// The readout marks a size that stands in for one still being worked out. +#[test] +fn a_pending_size_is_marked() { + assert_eq!(Estimate::Known(Some(155_955)).label(), "152.3K"); + assert_eq!(Estimate::Pending(Some(155_955)).label(), "152.3K…"); + assert_eq!(Estimate::Pending(None).label(), "…"); + assert_eq!(Estimate::Known(None).label(), "—"); +} + +/// Documents larger than the limit are not encoded: the readout is a dash. +#[test] +fn large_documents_are_not_encoded() { + assert!(estimable(photocraft_doc::Size::new(6000, 4000)), "24 MP"); + assert!(!estimable(photocraft_doc::Size::new(10_000, 10_000)), "100 MP"); + assert!(!estimable(photocraft_doc::Size::new(u32::MAX, u32::MAX))); +} + +/// The dialog shows the size its settings write, next to its buttons. +#[test] +fn the_dialog_shows_the_size_it_will_write() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.sync_views(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 600.0)).build_ui_state( + |ui, app| { + super::super::show(app, ui.ctx()); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + super::super::park(h.state_mut(), "p.jpg".into(), false, "file.saveAs").unwrap(); + let src = Source::of(h.state()).unwrap(); + let quality = h.state().jpeg_options.as_ref().unwrap().quality; + let expected = size_label(encoded_size(&src.doc, &src.settings(quality, JpegFormat::Baseline)).unwrap()); + let deadline = Instant::now() + Duration::from_secs(20); + while h.query_by_label(&expected).is_none() { + assert!(Instant::now() < deadline, "JPEG Options never showed {expected}"); + h.run_steps(1); + std::thread::sleep(Duration::from_millis(5)); + } +} diff --git a/crates/ui-egui/src/dialogs/liquify_ui.rs b/crates/ui-egui/src/dialogs/liquify_ui.rs index d6b91bd300..f2649a49bf 100644 --- a/crates/ui-egui/src/dialogs/liquify_ui.rs +++ b/crates/ui-egui/src/dialogs/liquify_ui.rs @@ -917,11 +917,13 @@ fn brush_resize_gesture(mods: egui::Modifiers, secondary: bool) -> bool { } /// Horizontal motion sets the diameter (the circle's edge follows the pointer). Vertical motion -/// sets density, Liquify's edge falloff, over the same 200 px travel the canvas uses for hardness. +/// sets density, Liquify's edge falloff, over 200 px of travel. fn resized_brush(start_size: f32, start_density: f32, dx: f32, dy: f32, zoom: f32) -> (f32, f32) { // Liquify stores density as 0–100; the shared brush gesture works on normalized hardness. // Use the same zoom-corrected screen movement and size limits as the main canvas. let zoom = if zoom.is_finite() && zoom > 0.0 { zoom } else { 1.0 }; + // Density keeps its 200 px travel; the canvas hardness took Photoshop's slower rate (#11891). + let dy = dy * crate::brush_resize::HARDNESS_TRAVEL / 200.0; let (size, density) = crate::brush_resize::resized((start_size, start_density / 100.0), f64::from(dx / zoom), f64::from(dy / zoom), zoom); (size, (density * 100.0).round()) } diff --git a/crates/ui-egui/src/dialogs/live_shape_prompt.rs b/crates/ui-egui/src/dialogs/live_shape_prompt.rs new file mode 100644 index 0000000000..6db96b6760 --- /dev/null +++ b/crates/ui-egui/src/dialogs/live_shape_prompt.rs @@ -0,0 +1,81 @@ +//! The question the Delete Anchor Point tool asks before it turns a live shape into a regular path +//! (#12768): "This operation will turn a live shape into a regular path. Continue?", Yes (the +//! default) and No, and a "Don't show again" box kept with the other dialog preferences. Yes runs +//! the `path.deleteAnchor` the click would have run; No changes nothing. + +use serde_json::{Map, Value, json}; + +use super::dont_show_again; +use crate::PhotocraftApp; +use crate::direct_select::{DirectSelection, PathRef}; +use crate::state::DialogKind; +use photocraft_doc::{LayerContent, LayerId}; + +/// Marks the question; the dialog's fields carry the layer and the command's parameters. +const MARK: &str = "__liveShapeDeleteAnchor"; + +/// Its "Don't show again", under `Preferences::dialogs`. +pub const PREF: &str = "path.deleteAnchor.liveShape"; + +pub fn owns(fields: &Map) -> bool { + fields.contains_key(MARK) +} + +/// Whether `r` is a live shape layer, such as a rectangle from the Rectangle tool in Shape mode. +fn is_live(app: &PhotocraftApp, r: PathRef) -> bool { + let PathRef::Layer(id) = r else { return false }; + app.session.active().and_then(|st| st.doc.layer(LayerId(id))).is_some_and(|layer| matches!(&layer.content, LayerContent::Shape(sh) if sh.live.is_some())) +} + +/// Ask before `path.deleteAnchor` with `params` runs on `r`. True when the question is open (or +/// already was), so the caller stops; false when the deletion goes ahead: `r` is not a live shape +/// or "Don't show again" was ticked. +pub fn ask(app: &mut PhotocraftApp, r: PathRef, params: &Value) -> bool { + let PathRef::Layer(layer) = r else { return false }; + let Some((document, revision)) = app.session.active().map(|st| (st.doc.id.0, st.revision)) else { return false }; + if !is_live(app, r) || dont_show_again::dismissed(app, PREF) { + return false; + } + if app.ui.dialogs.iter().any(|d| owns(&d.fields)) { + return true; + } + let mut f = Map::new(); + f.insert(MARK.into(), json!(true)); + f.insert("__command".into(), json!("path.deleteAnchor")); + f.insert("__label".into(), json!(tl!("Delete Anchor Point"))); + f.insert("layer".into(), json!(layer)); + // The layer id means something only in this document (another may become active meanwhile), + // and the knot index only in this revision of it (an edit meanwhile can shift the anchors). + f.insert("__document".into(), json!(document)); + f.insert("__revision".into(), json!(revision)); + f.insert("params".into(), params.clone()); + f.insert("__dontShowAgain".into(), json!(PREF)); + f.insert("skip".into(), json!(false)); + app.ui.open_dialog(DialogKind::Command, f); + true +} + +pub fn body(ui: &mut egui::Ui, fields: &mut Map) { + ui.label(tl!("This operation will turn a live shape into a regular path. Continue?")); + dont_show_again::body(ui, fields); +} + +/// Yes: the anchor goes in one "Delete Anchor Point" step, and a ticked "Don't show again" is kept. +pub fn confirm(app: &mut PhotocraftApp, fields: &Map) -> Result { + let layer = fields.get("layer").and_then(Value::as_u64).ok_or(tl!("No anchor to delete"))?; + let params = fields.get("params").cloned().ok_or(tl!("No anchor to delete"))?; + let asked = fields.get("__document").and_then(Value::as_u64).zip(fields.get("__revision").and_then(Value::as_u64)); + if asked.is_none() || app.session.active().map(|st| (st.doc.id.0, st.revision)) != asked { + return Err(tl!("No anchor to delete").into()); + } + let result = app.run("path.deleteAnchor", params)?; + // The anchors shift: a Direct Selection on this path would point at the wrong ones. + let r = PathRef::Layer(layer); + if app.ui.direct_selection.target.as_ref() == Some(&r) { + app.ui.direct_selection = DirectSelection { target: Some(r), ..Default::default() }; + } + if fields.get("skip").and_then(Value::as_bool) == Some(true) { + dont_show_again::remember(app, PREF); + } + Ok(result) +} diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index a34eae8ecd..98f7b614fe 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -359,7 +359,7 @@ fn open(app: &mut PhotocraftApp, held: Held, action: Option<&str>) -> Result index, }; app.session.set_active(index); - crate::jobs_ui::after_open(app, document, &name, path.as_deref(), &warnings, bytes.as_deref().map(Vec::as_slice))?; + crate::jobs_ui::after_open(app, document, &name, path.as_deref(), &warnings, bytes.as_ref())?; Ok(json!({"document": index, "action": action})) } diff --git a/crates/ui-egui/src/dialogs/paths_export_default_tests.rs b/crates/ui-egui/src/dialogs/paths_export_default_tests.rs new file mode 100644 index 0000000000..55ba9f74ab --- /dev/null +++ b/crates/ui-egui/src/dialogs/paths_export_default_tests.rs @@ -0,0 +1,89 @@ +//! #13777: File › Export › Paths to Illustrator opens its Paths dropdown on the row that is +//! selected in the Paths panel, as the reference application does: a saved path or the Work +//! Path when that row is selected, All Paths when no row is (or the row is gone), and the +//! choice is not remembered between openings. The shape layer's path is not an entry yet +//! (#13774), so that row keeps today's All Paths. + +use crate::PhotocraftApp; +use serde_json::{Value, json}; + +const COMMAND: &str = "file.export.pathsToIllustrator"; + +/// A document with a Work Path and two saved paths, "Curve A" and "Curve B". +fn app_with_paths() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + let path = |x: f64| json!({"subpaths": [{"closed": true, "knots": [[x, 10.0], [x + 40.0, 10.0], [x + 40.0, 50.0]]}]}); + for (name, x) in [("Curve A", 10.0), ("Curve B", 60.0), ("work", 110.0)] { + app.run("path.set", json!({"name": name, "path": path(x)})).unwrap(); + } + app +} + +/// Opens the dialog as the menu item does and returns its id and the preselected entry. +fn open(app: &mut PhotocraftApp) -> (u64, Value) { + let r = super::file_ui::invoke(app, &egui::Context::default(), COMMAND, &json!({})).unwrap().unwrap(); + let id = r["dialog"].as_u64().unwrap(); + let paths = app.ui.dialog_mut(id).unwrap().fields["paths"].clone(); + (id, paths) +} + +#[test] +fn a_selected_saved_path_is_preselected() { + let mut app = app_with_paths(); + app.ui.selected_path = Some("Curve B".into()); + assert_eq!(open(&mut app).1, "Curve B"); +} + +#[test] +fn the_selected_work_path_is_preselected() { + let mut app = app_with_paths(); + app.ui.selected_path = Some("work".into()); + assert_eq!(open(&mut app).1, "work"); +} + +#[test] +fn no_selected_row_preselects_all_paths() { + let mut app = app_with_paths(); + app.ui.selected_path = None; + assert_eq!(open(&mut app).1, "all"); +} + +#[test] +fn a_row_the_document_no_longer_has_preselects_all_paths() { + let mut app = app_with_paths(); + app.ui.selected_path = Some("Deleted path".into()); + assert_eq!(open(&mut app).1, "all"); + app.run("path.delete", json!({"name": "work"})).unwrap(); + app.ui.selected_path = Some("work".into()); + assert_eq!(open(&mut app).1, "all", "a selected Work Path the document no longer has"); +} + +/// The layer path entry does not exist yet (#13774): that row keeps today's default. +#[test] +fn the_shape_layer_path_row_keeps_all_paths() { + let mut app = app_with_paths(); + app.ui.selected_path = Some("layer".into()); + assert_eq!(open(&mut app).1, "all"); +} + +#[test] +fn the_choice_is_not_remembered_between_openings() { + let mut app = app_with_paths(); + app.ui.selected_path = Some("Curve A".into()); + let (id, paths) = open(&mut app); + assert_eq!(paths, "Curve A"); + app.ui.dialog_mut(id).unwrap().fields.insert("paths".into(), json!("work")); + app.ui.close_dialog(id); + app.ui.selected_path = Some("Curve B".into()); + assert_eq!(open(&mut app).1, "Curve B"); +} + +/// The dropdown's entries and the command's parameter values stay as they are. +#[test] +fn the_entries_keep_their_parameter_values() { + let mut app = app_with_paths(); + let (id, _) = open(&mut app); + let choices = app.ui.dialog_mut(id).unwrap().fields["__choices"]["paths"].clone(); + assert_eq!(choices, json!(["all", "work", "Curve A", "Curve B"])); +} diff --git a/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs b/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs index 2f0839c7be..7a7ace0079 100644 --- a/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs +++ b/crates/ui-egui/src/dialogs/preset_group_prompt/tests.rs @@ -48,7 +48,7 @@ impl Fixture { fn new(kind: Kind) -> Self { let (name, stem, bytes) = match kind { Kind::Brushes => { - use photocraft_psd::abr::{LegacyBrush, LegacyTip, write_v12}; + use craft_psd::abr::{LegacyBrush, LegacyTip, write_v12}; let brush = |diameter| LegacyBrush { name: String::new(), spacing: 25, @@ -58,7 +58,7 @@ impl Fixture { ("Kit.abr", "Kit", write_v12(2, &[brush(9), brush(17)], true).unwrap()) } Kind::Gradients => { - use photocraft_psd::grd::{GrdColor, GrdGradient, GrdStop, write}; + use craft_psd::grd::{GrdColor, GrdGradient, GrdStop, write}; let gradient = |name: &str, rgb| GrdGradient { name: name.into(), stops: vec![ diff --git a/crates/ui-egui/src/dialogs/rasterize_prompt.rs b/crates/ui-egui/src/dialogs/rasterize_prompt.rs index c099f6b76e..f6377999f8 100644 --- a/crates/ui-egui/src/dialogs/rasterize_prompt.rs +++ b/crates/ui-egui/src/dialogs/rasterize_prompt.rs @@ -102,12 +102,17 @@ pub fn needed(app: &PhotocraftApp) -> Option<(Kind, photocraft_doc::LayerId)> { } /// A tool's pointer press: when it would paint a layer that must be rasterized first, park it -/// behind the prompt and return true (the tool must not see the press). +/// behind the prompt, or drop it (the Remove tool on a type layer), and return true (the tool +/// must not see the press). pub fn intercept(app: &mut PhotocraftApp, tool: Tool, x: f64, y: f64, pressure: f32) -> bool { if !paints_pixels(app, tool) { return false; } let Some((kind, layer)) = needed(app) else { return false }; + // The reference's Remove tool ignores a type layer: no prompt and no stroke (#12553). + if tool == Tool::Remove && kind == Kind::Type { + return true; + } if !app.ui.dialogs.iter().any(|d| owns(&d.fields)) { open(app, kind, layer, tool, [x, y, f64::from(pressure)]); } @@ -259,3 +264,7 @@ mod rasterize_prompt_fill_text_tests; #[cfg(test)] #[path = "../rasterize_prompt_history_name_tests.rs"] mod rasterize_prompt_history_name_tests; + +#[cfg(test)] +#[path = "../tools/remove_type_layer_tests.rs"] +mod remove_type_layer_tests; diff --git a/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs b/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs index e1d320322c..e6e321985a 100644 --- a/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs @@ -888,7 +888,8 @@ fn alt_right_drag_resizes_the_workspace_brush() { let w = h.state().distort.select_mask.as_ref().unwrap(); let want = (30.0 + 2.0 * f64::from(40.0 / zoom)).round(); assert_eq!(w.brush_size, want, "horizontal motion sets the diameter (zoom {zoom})"); - assert_eq!(w.hardness, 70.0, "upward motion softens the brush, 200 points for 100 %"); + let soft = (100.0 - 60.0 * 100.0 / crate::brush_resize::HARDNESS_TRAVEL).round(); + assert_eq!(w.hardness, soft, "upward motion softens the brush, at the canvas HUD's rate"); assert_eq!((w.quick_size, w.refine_size), (30.0, 30.0), "the other tools keep their sizes"); assert!(w.strokes.is_empty() && w.edits.is_empty() && w.undo.is_empty(), "resizing selected nothing"); assert!(w.resize.is_none(), "the gesture ends with the button"); @@ -904,7 +905,7 @@ fn alt_right_drag_resizes_the_workspace_brush() { pointer_drag(&mut h, over, PointerButton::Primary, Modifiers::CTRL | Modifiers::ALT, vec2(-10.0, 0.0)); let w = h.state().distort.select_mask.as_ref().unwrap(); assert_eq!(w.quick_size, (30.0 - 2.0 * f64::from(10.0 / zoom)).round().max(1.0)); - assert_eq!((w.brush_size, w.hardness), (want, 70.0), "the Brush keeps its size and hardness"); + assert_eq!((w.brush_size, w.hardness), (want, soft), "the Brush keeps its size and hardness"); assert!(w.strokes.is_empty() && w.edits.len() == 1, "resizing Quick Selection selected nothing"); } diff --git a/crates/ui-egui/src/dialogs/shape_dialog.rs b/crates/ui-egui/src/dialogs/shape_dialog.rs index fc9a3e9ea6..066e5e4147 100644 --- a/crates/ui-egui/src/dialogs/shape_dialog.rs +++ b/crates/ui-egui/src/dialogs/shape_dialog.rs @@ -47,10 +47,41 @@ fn valid(key: &str, v: &Value) -> bool { /// True for a press and release that never left `start` by more than a few screen pixels. pub fn is_click(start: [f64; 2], points: &[[f64; 3]], zoom: f32) -> bool { - let slop = 3.0 / f64::from(zoom.max(0.01)); + within_click_slop(start, points, zoom, 3.0) +} + +pub(crate) fn is_tool_click(tool: Tool, options: &crate::state::ToolOptions, start: [f64; 2], points: &[[f64; 3]], zoom: f32) -> bool { + if tool == Tool::Rectangle && options.shape_mode == "shape" { within_click_slop(start, points, zoom, 1.0) } else { is_click(start, points, zoom) } +} + +fn within_click_slop(start: [f64; 2], points: &[[f64; 3]], zoom: f32, pixels: f64) -> bool { + let slop = pixels / f64::from(zoom.max(0.01)); points.iter().all(|p| (p[0] - start[0]).hypot(p[1] - start[1]) <= slop) } +/// A Shape-mode Rectangle click inside the active live rectangle leaves the shape alone (#13340). +pub(crate) fn click_inside_active_rectangle(app: &PhotocraftApp, tool: Tool, at: [f64; 2]) -> bool { + use photocraft_doc::{LayerContent, LiveShape}; + + if tool != Tool::Rectangle || app.ui.tool_options.shape_mode != "shape" { + return false; + } + let Some(layer) = app.session.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))) else { return false }; + let LayerContent::Shape(shape) = &layer.content else { return false }; + let Some(LiveShape::Rect { rect: [x, y, w, h], radii }) = shape.live else { return false }; + let (left, top) = (x.min(x + w), y.min(y + h)); + let (right, bottom) = (x.max(x + w), y.max(y + h)); + let [px, py] = at; + if !((left..=right).contains(&px) && (top..=bottom).contains(&py)) { + return false; + } + let (l, r, t, b) = (px - left, right - px, py - top, bottom - py); + [(l, t), (r, t), (r, b), (l, b)] + .into_iter() + .zip(photocraft_vector::shapes::clamp_radii(w.abs(), h.abs(), radii)) + .all(|((dx, dy), radius)| dx >= radius || dy >= radius || (radius - dx).hypot(radius - dy) <= radius) +} + /// Open the creation dialog of `tool` for a click at `at` (document px). `None` for a tool without /// one (Line, Custom Shape). pub fn open(app: &mut PhotocraftApp, tool: Tool, at: [f64; 2]) -> Option { @@ -124,7 +155,7 @@ pub fn geometry(f: &Map) -> Result { if radii.iter().any(|r| *r > 0.0) { json!({"kind": "roundedRect", "rect": rect, "radii": radii}) } else { json!({"kind": "rect", "rect": rect}) } } "ellipse" => json!({"kind": "ellipse", "rect": rect}), - "triangle" => json!({"kind": "polygon", "rect": rect, "sides": 3}), + "triangle" => json!({"kind": "triangle", "rect": rect}), "polygon" => { let sides = num(f, "sides").map_or(5.0, |s| s.round().clamp(3.0, 100.0)); let ratio = num(f, "starRatio").map_or(100.0, |r| r.clamp(1.0, 100.0)); diff --git a/crates/ui-egui/src/dialogs/shape_dialog/tests.rs b/crates/ui-egui/src/dialogs/shape_dialog/tests.rs index 1ca5de28f7..09591bbc8c 100644 --- a/crates/ui-egui/src/dialogs/shape_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/shape_dialog/tests.rs @@ -81,7 +81,7 @@ fn from_center_and_the_other_tools() { press(&mut app, Tool::Triangle, [5.0, 6.0], [5.0, 6.0]); let id = only_dialog(&app); crate::dialogs::confirm(&mut app, id).unwrap(); - let LiveShape::Polygon { sides: 3, .. } = live(&app) else { panic!("a triangle") }; + assert_eq!(live(&app), LiveShape::Triangle { rect: [5.0, 6.0, 100.0, 100.0], corner_radius: 0.0 }); } #[test] @@ -174,7 +174,7 @@ fn a_click_with_jitter_opens_the_dialog_on_hidpi() { let i = app.session.active_index().unwrap(); app.ui.views[i].zoom = 1.0; let before = layers(&app); - press(&mut app, Tool::Rectangle, [20.0, 30.0], [24.0, 30.0]); + press(&mut app, Tool::Rectangle, [20.0, 30.0], [22.0, 30.0]); only_dialog(&app); assert_eq!(layers(&app), before, "a jittery click draws nothing"); } @@ -347,7 +347,7 @@ fn right_click_picks_the_unit_of_that_field_only_and_it_is_not_remembered() { set(&mut app, id, json!({"widthUnit": "mm", "width": 50})); crate::dialogs::confirm(&mut app, id).unwrap(); app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "cm"})).unwrap(); - press(&mut app, Tool::Rectangle, [40.0, 40.0], [40.0, 40.0]); + press(&mut app, Tool::Rectangle, [140.0, 140.0], [140.0, 140.0]); let id = only_dialog(&app); let mut f = app.ui.dialog_mut(id).unwrap().fields.clone(); assert_eq!((f.get("widthUnit"), f["width"].as_f64()), (None, Some(50.0)), "the size is remembered, the unit isn't"); diff --git a/crates/ui-egui/src/dodge_default_tip_tests.rs b/crates/ui-egui/src/dodge_default_tip_tests.rs index b2eb59524c..58beb52e2d 100644 --- a/crates/ui-egui/src/dodge_default_tip_tests.rs +++ b/crates/ui-egui/src/dodge_default_tip_tests.rs @@ -43,7 +43,6 @@ fn scramble(app: &mut PhotocraftApp) { } const DODGE_TIP: [f64; 5] = [65.0, 0.0, 0.25, 0.0, 1.0]; -const DEFAULT_TIP: [f64; 5] = [20.0, 1.0, 0.1, 0.0, 1.0]; #[test] fn reset_tool_gives_the_dodge_tool_a_65_px_soft_tip() { @@ -87,18 +86,3 @@ fn reset_all_tools_gives_it_the_tip_active_or_picked_later() { pick(&mut app, Tool::Dodge); assert_eq!(tip(&mut app), DODGE_TIP, "picked after the reset"); } - -#[test] -fn the_sponge_tool_keeps_its_tip() { - let mut a = app(); - pick(&mut a, Tool::Sponge); - scramble(&mut a); - invoke(&mut a, "tool.reset", json!({})); - assert_eq!(tip(&mut a), DEFAULT_TIP); - // A first use still takes the current tip, as before. - let mut a = app(); - pick(&mut a, Tool::Pencil); - scramble(&mut a); - pick(&mut a, Tool::Sponge); - assert_eq!(tip(&mut a)[0], 57.0, "first use"); -} diff --git a/crates/ui-egui/src/eraser_block_right_click_tests.rs b/crates/ui-egui/src/eraser_block_right_click_tests.rs index 73be8c8750..720865444d 100644 --- a/crates/ui-egui/src/eraser_block_right_click_tests.rs +++ b/crates/ui-egui/src/eraser_block_right_click_tests.rs @@ -10,7 +10,7 @@ use crate::PhotocraftApp; use crate::control::{ControlRequest, Outcome, handle}; use crate::state::Tool; -fn app(mode: &str) -> PhotocraftApp { +pub(super) fn app(mode: &str) -> PhotocraftApp { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap(); app.run("layer.new.layer", json!({})).unwrap(); @@ -21,7 +21,7 @@ fn app(mode: &str) -> PhotocraftApp { app } -fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { +pub(super) fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { let (req, _rx) = ControlRequest::new(method, params); match handle(app, ctx, &req) { Outcome::Done(v) => v, @@ -29,7 +29,7 @@ fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Valu } } -fn right_click(app: &mut PhotocraftApp, ctx: &egui::Context, modifiers: Value) { +pub(super) fn right_click(app: &mut PhotocraftApp, ctx: &egui::Context, modifiers: Value) { call( app, ctx, @@ -38,7 +38,7 @@ fn right_click(app: &mut PhotocraftApp, ctx: &egui::Context, modifiers: Value) { ); } -fn steps(app: &PhotocraftApp) -> usize { +pub(super) fn steps(app: &PhotocraftApp) -> usize { app.session.active().unwrap().history.past_len() } @@ -94,18 +94,7 @@ fn with_the_erase_preference_block_mode_still_erases() { /// nothing is erased. #[test] fn a_real_right_click_opens_the_menu_and_escape_closes_it() { - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( - |ui, app: &mut PhotocraftApp| { - let ctx = ui.ctx().clone(); - if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { - return; - } - egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); - }, - app("block"), - ); - crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); - h.run_steps(4); + let mut h = harness(app("block")); let n = steps(h.state()); let c = h.state().last_canvas_rect.center(); h.event(egui::Event::PointerMoved(c)); @@ -121,3 +110,20 @@ fn a_real_right_click_opens_the_menu_and_escape_closes_it() { assert!(h.state().ui.brush_mode_menu.is_none(), "Escape closes it"); assert_eq!(steps(h.state()), n, "nothing erased"); } + +/// The canvas alone, drawn by the real mouse path. +pub(super) fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + h +} diff --git a/crates/ui-egui/src/healing_alt_cursor_tests.rs b/crates/ui-egui/src/healing_alt_cursor_tests.rs new file mode 100644 index 0000000000..d129752a63 --- /dev/null +++ b/crates/ui-egui/src/healing_alt_cursor_tests.rs @@ -0,0 +1,157 @@ +//! #12113: with Painting Cursors = Normal Brush Tip, holding ⌥ with the Healing Brush shows the +//! reference's fixed target crosshair (19 × 19, hotspot at its centre) whatever the tip size, and +//! releasing ⌥ brings the tip outline back. The Clone Stamp keeps its tip circle with a centre +//! mark, and the unmeasured Painting Cursors settings keep today's cursors. + +use egui::{Modifiers, PointerButton}; +use egui_kittest::Harness; +use serde_json::json; + +use super::mixer_cursor_tests::{Bitmap, assert_centred, bitmap, centre, harness, has_fonts, hotspot_drawn, hover}; +use crate::PhotocraftApp; +use crate::state::Tool; + +/// The first column and row of the bitmap's visible (non-transparent) pixels, and their width and +/// height. +fn visible_box((size, _, alpha): &Bitmap) -> ([usize; 2], [usize; 2]) { + let w = usize::from(size[0]); + let (mut lo, mut hi) = ([usize::MAX; 2], [0; 2]); + for (i, _) in alpha.iter().enumerate().filter(|(_, a)| **a > 0) { + for (k, v) in [i % w, i / w].into_iter().enumerate() { + lo[k] = lo[k].min(v); + hi[k] = hi[k].max(v); + } + } + (lo, [0, 1].map(|k| if lo[k] > hi[k] { 0 } else { hi[k] - lo[k] + 1 })) +} + +/// The width and height of the bitmap's visible pixels. +fn visible(b: &Bitmap) -> [usize; 2] { + visible_box(b).1 +} + +/// Asserts `b` is the target: 19 × 19 visible points, centred, its cross through the hotspot. +fn assert_target(h: &Harness<'static, PhotocraftApp>, b: &Bitmap, what: &str) { + let side = 19.0 * crate::tool_cursor::native_scale(&h.ctx); + assert_centred(b.0, b.1, what); + let (lo, seen) = visible_box(b); + let [w, hh] = seen; + assert!((w as f32 - side).abs() <= 1.0 && (hh as f32 - side).abs() <= 1.0, "{what}: a 19 × 19 target, not {w} × {hh}"); + // The reference's hotspot 9,9 in its 19 × 19 bitmap: the centre of the visible target. + for k in 0..2 { + let at = usize::from(b.1[k]) - lo[k]; + assert!(at.abs_diff((seen[k] - 1) / 2) <= 1, "{what}: hotspot {at} px into the {} px target", seen[k]); + } + assert!(hotspot_drawn(b), "{what}: the cross runs through the hotspot"); +} + +fn tip(h: &mut Harness<'static, PhotocraftApp>, size: f32) { + h.state_mut().session.tools.brush.size = size; +} + +fn painting(h: &mut Harness<'static, PhotocraftApp>, value: &str) { + h.state_mut().run("prefs.set", json!({"path": "cursors.painting", "value": value})).unwrap(); +} + +#[test] +fn alt_shows_the_fixed_target_at_any_tip_size_and_releasing_it_brings_the_tip_back() { + let mut h = harness(Tool::Healing); + if !has_fonts(&h) { + return; + } + let mut target: Option = None; + // 200 px is the largest of these that every platform still draws as an outline bitmap + // (Linux caps cursor bitmaps at 255 px a side). + for size in [10.0, 40.0, 200.0] { + tip(&mut h, size); + hover(&mut h, Modifiers::ALT); + let alt = bitmap(&h).expect("the target is an OS cursor bitmap"); + assert_target(&h, &alt, &format!("{size} px tip")); + match &target { + Some(t) => assert_eq!(&alt, t, "{size} px tip: the same target as the smaller tips"), + None => target = Some(alt.clone()), + } + hover(&mut h, Modifiers::NONE); + let released = bitmap(&h).expect("the tip outline is an OS cursor bitmap"); + assert_ne!(released, alt, "{size} px tip: releasing ⌥ brings the tip outline back"); + assert!(!hotspot_drawn(&released), "{size} px tip: the plain outline has no centre mark"); + } + tip(&mut h, 200.0); + hover(&mut h, Modifiers::NONE); + let outline = bitmap(&h).expect("the tip outline"); + assert!(visible(&outline)[0] > 4 * 19, "the 200 px tip's outline, not the target: {:?}", visible(&outline)); +} + +#[test] +fn sticky_alt_shows_the_target_too() { + let mut h = harness(Tool::Healing); + if !has_fonts(&h) { + return; + } + tip(&mut h, 120.0); + h.state_mut().ui.shell.sticky_alt = true; + hover(&mut h, Modifiers::NONE); + let target = bitmap(&h).expect("the target"); + assert_target(&h, &target, "sticky ⌥"); + h.state_mut().ui.shell.sticky_alt = false; + hover(&mut h, Modifiers::NONE); + assert_ne!(bitmap(&h), Some(target), "off again: the tip outline"); +} + +#[test] +fn the_target_stays_while_an_alt_click_is_held() { + let mut h = harness(Tool::Healing); + if !has_fonts(&h) { + return; + } + tip(&mut h, 120.0); + hover(&mut h, Modifiers::ALT); + let target = bitmap(&h).expect("the target"); + assert_target(&h, &target, "⌥ hover"); + let p = centre(&h); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::ALT }); + h.run_steps(2); + assert_eq!(bitmap(&h), Some(target), "the target stays while the ⌥-click is held"); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::ALT }); + h.run_steps(2); +} + +#[test] +fn the_clone_stamp_keeps_its_tip_circle_with_a_centre_mark() { + let mut h = harness(Tool::CloneStamp); + if !has_fonts(&h) { + return; + } + tip(&mut h, 100.0); + hover(&mut h, Modifiers::NONE); + let plain = bitmap(&h).expect("the tip circle"); + assert!(!hotspot_drawn(&plain), "no centre mark without ⌥"); + hover(&mut h, Modifiers::ALT); + let alt = bitmap(&h).expect("the tip circle with ⌥"); + assert_eq!(visible(&alt), visible(&plain), "the tip circle keeps the tip size"); + assert!(hotspot_drawn(&alt), "⌥ adds the centre mark"); +} + +/// Standard, Precise and Full Size Brush Tip weren't measured with the Healing Brush's ⌥, so ⌥ +/// shows what it does today: the standard pointer, the precise crosshair, or the full-size tip +/// with its centre mark. +#[test] +fn unmeasured_painting_cursors_keep_todays_alt_cursor() { + let mut h = harness(Tool::Healing); + if !has_fonts(&h) { + return; + } + tip(&mut h, 100.0); + for value in ["standard", "precise"] { + painting(&mut h, value); + hover(&mut h, Modifiers::NONE); + let plain = (h.output().platform_output.cursor_icon, bitmap(&h)); + hover(&mut h, Modifiers::ALT); + assert_eq!((h.output().platform_output.cursor_icon, bitmap(&h)), plain, "{value}: ⌥ changes nothing"); + } + painting(&mut h, "fullSizeTip"); + hover(&mut h, Modifiers::ALT); + let full = bitmap(&h).expect("the full-size tip"); + assert!(visible(&full)[0] > 4 * 19, "fullSizeTip: the tip circle, {:?}", visible(&full)); + assert!(hotspot_drawn(&full), "fullSizeTip: with its centre mark"); +} diff --git a/crates/ui-egui/src/healing_indexed_alert_tests.rs b/crates/ui-egui/src/healing_indexed_alert_tests.rs new file mode 100644 index 0000000000..727caf11f5 --- /dev/null +++ b/crates/ui-egui/src/healing_indexed_alert_tests.rs @@ -0,0 +1,104 @@ +//! #12112: in an Indexed Color document an ⌥-click and a stroke with the Healing Brush open the +//! reference application's alert with OK and change neither the clone source, the pixels nor the +//! History. RGB documents keep healing, and the Clone Stamp (not measured) keeps setting its source. + +use egui::Modifiers; +use serde_json::{Value, json}; + +use super::tests::{app, stripes}; +use super::*; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::DialogKind; + +const MESSAGE: &str = "Could not set the clone source because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; + +fn to_indexed(app: &mut PhotocraftApp) { + app.run("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none"})).unwrap(); +} + +fn click(app: &mut PhotocraftApp, x: f64, mods: Modifiers) { + tool_event(app, ToolEvent::Down { x, y: 30.0, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x, y: 30.0 }, mods); +} + +fn alerts(app: &PhotocraftApp) -> Vec { + app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message").and_then(Value::as_str).map(str::to_string)).collect() +} + +/// The clone source (the options bar's and the engine's), the layer's pixels and the History length. +type State = (Option<[f64; 2]>, Option<[f64; 2]>, Vec, usize); + +fn state(app: &PhotocraftApp) -> State { + let st = app.session.active().unwrap(); + let pixels = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().read_region(st.doc.bounds()); + (app.ui.clone_source, app.session.presets.clone.active().source, pixels, st.history.past_len()) +} + +/// The alert is up once; OK closes it and leaves `before` as it was. +fn alerted_once(app: &mut PhotocraftApp, before: &State) { + assert_eq!(alerts(app), [MESSAGE]); + assert!(state(app) == *before, "the source, the pixels and the History are unchanged"); + let id = app.ui.dialogs.iter().find(|d| d.kind == DialogKind::Error).map(|d| d.id).unwrap(); + crate::dialogs::confirm(app, id).unwrap(); + assert!(alerts(app).is_empty()); + assert!(state(app) == *before, "OK changes nothing"); +} + +/// An Indexed Color document with stripes to heal, the Healing Brush active. +fn indexed() -> PhotocraftApp { + let mut app = app(); + stripes(&mut app, 4, "pixels"); + to_indexed(&mut app); + app.ui.tool = Tool::Healing; + app +} + +#[test] +fn an_alt_click_alerts_and_sets_no_source() { + let mut app = indexed(); + let before = state(&app); + click(&mut app, 70.0, Modifiers::ALT); + alerted_once(&mut app, &before); +} + +#[test] +fn a_click_alerts_and_heals_nothing() { + let mut app = app(); + stripes(&mut app, 4, "pixels"); + app.ui.tool = Tool::Healing; + // The source set while the document was RGB: the stroke must still be refused. + click(&mut app, 70.0, Modifiers::ALT); + to_indexed(&mut app); + let before = state(&app); + assert!(before.0.is_some(), "the source is set"); + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, Modifiers::NONE); + assert!(crate::canvas::live_retouch_points(&app).is_none(), "no live preview"); + tool_event(&mut app, ToolEvent::Up { x: 20.0, y: 30.0 }, Modifiers::NONE); + alerted_once(&mut app, &before); + // Without a source too: the same alert, not the status-bar hint. + let mut app = indexed(); + let before = state(&app); + click(&mut app, 20.0, Modifiers::NONE); + assert!(!app.ui.status_error, "{}", app.ui.status); + alerted_once(&mut app, &before); +} + +#[test] +fn an_rgb_document_keeps_healing_and_the_clone_stamp_its_source() { + let mut app = app(); + stripes(&mut app, 4, "pixels"); + app.ui.tool = Tool::Healing; + click(&mut app, 70.0, Modifiers::ALT); + let before = state(&app); + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 30.0, pressure: 1.0 }, Modifiers::NONE); + assert!(crate::canvas::live_retouch_points(&app).is_some(), "the live preview"); + tool_event(&mut app, ToolEvent::Up { x: 20.0, y: 30.0 }, Modifiers::NONE); + assert!(alerts(&app).is_empty()); + assert_eq!(state(&app).3, before.3 + 1, "one Healing Brush state"); + // Not measured in the reference: the Clone Stamp's ⌥-click in an Indexed document is kept. + let mut app = indexed(); + app.ui.tool = Tool::CloneStamp; + click(&mut app, 70.0, Modifiers::ALT); + assert!(alerts(&app).is_empty()); + assert_eq!(app.ui.clone_source, Some([70.0, 30.0])); +} diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index 0c0a770276..e8f25a1e72 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -82,18 +82,13 @@ impl ThumbnailCache { /// Check if two path strings match, tolerating slash direction and Windows case differences. fn paths_match(a: &str, b: &str) -> bool { - if a == b { - return true; - } #[cfg(windows)] { - let a_norm = a.replace('\\', "/"); - let b_norm = b.replace('\\', "/"); - a_norm.eq_ignore_ascii_case(&b_norm) + a == b || a.replace('\\', "/").eq_ignore_ascii_case(&b.replace('\\', "/")) } #[cfg(not(windows))] { - false + a == b } } @@ -180,14 +175,14 @@ fn read_psd_thumbnail_bounded(path: &Path, file_len: u64) -> Option if res_len > 0 && res_len <= 32 * 1024 * 1024 && (res_len as u64) <= file_len { let mut res_bytes = vec![0u8; res_len as usize]; if file.read_exact(&mut res_bytes).is_ok() - && let Ok((resources, _)) = photocraft_psd::tiff::resources_from_bytes(&res_bytes) + && let Ok((resources, _)) = craft_psd::tiff::resources_from_bytes(&res_bytes) { let decode_opts = photocraft_codecs::DecodeOptions { limits: photocraft_codecs::Limits { max_width: 4096, max_height: 4096, max_pixels: 4096 * 4096, max_alloc: 4096 * 4096 * 4 }, ..Default::default() }; for r in &resources { - if (r.id == photocraft_psd::resources::ids::THUMBNAIL || r.id == photocraft_psd::resources::ids::THUMBNAIL_PS4) + if (r.id == craft_psd::resources::ids::THUMBNAIL || r.id == craft_psd::resources::ids::THUMBNAIL_PS4) && let Some(jfif) = r.data.get(28..) && let Ok(img) = photocraft_codecs::decode_with(jfif, &decode_opts) { @@ -227,7 +222,7 @@ fn read_psd_thumbnail_bounded(path: &Path, file_len: u64) -> Option // Fourth, within budget and safe dimensions: read file and decode merged composite let bytes = std::fs::read(path).ok()?; - if let Ok(file) = photocraft_psd::PsdFile::from_bytes(&bytes) + if let Ok(file) = craft_psd::PsdFile::from_bytes(&bytes) && let Ok(comp) = photocraft_io::merged_composite(&file) { let w = file.header.width; @@ -1244,23 +1239,23 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] #[test] fn recent_thumbnail_skips_composite_for_oversized_psd_without_preview() { - let temp_dir = std::env::temp_dir().join(format!("photocraft_psd_bound_test_{}", std::process::id())); + let temp_dir = std::env::temp_dir().join(format!("craft_psd_bound_test_{}", std::process::id())); let _ = std::fs::create_dir_all(&temp_dir); let file_path = temp_dir.join("oversized.psd"); let path_str = file_path.to_string_lossy().into_owned(); // Create an oversized PSD (3000 x 3000) with no thumbnail resource - let header = photocraft_psd::Header::new(photocraft_psd::Version::Psd, 3000, 3000, 3, 8, photocraft_psd::ColorMode::Rgb); - let file = photocraft_psd::PsdFile { + let header = craft_psd::Header::new(craft_psd::Version::Psd, 3000, 3000, 3, 8, craft_psd::ColorMode::Rgb); + let file = craft_psd::PsdFile { header, color_mode_data: Vec::new(), resources: Vec::new(), layer_info: None, - layer_info_placement: photocraft_psd::LayerInfoPlacement::Section, + layer_info_placement: craft_psd::LayerInfoPlacement::Section, global_layer_mask: None, global_blocks: Vec::new(), layer_mask_trailing: Vec::new(), - image_data: photocraft_psd::ImageData { compression: photocraft_psd::Compression::Raw, data: Vec::new(), stored: None }, + image_data: craft_psd::ImageData { compression: craft_psd::Compression::Raw, data: Vec::new(), stored: None }, write_as_psb: false, }; let mut bytes = file.to_bytes().unwrap(); @@ -1279,23 +1274,23 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] #[test] fn recent_thumbnail_skips_composite_for_high_channel_psd_without_preview() { - let temp_dir = std::env::temp_dir().join(format!("photocraft_psd_channels_test_{}", std::process::id())); + let temp_dir = std::env::temp_dir().join(format!("craft_psd_channels_test_{}", std::process::id())); let _ = std::fs::create_dir_all(&temp_dir); let file_path = temp_dir.join("high_channels.psd"); let path_str = file_path.to_string_lossy().into_owned(); // 2000 x 2000 with 56 channels: decoded uncompressed size = 2000 * 2000 * 56 = 224 MB (> 64 MB cap) - let header = photocraft_psd::Header::new(photocraft_psd::Version::Psd, 2000, 2000, 56, 8, photocraft_psd::ColorMode::Rgb); - let file = photocraft_psd::PsdFile { + let header = craft_psd::Header::new(craft_psd::Version::Psd, 2000, 2000, 56, 8, craft_psd::ColorMode::Rgb); + let file = craft_psd::PsdFile { header, color_mode_data: Vec::new(), resources: Vec::new(), layer_info: None, - layer_info_placement: photocraft_psd::LayerInfoPlacement::Section, + layer_info_placement: craft_psd::LayerInfoPlacement::Section, global_layer_mask: None, global_blocks: Vec::new(), layer_mask_trailing: Vec::new(), - image_data: photocraft_psd::ImageData { compression: photocraft_psd::Compression::Raw, data: Vec::new(), stored: None }, + image_data: craft_psd::ImageData { compression: craft_psd::Compression::Raw, data: Vec::new(), stored: None }, write_as_psb: false, }; let bytes = file.to_bytes().unwrap(); @@ -1310,7 +1305,7 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] #[test] fn recent_thumbnail_extracts_embedded_preview_from_large_psd_without_reading_payload() { - let temp_dir = std::env::temp_dir().join(format!("photocraft_psd_large_preview_test_{}", std::process::id())); + let temp_dir = std::env::temp_dir().join(format!("craft_psd_large_preview_test_{}", std::process::id())); let _ = std::fs::create_dir_all(&temp_dir); let file_path = temp_dir.join("large_payload.psd"); let path_str = file_path.to_string_lossy().into_owned(); @@ -1329,19 +1324,19 @@ mod tests { res_data[4..8].copy_from_slice(&512u32.to_be_bytes()); // width: 512 res_data[8..12].copy_from_slice(&512u32.to_be_bytes()); // height: 512 res_data.extend_from_slice(&jfif); - let resource = photocraft_psd::resources::ImageResource::new(photocraft_psd::resources::ids::THUMBNAIL, res_data); + let resource = craft_psd::resources::ImageResource::new(craft_psd::resources::ids::THUMBNAIL, res_data); - let header = photocraft_psd::Header::new(photocraft_psd::Version::Psd, 400, 400, 3, 8, photocraft_psd::ColorMode::Rgb); - let file = photocraft_psd::PsdFile { + let header = craft_psd::Header::new(craft_psd::Version::Psd, 400, 400, 3, 8, craft_psd::ColorMode::Rgb); + let file = craft_psd::PsdFile { header, color_mode_data: Vec::new(), resources: vec![resource], layer_info: None, - layer_info_placement: photocraft_psd::LayerInfoPlacement::Section, + layer_info_placement: craft_psd::LayerInfoPlacement::Section, global_layer_mask: None, global_blocks: Vec::new(), layer_mask_trailing: Vec::new(), - image_data: photocraft_psd::ImageData { compression: photocraft_psd::Compression::Raw, data: Vec::new(), stored: None }, + image_data: craft_psd::ImageData { compression: craft_psd::Compression::Raw, data: Vec::new(), stored: None }, write_as_psb: false, }; let mut bytes = file.to_bytes().unwrap(); diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index c29e2192fa..8e32a301c8 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -184,6 +184,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("type-mask-vertical", include_bytes!("../../../assets/icons/type-mask-vertical.svg")), ("undo-2", include_bytes!("../../../assets/icons/undo-2.svg")), ("unlink", include_bytes!("../../../assets/icons/unlink.svg")), + ("vector-shape", include_bytes!("../../../assets/icons/vector-shape.svg")), ("vertical-align-bottom", include_bytes!("../../../assets/icons/vertical-align-bottom.svg")), ("vertical-align-middle", include_bytes!("../../../assets/icons/vertical-align-middle.svg")), ("vertical-align-top", include_bytes!("../../../assets/icons/vertical-align-top.svg")), @@ -191,4 +192,5 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("wand-sparkles", include_bytes!("../../../assets/icons/wand-sparkles.svg")), ("x", include_bytes!("../../../assets/icons/x.svg")), ("zoom-in", include_bytes!("../../../assets/icons/zoom-in.svg")), + ("zoom-out", include_bytes!("../../../assets/icons/zoom-out.svg")), ]; diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index a3c702bf8c..c8594a61cd 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -80,21 +80,45 @@ pub fn cursor(ctx: &egui::Context, name: &str, p: egui::Pos2, hot: Vec2, size: f }); } +/// A solid black arrow as the pointer, above every window, its tip on `p` (the reference +/// application's arrow, hotspot at its tip): filled black with a thin light outline so it reads on +/// any image, and the same on every system. The caller hides the OS cursor (`CursorIcon::None`). +pub fn cursor_arrow(ctx: &egui::Context, p: egui::Pos2) { + // The outline of the arrow in pixels from its tip, and its split into triangles. + const OUTLINE: [(f32, f32); 7] = [(0.0, 0.0), (0.0, 16.0), (3.6, 12.6), (6.8, 19.0), (9.6, 17.8), (6.6, 11.6), (11.5, 11.5)]; + const TRIANGLES: [[u32; 3]; 5] = [[0, 1, 2], [0, 2, 5], [0, 5, 6], [2, 3, 4], [2, 4, 5]]; + let points: Vec = OUTLINE.iter().map(|&(x, y)| p + egui::vec2(x, y)).collect(); + // A new id every frame would restart the Area's fade-in each time and leave the arrow pale. + let area = + egui::Area::new(egui::Id::unique("pc-arrow-cursor")).order(egui::Order::Tooltip).fixed_pos(p).constrain(false).interactable(false).fade_in(false); + area.show(ctx, |ui| { + let vertices = points.iter().map(|&pos| egui::epaint::Vertex { pos, uv: egui::epaint::WHITE_UV, color: Color32::BLACK }).collect(); + let fill = egui::Mesh { indices: TRIANGLES.iter().flatten().copied().collect(), vertices, ..Default::default() }; + ui.painter().add(fill); + ui.painter().add(egui::Shape::closed_line(points, egui::Stroke::new(1.0, Color32::from_white_alpha(235)))); + }); +} + /// A small icon beside the OS arrow pointer at `p` (Photoshop's cursor badges: scissors for /// cutting the selected pixels). Below-right of the arrow, white with a dark outline. The caller /// keeps the arrow (`CursorIcon::Default`). pub fn cursor_badge(ctx: &egui::Context, name: &str, p: egui::Pos2) { - badge(ctx, name, p, false); + badge(ctx, name, p + egui::vec2(20.0, 19.0), false); +} + +/// A small icon below right of a crosshair centred on `p` (the Perspective Crop's idle pointer). +pub fn crosshair_badge(ctx: &egui::Context, name: &str, p: egui::Pos2) { + badge(ctx, name, p + egui::vec2(13.0, 13.0), false); } /// Photoshop's duplicate badge: a second, dark arrowhead behind a white one. pub fn cursor_copy_badge(ctx: &egui::Context, p: egui::Pos2) { - badge(ctx, "mouse-pointer-2", p, true); + badge(ctx, "mouse-pointer-2", p + egui::vec2(20.0, 19.0), true); } -fn badge(ctx: &egui::Context, name: &str, p: egui::Pos2, doubled: bool) { +fn badge(ctx: &egui::Context, name: &str, centre: egui::Pos2, doubled: bool) { const SIZE: f32 = 12.0; - let rect = Rect::from_center_size(p + egui::vec2(20.0, 19.0), Vec2::splat(SIZE)); + let rect = Rect::from_center_size(centre, Vec2::splat(SIZE)); let area = egui::Area::new(egui::Id::unique(("pc-cursor-badge", name))).order(egui::Order::Tooltip).fixed_pos(rect.min).constrain(false).interactable(false); area.show(ctx, |ui| { diff --git a/crates/ui-egui/src/input/blend_keys.rs b/crates/ui-egui/src/input/blend_keys.rs index 9ea13d6a19..fec117dac2 100644 --- a/crates/ui-egui/src/input/blend_keys.rs +++ b/crates/ui-egui/src/input/blend_keys.rs @@ -2,7 +2,10 @@ //! letter picks one (⇧⌥M Multiply, ⇧⌥S Screen…). With a painting tool that has a Mode of its own //! (`tool_modes`: Brush, Pencil, Paint Bucket, Gradient, the stamps, History Brush, Healing) they //! set that tool's mode within its menu and never the layer's. With a tool that has no blend mode -//! (Move, the selection tools, the Erasers…) they set every selected layer's mode. +//! (Move, the selection tools, the Erasers…) they set every selected layer's mode. With the Color +//! Replacement tool the ⇧⌥ letters for Normal, Multiply, Hue and Luminosity set the active layer's +//! mode too and its own Mode stays, as measured in the reference application (#11928); its other +//! letters, the letters with several layers selected, and ⇧+ / ⇧− do nothing. //! The step list wraps at either end. Each press is one call of an engine command //! (`tools.setBrush`, `layer.setProps` with every target layer), so it is one undo step. @@ -149,6 +152,10 @@ enum Target { /// nothing, and never reach the layer. Nothing, Layers, + /// The ⇧⌥ letters for these modes set the active layer's mode while it is the only one + /// selected; the other letters, several selected layers and ⇧+ / ⇧− do nothing (the Color + /// Replacement tool, #11928: only these letters on one layer were measured). + LayerLetters(&'static [BlendMode]), } fn target(tool: Tool) -> Target { @@ -156,7 +163,9 @@ fn target(tool: Tool) -> Target { return Target::Tool(modes); } match tool { - Tool::SpotHealing | Tool::ColorReplacement | Tool::Blur | Tool::Sharpen | Tool::Smudge | Tool::ArtHistoryBrush => Target::Nothing, + Tool::SpotHealing | Tool::Blur | Tool::Sharpen | Tool::Smudge | Tool::ArtHistoryBrush => Target::Nothing, + // Its ⇧⌥ letters set the active layer's mode and leave the tool's own Mode (#11928). + Tool::ColorReplacement => Target::LayerLetters(&[BlendMode::Normal, BlendMode::Multiply, BlendMode::Hue, BlendMode::Luminosity]), // Photoshop's ⇧⌥S/M/H pick the Dodge and Burn Range and ⇧⌥D/S the Sponge's mode: never // the layer's. Tool::Dodge | Tool::Burn | Tool::Sponge => Target::Nothing, @@ -251,7 +260,7 @@ pub fn press(app: &mut PhotocraftApp, step: i32) { set_tool_mode(app, mode); } } - Target::Nothing => {} + Target::Nothing | Target::LayerLetters(_) => {} Target::Layers => { let Some(st) = app.session.active() else { return }; let Some(layer) = st.active_layer.and_then(|id| st.doc.layer(id)) else { return }; @@ -298,6 +307,13 @@ pub fn pick_mode(app: &mut PhotocraftApp, pick: Pick) { set_layers_mode(app, m); } } + Target::LayerLetters(modes) => { + // Only one selected layer was measured; several keep today's (nothing). + let one = app.session.active().is_some_and(|st| st.selected_layers().len() == 1); + if let Some(m) = want.filter(|m| one && modes.contains(m)) { + set_layers_mode(app, m); + } + } _ => {} } } @@ -309,6 +325,10 @@ mod tests; #[path = "../brush_behind_key_tests.rs"] mod brush_behind_key_tests; +#[cfg(test)] +#[path = "../color_replacement_blend_keys_tests.rs"] +mod color_replacement_blend_keys_tests; + #[cfg(test)] #[path = "../brush_blend_keys_behind_tests.rs"] mod brush_blend_keys_behind_tests; diff --git a/crates/ui-egui/src/input/hold_keys/tests.rs b/crates/ui-egui/src/input/hold_keys/tests.rs index 3fc3e2e030..0658b9f816 100644 --- a/crates/ui-egui/src/input/hold_keys/tests.rs +++ b/crates/ui-egui/src/input/hold_keys/tests.rs @@ -782,7 +782,14 @@ fn tilde_held_with_the_brush_or_pencil_erases_with_its_brush() { drag_with(&mut h, Modifiers::NONE, 110.0, 130.0, 150.0, 130.0); key(&mut h, Key::Backtick, false, Modifiers::NONE); assert_eq!(last_stroke_erases(&h), Some(true), "{tool:?}"); - assert_eq!(rgba(&h, 130, 130)[3], 0.0, "{tool:?}: erased to transparency"); + // `drag_with` bends through `(118, 136)` on the way from `(110, 130)` to `(150, 130)`, + // so the Pencil's 1 px tip (#12200) no longer reaches `(130, 130)`; check `(110, 130)` + // at the stroke start instead. + assert_eq!(rgba(&h, 110, 130)[3], 0.0, "{tool:?}: erased to transparency"); + // The whole drag erases, not only its first dab: a 1 px Pencil line along the 40 px drag + // clears far more pixels than one dab. + let cleared = (100..160).flat_map(|x| (120..146).map(move |y| (x, y))).filter(|&(x, y)| rgba(&h, x, y)[3] == 0.0).count(); + assert!(cleared >= 20, "{tool:?}: erased along the drag, {cleared} pixels"); assert_eq!(last_stroke(h.state())["mode"], json!("clear"), "{tool:?}"); assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some(label)); assert_eq!(h.state().ui.tool, tool, "the tool stays"); @@ -1152,3 +1159,106 @@ fn command_or_alt_space_right_click_opens_no_view_menu() { } } } + +/// A right-click at `p` with Space already held (the Hand over the selected tool). +fn right_click_at(h: &mut Harness<'static, PhotocraftApp>, p: Pos2) { + h.event(Event::PointerMoved(p)); + h.run_steps(1); + h.event(Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +/// A pending crop frame on the Crop tool, as the held-key test above sets one up. +fn with_pending_crop(h: &mut Harness<'static, PhotocraftApp>) -> [f64; 4] { + let frame = [100.0, 50.0, 300.0, 200.0]; + h.state_mut().ui.crop_rect = Some(frame); + h.state_mut().crop.default_frame = false; + h.run_steps(2); + assert!(crate::crop_ui::pending(h.state())); + frame +} + +/// The Space-Hand view menu over a pending crop (#11271): Esc closes only the menu and Enter +/// commits nothing, as under the crop's own menu; with the menu closed Esc discards the crop. +#[test] +fn space_hand_view_menu_keeps_escape_and_enter_from_the_pending_crop() { + let mut h = harness(Tool::Crop); + let frame = with_pending_crop(&mut h); + let size = h.state().session.active().map(|s| s.doc.size); + let steps = h.state().session.active().map(|s| s.history.past_len()); + let p = screen(&h, 200.0, 125.0); + key(&mut h, Key::Space, true, Modifiers::NONE); + right_click_at(&mut h, p); + assert!( + h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_none() && crate::canvas_tool_menu::is_view_tool(m.tool)), + "Space's Hand opens the view menu" + ); + tap(&mut h, Key::Escape, Modifiers::NONE); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none(), "Esc closes the menu"); + assert_eq!(h.state().ui.crop_rect, Some(frame), "and only the menu: the crop is not discarded"); + assert!(crate::crop_ui::pending(h.state())); + right_click_at(&mut h, p); + assert!(h.state().ui.canvas_tool_menu.is_some(), "the view menu opens again"); + tap(&mut h, Key::Enter, Modifiers::NONE); + h.run_steps(2); + assert_eq!(h.state().session.active().map(|s| s.doc.size), size, "Enter under the menu doesn't crop"); + assert_eq!(h.state().session.active().map(|s| s.history.past_len()), steps, "no history step"); + assert_eq!(h.state().ui.crop_rect, Some(frame)); + // Close the menu and let Space go: Esc discards the pending crop as ever. + h.state_mut().ui.canvas_tool_menu = None; + key(&mut h, Key::Space, false, Modifiers::NONE); + h.run_steps(3); + tap(&mut h, Key::Escape, Modifiers::NONE); + h.run_steps(2); + assert!(!crate::crop_ui::pending(h.state()), "with no menu open Esc discards the crop"); +} + +/// Only a plain Esc and Enter are the view menu's (#11271): Ctrl+Alt+Enter dispatches with the menu +/// open (it leaves the menu open), and Esc with a tool key in one pass closes the menu and picks +/// the tool. +#[test] +fn space_hand_view_menu_reserves_only_plain_escape_and_enter() { + let mut h = harness(Tool::Move); + let p = screen(&h, 200.0, 125.0); + key(&mut h, Key::Space, true, Modifiers::NONE); + right_click_at(&mut h, p); + assert!(h.state().ui.canvas_tool_menu.is_some(), "Space's Hand opens the view menu"); + let mods = platform(Modifiers::COMMAND | Modifiers::ALT); + let steps = h.state().session.active().map(|s| s.history.past_len()); + h.input_mut() + .events + .extend([Event::ModifiersChanged(mods), Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: mods }]); + h.run_steps(2); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(1); + assert!(h.state().ui.canvas_tool_menu.is_some(), "a modified Enter leaves the menu open"); + assert_eq!(h.state().session.active().map(|s| s.history.past_len()), steps, "and changes nothing"); + h.input_mut().events.extend([ + Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }, + Event::Key { key: Key::B, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }, + ]); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none(), "Esc closes the menu"); + assert_eq!(h.state().ui.tool, Tool::Brush, "and B in the same pass still picks the Brush"); +} + +/// Space's Hand outside the image opens the pasteboard menu, which outlives the held Space and +/// closes when the tool underneath changes (#11271). +#[test] +fn space_hand_pasteboard_menu_opens_outside_the_image_and_outlives_space() { + let mut h = harness(Tool::Move); + let outside = screen(&h, -60.0, -60.0); + key(&mut h, Key::Space, true, Modifiers::NONE); + right_click_at(&mut h, outside); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "Space's Hand opens the pasteboard menu outside"); + assert_eq!(h.state().ui.tool, Tool::Move, "the Move tool stays selected"); + key(&mut h, Key::Space, false, Modifiers::NONE); + h.run_steps(3); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "the pasteboard menu outlives the held Space"); + h.state_mut().ui.tool = Tool::Brush; + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none(), "another tool selected closes it"); +} diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 158079ddf0..0628aa94f8 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -534,6 +534,20 @@ fn preflight_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { if app.ui.canvas_tool_menu.as_ref().is_some_and(|m| m.text || m.crop.is_some()) { return false; } + // The Space-Hand view menu (the menu of a view tool opened over another tool, #11271) takes a + // plain Esc and ↵ too: they don't cancel or commit a pending crop under it. Esc closes the + // menu here and both keys are withheld from the dispatch below; every other key, modified ↵ + // and tool keys included, dispatches as usual. + if app.ui.canvas_tool_menu.as_ref().is_some_and(|m| m.under.is_some() && crate::canvas_tool_menu::is_view_tool(m.tool)) { + let plain = |e: &egui::Event, k: egui::Key| matches!(e, egui::Event::Key { key, pressed: true, modifiers, .. } if *key == k && modifiers.is_none()); + let (esc, enter) = ctx.input(|i| (i.events.iter().any(|e| plain(e, egui::Key::Escape)), i.events.iter().any(|e| plain(e, egui::Key::Enter)))); + if esc { + app.ui.canvas_tool_menu = None; + } + if esc || enter { + ctx.input_mut(|i| i.events.retain(|e| !plain(e, egui::Key::Escape) && !plain(e, egui::Key::Enter))); + } + } let symmetry_editing = app.ui.symmetry_transform.is_some(); crate::symmetry_ui::track(app, ctx); if symmetry_editing && (app.ui.symmetry_transform.is_none() || egui::Popup::is_any_open(ctx)) { @@ -693,9 +707,11 @@ fn handle_pen_and_work_path_keys(app: &mut PhotocraftApp, ctx: &egui::Context, f // Backspace/Delete. Once the last anchor is removed, regular Undo works again. if app.ui.pen.as_ref().is_some_and(|pen| !pen.knots.is_empty()) { let mods = ctx.input(|i| i.modifiers); - let command_undo = effective_shortcut(app, "edit.undo", default_shortcut("edit.undo").as_deref()) - .and_then(|shortcut| parse(&shortcut)) - .is_some_and(|shortcut| consume(ctx, &shortcut)); + // Not while a Free Transform or Crop box owns Undo: Edit › Undo steps the box. + let command_undo = !crate::vector_ui::box_steps(app, "edit.undo") + && effective_shortcut(app, "edit.undo", default_shortcut("edit.undo").as_deref()) + .and_then(|shortcut| parse(&shortcut)) + .is_some_and(|shortcut| consume(ctx, &shortcut)); let remove = !mods.command && !mods.ctrl && !mods.shift @@ -837,7 +853,7 @@ fn handle_registry_and_tool_keys(app: &mut PhotocraftApp, ctx: &egui::Context, f } } if app.ui.frame_tool.drag.is_some() && pressed(Key::Escape) { - crate::frame_tool::cancel(app); + crate::frame_tool::escape(app); return true; } // Enter / Escape commit or cancel in-progress tool state (polygonal lasso, crop). @@ -893,6 +909,9 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { // Rotate View, Adaptive Wide Angle, the Filter Gallery, the TIFF prompt, any open egui popup // and the toolbar tool and "…" flyouts. A canvas drag in progress (a marquee being drawn) keeps it too. let esc_taken = app.drag.is_some() + // A Direct Selection drag (a Cmd-drag on an anchor) never reaches `app.drag`: Esc must not + // leave full screen or deselect pixels while its release is still to come (#13072). + || (app.ui.tool == Tool::DeleteAnchorPoint && app.ui.direct_selection.drag.is_some()) || app.ui.palette_open || app.ui.canvas_tool_menu.is_some() || app.ui.layer_menu.is_some() @@ -905,6 +924,17 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { || ctx.any_popup_open() || ctx.data(|d| d.get_temp::<(egui::Id, egui::Rect)>(egui::Id::unique("tool-flyout")).is_some()) || crate::panels::toolbar::more_flyout_open(ctx); + // Active operations and popups have already had priority. Reset a rotated view before + // idle Escape actions such as leaving full screen or deselecting; Rotate View handles its + // own Escape later, where it also clears an in-progress rotation drag. + if !esc_taken + && let Some(view) = app.session.active_index().and_then(|i| app.ui.views.get_mut(i)) + && view.rotation != 0.0 + && pressed(Key::Escape) + { + view.rotation = 0.0; + return; + } // Both full screen modes (with and without the menu bar) return to Standard, as in Photoshop // (#4116), through the menu command so the window and the Screen Mode check follow. if !esc_taken && app.ui.view.screen_mode != "standard" && pressed(Key::Escape) { @@ -921,22 +951,64 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { } return; } - // Delete Anchor Point (#12773): Esc first clears anchors selected on the saved path targeted in - // the Paths panel, then deselects that path, so clicks edit nothing. Not while its name is typed - // in the panel: egui has already dropped the field's focus, and the panel cancels on Esc. + // Delete Anchor Point (#12773): Esc first hides the anchors of the saved path targeted in the + // Paths panel, then deselects that path, so clicks edit nothing. The first Esc leaves the path + // targeted whether or not an anchor was selected (#13072), and clears only anchors selected on + // that path, never another path's. Not while its name is typed in the panel: egui has already + // dropped the field's focus, and the panel cancels on Esc. A Direct Selection drag keeps Esc + // away through `esc_taken` above, so its release still moves the anchors (#13072). if !esc_taken && app.ui.tool == Tool::DeleteAnchorPoint && !crate::vector_ui::path_renaming(app, ctx) && let Some((index, _)) = crate::vector_ui::selected_saved_path_index(app) { let ds = &app.ui.direct_selection; - let selected = ds.target == Some(crate::direct_select::PathRef::Saved(index)) && (!ds.anchors.is_empty() || ds.segment.is_some()); + let on_this_path = ds.target == Some(crate::direct_select::PathRef::Saved(index)); + let selected = on_this_path && (!ds.anchors.is_empty() || ds.segment.is_some()); if pressed(Key::Escape) { - if selected { - app.ui.direct_selection.anchors.clear(); - app.ui.direct_selection.segment = None; + // The stage belongs to this path: choosing another one starts at the first Esc again. + if selected || app.ui.direct_selection.escape_hidden != Some(index) { + if selected { + app.ui.direct_selection.anchors.clear(); + app.ui.direct_selection.segment = None; + } + app.ui.direct_selection.escape_hidden = Some(index); } else { app.ui.selected_path = None; + app.ui.direct_selection.escape_hidden = None; + } + return; + } + } + // Path Selection (#13287): with components of the saved path targeted in the Paths panel + // selected, Esc deselects the components and keeps the path targeted and drawn, while a plain + // Enter deselects the components and also untargets the path (its Paths panel row and outline + // go). Neither adds a History step. Free Transform Path and ⌘↩ (Make Selection) took their + // keys earlier; with no component selected both keys keep today's behaviour. Not while the + // path's name is typed in the panel. Only the bare keys: `consume_key` would also take them with + // ⇧ or ⌥, which were not measured. + let bare = |k: Key| { + ctx.input_mut(|i| { + let n = i.events.len(); + i.events.retain(|e| !matches!(e, egui::Event::Key { key, pressed: true, modifiers, .. } if *key == k && modifiers.is_none())); + i.events.len() != n + }) + }; + if !esc_taken + && app.ui.tool == Tool::PathSelection + && !crate::vector_ui::path_renaming(app, ctx) + && let Some((index, _)) = crate::vector_ui::selected_saved_path_index(app) + && let Some((crate::direct_select::PathRef::Saved(i), ..)) = crate::path_components::selected(app) + && i == index + { + if bare(Key::Escape) { + crate::path_components::deselect_components(app); + return; + } + if bare(Key::Enter) { + crate::path_components::deselect_components(app); + if let Some(name) = app.ui.selected_path.clone() { + crate::vector_ui::deselect_loaded_path(app, &name); } return; } diff --git a/crates/ui-egui/src/input/spring_tools.rs b/crates/ui-egui/src/input/spring_tools.rs index 5f51136cdb..e87ec56684 100644 --- a/crates/ui-egui/src/input/spring_tools.rs +++ b/crates/ui-egui/src/input/spring_tools.rs @@ -82,6 +82,12 @@ pub fn pressed(app: &mut PhotocraftApp, letter: char, before: Tool, plain: bool, app.ui.spring = (before.key() != letter).then(|| Spring { previous: before, tool, keys: vec![letter], since: now, used: false, released: false }); } +/// Is `tool` in effect only while its letter is held (or its drag finishes)? A tap that turns out +/// permanent has no spring left by then (`tick`). +pub fn holds(app: &PhotocraftApp, tool: Tool) -> bool { + app.ui.tool == tool && app.ui.spring.as_ref().is_some_and(|s| s.tool == tool) +} + /// The canvas was pressed: a held letter's tool becomes temporary. pub fn note_canvas_press(app: &mut PhotocraftApp) { if let Some(s) = app.ui.spring.as_mut().filter(|s| !s.released) { diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rs index e70f05d257..64106a057d 100644 --- a/crates/ui-egui/src/input_tests.rs +++ b/crates/ui-egui/src/input_tests.rs @@ -34,6 +34,45 @@ fn zoom(h: &Harness<'static, PhotocraftApp>) -> f32 { h.state().current_zoom() } +/// Check the bitmap contract, not merely that some custom cursor reached the backend. +fn assert_pipette(h: &Harness<'static, PhotocraftApp>) { + let output = &h.output().platform_output; + if cfg!(target_arch = "wasm32") || h.input().viewport_id != egui::ViewportId::ROOT { + assert_eq!(output.cursor_icon, egui::CursorIcon::None, "painted-only viewports hide the system cursor"); + assert!(output.cursor_image.is_none()); + let textures = h.ctx.tex_manager(); + let textures = textures.read(); + let pipettes: Vec<_> = h + .output() + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Mesh(mesh) => textures.meta(mesh.texture_id).filter(|meta| meta.name == "pc-pipette-icon").map(|meta| (mesh, meta)), + _ => None, + }) + .collect(); + assert_eq!(pipettes.len(), 1, "the canvas sampling caller paints one pipette, not just a hidden OS cursor"); + let (mesh, meta) = pipettes[0]; + let scale = h.output().pixels_per_point.clamp(0.5, 8.0); + let hot = (24.5 * scale + 1.0).ceil(); + assert_eq!(meta.size, [(2.0 * hot + 1.0) as usize; 2]); + let at = h.ctx.input_for(h.input().viewport_id, |i| i.pointer.hover_pos()).unwrap(); + let expected = egui::Rect::from_min_size(at - egui::Vec2::splat((hot + 0.5) / scale), egui::Vec2::splat(meta.size[0] as f32 / scale)); + assert!(mesh.calc_bounds().min.distance(expected.min) < 0.001, "the sampling tip follows the pointer"); + assert!(mesh.calc_bounds().max.distance(expected.max) < 0.001, "the artwork keeps its logical size"); + } else { + assert_eq!(output.cursor_icon, egui::CursorIcon::Crosshair, "visible fallback underneath the native pipette"); + let image = output.cursor_image.as_ref().expect("the pipette must reach the OS"); + let scale = if cfg!(target_os = "macos") { h.ctx.zoom_factor() } else { h.ctx.pixels_per_point() }; + // 23 logical points of reach, 1.5 of stroke padding, then one bitmap pixel for AA. + let hot = (24.5 * scale + 1.0).ceil() as u16; + assert_eq!(image.size, [2 * hot + 1; 2]); + assert_eq!(image.hotspot, [hot; 2]); + let i = (usize::from(hot) * usize::from(image.size[0]) + usize::from(hot)) * 4; + assert!(image.rgba[i + 3] > 230, "the SVG sampling tip occupies the hotspot"); + } +} + fn open_dialog(h: &mut Harness<'static, PhotocraftApp>) { crate::dialogs::open_command_dialog(h.state_mut(), "image.adjustments.brightnessContrast", "Brightness/Contrast…"); h.run_steps(3); @@ -260,6 +299,25 @@ fn picker_color(h: &Harness<'static, PhotocraftApp>) -> String { d.fields.get("color").and_then(serde_json::Value::as_str).unwrap().to_string() } +/// Check artwork and hotspot through the real canvas picker, not just the cursor renderer. +#[test] +fn color_picker_paints_a_pipette_on_a_high_dpi_child_canvas() { + let mut h = harness(); + let child = egui::ViewportId::from_hash_of("sampling-painted-pipette"); + h.input_mut().viewport_id = child; + h.input_mut().viewports.entry(child).or_default().native_pixels_per_point = Some(6.0); + h.run_steps(4); + crate::color_picker_ui::open(h.state_mut(), "foreground"); + h.run_steps(3); + h.hover_at(free_canvas(&h)); + h.run_steps(1); + assert_pipette(&h); + h.hover_at(h.state().last_canvas_rect.center()); + h.run_steps(1); + assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::None, "dialog controls release the painted pipette"); + assert!(h.output().platform_output.cursor_image.is_none()); +} + /// The Color Picker's eyedropper, as in Photoshop: over the image the pointer is a pipette, and a /// click or drag there samples into the picker's new colour, whatever the tool. OK applies it. #[test] @@ -279,10 +337,11 @@ fn color_picker_samples_the_image_under_its_pipette() { h.hover_at(red); h.run_steps(1); - assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::None, "the pipette replaces the pointer"); + assert_pipette(&h); h.hover_at(r.center()); h.run_steps(1); assert_ne!(h.output().platform_output.cursor_icon, egui::CursorIcon::None, "over the dialog it is the normal pointer"); + assert!(h.output().platform_output.cursor_image.is_none(), "dialog widgets must release the pipette"); // A click samples; the press and release may land in one frame (`ui.click`). h.hover_at(red); @@ -350,7 +409,7 @@ fn curves_picker_samples_document_coordinates_through_the_view_transform() { let left = pos2(canvas.left() + 60.0, canvas.center().y); h.hover_at(left); h.run_steps(1); - assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::None); + assert_pipette(&h); press(&mut h, left, true); press(&mut h, left, false); h.run_steps(3); @@ -663,7 +722,8 @@ fn a_notch_pans_the_canvas_at_once_without_a_glide() { let p = h.state().last_canvas_rect.center(); h.hover_at(p); h.run_steps(2); - let notch = h.ctx.options(|o| o.input_options.line_scroll_speed); + // The canvas' own notch (#12028), not egui's. + let notch = crate::wheel_nav::CANVAS_PAN_PER_LINE; let (z, c0) = (zoom(&h), h.state().ui.views[0].center); wheel(&h, -1.0, m); h.run_steps(1); @@ -1013,10 +1073,12 @@ fn eyedropper_and_alt_sampling_show_a_pipette() { h.output().platform_output.cursor_icon }; h.state_mut().ui.tool = crate::state::Tool::Eyedropper; - assert_eq!(cursor(&mut h), egui::CursorIcon::None, "the pipette replaces the pointer"); + cursor(&mut h); + assert_pipette(&h); h.state_mut().ui.tool = crate::state::Tool::Brush; h.event(egui::Event::ModifiersChanged(Modifiers::ALT)); - assert_eq!(cursor(&mut h), egui::CursorIcon::None, "⌥ samples with a pipette"); + cursor(&mut h); + assert_pipette(&h); h.state_mut().run("prefs.set", json!({"values": {"cursors.other": "precise"}})).unwrap(); // Every platform reports the crosshair. The desktop builds also hand the OS a black-and-white // bitmap for it (`tool_cursor`, #1160, #1343), with `Crosshair` underneath as the fallback. @@ -1051,15 +1113,15 @@ fn paint_bucket_shows_a_bucket_cursor() { let cursor = output.platform_output.cursor_image.as_ref().expect("native root viewport uses the unified bucket bitmap"); let [hot_x, hot_y] = cursor.hotspot; let hot_pixel = (usize::from(hot_y) * usize::from(cursor.size[0]) + usize::from(hot_x)) * 4 + 3; - assert_eq!(cursor.rgba[hot_pixel], 0, "the Gradient-style crosshair leaves its exact bitmap hotspot open"); + assert!(cursor.rgba[hot_pixel] > 128, "the arrow tip is drawn on the exact bitmap hotspot"); let side = usize::from(cursor.size[0]); assert!( cursor.rgba.as_chunks::<4>().0.iter().enumerate().any(|(i, pixel)| { let x = (i % side) as u16; let y = (i / side) as u16; - pixel[3] > 200 && x + 2 < hot_x && y + 2 < hot_y + pixel[3] > 200 && x > hot_x + 2 && y > hot_y + 2 }), - "the bucket artwork is opaque above-left of the same hotspot" + "the bucket artwork is opaque below-right of the same hotspot" ); assert!(!cursor_area_visible(&h, "pc-icon-cursor"), "native cursor has no frame-painted icon overlay"); assert!(!cursor_area_visible(&h, "pc-tool-cursor"), "native cursor does not create a painted cursor Area"); @@ -1189,12 +1251,14 @@ fn hand_pointer_over_the_canvas_under_a_dialog() { fn esc_ends_a_pen_path_and_keeps_it() { let mut h = harness(); h.state_mut().ui.tool = crate::state::Tool::Pen; + h.state_mut().ui.views[0].rotation = 40.0; let owner = crate::vector_ui::capture_pen_owner(h.state()); h.state_mut().ui.pen = Some(crate::vector_ui::PenPath { knots: vec![[[50.0, 50.0]; 3], [[150.0, 50.0]; 3], [[150.0, 120.0]; 3]], owner, ..Default::default() }); h.key_press(Key::Escape); h.run_steps(2); assert!(h.state().ui.pen.is_none(), "the Pen leaves drawing state"); + assert_eq!(h.state().ui.views[0].rotation, 40.0, "the active path owns Escape"); let doc = &h.state().session.active().unwrap().doc; let path = doc.work_path.as_ref().expect("the path is kept as the work path"); assert_eq!(path.subpaths.len(), 1); @@ -1233,6 +1297,27 @@ fn pen_shows_the_close_path_pointer_over_the_first_anchor() { assert_eq!(pointer(&mut h, 50.0, 50.0), close, "back on the first anchor"); } +/// A rotated view takes the first idle Esc; the next retains normal deselection. +#[test] +fn escape_resets_rotation_before_idle_deselection_for_paint_tools() { + for tool in [crate::state::Tool::Brush, crate::state::Tool::Pencil] { + let mut h = harness(); + h.state_mut().ui.tool = tool; + h.state_mut().ui.views[0].rotation = 40.0; + h.state_mut().run("select.all", json!({})).unwrap(); + h.run_steps(1); + let history = h.state().session.active().unwrap().history.entries().len(); + h.key_press(Key::Escape); + h.run_steps(2); + assert_eq!(h.state().ui.views[0].rotation, 0.0, "{tool:?}"); + assert!(h.state().session.active().unwrap().doc.selection.is_some(), "first Esc keeps the selection"); + assert_eq!(h.state().session.active().unwrap().history.entries().len(), history, "view reset is not an edit"); + h.key_press(Key::Escape); + h.run_steps(2); + assert!(h.state().session.active().unwrap().doc.selection.is_none(), "second Esc deselects normally"); + } +} + /// Esc with no active operation deselects (#2674), like ⌘D. #[test] fn escape_deselects_when_nothing_else_needs_cancelling() { @@ -1256,11 +1341,13 @@ fn escape_deselects_when_nothing_else_needs_cancelling() { fn escape_with_a_dialog_open_cancels_the_dialog_not_the_selection() { let mut h = harness(); h.state_mut().run("select.all", json!({})).unwrap(); + h.state_mut().ui.views[0].rotation = 40.0; open_dialog(&mut h); h.key_press(Key::Escape); h.run_steps(2); assert!(h.state().ui.dialogs.is_empty(), "Esc cancelled the dialog"); assert!(h.state().session.active().unwrap().doc.selection.is_some(), "the selection stays"); + assert_eq!(h.state().ui.views[0].rotation, 40.0, "the dialog owns the first Esc"); } /// The command palette owns Esc: it closes the palette and the selection stays. @@ -1505,3 +1592,47 @@ fn marquee_drag_after_hiding_extras_restores_selection_visibility() { h.state_mut().run("edit.fill", json!({"color": "#22cc44"})).unwrap(); assert!(!h.state().ui.view.extras, "painting an existing selection must preserve the user's hide choice"); } + +/// Text Color Picker hover must use a cached OS bitmap instead of an app-painted cursor. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn text_color_picker_pipette_is_native_cached_and_released_over_dialog() { + let mut h = harness(); + h.state_mut().run("type.create", json!({"text":"Cursor test","color":"#000000","size":24,"x":10,"y":60})).unwrap(); + h.state_mut().ui.tool = crate::state::Tool::Type; + let v = &mut h.state_mut().ui.views[0]; + (v.zoom, v.center, v.fit_pending) = (4.0, [200.0, 150.0], false); + crate::type_tool::open_color_picker(h.state_mut(), [0.0; 3]); + h.run_steps(3); + assert_eq!(h.state().ui.dialogs.last().unwrap().fields["__label"], "Color Picker (Text Color)"); + let r = h.state().last_canvas_rect; + let p = pos2(r.left() + 60.0, r.center().y); + h.hover_at(p); + h.run_steps(1); + assert_pipette(&h); + let image = h.output().platform_output.cursor_image.clone().unwrap(); + h.hover_at(p + vec2(20.0, 0.0)); + h.run_steps(1); + let moved = h.output().platform_output.cursor_image.as_ref().unwrap(); + assert!(std::sync::Arc::ptr_eq(&image.rgba, &moved.rgba), "pointer motion must reuse the OS cursor bitmap"); + + h.ctx.set_zoom_factor(1.5); + h.run_steps(3); + let r = h.state().last_canvas_rect; + h.hover_at(pos2(r.left() + 30.0, r.center().y)); + h.run_steps(1); + assert_pipette(&h); + let scaled = h.output().platform_output.cursor_image.as_ref().unwrap(); + assert_ne!(scaled.size, image.size, "UI scale change replaces the displayed bitmap"); + assert!(!std::sync::Arc::ptr_eq(&image.rgba, &scaled.rgba)); + + h.hover_at(r.center()); + h.run_steps(1); + assert!(h.output().platform_output.cursor_image.is_none(), "dialog widgets release the pipette"); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Default, "dialog keeps its arrow"); + h.key_press(Key::Escape); + h.run_steps(2); + assert!(h.state().ui.dialogs.is_empty()); + assert!(h.output().platform_output.cursor_image.is_none(), "Escape releases the pipette"); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Text, "the Type tool regains its I-beam"); +} diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index 7459f54be6..b0c4a6569c 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -766,7 +766,7 @@ pub(crate) fn after_open( name: &str, path: Option<&str>, warnings: &[String], - bytes: Option<&[u8]>, + bytes: Option<&Arc>>, ) -> Result<(), String> { let index = app.session.documents().iter().position(|st| st.doc.id == document).ok_or("the opened document is missing")?; app.session.set_active(index); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f674a47b7d..0b97cec93f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -261,11 +261,12 @@ pub(crate) use services::SAVE_OPTIONS_OPEN; #[cfg(test)] pub(crate) use services::saved_revision_after_write; pub use services::{ - AdoptAutosaveFn, AppendTextFn, AutomationCommandFn, AutomationOpenPcraftFn, AutomationReadFn, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn, - CaptionStyleFn, ClipboardGetFn, ClipboardGetSvgFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn, EncodePngFn, ExportFn, - ExportSettings, ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp, FileStampFn, FormatChoices, ImportFn, Inbox, - LastUpdateFn, LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PenEndFn, PenScreenFn, PhotoshopShortcutsFn, PlaceInbox, QuitFn, RecoverFn, - Recoverable, RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn, + AdoptAutosaveFn, AgentLink, AgentLinkFn, AgentLinkStatus, AppendTextFn, AutomationAuthorizeFn, AutomationCommandFn, AutomationOpenPcraftFn, + AutomationReadFn, AutomationServices, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn, CaptionStyleFn, ClipboardGetFn, ClipboardGetSvgFn, + ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn, EncodePngFn, ExportFn, ExportSettings, ExternalSvgEditor, ExternalSvgSession, + ExternalVectorSave, ExternalVectorSource, FileStamp, FileStampFn, FormatChoices, ImportFn, Inbox, LastUpdateFn, LoadTextFn, OpenExternalSvgFn, OpenUrlFn, + OsEventsFn, PenEndFn, PenScreenFn, PhotoshopShortcutsFn, PlaceInbox, QuitFn, RecoverFn, Recoverable, RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, + Services, SystemThemeFn, TabletPollFn, WindowFrameFn, WriteFn, }; pub(crate) use services::{opaque_layer, saves_flat_in_place}; pub use text::bidi_text; @@ -459,6 +460,8 @@ pub struct PhotocraftApp { /// The first digit of a two-digit opacity typed on the number keys (`opacity_keys`, #352). pub(crate) opacity_keys: opacity_keys::Pending, control_rx: Option>, + /// Preferences › AI Integrations: the agent connection's state (see [`Services::agent_link`]). + pub agent_link: AgentLinkStatus, /// `ui.screenshot` requests: bounded admission, a weak-slot callback per issuance, monotonic /// deadlines and a capture-time geometry epoch (see `screenshot.rs`). captures: screenshot::Captures, @@ -592,6 +595,10 @@ pub struct PhotocraftApp { pub(crate) hist_job: Option, /// The (document, revision) an Uncached Refresh asked to count at cache level 1. pub(crate) hist_uncached: Option<(DocId, u64)>, + /// Memoized `tone::selection_key` of the active document's current revision + /// (`histogram_panel::update` refreshes it once per frame; the hash walks every tile of the + /// selection mask, while any change to the selection arrives as a new document revision). + pub(crate) hist_sel_key: Option<(DocId, u64, u64)>, /// Free Transform preview (document without the moving pixels + their texture). pub(crate) transform_preview: Option, /// The canvas area the last Free Transform box's preview changes (`transform_tool::damage`). @@ -665,6 +672,9 @@ pub struct PhotocraftApp { pub(crate) guide_drag: Option, /// Move tool marquee selecting layers (`move_box`). pub(crate) layer_box: Option, + /// Pen paths finished, which Undo back to their finish gives back to the Pen + /// (`vector_ui::pen_resume_on_undo`). + pub(crate) finished_pens: Vec, /// Crop tool gesture in progress (see `crop_ui`). pub(crate) crop: crop_ui::CropState, /// Perspective Crop tool gesture and clicked corners (see `perspective_crop_ui`). @@ -802,6 +812,8 @@ mod cam_no_pixels_alert_tests; #[cfg(test)] mod eyedropper_context_menu_tests; #[cfg(test)] +mod menu_automate_groups_tests; +#[cfg(test)] mod patch_shift_constrain_tests; #[cfg(test)] mod pencil_pressure_toggles_tests; @@ -872,6 +884,8 @@ mod transform_fx_tests; #[cfg(test)] mod transform_commit_click_tests; +#[cfg(test)] +mod transform_drag_start_tests; #[cfg(test)] mod layer_props_ui_tests; @@ -1028,6 +1042,10 @@ mod status_bar_tests; #[cfg(test)] mod stroke_timing_tests; +#[cfg(test)] +mod cam_reset_tool_mode_tests; +#[cfg(test)] +mod patch_reset_tool_tests; #[cfg(test)] mod patch_tool_history_names_tests; #[cfg(test)] @@ -1064,6 +1082,8 @@ mod background_eraser_bar_angle_tests; #[cfg(test)] mod brush_alt_digit_smoothing_tests; #[cfg(test)] +mod brush_hud_rate_tests; +#[cfg(test)] mod brush_opacity_minimum_tests; #[cfg(test)] mod burn_default_tip_tests; @@ -1091,3 +1111,13 @@ mod background_eraser_digit_keys_tests; #[cfg(test)] mod clone_stamp_reset_tip_tests; +#[cfg(test)] +mod smudge_default_tip_tests; +#[cfg(test)] +mod sponge_default_tip_tests; + +#[cfg(test)] +mod red_eye_context_menu_tests; + +#[cfg(test)] +mod clone_stamp_indexed_bar_tests; diff --git a/crates/ui-egui/src/marquee_tests.rs b/crates/ui-egui/src/marquee_tests.rs index 5a42aab0fc..d0087e55e3 100644 --- a/crates/ui-egui/src/marquee_tests.rs +++ b/crates/ui-egui/src/marquee_tests.rs @@ -188,6 +188,8 @@ fn object_selection_keeps_the_mode_from_the_mouse_press() { let sel = app.session.active().unwrap().doc.selection.as_ref().expect("the old selection survives outside the object"); assert!(sel.sample_channel(20, 20, 0) > 0.99, "the gesture must preserve selection outside the object"); assert_eq!(sel.sample_channel(220, 150, 0) > 0.5, !at_press.alt, "the disc follows the requested mode"); + // From no selection: a New-mode click inside the selection deselects (#12853). + h.state_mut().run("select.deselect", json!({})).unwrap(); mods(&mut h, Modifiers::NONE); move_to(&mut h, 220.0, 150.0); let next = screen(&h, 220.0, 150.0); diff --git a/crates/ui-egui/src/menu_automate_groups_tests.rs b/crates/ui-egui/src/menu_automate_groups_tests.rs new file mode 100644 index 0000000000..22574058a2 --- /dev/null +++ b/crates/ui-egui/src/menu_automate_groups_tests.rs @@ -0,0 +1,22 @@ +//! File > Automate groups its rows with separators as the reference application does (#13704). + +use crate::menu_catalog::CATALOG; + +#[test] +fn automate_rows_fall_into_the_measured_separator_groups() { + let mut groups: Vec> = vec![Vec::new()]; + for row in CATALOG.iter().filter(|r| r.0 == ["File", "Automate"]) { + if row.3 == "---" { + groups.push(Vec::new()); + } else if let Some(last) = groups.last_mut() { + last.push(row.3.trim_start_matches("file.automate.")); + } + } + let expected: Vec> = vec![ + vec!["batch", "createDroplet"], + vec!["cropAndStraightenPhotos"], + vec!["contactSheetII"], + vec!["conditionalModeChange", "fitImage", "lensCorrection", "mergeToHdrPro", "photomerge"], + ]; + assert_eq!(groups, expected); +} diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs index d6db835eab..b4bf26a64e 100644 --- a/crates/ui-egui/src/menu_catalog.rs +++ b/crates/ui-egui/src/menu_catalog.rs @@ -45,11 +45,12 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["File", "Automate"], "Create Droplet…", None, "file.automate.createDroplet"), (&["File", "Automate"], "---", None, "---"), (&["File", "Automate"], "Crop and Straighten Photos", None, "file.automate.cropAndStraightenPhotos"), + (&["File", "Automate"], "---", None, "---"), (&["File", "Automate"], "Contact Sheet II…", None, "file.automate.contactSheetII"), + (&["File", "Automate"], "---", None, "---"), (&["File", "Automate"], "Conditional Mode Change…", None, "file.automate.conditionalModeChange"), (&["File", "Automate"], "Fit Image…", None, "file.automate.fitImage"), (&["File", "Automate"], "Lens Correction…", None, "file.automate.lensCorrection"), - (&["File", "Automate"], "---", None, "---"), (&["File", "Automate"], "Merge to HDR Pro…", None, "file.automate.mergeToHdrPro"), (&["File", "Automate"], "Photomerge…", None, "file.automate.photomerge"), (&["File", "Scripts"], "Image Processor…", None, "file.scripts.imageProcessor"), diff --git a/crates/ui-egui/src/menus/enable_rules.rs b/crates/ui-egui/src/menus/enable_rules.rs index a13d9059fe..d9995a83bd 100644 --- a/crates/ui-egui/src/menus/enable_rules.rs +++ b/crates/ui-egui/src/menus/enable_rules.rs @@ -1,6 +1,7 @@ //! Photoshop menu enablement the engine's per-command checks don't express: the Background layer -//! (no styles, masks, clipping, arranging, transforms without a selection), layer-kind specific -//! items (Rasterize ›, Combine Shapes ›), and single-layer documents (Merge Visible, Flatten Image). +//! (no styles, masks, clipping, arranging, grouping, transforms without a selection), layer-kind +//! specific items (Rasterize ›, Combine Shapes ›), and single-layer documents (Merge Visible, +//! Flatten Image, Load Selection without a saved selection). //! Applied on top of `menus::is_enabled`, so menus, shortcuts and the Layers context menu grey the //! same items Photoshop greys. @@ -27,6 +28,8 @@ fn background_blocks(id: &str, has_selection: bool) -> bool { "layer.createClippingMask" | "layer.releaseClippingMask" | "layer.mergeDown" + // The Background can't go into a group (#12866, measured on the canvas menu). + | "layer.new.groupFromLayers" | "layer.lockLayers" | "layer.maskAllObjects" | "edit.puppetWarp" @@ -60,6 +63,12 @@ pub fn disabled_for(doc: &Document, active: Option<&Layer>, id: &str) -> bool { if only_background && matches!(id, "layer.mergeVisible" | "layer.flattenImage" | "layer.mergeLayers" | "layer.rasterize.allLayers") { return true; } + // A lone Background has no transparency or mask to load: Load Selection waits for a saved + // selection or Quick Mask (#13293). The command itself still loads the colour channels, as a + // Ctrl-click on a channel does. + if only_background && id == "select.loadSelection" && doc.channels.is_empty() && doc.quick_mask.is_none() { + return true; + } if id == "layer.delete.hiddenLayers" && doc.walk().iter().all(|(_, _, l)| l.visible) { return true; } @@ -104,6 +113,11 @@ fn selection_targets(id: &str) -> Option { /// runs on all of them is greyed only when none of them can take it (the active layer alone must /// not decide). Everything else, and a single selected layer, is judged by the active layer. pub fn disabled_for_selection(doc: &Document, selected: &[LayerId], active: Option<&Layer>, id: &str) -> bool { + // The reference application refuses Group from Layers whenever the Background is among the + // selected layers, not only when it is the active one. + if id == "layer.new.groupFromLayers" && selected.iter().filter_map(|l| doc.layer(*l)).any(|l| crate::doc_props_ui::is_background(doc, l)) { + return true; + } let Some(rule) = selection_targets(id).filter(|_| selected.len() > 1) else { return disabled_for(doc, active, id) }; let layers = selected.iter().filter_map(|l| doc.layer(*l)); let can = |l: &Layer| !disabled_for(doc, Some(l), id) && (!matches!(rule, Targets::WithoutMask) || l.mask.is_none()); @@ -117,6 +131,25 @@ pub fn disabled_for_selection(doc: &Document, selected: &[LayerId], active: Opti pub fn disabled(app: &crate::PhotocraftApp, id: &str) -> bool { let Some(st) = app.session.active() else { return false }; let active = st.active_layer.and_then(|a| st.doc.layer(a)); + // The split warps edit the open Warp box's grid, or a smart object's stored warp: without + // either there is no grid to split (#12494). + if matches!( + id, + "edit.transform.splitWarpCrosswise" | "edit.transform.splitWarpHorizontally" | "edit.transform.splitWarpVertically" | "edit.transform.removeWarpSplit" + ) && !crate::transform_tool::warps_active_layer(app) + { + return true; + } + // Remove Warp Split takes out a split line of the open grid; with none (a single patch, as + // the engine's `Split::Remove` sees it) there is nothing to remove. + if id == "edit.transform.removeWarpSplit" + && app.ui.transform.as_ref().and_then(|t| t.warp.as_ref()).is_some_and(|w| { + let m = w.to_mesh(1, 1); + m.us.len() <= 2 && m.vs.len() <= 2 + }) + { + return true; + } // Free Transform Path works on the Background too: it moves the path, not the pixels. let transform = id == "edit.freeTransform" || (id.starts_with("edit.transform.") && id != "edit.transform.again"); if transform && crate::vector_ui::free_transform_path(app).is_some() { @@ -167,7 +200,7 @@ pub fn disabled(app: &crate::PhotocraftApp, id: &str) -> bool { return true; } // Only these commands depend on the selection; skip walking the layers for the rest. - if selection_targets(id).is_some() { + if selection_targets(id).is_some() || id == "layer.new.groupFromLayers" { return disabled_for_selection(&st.doc, &st.selected_layers(), active, id); } disabled_for(&st.doc, active, id) @@ -406,6 +439,51 @@ mod tests { assert!(!disabled(&app, "edit.transform.warp"), "an unlinked layer warps"); } + /// #13293: on a lone Background, Group from Layers… and Load Selection… are greyed, as in the + /// reference. A pixel selection doesn't change that; a saved selection enables Load Selection…. + #[test] + fn a_lone_background_greys_group_from_layers_and_load_selection() { + let mut app = crate::PhotocraftApp::new(session(), crate::Services::default()); + for id in ["layer.new.groupFromLayers", "select.loadSelection"] { + assert!(!crate::menus::is_enabled(&app, id), "{id} is greyed on a lone Background"); + } + app.session.execute("select.rect", json!({"x": 2, "y": 2, "width": 8, "height": 8})).unwrap(); + for id in ["layer.new.groupFromLayers", "select.loadSelection"] { + assert!(!crate::menus::is_enabled(&app, id), "{id} is greyed with a pixel selection"); + } + app.session.execute("select.saveSelection", json!({"name": "Keep"})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + assert!(crate::menus::is_enabled(&app, "select.loadSelection"), "a saved selection can be loaded"); + assert!(!crate::menus::is_enabled(&app, "layer.new.groupFromLayers"), "the Background still can't be grouped"); + // The command itself still loads, as a Ctrl-click on a channel does. + let mut s = session(); + s.execute("select.loadSelection", json!({"channel": "red"})).unwrap(); + } + + /// #13293: where they apply, both rows stay live: a plain layer, and a document with more than + /// the Background or with Quick Mask on. Group from Layers… stays greyed whenever the Background + /// is among the selected layers (#12866). + #[test] + fn group_from_layers_and_load_selection_stay_live_where_they_apply() { + let mut s = session(); + let bg = s.active().unwrap().doc.layers[0].id; + let layer = photocraft_doc::LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + let mut app = crate::PhotocraftApp::new(s, crate::Services::default()); + let on = |app: &crate::PhotocraftApp, id: &str| crate::menus::is_enabled(app, id); + assert!(on(&app, "layer.new.groupFromLayers") && on(&app, "select.loadSelection"), "a plain layer"); + app.session.execute("layer.select", json!({"layer": bg.0, "mode": "add"})).unwrap(); + assert_eq!(app.session.active().unwrap().selected_layers().len(), 2); + assert!(!on(&app, "layer.new.groupFromLayers"), "the Background with another layer selected (#12866)"); + app.session.execute("layer.select", json!({"layer": bg.0})).unwrap(); + assert!(!on(&app, "layer.new.groupFromLayers"), "the Background alone"); + assert!(on(&app, "select.loadSelection"), "another layer's transparency can be loaded"); + app.session.execute("layer.select", json!({"layer": layer.0})).unwrap(); + app.session.execute("layer.delete", json!({})).unwrap(); + assert!(!on(&app, "select.loadSelection")); + app.session.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + assert!(on(&app, "select.loadSelection"), "Quick Mask keeps today's state"); + } + #[test] fn ordinary_layers_keep_their_items() { let mut s = session(); @@ -417,3 +495,7 @@ mod tests { assert!(off(&s, "layer.layerStyle.copyLayerStyle")); } } + +#[cfg(test)] +#[path = "warp_split_enable_tests.rs"] +mod warp_split_enable_tests; diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 4d94412ebe..3471e4404e 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -106,6 +106,9 @@ fn frame_convert_dialog(app: &mut PhotocraftApp, id: &str) -> Result Option> { if let Some(tool) = crate::tool_shortcuts::tool(id) { crate::tool_memory::select(app, tool); + // The tool's own brush now, not at the next frame, so a paint command right after uses + // it: a first Pencil pick its 1 px tip (#12200), any other tool its remembered brush. + crate::paint_mouse::sync_tool_brush(app); return Some(Ok(json!({"tool": tool}))); } if id == "layer.frame.convert" && params.as_object().is_none_or(|o| o.is_empty()) { @@ -132,9 +135,12 @@ fn invoke_early_commands(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, if let Some(r) = crate::rasterize_prompt::intercept_filter(app, id, params) { return Some(r); } - // A pending Pen anchor is gesture state; Edit › Undo must match the keyboard. - if id == "edit.undo" && crate::vector_ui::pen_undo_last_point(app) { - return Some(Ok(Value::Null)); + // A pending Pen anchor is gesture state; Edit › Undo must match the keyboard. Undo back to + // where a Pen path was finished (closed, ↩/Esc, another tool) gives the path back to the Pen + // rather than deleting it; Redo finishes it again. Step Backward/Forward step the same way. + // An open Free Transform or Crop box steps itself first. + if let Some(r) = crate::vector_ui::pen_history_step(app, id) { + return Some(r.map(|_| Value::Null)); } // Image › Crop while the Crop tool has a pending frame commits that frame (#1918). if id == "image.crop" && crate::crop_ui::pending(app) { diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 1b814c27e1..e4bdc7a66c 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -12,9 +12,10 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool { if id == "ui.symmetryTransform" { return crate::symmetry_ui::can_transform(app); } - // Draft Pen points can be undone even when the document has no History entries. - if id == "edit.undo" && app.ui.pen.as_ref().is_some_and(|pen| !pen.knots.is_empty()) { - return true; + // Draft Pen points can be undone even when the document has no History entries; Redo would + // put a finished Pen path back beside its own edited draft. Step Backward/Forward alike. + if let Some(on) = crate::vector_ui::pen_history_enabled(app, id) { + return on; } // Photoshop greys these for the Background layer, other layer kinds or single-layer documents. if crate::enable_rules::disabled(app, id) { diff --git a/crates/ui-egui/src/menus/warp_split_enable_tests.rs b/crates/ui-egui/src/menus/warp_split_enable_tests.rs new file mode 100644 index 0000000000..84ca3a4175 --- /dev/null +++ b/crates/ui-egui/src/menus/warp_split_enable_tests.rs @@ -0,0 +1,135 @@ +//! Edit › Transform's split warp entries follow the Warp box (#12494): greyed with none open, +//! enabled in one. A warped smart object keeps them, and several layers, a link group and +//! editable type still grey them. + +use photocraft_doc::{LayerContent, LayerId}; +use serde_json::json; + +use crate::PhotocraftApp; + +const SPLITS: [&str; 3] = ["edit.transform.splitWarpCrosswise", "edit.transform.splitWarpHorizontally", "edit.transform.splitWarpVertically"]; +const REMOVE: &str = "edit.transform.removeWarpSplit"; + +fn four() -> impl Iterator { + SPLITS.into_iter().chain([REMOVE]) +} + +/// A 100 × 100 document with a pixel layer "Paint" holding a red block, active. +fn app() -> (PhotocraftApp, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 100, "height": 100, "background": "white"})).unwrap(); + app.sync_views(); + let paint = LayerId(app.run("layer.new.layer", json!({"name": "Paint"})).unwrap()["layer"].as_u64().unwrap()); + app.run("select.rect", json!({"x": 10, "y": 10, "width": 50, "height": 30})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + (app, paint) +} + +/// The Edit › Transform row's state as the menu builds it. +fn enabled(app: &PhotocraftApp, id: &str) -> bool { + let row = crate::menus::menu_items(app).into_iter().find(|i| i.path == ["Edit", "Transform"] && i.id == id); + row.unwrap_or_else(|| panic!("{id} is in Edit › Transform")).enabled +} + +fn choose(app: &mut PhotocraftApp, id: &str) -> Result { + crate::menus::invoke(app, &egui::Context::default(), id, json!({})) +} + +fn warped_smart_object(app: &mut PhotocraftApp) { + app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + app.run("layer.smartObjects.warp", json!({"style": "arc", "bend": 30, "rect": [10, 10, 60, 40]})).unwrap(); + assert!(crate::transform_tool::warps_active_layer(app), "the smart object has a stored warp"); +} + +fn stored_warp(app: &PhotocraftApp) -> Option { + let st = app.session.active().unwrap(); + match &st.doc.layer(st.active_layer.unwrap()).unwrap().content { + LayerContent::Smart(sm) => sm.warp.clone(), + _ => None, + } +} + +#[test] +fn the_split_entries_are_greyed_until_warp_opens() { + let (mut app, _) = app(); + for id in four() { + assert!(!enabled(&app, id), "{id} is greyed with no Warp box"); + } + choose(&mut app, "edit.transform.warp").unwrap(); + assert!(app.ui.transform.as_ref().is_some_and(|t| t.warp.is_some()), "Warp is open"); + for id in SPLITS { + assert!(enabled(&app, id), "{id} is enabled in Warp"); + } + assert!(!enabled(&app, REMOVE), "a fresh grid has no split line to remove"); + let before = app.ui.transform.as_ref().and_then(|t| t.warp.clone()); + choose(&mut app, "edit.transform.splitWarpCrosswise").unwrap(); + assert_ne!(app.ui.transform.as_ref().and_then(|t| t.warp.clone()), before, "the menu's split cuts the open grid"); + assert!(enabled(&app, REMOVE), "the new split line can be removed"); + crate::transform_tool::cancel(&mut app); + assert!(app.ui.transform.is_none()); + for id in four() { + assert!(!enabled(&app, id), "{id} is greyed again once Warp closes"); + } +} + +/// Only the menu greys: the commands with the warp passed inline still run without a Warp box. +#[test] +fn inline_warp_commands_run_without_a_warp_box() { + let (mut app, _) = app(); + let warp = json!({"style": "bulge", "bend": 30.0, "bounds": [10.0, 10.0, 60.0, 40.0]}); + let at = json!([30.0, 20.0]); + for id in ["edit.transform.splitWarpHorizontally", "edit.transform.splitWarpVertically"] { + let r = app.run(id, json!({"warp": warp, "at": at})).unwrap(); + assert!(r["warp"]["mesh"].is_object(), "{id} returns the split mesh"); + } + // The control channel's `ui.menu.invoke` path. + let ctx = egui::Context::default(); + let split = crate::menus::invoke(&mut app, &ctx, "edit.transform.splitWarpCrosswise", json!({"warp": warp, "at": at})).unwrap()["warp"].clone(); + assert!(split["mesh"].is_object(), "Split Warp Crosswise returns the split mesh"); + let r = crate::menus::invoke(&mut app, &ctx, REMOVE, json!({"warp": split, "at": at})).unwrap(); + assert!(r["warp"]["mesh"].is_object(), "Remove Warp Split returns the mesh"); +} + +#[test] +fn a_warped_smart_object_keeps_the_split_entries() { + let (mut app, _) = app(); + warped_smart_object(&mut app); + for id in four() { + assert!(enabled(&app, id), "{id} stays enabled on a warped smart object"); + } + let before = stored_warp(&app); + choose(&mut app, "edit.transform.splitWarpCrosswise").unwrap(); + assert!(app.ui.transform.is_none(), "the split edits the stored warp, without a box"); + assert_ne!(stored_warp(&app), before, "the smart object's stored warp is split"); +} + +#[test] +fn several_layers_a_link_group_and_type_still_grey_them() { + let (mut app, paint) = app(); + let other = LayerId(app.run("layer.new.layer", json!({"name": "Other"})).unwrap()["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": paint.0})).unwrap(); + warped_smart_object(&mut app); + let smart = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.select", json!({"layer": other.0, "mode": "add"})).unwrap(); + for id in four() { + assert!(!enabled(&app, id), "{id} is greyed for several layers"); + } + assert_eq!(app.run("layer.linkLayers", json!({})).unwrap()["linked"], true); + app.run("layer.select", json!({"layer": smart.0})).unwrap(); + for id in four() { + assert!(!enabled(&app, id), "{id} is greyed for a layer of a link group"); + } + app.run("layer.linkLayers", json!({"linked": false})).unwrap(); + for id in four() { + assert!(enabled(&app, id), "{id} is back once the layer is unlinked"); + } + + let text = LayerId(app.run("type.create", json!({"x": 20, "y": 80, "text": "Hi", "size": 20})).unwrap()["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": text.0})).unwrap(); + choose(&mut app, "edit.transform.warp").unwrap(); + assert!(app.ui.transform.as_ref().is_some_and(|t| t.warp.is_some()), "Warp is open on the type"); + for id in four() { + assert!(!enabled(&app, id), "{id} is greyed for editable type in Warp"); + } +} diff --git a/crates/ui-egui/src/mixer_cursor_tests.rs b/crates/ui-egui/src/mixer_cursor_tests.rs new file mode 100644 index 0000000000..90662efdeb --- /dev/null +++ b/crates/ui-egui/src/mixer_cursor_tests.rs @@ -0,0 +1,205 @@ +//! The Mixer Brush's cursors (#11957): with ⌥ held, the reference's sample target (a small circle +//! with a crosshair, hotspot at its centre) instead of the Eyedropper's pipette, and no comparison +//! ring while an ⌥-click is held; over a layer with Lock All, a no-entry sign. The Brush keeps its +//! ⌥ pipette. The cursors are OS bitmaps: their hotspot sits at the bitmap's centre, the target is +//! mirror-symmetric left to right and the no-entry sign is not (its bar runs corner to corner). + +use egui::{Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +pub(super) fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.sync_views(); + app.ui.extras.rulers = false; + app.ui.tool = tool; + crate::paint_mouse::sync_tool_brush(&mut app); + let mut h = Harness::builder().with_size(vec2(900.0, 600.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + v.zoom = 1.0; + v.center = [200.0, 150.0]; + v.fit_pending = false; + h.run_steps(2); + h +} + +pub(super) fn has_fonts(h: &Harness<'static, PhotocraftApp>) -> bool { + h.ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) +} + +pub(super) fn centre(h: &Harness<'static, PhotocraftApp>) -> Pos2 { + h.state().last_canvas_rect.center() +} + +pub(super) fn hover(h: &mut Harness<'static, PhotocraftApp>, m: Modifiers) { + h.event(egui::Event::ModifiersChanged(m)); + let p = centre(h); + h.hover_at(p); + h.run_steps(2); +} + +/// The Eyedropper's pipette: the OS bitmap where one uploads, else drawn (#12523). +fn pipette_shown(h: &Harness<'static, PhotocraftApp>) -> bool { + crate::tool_cursor::pipette_shown(&h.ctx, &h.output().platform_output) +} + +/// An OS cursor bitmap's size, hotspot and alpha channel. +pub(super) type Bitmap = ([u16; 2], [u16; 2], Vec); + +/// The OS cursor bitmap's size, hotspot and alpha channel. +pub(super) fn bitmap(h: &Harness<'static, PhotocraftApp>) -> Option { + h.output().platform_output.cursor_image.as_ref().map(|i| (i.size, i.hotspot, i.rgba.as_chunks::<4>().0.iter().map(|p| p[3]).collect())) +} + +/// Whether a line passes through the hotspot: its pixel or the one to its left, as a 1 px line +/// centred on the hotspot may land on either at an even scale. +pub(super) fn hotspot_drawn((size, hotspot, alpha): &Bitmap) -> bool { + let (w, hx, hy) = (usize::from(size[0]), usize::from(hotspot[0]), usize::from(hotspot[1])); + alpha[hy * w + hx] > 0 || alpha[hy * w + hx.saturating_sub(1)] > 0 +} + +/// The share of pixels whose alpha differs (by more than a quarter) from the pixel `mirror` maps +/// them to. +fn asymmetry(size: [u16; 2], alpha: &[u8], mirror: impl Fn(usize, usize) -> (usize, usize)) -> f32 { + let (w, h) = (usize::from(size[0]), usize::from(size[1])); + let mut off = 0; + for y in 0..h { + for x in 0..w { + let (mx, my) = mirror(x, y); + if alpha[y * w + x].abs_diff(alpha[my * w + mx]) > 64 { + off += 1; + } + } + } + off as f32 / (w * h) as f32 +} + +/// Whether the Eyedropper's comparison ring is painted: its circles have the ring's 17 pt band. +fn ring_drawn(h: &Harness<'static, PhotocraftApp>) -> bool { + fn ring(shape: &egui::Shape) -> bool { + match shape { + egui::Shape::Circle(c) => (c.stroke.width - 17.0).abs() < 0.5 && c.radius > 50.0, + egui::Shape::Vec(shapes) => shapes.iter().any(ring), + _ => false, + } + } + h.output().shapes.iter().any(|c| ring(&c.shape)) +} + +pub(super) fn assert_centred(size: [u16; 2], hotspot: [u16; 2], what: &str) { + for k in 0..2 { + assert!((f32::from(hotspot[k]) - f32::from(size[k]) / 2.0).abs() <= 1.0, "{what}: hotspot {hotspot:?} in a {size:?} bitmap"); + } +} + +#[test] +fn alt_shows_the_sample_target_and_no_ring_while_held() { + let mut h = harness(Tool::MixerBrush); + if !has_fonts(&h) { + return; + } + hover(&mut h, Modifiers::ALT); + assert!(!pipette_shown(&h), "no pipette"); + let target = bitmap(&h).expect("the sample target is an OS cursor bitmap"); + let (size, hotspot, alpha) = ⌖ + assert_centred(*size, *hotspot, "sample target"); + let w = usize::from(size[0]); + assert!(asymmetry(*size, alpha, |x, y| (w - 1 - x, y)) < 0.02, "the target is symmetric left to right"); + assert!(hotspot_drawn(&target), "the crosshair passes through the hotspot"); + let target = Some(target); + // An ⌥-click held: still the target, no comparison ring. + let p = centre(&h); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::ALT }); + h.run_steps(2); + assert!(h.state().mixer_sampling, "the ⌥-click is held and loads"); + assert_eq!(bitmap(&h), target, "the target stays while the ⌥-click is held"); + assert!(!pipette_shown(&h)); + assert!(!ring_drawn(&h), "no comparison ring"); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::ALT }); + h.run_steps(2); +} + +#[test] +fn a_locked_layer_shows_the_no_entry_sign() { + let mut h = harness(Tool::MixerBrush); + if !has_fonts(&h) { + return; + } + hover(&mut h, Modifiers::NONE); + let tip = bitmap(&h); + h.state_mut().run("layer.lockLayers", json!({"all": true})).unwrap(); + hover(&mut h, Modifiers::NONE); + let (size, hotspot, alpha) = bitmap(&h).expect("the no-entry sign is an OS cursor bitmap"); + assert_ne!(Some((size, hotspot, alpha.clone())), tip, "not the brush tip"); + assert_centred(size, hotspot, "no-entry sign"); + let w = usize::from(size[0]); + assert!(asymmetry(size, &alpha, |x, y| (y, x)) < 0.02, "the bar runs corner to corner"); + assert!(asymmetry(size, &alpha, |x, y| (w - 1 - x, y)) > 0.02, "a sign, not the sample target"); + // Unlocked again: the brush tip. + h.state_mut().run("layer.lockLayers", json!({"all": false})).unwrap(); + hover(&mut h, Modifiers::NONE); + assert_eq!(bitmap(&h), tip); +} + +#[test] +fn the_brush_keeps_its_alt_pipette() { + let mut h = harness(Tool::Brush); + if !has_fonts(&h) { + return; + } + hover(&mut h, Modifiers::ALT); + assert!(pipette_shown(&h), "the Brush's ⌥ is the Eyedropper's pipette"); +} + +/// The Brush's held ⌥-click still shows the Eyedropper's comparison ring around its pipette, so +/// the ring test above can see one. +#[test] +fn the_brush_shows_its_ring_while_an_alt_click_is_held() { + let mut h = harness(Tool::Brush); + if !has_fonts(&h) { + return; + } + hover(&mut h, Modifiers::ALT); + assert!(!ring_drawn(&h), "no ring on hover"); + let p = centre(&h); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::ALT }); + h.run_steps(2); + assert!(h.state().alt_sampling, "the Brush's ⌥-click samples"); + assert!(ring_drawn(&h), "the comparison ring"); + assert!(pipette_shown(&h)); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::ALT }); + h.run_steps(2); +} + +/// Other Cursors = Precise wasn't measured with the Mixer Brush's ⌥, so it keeps today's precise +/// crosshair rather than the sample target. +#[test] +fn precise_other_cursors_keep_the_crosshair_with_alt() { + let mut h = harness(Tool::MixerBrush); + if !has_fonts(&h) { + return; + } + hover(&mut h, Modifiers::ALT); + let target = bitmap(&h).expect("the sample target"); + h.state_mut().run("prefs.set", json!({"values": {"cursors.other": "precise"}})).unwrap(); + hover(&mut h, Modifiers::ALT); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Crosshair); + assert_ne!(bitmap(&h), Some(target), "the precise crosshair, not the sample target"); + assert!(!pipette_shown(&h)); +} diff --git a/crates/ui-egui/src/options_bar_mode_wheel_tests.rs b/crates/ui-egui/src/options_bar_mode_wheel_tests.rs index 7870917ded..3147d235d4 100644 --- a/crates/ui-egui/src/options_bar_mode_wheel_tests.rs +++ b/crates/ui-egui/src/options_bar_mode_wheel_tests.rs @@ -13,7 +13,7 @@ use crate::PhotocraftApp; use crate::state::Tool; /// The app with a new document and `tool` chosen. -fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> { +pub(super) fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> { let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(move |cc| { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); @@ -26,12 +26,12 @@ fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> { } /// The options bar's Mode dropdown: the highest one showing `Normal` (the Layers panel's is lower). -fn mode_dropdown(h: &Harness<'_, PhotocraftApp>) -> Rect { +pub(super) fn mode_dropdown(h: &Harness<'_, PhotocraftApp>) -> Rect { h.query_all_by_role(Role::ComboBox).filter(|n| n.value().as_deref() == Some("Normal")).map(|n| n.rect()).min_by(|a, b| a.top().total_cmp(&b.top())).unwrap() } /// `lines` wheel lines at `at` in one event: negative is down. -fn wheel(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, lines: f32) { +pub(super) fn wheel(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, lines: f32) { h.hover_at(at); h.run_steps(1); h.event(egui::Event::MouseWheel { @@ -44,7 +44,7 @@ fn wheel(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, lines: f32) { h.run_steps(3); } -fn brush_mode(h: &Harness<'_, PhotocraftApp>) -> BlendMode { +pub(super) fn brush_mode(h: &Harness<'_, PhotocraftApp>) -> BlendMode { h.state().session.tools.brush.mode } @@ -127,6 +127,27 @@ fn the_pattern_stamp_mode_dropdown_has_behind() { assert_eq!(h.state().ui.tool, Tool::PatternStamp); } +/// The centre of a dropdown showing `value`. +fn combo(h: &Harness<'_, PhotocraftApp>, value: &str) -> Option { + h.query_all_by_role(Role::ComboBox).find(|n| n.value().as_deref() == Some(value)).map(|n| n.rect().center()) +} + +/// In an Indexed Color document the Pattern Stamp's Mode reads "Threshold" for Normal (#12887); the +/// other entries weren't measured there, so the list and the wheel stay as today. +#[test] +fn the_pattern_stamp_mode_reads_threshold_in_an_indexed_document() { + let mut h = harness(Tool::PatternStamp); + h.state_mut().run("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none"})).unwrap(); + h.run_steps(4); + let at = combo(&h, "Threshold").expect("Mode reads Threshold"); + wheel(&mut h, at, -1.0); + assert_eq!(brush_mode(&h), BlendMode::Dissolve); + assert!(combo(&h, "Dissolve").is_some() && combo(&h, "Threshold").is_none(), "Dissolve reads as itself"); + wheel(&mut h, at, 1.0); + assert_eq!(brush_mode(&h), BlendMode::Normal); + assert!(combo(&h, "Threshold").is_some()); +} + /// The Paint Bucket's Mode dropdown has Clear after Dissolve, as the Brush's does. #[test] fn the_paint_bucket_mode_dropdown_has_clear() { diff --git a/crates/ui-egui/src/paint_bucket_right_click_menu_tests.rs b/crates/ui-egui/src/paint_bucket_right_click_menu_tests.rs new file mode 100644 index 0000000000..eff0ec017f --- /dev/null +++ b/crates/ui-egui/src/paint_bucket_right_click_menu_tests.rs @@ -0,0 +1,184 @@ +//! #12530: with the Paint Bucket a plain right-click on the image opens its Mode list at the +//! pointer, the options bar's entries with none checked; picking one sets the Mode, adds no history +//! and fills nothing. The pasteboard keeps its colour menu, Shift+right-click keeps its checked +//! menu and other tools keep their right-click. + +use egui::{Modifiers, PointerButton, Pos2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::BlendMode; +use serde_json::{Value, json}; + +use super::eraser_block_right_click_tests::{app, call, harness, right_click, steps}; +use crate::PhotocraftApp; +use crate::state::Tool; + +fn bucket() -> PhotocraftApp { + let mut app = app("brush"); + app.ui.tool = Tool::PaintBucket; + app +} + +/// The options bar's Mode list for the Paint Bucket, Clear included. +fn options_bar_modes() -> Vec<&'static str> { + crate::blend_keys::tool_modes(Tool::PaintBucket).unwrap().into_iter().map(|m| m.map_or("Clear", BlendMode::label)).collect() +} + +fn checked_rows(inspect: &Value) -> Vec { + let items = inspect["result"]["brushModeMenu"]["items"].as_array().unwrap(); + items.iter().filter(|i| i["checked"] == true).map(|i| i["label"].clone()).collect() +} + +#[test] +fn a_plain_right_click_lists_the_options_bar_modes_with_none_checked() { + let ctx = egui::Context::default(); + let mut app = bucket(); + right_click(&mut app, &ctx, json!({})); + assert!(app.ui.brush_mode_menu.is_some(), "the Mode list opens"); + assert!(app.ui.brush_picker.is_none() && app.ui.canvas_tool_menu.is_none()); + let inspect = call(&mut app, &ctx, "ui.inspect", json!({})); + assert_eq!(inspect["result"]["brushModeMenu"]["choices"], json!(options_bar_modes()), "{inspect}"); + assert_eq!(checked_rows(&inspect), Vec::::new(), "no entry is checked"); + assert_eq!(inspect["result"]["brushModeMenu"]["mode"], "Normal", "the tool's mode is still reported"); +} + +#[test] +fn picking_an_entry_sets_the_mode_and_adds_no_history() { + let ctx = egui::Context::default(); + let mut app = bucket(); + let (n, journal) = (steps(&app), app.session.journal.len()); + right_click(&mut app, &ctx, json!({})); + assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id": "Multiply"}))["ok"], true); + assert_eq!(app.ui.tool_options.bucket_blend_mode, BlendMode::Multiply); + assert!(!app.ui.tool_options.bucket_clear); + assert!(app.ui.brush_mode_menu.is_none()); + assert_eq!((steps(&app), app.session.journal.len()), (n, journal), "nothing is filled"); +} + +#[test] +fn shift_right_click_still_checks_the_current_mode() { + let ctx = egui::Context::default(); + let mut app = bucket(); + app.ui.tool_options.bucket_blend_mode = BlendMode::Screen; + right_click(&mut app, &ctx, json!({"shift": true})); + let inspect = call(&mut app, &ctx, "ui.inspect", json!({})); + assert_eq!(checked_rows(&inspect), vec![json!("Screen")], "{inspect}"); +} + +#[test] +fn other_tools_keep_their_plain_right_click() { + let ctx = egui::Context::default(); + for tool in [Tool::Brush, Tool::Pencil, Tool::CloneStamp, Tool::Gradient, Tool::Eraser] { + let mut app = bucket(); + app.ui.tool = tool; + right_click(&mut app, &ctx, json!({})); + assert!(app.ui.brush_mode_menu.is_none(), "{tool:?}"); + } +} + +/// A real right-click at `at` with `mods` held. +fn mouse_right_click(h: &mut Harness<'static, PhotocraftApp>, at: Pos2, mods: Modifiers) { + h.event(egui::Event::ModifiersChanged(mods)); + h.event(egui::Event::PointerMoved(at)); + h.run_steps(1); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: mods }); + h.run_steps(2); + } + h.event(egui::Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(1); +} + +fn row_checked(h: &Harness<'static, PhotocraftApp>, label: &str) -> bool { + h.get_by_label(label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +/// The real mouse: the menu opens at the pointer with no row checked; Escape and a click outside +/// close it without a change; a row sets the Mode. Nothing is filled. +#[test] +fn a_real_right_click_opens_the_unchecked_menu_at_the_pointer() { + let mut h = harness(bucket()); + let (n, journal) = (steps(h.state()), h.state().session.journal.len()); + let c = h.state().last_canvas_rect.center(); + mouse_right_click(&mut h, c, Modifiers::NONE); + assert_eq!(h.state().ui.brush_mode_menu, Some([c.x, c.y]), "the menu at the pointer"); + assert!(!row_checked(&h, "Normal"), "the current mode is not checked"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + assert!(h.state().ui.brush_mode_menu.is_none(), "Escape closes it"); + mouse_right_click(&mut h, c, Modifiers::NONE); + let outside = c - egui::vec2(20.0, 0.0); + h.event(egui::Event::PointerMoved(outside)); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: outside, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.run_steps(2); + } + assert!(h.state().ui.brush_mode_menu.is_none(), "a click outside closes it"); + assert_eq!(h.state().ui.tool_options.bucket_blend_mode, BlendMode::Normal); + mouse_right_click(&mut h, c, Modifiers::NONE); + h.get_by_label("Multiply").click(); + h.run_steps(2); + assert_eq!(h.state().ui.tool_options.bucket_blend_mode, BlendMode::Multiply); + assert!(h.state().ui.brush_mode_menu.is_none()); + assert_eq!((steps(h.state()), h.state().session.journal.len()), (n, journal), "nothing is filled"); +} + +#[test] +fn a_real_shift_right_click_checks_the_current_mode() { + let mut h = harness(bucket()); + let c = h.state().last_canvas_rect.center(); + mouse_right_click(&mut h, c, Modifiers::SHIFT); + assert!(h.state().ui.brush_mode_menu.is_some()); + assert!(row_checked(&h, "Normal")); +} + +#[test] +fn a_real_right_click_on_the_pasteboard_opens_its_colour_menu() { + let mut h = harness(bucket()); + let c = h.state().last_canvas_rect.center(); + mouse_right_click(&mut h, c + egui::vec2(300.0, 0.0), Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "the pasteboard colour menu"); + assert!(h.state().ui.brush_mode_menu.is_none(), "not the Mode list"); +} + +/// An open Free Transform box keeps its transform menu: the Mode list does not open over it. +#[test] +fn a_real_right_click_on_a_free_transform_box_opens_only_the_transform_menu() { + let mut app = bucket(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 4, "y": 6, "width": 10, "height": 8})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + let mut h = harness(app); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); + h.run_steps(2); + let c = h.state().last_canvas_rect.center(); + mouse_right_click(&mut h, c, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.transform), "the transform menu"); + assert!(h.state().ui.brush_mode_menu.is_none(), "not the Mode list"); +} + +/// Window › Arrange: each document's canvas is a cell, and a right-click is placed on the image or +/// the pasteboard by that cell's view, not by the whole work area's. +#[test] +fn arranged_cells_place_the_right_click_by_their_own_view() { + let mut h = harness(bucket()); + h.state_mut().run("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap(); + h.state_mut().ui.view.arrange = "twoUpVertical".into(); + h.run_steps(4); + let full = h.state().last_canvas_rect; + let active = h.state().session.active_index().unwrap(); + let cell = crate::canvas::arranged_cells(h.state(), full).unwrap().into_iter().find(|(i, _)| *i == active).unwrap().1; + mouse_right_click(&mut h, cell.center(), Modifiers::NONE); + assert!(h.state().ui.brush_mode_menu.is_some(), "the image in the active cell: the Mode list"); + assert!(h.state().ui.canvas_tool_menu.is_none()); + h.key_press(egui::Key::Escape); + h.run_steps(2); + // The pasteboard at the cell's inner edge, where the whole work area's view has the image. + let edge = cell.clamp(full.center()); + let pasteboard = edge + (cell.center() - edge).normalized() * 10.0; + mouse_right_click(&mut h, pasteboard, Modifiers::NONE); + assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "the pasteboard colour menu"); + assert!(h.state().ui.brush_mode_menu.is_none(), "not the Mode list"); +} diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 8dc34da45a..5d072f2f19 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -474,7 +474,7 @@ fn play_steps(app: &mut PhotocraftApp, params: &Value, suspended: Option, return Err(e.to_string()); } }; - let recording = match actions_cmds::begin_playback(&mut app.session, &action) { + let recording = match actions_cmds::begin_playback_from(&mut app.session, &action, from) { Ok(r) => r, Err(e) => { actions_cmds::finish_pending_history(&mut app.session); diff --git a/crates/ui-egui/src/panels/actions/tests.rs b/crates/ui-egui/src/panels/actions/tests.rs index 4755a97321..b9ca5b0d8a 100644 --- a/crates/ui-egui/src/panels/actions/tests.rs +++ b/crates/ui-egui/src/panels/actions/tests.rs @@ -2,9 +2,9 @@ use super::*; /// A small valid Photoshop set, generated without external action files. fn action_set_bytes(set: &str, action: &str) -> Vec { - use photocraft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; - use photocraft_psd::descriptor::UnicodeString; - photocraft_psd::atn::write(&AtnFile { + use craft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; + use craft_psd::descriptor::UnicodeString; + craft_psd::atn::write(&AtnFile { name: UnicodeString::new_nul(set), actions: vec![AtnAction { name: UnicodeString::new_nul(action), @@ -247,9 +247,9 @@ fn bulk_load_keeps_selection_order_and_earlier_warnings_and_errors() { let first = dir.path().join("z-first.atn"); let broken = dir.path().join("broken.atn"); let last = dir.path().join("a-last.atn"); - let mut unsupported = photocraft_psd::atn::parse(&action_set_bytes("Same set", "Old")).unwrap(); - unsupported.actions[0].items[0].event = photocraft_psd::atn::AtnEvent::Code(*b"Xxxx"); - std::fs::write(&first, photocraft_psd::atn::write(&unsupported).unwrap()).unwrap(); + let mut unsupported = craft_psd::atn::parse(&action_set_bytes("Same set", "Old")).unwrap(); + unsupported.actions[0].items[0].event = craft_psd::atn::AtnEvent::Code(*b"Xxxx"); + std::fs::write(&first, craft_psd::atn::write(&unsupported).unwrap()).unwrap(); std::fs::write(&broken, b"not an action file").unwrap(); std::fs::write(&last, action_set_bytes("Same set", "Replacement")).unwrap(); let paths = [first, broken, last].map(|p| p.to_string_lossy().into_owned()).to_vec(); @@ -282,9 +282,9 @@ fn bulk_load_status(app: &mut PhotocraftApp, files: Vec<(String, Vec)>) -> S /// what the panel holds afterwards and says which set was replaced. fn bulk_load_summary_counts_a_replaced_set_once() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut a = photocraft_psd::atn::parse(&action_set_bytes("Set 1", "A")).unwrap(); - a.actions[0].items[0].event = photocraft_psd::atn::AtnEvent::Code(*b"Xxxx"); - let files = vec![("a.atn".into(), photocraft_psd::atn::write(&a).unwrap()), ("b.atn".into(), action_set_bytes("Set 1", "B"))]; + let mut a = craft_psd::atn::parse(&action_set_bytes("Set 1", "A")).unwrap(); + a.actions[0].items[0].event = craft_psd::atn::AtnEvent::Code(*b"Xxxx"); + let files = vec![("a.atn".into(), craft_psd::atn::write(&a).unwrap()), ("b.atn".into(), action_set_bytes("Set 1", "B"))]; let status = bulk_load_status(&mut app, files); assert_eq!(app.session.actions.list.iter().map(|a| a.name.as_str()).collect::>(), ["B"]); assert!(!app.ui.status_error, "{status}"); @@ -934,8 +934,8 @@ fn recorded_save_never_flattens_layers_over_a_flat_file() { /// Photoshop's "save in directory", `out` itself) and plays it on each PSD in `sources`. /// Returns the played results, whether any PSD changed on disk and the files in `out`. fn play_imported_save_as(dest: &str, in_folder: bool, sources: &[&str]) -> (Vec, bool, Vec) { - use photocraft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; - use photocraft_psd::descriptor::{Descriptor, UnicodeString, Value as D}; + use craft_psd::atn::{AtnAction, AtnEvent, AtnFile, AtnItem}; + use craft_psd::descriptor::{Descriptor, UnicodeString, Value as D}; let dir = std::env::temp_dir().join(format!("photocraft-atn-save-as-{dest}-{in_folder}-{}", std::process::id())); let out = dir.join("out"); std::fs::create_dir_all(&out).unwrap(); @@ -977,7 +977,7 @@ fn play_imported_save_as(dest: &str, in_folder: bool, sources: &[&str]) -> (Vec< app.save_as(Some(src.clone())).unwrap(); before.push(std::fs::read(src).unwrap()); } - app.run("actions.load", json!({"data": photocraft_engine::paint::tile::b64_encode(&photocraft_psd::atn::write(&set).unwrap())})).unwrap(); + app.run("actions.load", json!({"data": photocraft_engine::paint::tile::b64_encode(&craft_psd::atn::write(&set).unwrap())})).unwrap(); let mut played = Vec::new(); for src in &sources { app.open_path(src).unwrap(); @@ -2965,8 +2965,8 @@ fn button_mode_plays_the_clicked_action_and_hides_its_steps() { /// document (#7367). #[test] fn save_hook_closing_the_target_stops_an_imported_close_with_save() { - use photocraft_psd::atn::{self, AtnEvent, AtnItem}; - use photocraft_psd::descriptor::{Descriptor, Id, Value as D}; + use craft_psd::atn::{self, AtnEvent, AtnItem}; + use craft_psd::descriptor::{Descriptor, Id, Value as D}; use std::{cell::RefCell, rc::Rc}; // A one-step .atn: Close (`Cls `) with Save: Yes. let seed = Action::new("Seed", vec![("layer.new.layer".into(), json!({}))]); @@ -3033,9 +3033,9 @@ fn save_hook_closing_the_target_stops_an_imported_close_with_save() { /// one in a set a later file replaced (CodeRabbit on #10776). fn bulk_load_summary_counts_unsupported_steps_of_surviving_sets() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); - let mut a = photocraft_psd::atn::parse(&action_set_bytes("Set A", "A")).unwrap(); - a.actions[0].items[0].event = photocraft_psd::atn::AtnEvent::Code(*b"Xxxx"); - let files = vec![("a.atn".into(), photocraft_psd::atn::write(&a).unwrap()), ("b.atn".into(), action_set_bytes("Set B", "B"))]; + let mut a = craft_psd::atn::parse(&action_set_bytes("Set A", "A")).unwrap(); + a.actions[0].items[0].event = craft_psd::atn::AtnEvent::Code(*b"Xxxx"); + let files = vec![("a.atn".into(), craft_psd::atn::write(&a).unwrap()), ("b.atn".into(), action_set_bytes("Set B", "B"))]; let status = bulk_load_status(&mut app, files); assert!(status.contains("1 step has no PhotoCraft equivalent yet"), "{status}"); assert!(!app.ui.status_error, "{status}"); diff --git a/crates/ui-egui/src/panels/brush_controls.rs b/crates/ui-egui/src/panels/brush_controls.rs index 4f30ac1bdf..7f2aa4996b 100644 --- a/crates/ui-egui/src/panels/brush_controls.rs +++ b/crates/ui-egui/src/panels/brush_controls.rs @@ -3,8 +3,19 @@ use super::{Align2, BlendMode, Color32, PhotocraftApp, Rect, Sense, Stroke, Stro /// A painting tool's Mode dropdown over `modes` (`None` is Clear); the wheel over it steps the /// mode. Returns the mode picked this frame. A list of every blend mode draws the Layers panel's /// group lines (#5532; Clear starts none); a short one (the Healing Brush's) draws none. -pub(super) fn tool_mode_dropdown(ui: &mut egui::Ui, id: &str, modes: &[Option], current: Option) -> Option> { - let opts: Vec<(Option, &str)> = modes.iter().map(|m| (*m, m.map_or("Clear", BlendMode::label))).collect(); +/// `threshold` names Normal "Threshold", as the reference does in an Indexed Color document. +pub(super) fn tool_mode_dropdown( + ui: &mut egui::Ui, + id: &str, + modes: &[Option], + current: Option, + threshold: bool, +) -> Option> { + let label = |m: &Option| match m { + Some(BlendMode::Normal) if threshold => tl!("Threshold"), + _ => m.map_or("Clear", BlendMode::label), + }; + let opts: Vec<(Option, &str)> = modes.iter().map(|m| (*m, label(m))).collect(); let grouped = BlendMode::LAYER_MODES.iter().all(|m| modes.contains(&Some(*m))); let mut mode = current; let chosen = widgets::dropdown_wheel_grouped(ui, id, tl!("Mode"), &mut mode, &opts, 96.0, |m| grouped && m.is_some_and(starts_blend_group)).0; @@ -40,8 +51,11 @@ pub(super) fn paint_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraf /// picking another mode leaves it. The wheel steps it as it steps the other Mode dropdowns. /// Without `behind_enabled` (the Background is the active layer) Behind is greyed, as in the /// Shift+right-click menu, and the wheel and the keys step past it. -pub(super) fn pattern_stamp_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraft_engine::BrushSettings, behind_enabled: bool) { - let opts = crate::brush_mode_menu::pattern_stamp_choices(); +pub(super) fn pattern_stamp_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraft_engine::BrushSettings, behind_enabled: bool, threshold: bool) { + let mut opts = crate::brush_mode_menu::pattern_stamp_choices(); + if threshold && let Some(normal) = opts.iter_mut().find(|o| o.0 == (Some(BlendMode::Normal), false)) { + normal.1 = tl!("Threshold"); + } let before = if b.behind { (None, true) } else { (Some(b.mode), false) }; let mut mode = before; let groups = |m: &(Option, bool)| m.0.is_some_and(starts_blend_group); diff --git a/crates/ui-egui/src/panels/brush_panel/tests.rs b/crates/ui-egui/src/panels/brush_panel/tests.rs index 305a31c47a..d8ee4e2683 100644 --- a/crates/ui-egui/src/panels/brush_panel/tests.rs +++ b/crates/ui-egui/src/panels/brush_panel/tests.rs @@ -456,7 +456,7 @@ fn clone_stamp_opacity_and_flow_are_journaled_per_gesture() { assert_eq!(id, "tools.setBrush"); assert_eq!(params["brush"][field].as_f64().map(|v| v as f32), Some(value)); } - h.state_mut().ui.clone_source = Some([0.0, 0.0]); + crate::retouch_ui::set_source(h.state_mut(), 0.0, 0.0); let params = crate::retouch_ui::clone_params(h.state()).unwrap(); assert_eq!(params["opacity"], json!(h.state().session.tools.brush.opacity * 100.0)); assert_eq!(params["flow"], json!(h.state().session.tools.brush.flow * 100.0)); diff --git a/crates/ui-egui/src/panels/histogram_panel.rs b/crates/ui-egui/src/panels/histogram_panel.rs index a3576b0df9..06853b523c 100644 --- a/crates/ui-egui/src/panels/histogram_panel.rs +++ b/crates/ui-egui/src/panels/histogram_panel.rs @@ -4,8 +4,10 @@ //! over the original while an adjustment previews. //! //! Histograms are counted off the UI thread (`tone::compute_histograms_at`) for the document -//! revision, source and preview they describe, and kept until one of those changes; the panel -//! shows the last one with the cached-data warning until the new one lands. +//! revision, source, selection and preview they describe, and kept until one of those changes; +//! the panel shows the last one with the cached-data warning until the new one lands. Like +//! Photoshop's panel it follows the selection (`tone::HistScope::Selection`): a selection change +//! makes every cached histogram stale, however few pixels it moved. use std::sync::Arc; @@ -18,7 +20,7 @@ use serde_json::{Value, json}; use crate::PhotocraftApp; use crate::theme::Tokens; -use crate::tone::{self, HistSource, Histograms}; +use crate::tone::{self, HistScope, HistSource, Histograms}; /// Where the panel options are kept between launches (`prefs.dialogs`). const OPTIONS_PREF: &str = "histogramPanel"; @@ -261,14 +263,17 @@ pub struct Stats { pub clipped: [f64; 2], } -/// The statistics of `h`, inspecting `levels` (a level or a range, in either order). None when -/// nothing was counted. -pub fn stats(h: &[u32; 256], levels: Option<[u8; 2]>) -> Option { +/// The statistics of `h`, inspecting `levels` (a level or a range, in either order). `pixels` is +/// the count the Pixels row reports — every pixel the count kept, transparent ones included, so +/// with a selection it is the selection's size (see [`Histograms::pixel_count`]) — while the +/// ratios and moments come from the bins, which hold only the visible pixels. None when nothing +/// was counted. +pub fn stats(h: &[u32; 256], levels: Option<[u8; 2]>, pixels: u64) -> Option { let n: u64 = h.iter().map(|v| u64::from(*v)).sum(); - if n == 0 { + if n == 0 && pixels == 0 { return None; } - let nf = n as f64; + let nf = n.max(1) as f64; let mean = h.iter().enumerate().map(|(i, v)| i as f64 * f64::from(*v)).sum::() / nf; let var = h.iter().enumerate().map(|(i, v)| (i as f64 - mean).powi(2) * f64::from(*v)).sum::() / nf; let mut acc = 0u64; @@ -284,7 +289,7 @@ pub fn stats(h: &[u32; 256], levels: Option<[u8; 2]>) -> Option { let count = level.map(|[lo, hi]| sum(lo, hi)); let percentile = level.map(|[lo, hi]| 100.0 * if lo == hi { sum(0, hi) } else { sum(lo, hi) } as f64 / nf); let clipped = [100.0 * f64::from(h[0]) / nf, 100.0 * f64::from(h[255]) / nf]; - Some(Stats { mean, std_dev: var.sqrt(), median, pixels: n, level, count, percentile, clipped }) + Some(Stats { mean, std_dev: var.sqrt(), median, pixels, level, count, percentile, clipped }) } // --------------------------------------------------------------------------------------------- @@ -295,7 +300,8 @@ pub fn stats(h: &[u32; 256], levels: Option<[u8; 2]>) -> Option { pub struct HistKey { pub doc: DocId, pub revision: u64, - /// `tone::tag` of the source and space. + /// `tone::tag` of the source, space and selection (the panel counts `HistScope::Selection`, + /// so a selection change is a new key however few pixels it moved). pub source: u64, /// The adjustment preview's display key; 0 for the document itself. pub preview: u64, @@ -352,7 +358,15 @@ fn committed_key(app: &PhotocraftApp) -> Option<(HistKey, ToneSpace, HistSource) let space = tone_space(st.doc.mode); let (_, source) = resolve_source(st, source_choice(&app.ui.histogram_panel)); let max_level = if app.hist_uncached == Some((doc, revision)) { 1 } else { max_cache_level(app) }; - Some((HistKey { doc, revision, source: tone::tag(source, space), preview: 0, max_level }, space, source)) + // The panel counts the selected pixels (HistScope::Selection), so its key carries the + // selection's identity: a selection change makes every cached histogram stale. The mask is + // hashed per revision (refreshed by `update`); hashing here is the between-frames cold path. + let sel = match app.hist_sel_key { + Some((d, r, k)) if d == doc && r == revision => k, + _ => tone::selection_key(&st.doc), + }; + let source_tag = tone::tag(source, space, HistScope::Selection, sel); + Some((HistKey { doc, revision, source: source_tag, preview: 0, max_level }, space, source)) } /// The document an open adjustment previews on the canvas (an Image › Adjustments dialog through @@ -383,22 +397,43 @@ fn want(app: &mut PhotocraftApp) -> Option { Some(Want { committed, preview, space, source }) } +/// Refreshes the memoized selection key for the active document's revision: the panel's keying +/// asks for it every frame, the hash walks every tile of the selection mask, and any change to +/// the selection arrives as a new document revision — so the same revision always keeps its key. +fn refresh_sel_key(app: &mut PhotocraftApp) { + let Some(st) = app.session.active() else { return }; + if matches!(app.hist_sel_key, Some((d, r, _)) if d == st.doc.id && r == st.revision) { + return; + } + app.hist_sel_key = Some((st.doc.id, st.revision, tone::selection_key(&st.doc))); +} + /// Brings the panel's histograms up to date as far as one frame should: lands a finished count, /// keeps entries a view-only revision didn't invalidate, and starts the next count (at most one at /// a time, at most every 250 ms per entry). `ctx` repaints when a worker delivers. pub fn update(app: &mut PhotocraftApp, ctx: &egui::Context) { - // A finished worker lands its histogram in the slot its key names. A worker that died - // without sending clears the job so the next frame schedules a new one. + refresh_sel_key(app); + let want = want(app); + // A finished worker lands its histogram in the slot its key names — unless it was computed + // for another document or selection, which is dropped at the door: caching it would reset + // the panel's 250 ms throttle without ever being shown fresh. A result for the same + // document and selection still lands when the revision moved on under it (continuous + // edits): the panel shows the newer data, marked stale, instead of waiting for an edit-free + // moment. A worker that died without sending clears the job so the next frame schedules a + // new one. if let Some((_, rx)) = &app.hist_job { match rx.try_recv() { Ok((key, ms, hist)) => { app.perf.span("histogram", ms); - // egui's clock works on every target; `gpu_canvas::now_ms` is always 0 on wasm32. - let entry = PanelHist { key, at: ctx.input(|i| i.time) * 1000.0, hist }; - if key.preview == 0 { - app.doc_hist = Some(entry); - } else { - app.doc_hist_preview = Some(entry); + let wanted = want.as_ref().is_some_and(|w| key.doc == w.committed.doc && key.source == w.committed.source); + if wanted { + // egui's clock works on every target; `gpu_canvas::now_ms` is always 0 on wasm32. + let entry = PanelHist { key, at: ctx.input(|i| i.time) * 1000.0, hist }; + if key.preview == 0 { + app.doc_hist = Some(entry); + } else { + app.doc_hist_preview = Some(entry); + } } app.hist_job = None; } @@ -407,7 +442,8 @@ pub fn update(app: &mut PhotocraftApp, ctx: &egui::Context) { } } // Revisions that changed no pixels since the histogram's (selecting a layer, say) keep it - // (#125), and an Uncached Refresh with it. + // (#125), and an Uncached Refresh with it — but only for the same selection: a selection + // change moves no pixels yet changes what the panel counts. if let Some(st) = app.session.active() { let (doc, rev) = (st.doc.id, st.revision); if let Some((d, r)) = app.hist_uncached @@ -416,14 +452,14 @@ pub fn update(app: &mut PhotocraftApp, ctx: &egui::Context) { { app.hist_uncached = Some((doc, rev)); } - if let Some(e) = app.doc_hist.as_mut() - && e.key.doc == doc - && tone::pixels_kept_since(st, e.key.revision) - { - e.key.revision = rev; + let same_selection = want.as_ref().map(|w| w.committed.source); + for e in [app.doc_hist.as_mut(), app.doc_hist_preview.as_mut()].into_iter().flatten() { + if e.key.doc == doc && tone::pixels_kept_since(st, e.key.revision) && same_selection.is_none_or(|s| e.key.source == s) { + e.key.revision = rev; + } } } - let Some(want) = want(app) else { return }; + let Some(want) = want else { return }; if want.preview.is_none() { app.doc_hist_preview = None; } @@ -469,7 +505,7 @@ fn spawn(app: &mut PhotocraftApp, ctx: &egui::Context, doc: Arc, key: .name("histogram".into()) .spawn(move || { let t0 = crate::gpu_canvas::now_ms(); - let h = Arc::new(tone::compute_histograms_at(&doc, source, space, key.max_level)); + let h = Arc::new(tone::compute_histograms_at(&doc, source, space, HistScope::Selection, key.max_level)); let _ = tx.send((key, crate::gpu_canvas::now_ms() - t0, h)); ctx.request_repaint(); }) @@ -482,7 +518,7 @@ fn spawn(app: &mut PhotocraftApp, ctx: &egui::Context, doc: Arc, key: }; if !spawned { let t0 = crate::gpu_canvas::now_ms(); - let h = Arc::new(tone::compute_histograms_at(&doc, source, space, key.max_level)); + let h = Arc::new(tone::compute_histograms_at(&doc, source, space, HistScope::Selection, key.max_level)); let _ = tx.send((key, crate::gpu_canvas::now_ms() - t0, h)); } app.hist_job = Some((key, rx)); @@ -706,16 +742,28 @@ fn outline(p: &egui::Painter, r: Rect, h: &[u32; 256], color: Color32) { /// The statistics grid: Mean, Std Dev, Median, Pixels | Level, Count, Percentile, Cache Level. fn statistics(ui: &mut egui::Ui, h: &Histograms, mode: ColorMode, channel: HistChannel, levels: Option<[u8; 2]>, t: &Tokens) { let ch = if channel == HistChannel::Colors { HistChannel::Composite } else { channel }; - let Some(s) = stats(bins(h, mode, ch), levels) else { return }; + let histogram = bins(h, mode, ch); + let Some(s) = stats(histogram, levels, h.pixel_count) else { return }; + let no_visible_samples = histogram.iter().all(|&v| v == 0); let level = match s.level { Some([a, b]) if a == b => a.to_string(), Some([a, b]) => format!("{a}..{b}"), None => String::new(), }; let rows = [ - (tl!("Mean:"), format!("{:.2}", s.mean), tl!("Level:"), level), - (tl!("Std Dev:"), format!("{:.2}", s.std_dev), tl!("Count:"), s.count.map(|c| c.to_string()).unwrap_or_default()), - (tl!("Median:"), s.median.to_string(), tl!("Percentile:"), s.percentile.map(|p| format!("{p:.2}")).unwrap_or_default()), + (tl!("Mean:"), if no_visible_samples { "--".into() } else { format!("{:.2}", s.mean) }, tl!("Level:"), level), + ( + tl!("Std Dev:"), + if no_visible_samples { "--".into() } else { format!("{:.2}", s.std_dev) }, + tl!("Count:"), + s.count.map(|c| c.to_string()).unwrap_or_default(), + ), + ( + tl!("Median:"), + if no_visible_samples { "--".into() } else { s.median.to_string() }, + tl!("Percentile:"), + s.percentile.filter(|_| !no_visible_samples).map(|p| format!("{p:.2}")).unwrap_or_default(), + ), (tl!("Pixels:"), s.pixels.to_string(), tl!("Cache Level:"), h.level.max(1).to_string()), ]; let mono = crate::theme::mono(11.5); @@ -862,7 +910,7 @@ pub fn inspect(app: &PhotocraftApp) -> Value { "current": entry.zip(committed).is_some_and(|(e, k)| e.key == HistKey { preview: e.key.preview, ..k }), "cacheLevel": entry.map(|e| e.hist.level.max(1)), "maxCacheLevel": max_cache_level(app), - "stats": entry.and_then(|e| stats(bins(&e.hist, mode, ch), app.ui.histogram_range)), + "stats": entry.and_then(|e| stats(bins(&e.hist, mode, ch), app.ui.histogram_range, e.hist.pixel_count)), }) } diff --git a/crates/ui-egui/src/panels/histogram_panel/tests.rs b/crates/ui-egui/src/panels/histogram_panel/tests.rs index f5d660006b..87423d0897 100644 --- a/crates/ui-egui/src/panels/histogram_panel/tests.rs +++ b/crates/ui-egui/src/panels/histogram_panel/tests.rs @@ -55,19 +55,23 @@ fn stats_match_their_definitions() { h[0] = 25; h[100] = 50; h[255] = 25; - let s = stats(&h, None).unwrap(); + let s = stats(&h, None, 100).unwrap(); assert_eq!(s.pixels, 100); assert!((s.mean - (5000.0 + 6375.0) / 100.0).abs() < 1e-9); assert_eq!(s.median, 100); assert_eq!(s.clipped, [25.0, 25.0], "a quarter of the pixels clip at each end"); // One level: its count and the percent at or below it. - let one = stats(&h, Some([100, 100])).unwrap(); + let one = stats(&h, Some([100, 100]), 100).unwrap(); assert_eq!((one.count, one.percentile), (Some(50), Some(75.0))); // A dragged range (either direction): the count and percent within it. - let range = stats(&h, Some([200, 50])).unwrap(); + let range = stats(&h, Some([200, 50]), 100).unwrap(); assert_eq!((range.level, range.count, range.percentile), (Some([50, 200]), Some(50), Some(50.0))); - assert!(stats(&[0; 256], Some([0, 255])).is_none(), "an empty histogram has no statistics"); - assert!(stats(&h, None).unwrap().std_dev > 0.0); + assert!(stats(&[0; 256], Some([0, 255]), 0).is_none(), "an empty histogram has no statistics"); + assert!(stats(&h, None, 100).unwrap().std_dev > 0.0); + // The Pixels row reports the kept pixels (a selection's size, transparent ones included), + // not the bins' sum: a selection of only transparent pixels still has statistics. + let empty_bins = stats(&[0; 256], None, 500).expect("pixels were counted"); + assert_eq!(empty_bins.pixels, 500); } #[test] @@ -97,7 +101,8 @@ fn luminosity_and_rgb_channels_are_counted() { app.run("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); let doc = &app.session.active().unwrap().doc; - let h = tone::compute_histograms(doc, tone::IMAGE, ToneSpace::Rgb); + // The whole input: the selection left over the fill would mask the panel's count. + let h = tone::compute_histograms(doc, tone::IMAGE, ToneSpace::Rgb, HistScope::WholeInput); assert_eq!(bins(&h, doc.mode, HistChannel::Red)[255], 800); assert_eq!(bins(&h, doc.mode, HistChannel::Green)[0], 400); let red_lum = (0.30f32 * 255.0).round() as usize; @@ -115,9 +120,10 @@ fn sources_count_the_image_the_layer_or_the_adjustment_composite() { let st = app.session.active().unwrap(); let invert = st.doc.layers[1].id; let doc = &st.doc; - let image = tone::compute_histograms(doc, tone::IMAGE, ToneSpace::Rgb); + // The whole input: the selection left over the fill would mask the panel's count. + let image = tone::compute_histograms(doc, tone::IMAGE, ToneSpace::Rgb, HistScope::WholeInput); assert_eq!((image[0][0], image[0][128]), (512, 512), "black (inverted white) and the grey above it"); - let upto = tone::compute_histograms(doc, HistSource::UpTo(invert), ToneSpace::Rgb); + let upto = tone::compute_histograms(doc, HistSource::UpTo(invert), ToneSpace::Rgb, HistScope::WholeInput); assert_eq!(upto[0][0], 1024, "the adjustment composite hides the grey layer above"); // The panel offers Adjustment Composite only with an adjustment layer selected. assert_eq!(resolve_source(st, HistSourceChoice::AdjustmentComposite).0, HistSourceChoice::EntireImage); @@ -140,7 +146,7 @@ fn cache_level_follows_size_and_the_preference_cap() { assert!(auto > 1, "a large document counts a proxy, level {auto}"); assert_eq!(tone::cache_level(doc, 2), 2, "capped by Cache Levels"); assert_eq!(tone::cache_level(doc, 0), 1, "out-of-range caps clamp"); - let exact = tone::compute_histograms_at(doc, tone::IMAGE, ToneSpace::Rgb, 1); + let exact = tone::compute_histograms_at(doc, tone::IMAGE, ToneSpace::Rgb, HistScope::Selection, 1); assert_eq!(exact.level, 1); assert_eq!(exact[0][255], 6000 * 3000, "level 1 counts every pixel"); let small = app_with(json!({"width": 64, "height": 64})); @@ -363,9 +369,9 @@ fn uncapped_counts_keep_their_proxy_and_a_cap_reduces_by_powers_of_two() { let doc = &big.session.active().unwrap().doc; let pixels = |h: &Histograms| h[0].iter().map(|&c| u64::from(c)).sum::(); // 6000 / 768 = 7: a 7x proxy, 858 x 429 (rounded up), not an 8x one. - let auto = tone::compute_histograms(doc, tone::IMAGE, ToneSpace::Rgb); + let auto = tone::compute_histograms(doc, tone::IMAGE, ToneSpace::Rgb, HistScope::Selection); assert_eq!(pixels(&auto), 858 * 429); - let capped = tone::compute_histograms_at(doc, tone::IMAGE, ToneSpace::Rgb, 3); + let capped = tone::compute_histograms_at(doc, tone::IMAGE, ToneSpace::Rgb, HistScope::Selection, 3); assert_eq!(capped.level, 3); assert_eq!(pixels(&capped), 1500 * 750, "level 3 is a 4x proxy"); } @@ -416,3 +422,132 @@ fn inspect_preview_is_the_active_documents() { app.doc_hist_preview = Some(other); assert_eq!(inspect(&app)["preview"], false); } + +/// A selection changes no pixels, but the panel counts different ones: it must recompute for +/// the selection instead of riding the #125 view-only fast path, and its Pixels statistic +/// reports the selection's size. A later view-only edit without a selection change keeps the +/// selection's histogram. +#[test] +fn the_panel_follows_the_selection() { + let mut app = app_with(json!({"width": 640, "height": 480})); + settle(&mut app); + let whole = app.doc_hist.clone().expect("landed"); + assert_eq!(inspect_stats(&app)["pixels"], 640 * 480); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 10})).unwrap(); + assert_eq!(inspect(&app)["current"], false, "the selection changed what the panel counts"); + settle(&mut app); + let selected = app.doc_hist.clone().expect("landed"); + assert_eq!(selected.key.revision, app.session.active().unwrap().revision, "fresh for the selection revision"); + assert_eq!(inspect_stats(&app)["pixels"], 200, "Pixels counts the selection"); + assert_ne!(selected.key.source, whole.key.source, "the selection changed the histogram's identity"); + // A later view-only edit (no selection change) keeps the selection histogram. + app.run("layer.new.layer", json!({})).unwrap(); + settle(&mut app); + let after = app.doc_hist.clone().expect("landed"); + assert_eq!(after.key.source, selected.key.source, "same selection, same histogram identity"); + assert_eq!(inspect_stats(&app)["pixels"], 200); +} + +/// A worker result computed before a selection change is dropped at the door: it must not be +/// cached for the selection now on screen (which would reset the 250 ms throttle and delay the +/// recomputation). +#[test] +fn a_result_computed_before_a_selection_change_is_not_cached() { + let mut app = app_with(json!({"width": 64, "height": 64})); + settle(&mut app); + let before = app.doc_hist.clone().expect("landed"); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + // A worker still holding the pre-selection result lands: the panel must reject it. + let (tx, rx) = std::sync::mpsc::channel(); + let stale = Arc::new((*before.hist).clone()); + let _ = tx.send((before.key, 1.0, stale.clone())); + app.hist_job = Some((before.key, rx)); + let ctx = egui::Context::default(); + update(&mut app, &ctx); + assert!(app.hist_job.is_none(), "the stale job was consumed, not kept"); + let after = app.doc_hist.clone().expect("the previous entry stands"); + assert_eq!(after.key.revision, before.key.revision, "the stale result was not cached over it"); + assert!(!Arc::ptr_eq(&after.hist, &stale), "the stale result was not accepted"); + assert!(Arc::ptr_eq(&after.hist, &before.hist), "the previous histogram still stands"); +} + +/// A result computed for the revision just before a pixel edit still lands: the panel shows the +/// newer data, marked stale, instead of dropping it and lagging behind continuous edits. Only +/// another document or selection is dropped at the door. +#[test] +fn a_result_one_revision_behind_still_lands() { + let mut app = app_with(json!({"width": 64, "height": 64})); + settle(&mut app); + let before = app.doc_hist.clone().expect("landed"); + app.run("edit.fill", json!({"color": "#000000"})).unwrap(); // a newer revision exists + let (tx, rx) = std::sync::mpsc::channel(); + let newer = Arc::new((*before.hist).clone()); + let _ = tx.send((before.key, 1.0, newer.clone())); + app.hist_job = Some((before.key, rx)); + let ctx = egui::Context::default(); + update(&mut app, &ctx); + assert!(app.hist_job.is_none(), "the job was consumed"); + let landed = app.doc_hist.clone().expect("the one-revision-old result lands"); + assert_eq!(landed.key.revision, before.key.revision, "landed as computed"); + assert!(Arc::ptr_eq(&landed.hist, &newer)); + assert_eq!(inspect(&app)["current"], false, "still marked stale for the newer revision"); +} + +/// The selection key is hashed once per document revision, not per frame: a memo for the +/// current revision is served as-is, and a new revision (any selection change is one) rehashes. +#[test] +fn the_selection_key_is_memoized_per_revision() { + let mut app = app_with(json!({"width": 16, "height": 16})); + settle(&mut app); + let (doc, rev) = { + let st = app.session.active().unwrap(); + (st.doc.id, st.revision) + }; + let (_, _, real) = app.hist_sel_key.expect("refreshed while the panel updates"); + // A poisoned memo for the same revision is served verbatim: the mask is not rehashed. + app.hist_sel_key = Some((doc, rev, real ^ 0xdead_beef)); + let key_of = |app: &PhotocraftApp| { + let st = app.session.active().unwrap(); + let (_, source) = resolve_source(st, source_choice(&app.ui.histogram_panel)); + let poisoned = app.hist_sel_key.is_some_and(|(d, r, _)| d == st.doc.id && r == st.revision); + (poisoned, tone::tag(source, tone_space(st.doc.mode), HistScope::Selection, app.hist_sel_key.map_or(0, |(_, _, k)| k))) + }; + assert_eq!(key_of(&app), (true, committed_key(&app).unwrap().0.source), "the memo is served, not rehashed"); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + let (rev2, fresh) = { + let st = app.session.active().unwrap(); + (st.revision, tone::selection_key(&st.doc)) + }; + assert_ne!(rev2, rev, "a selection change is a new revision"); + let ctx = egui::Context::default(); + update(&mut app, &ctx); + assert_eq!(app.hist_sel_key, Some((doc, rev2, fresh)), "the new revision rehashed the mask"); +} + +/// The panel's Pixels statistic counts the pixels the selection covers, transparent ones +/// included, while the histogram bins keep skipping them: a selection over a transparent canvas +/// reports the selection's size. +#[test] +fn the_panel_reports_the_selection_size_over_transparent_pixels() { + let mut app = app_with(json!({"width": 32, "height": 32, "background": "transparent"})); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 16, "height": 32})).unwrap(); + settle(&mut app); + assert_eq!(inspect_stats(&app)["pixels"], 16 * 32, "the transparent selected pixels still count"); + app.ui.histogram_panel.view = HistView::Expanded; + frame(&mut app); +} + +/// The tone editors' histogram shows the adjustment's whole input (Photoshop's dialogs are not +/// selection-masked), so a selection change — view-only, no pixels moved — keeps the cached +/// histogram (#125). The panel's masked histogram is covered above. +#[test] +fn the_tone_histogram_cache_ignores_selection_changes() { + let mut app = app_with(json!({"width": 64, "height": 64})); + let src = tone::IMAGE; + let first = tone::histograms(&mut app, src, ToneSpace::Rgb); + assert!(Arc::ptr_eq(&first, &tone::histograms(&mut app, src, ToneSpace::Rgb)), "unchanged state reuses the cache"); + app.run("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + assert!(Arc::ptr_eq(&first, &tone::histograms(&mut app, src, ToneSpace::Rgb)), "a selection change is view-only for the whole-input histogram"); + app.run("select.deselect", json!({})).unwrap(); + assert!(Arc::ptr_eq(&first, &tone::histograms(&mut app, src, ToneSpace::Rgb)), "deselecting keeps it too"); +} diff --git a/crates/ui-egui/src/panels/history_menu_ui.rs b/crates/ui-egui/src/panels/history_menu_ui.rs index fa865d42c4..15fe4e9886 100644 --- a/crates/ui-egui/src/panels/history_menu_ui.rs +++ b/crates/ui-egui/src/panels/history_menu_ui.rs @@ -43,7 +43,11 @@ fn enabled(app: &PhotocraftApp, cmd: &str) -> bool { return !app.session.prefs().workspace_locked; } // An open Free Transform owns the history (see `panels::history`), and a drawn crop frame - // holds its jumps back (`crop_ui::holds_history`). + // holds its jumps back (`crop_ui::holds_history`). A Pen path being drawn steps back anchor + // by anchor (`vector_ui::pen_history_enabled`). + if let Some(on) = crate::vector_ui::pen_history_enabled(app, cmd) { + return on; + } app.ui.transform.is_none() && !crate::crop_ui::holds_history(app, cmd) && app.session.is_enabled(cmd) } @@ -64,8 +68,11 @@ pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let Some(cmd) = clicked else { return }; ui.close(); let (cmd, params) = resolve(cmd, snapshot); - // History Options… opens its dialog, as the menu bar's command does. - let result = crate::history_options_ui::menu(app, cmd, ¶ms).unwrap_or_else(|| app.run(cmd, params)); + // History Options… opens its dialog, as the menu bar's command does. Step Backward/Forward + // over a Pen path step it as Edit › Undo/Redo do (`vector_ui::pen_history_step`). + let result = crate::history_options_ui::menu(app, cmd, ¶ms) + .or_else(|| crate::vector_ui::pen_history_step(app, cmd).map(|r| r.map(|_| Value::Null))) + .unwrap_or_else(|| app.run(cmd, params)); if let Err(e) = result { app.ui.status = e; app.ui.status_error = true; @@ -159,6 +166,26 @@ mod tests { } } + /// Step Backward after a Pen path was closed gives it back to the Pen, open, rather than + /// deleting it; Step Forward closes it again (#6619), as Edit › Undo and Redo do. + #[test] + fn steps_over_a_finished_pen_path_give_it_back_to_the_pen() { + let mut app = app(); + app.ui.tool = crate::state::Tool::Pen; + for (x, y) in [(10.0, 10.0), (50.0, 10.0), (50.0, 40.0), (10.0, 10.0)] { + crate::vector_ui::pen_down(&mut app, x, y, false); + crate::vector_ui::pen_up(&mut app); + } + assert!(app.ui.pen.is_none(), "the path is closed"); + let mut h = harness(app); + click(&mut h, "Step Backward"); + assert_eq!(h.state().ui.pen.as_ref().map(|p| p.knots.len()), Some(3), "the open path is back on the Pen"); + assert!(h.state().session.active().unwrap().doc.work_path.is_none()); + click(&mut h, "Step Forward"); + assert!(h.state().ui.pen.is_none()); + assert!(h.state().session.active().unwrap().doc.work_path.as_ref().unwrap().subpaths[0].closed); + } + /// A drawn crop frame greys the items that move the document under it (#9285). #[test] fn jumps_wait_for_a_drawn_crop_frame() { diff --git a/crates/ui-egui/src/panels/layer_props_ui.rs b/crates/ui-egui/src/panels/layer_props_ui.rs index 9bba0ebf7e..677b332503 100644 --- a/crates/ui-egui/src/panels/layer_props_ui.rs +++ b/crates/ui-egui/src/panels/layer_props_ui.rs @@ -933,10 +933,10 @@ mod tests { ); // The next live-property edit must still be accepted after resizing. - s.execute("shape.edit", json!({"layer": id.0, "arrowConcavity": 60.0})).unwrap(); + s.execute("shape.edit", json!({"layer": id.0, "arrowConcavity": 40.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)); + assert!(matches!(shape.live.as_ref(), Some(photocraft_doc::vector::LiveShape::ArrowLine { concavity, .. }) if (*concavity - 40.0).abs() < 1e-9)); } /// A stroked shape's Transform fields show its path, not the stroke's pixels, and a W edit diff --git a/crates/ui-egui/src/panels/layer_row.rs b/crates/ui-egui/src/panels/layer_row.rs index d0cd501ef8..e207b609e4 100644 --- a/crates/ui-egui/src/panels/layer_row.rs +++ b/crates/ui-egui/src/panels/layer_row.rs @@ -165,6 +165,26 @@ pub(super) fn paint_clipping_indicator(painter: &egui::Painter, at: Pos2, color: painter.add(egui::Shape::line(vec![at + vec2(2.0, 0.0), tip, at + vec2(8.0, 0.0)], stroke)); } +/// Where the row's disclosure triangle starts (after the eye column and the depth's indentation) and +/// the layer thumbnail's size, for a row `rect` with thumbnails of `base` (0 when off). The painted +/// row and an off-screen group's widget-only triangle share it, so the hit area is the same (#13117). +fn triangle_x_and_thumb_size(l: &Layer, depth: usize, rect: Rect, base: f32) -> (f32, f32) { + // Everything but the thumbnails, the indentation and the name, so a narrow panel squeezes + // the indentation first, then the thumbnails (a layer with two masks has three). + let others = 6.0 + + 28.0 + + if l.is_group() { crate::layer_tree_ui::TRIANGLE_W } else { 0.0 } + + if l.clipped { 12.0 } else { 0.0 } + + crate::layer_row_ui::reserved_width(l); + let ts = if base == 0.0 { 0.0 } else { crate::mask_thumbs_ui::thumb_size(l, base, rect.width() - others) }; + let fixed = others + if ts == 0.0 { 0.0 } else { ts + 6.0 + crate::mask_thumbs_ui::width(l, ts) }; + // A layer inside a group (or an artboard) indents one step more than its depth, past the + // triangle's column, so it sits right of its parent: with only its depth its thumbnail lined + // up under the group's, hiding the hierarchy. Top-level rows don't move. + let steps = if !l.is_group() && depth > 0 { depth + 1 } else { depth }; + (rect.left() + 6.0 + 28.0 + crate::layer_row_ui::indent(steps, rect.width(), fixed), ts) +} + /// Height of an artboard's row. Photoshop sets artboards apart from layers and groups in the /// Layers panel: a shorter row with the name in bold and no thumbnail (a board is a canvas, not a /// folder), so the boards read as headings over their layers (#10218). @@ -215,9 +235,14 @@ pub(super) fn layer_row( // Rows are painted: name them for screen readers and UI tests. resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &l.name)); // A row scrolled out of view only keeps its place (#125): a layout's hundreds of rows would - // otherwise lay out names, icons and thumbnails every frame. Group rows stay whole: their - // disclosure triangle is a widget (accessibility, scroll-to). - if !ui.is_rect_visible(rect) && !l.is_group() && !resp.context_menu_opened() && crate::layer_row_ui::renaming(ctx) != Some(l.id.0) { + // otherwise lay out names, icons and thumbnails every frame. An off-screen group row keeps only + // its disclosure widget (accessibility, scroll-to) and paints nothing (#13117). A row whose + // menu (its own or the eye column's) is open, or that is being renamed, stays whole. + if !ui.is_rect_visible(rect) && !resp.context_menu_opened() && !eye_menu_open(ui, l) && crate::layer_row_ui::renaming(ctx) != Some(l.id.0) { + if l.is_group() { + let (x, _) = triangle_x_and_thumb_size(l, depth, rect, base); + crate::layer_tree_ui::disclosure_widget(ui, rect, x, l, actions); + } return rect; } let painter = ui.painter_at(rect.expand(1.0)); @@ -226,22 +251,8 @@ pub(super) fn layer_row( app.hover_layer = Some(l.id); } paint_row_background(&painter, &t, l, rect, selected, is_hovered); - let mut x = rect.left() + 6.0; let eye_resp = eye_column(app, ui, l, row, rect, actions); - // Everything but the thumbnails, the indentation and the name, so a narrow panel squeezes - // the indentation first, then the thumbnails (a layer with two masks has three). - let others = 6.0 - + 28.0 - + if l.is_group() { crate::layer_tree_ui::TRIANGLE_W } else { 0.0 } - + if l.clipped { 12.0 } else { 0.0 } - + crate::layer_row_ui::reserved_width(l); - let ts = if base == 0.0 { 0.0 } else { crate::mask_thumbs_ui::thumb_size(l, base, rect.width() - others) }; - let fixed = others + if ts == 0.0 { 0.0 } else { ts + 6.0 + crate::mask_thumbs_ui::width(l, ts) }; - // A layer inside a group (or an artboard) indents one step more than its depth, past the - // triangle's column, so it sits right of its parent: with only its depth its thumbnail lined - // up under the group's, hiding the hierarchy. Top-level rows don't move. - let steps = if !l.is_group() && depth > 0 { depth + 1 } else { depth }; - x += 28.0 + crate::layer_row_ui::indent(steps, rect.width(), fixed); + let (mut x, ts) = triangle_x_and_thumb_size(l, depth, rect, base); let toggled = crate::layer_tree_ui::disclosure(ui, rect, &mut x, l, actions); if l.clipped { paint_clipping_indicator(&painter, pos2(x, rect.center().y), t.text_faint); @@ -387,6 +398,18 @@ fn paint_row_background(painter: &egui::Painter, t: &Tokens, l: &Layer, rect: Re } } +/// The eye column's widget id. +fn eye_id(ui: &egui::Ui, l: &Layer) -> egui::Id { + ui.scope_id().with(("eye", l.id.0)) +} + +/// Whether the eye column's colour menu is open. It is the eye response's own context menu (egui +/// keys it `Popup::default_response_id`: the widget id with "popup"), not the row's, and egui closes +/// a popup that isn't shown in a frame, so a row with it open must not be culled. +fn eye_menu_open(ui: &egui::Ui, l: &Layer) -> bool { + egui::Popup::is_id_open(ui.ctx(), eye_id(ui, l).with("popup")) +} + /// The eye column: visibility toggle (⌥ shows only this layer), sweep-drag and its colour menu. fn eye_column(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, row: RowSel, rect: Rect, actions: &mut Vec<(String, Value)>) -> egui::Response { let ctx = &ui.ctx().clone(); @@ -395,7 +418,7 @@ fn eye_column(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, row: RowSel let eye_cell = eye_cell(rect); // The whole eye column takes drags too (so a drag starting on it never reorders the row): dragging down // the eyes gives every row swept over the visibility the first eye toggled to (#8467). - let eye_resp = ui.interact(eye_cell, ui.scope_id().with(("eye", l.id.0)), Sense::click_and_drag()); + let eye_resp = ui.interact(eye_cell, eye_id(ui, l), Sense::click_and_drag()); // A hidden layer's eye box is left empty (still clickable; the whole column takes the click, #8467). if l.visible { // Centre the drawing in the column while preserving the visibility hit area. diff --git a/crates/ui-egui/src/panels/layer_tree_ui.rs b/crates/ui-egui/src/panels/layer_tree_ui.rs index 1d7586f4c6..f6f36d4ae4 100644 --- a/crates/ui-egui/src/panels/layer_tree_ui.rs +++ b/crates/ui-egui/src/panels/layer_tree_ui.rs @@ -52,15 +52,33 @@ pub fn triangle_rect(row: Rect, x: f32) -> Rect { Rect::from_min_size(pos2(x - 2.0, row.top()), vec2(TRIANGLE_W + 2.0, row.height())) } -/// Paint and handle a group row's disclosure triangle at `*x` (advancing it). Returns true when -/// it was clicked this frame, so the row doesn't also treat the click as a selection. -pub fn disclosure(ui: &mut egui::Ui, row: Rect, x: &mut f32, l: &Layer, actions: &mut Vec<(String, Value)>) -> bool { +/// A group row's disclosure triangle as a widget only, at `x`: its hit area, the click that queues +/// `layer.setExpanded`, the tooltip and the accessibility label ("Expand group {name}" / "Collapse +/// group {name}"). Paints nothing, so a row scrolled out of view keeps the widget (accessibility, +/// scroll-to) without painting its row (#13117). `None` for a layer that is no group, or a frame. +pub fn disclosure_widget(ui: &mut egui::Ui, row: Rect, x: f32, l: &Layer, actions: &mut Vec<(String, Value)>) -> Option { if l.frame.is_some() { - return false; + return None; } + let LayerContent::Group(g) = &l.content else { return None }; + let resp = ui.interact(triangle_rect(row, x), ui.scope_id().with(("disclosure", l.id.0)), Sense::click()); + if resp.clicked() { + let all = ui.input(|i| i.modifiers.alt); + actions.push(("layer.setExpanded".into(), json!({"layer": l.id.0, "expanded": !g.expanded, "all": all}))); + } + let (verb, name) = (if g.expanded { tl!("Collapse") } else { tl!("Expand") }, l.name.clone()); + let tip = if g.expanded { tl!("Collapse group ({key}-click: all groups)") } else { tl!("Expand group ({key}-click: all groups)") }; + let resp = resp.on_hover_text(crate::i18n::fmt(tip, &[("key", &crate::shortcuts::pretty("Alt"))])); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("{verb} group {name}"))); + Some(resp) +} + +/// Paint and handle a group row's disclosure triangle at `*x` (advancing it): the widget of +/// [`disclosure_widget`] plus the triangle. Returns true when it was clicked this frame, so the row +/// doesn't also treat the click as a selection. +pub fn disclosure(ui: &mut egui::Ui, row: Rect, x: &mut f32, l: &Layer, actions: &mut Vec<(String, Value)>) -> bool { + let Some(resp) = disclosure_widget(ui, row, *x, l, actions) else { return false }; let LayerContent::Group(g) = &l.content else { return false }; - let hit = triangle_rect(row, *x); - let resp = ui.interact(hit, ui.scope_id().with(("disclosure", l.id.0)), Sense::click()); let t = Tokens::get(ui.ctx()); let c = pos2(*x + TRIANGLE_W / 2.0 - 1.0, row.center().y); let s = 3.5; @@ -72,16 +90,7 @@ pub fn disclosure(ui: &mut egui::Ui, row: Rect, x: &mut f32, l: &Layer, actions: let color = if resp.hovered() { t.text } else { t.icon }; ui.painter().add(Shape::convex_polygon(pts, color, Stroke::NONE)); *x += TRIANGLE_W; - let clicked = resp.clicked(); - if clicked { - let all = ui.input(|i| i.modifiers.alt); - actions.push(("layer.setExpanded".into(), json!({"layer": l.id.0, "expanded": !g.expanded, "all": all}))); - } - let (verb, name) = (if g.expanded { tl!("Collapse") } else { tl!("Expand") }, l.name.clone()); - let tip = if g.expanded { tl!("Collapse group ({key}-click: all groups)") } else { tl!("Expand group ({key}-click: all groups)") }; - let resp = resp.on_hover_text(crate::i18n::fmt(tip, &[("key", &crate::shortcuts::pretty("Alt"))])); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("{verb} group {name}"))); - clicked + resp.clicked() } #[cfg(test)] diff --git a/crates/ui-egui/src/panels/layer_tree_ui/tests.rs b/crates/ui-egui/src/panels/layer_tree_ui/tests.rs index dfc1f44fb0..0a0873e8cb 100644 --- a/crates/ui-egui/src/panels/layer_tree_ui/tests.rs +++ b/crates/ui-egui/src/panels/layer_tree_ui/tests.rs @@ -141,3 +141,91 @@ fn state_survives_psd_export_and_import_and_imported_groups_toggle() { click(&mut h, p, Modifiers::NONE); assert!(!group(&h, "outer").1); } + +/// Background, a collapsed group "Low Group" at the bottom of the list, 40 fillers above it (so it +/// sits below the Layers panel's fold) and a collapsed "High Group" on top (#13117). +fn long_list_with_groups() -> photocraft_engine::Session { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + s.execute("layer.new.layer", json!({"name": "low child"})).unwrap(); + s.execute("layer.groupLayers", json!({"name": "Low Group"})).unwrap(); + for i in 0..40 { + s.execute("layer.new.layer", json!({"name": format!("Filler {i}")})).unwrap(); + } + s.execute("layer.new.layer", json!({"name": "high child"})).unwrap(); + s.execute("layer.groupLayers", json!({"name": "High Group"})).unwrap(); + s +} + +/// Every text painted in the harness's last frame, with its screen position. +fn painted_texts(h: &Harness<'_, PhotocraftApp>) -> Vec<(String, Pos2)> { + fn walk(s: &egui::Shape, out: &mut Vec<(String, Pos2)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.pos)), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let mut out = Vec::new(); + h.output().shapes.iter().for_each(|c| walk(&c.shape, &mut out)); + out +} + +/// #13117: a group row scrolled out of view paints nothing, like any other off-screen row; only +/// its disclosure widget stays (the next test). +#[test] +fn off_screen_group_paints_no_row() { + let h = harness_with(long_list_with_groups(), 1.0); + let window = h.ctx.content_rect(); + let low = h.get_by_label("Low Group").rect(); + let high = h.get_by_label("High Group").rect(); + assert!(low.top() >= window.bottom(), "Low Group sits below the fold: {low:?} vs {window:?}"); + assert!(window.contains_rect(high), "High Group shows: {high:?}"); + let named_in = |name: &str, row: egui::Rect| painted_texts(&h).iter().any(|(t, p)| t == name && p.y >= row.top() && p.y <= row.bottom()); + assert!(named_in("High Group", high), "the on-screen group's name is painted"); + assert!(!named_in("Low Group", low), "the off-screen group's row paints no name"); + // Nor any other text: no text shape lands in the off-screen row at all. + let in_low: Vec<_> = painted_texts(&h).into_iter().filter(|(_, p)| low.contains(*p)).collect(); + assert!(in_low.is_empty(), "the off-screen group's row adds no text shapes: {in_low:?}"); +} + +/// #13117: skipping the off-screen group's painting keeps its triangle a widget: it is listed for +/// accessibility, and scrolled to, it still toggles the group. +#[test] +fn off_screen_group_disclosure_stays_reachable() { + let mut h = harness_with(long_list_with_groups(), 1.0); + assert!(h.query_by_label("Expand group Low Group").is_some(), "the off-screen group keeps its disclosure widget"); + assert!(!group(&h, "Low Group").1); + let p = triangle(&mut h, "Low Group").expect("scrolled to the off-screen group's triangle"); + click(&mut h, p, Modifiers::NONE); + assert!(group(&h, "Low Group").1, "clicking it expands the group"); +} + +/// #13127 review: a group row whose eye-column colour menu is open stays whole when it scrolls +/// out of view. The menu is the eye's own popup, which egui closes if a frame doesn't show it. +#[test] +fn eye_menu_survives_its_group_scrolling_off_screen() { + let mut h = harness_with(long_list_with_groups(), 1.0); + let window = h.ctx.content_rect(); + let high = h.get_by_label("High Group").rect(); + assert!(window.contains_rect(high), "High Group shows: {high:?}"); + // Right-click High Group's eye column (the row's left 30 points): its colour menu opens. + let eye = egui::pos2(high.left() + 15.0, high.center().y); + h.hover_at(eye); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: eye, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: eye, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + assert!(egui::Popup::is_any_open(&h.ctx), "the eye column's colour menu opened"); + // Scroll the list to its bottom group, taking High Group out of view, without a click. + h.query_by_label("Expand group Low Group").expect("Low Group's disclosure").scroll_to_me(); + h.run_steps(6); + let high = h.get_by_label("High Group").rect(); + let low = h.get_by_label("Low Group").rect(); + // Low Group is in view, and High Group sits more than a window's height above it, so it is + // outside the panel's (shorter) list. + assert!(window.contains_rect(low), "scrolled to Low Group: {low:?}"); + assert!(high.bottom() < low.top() - window.height(), "High Group is out of view: {high:?} vs {low:?}"); + assert!(egui::Popup::is_any_open(&h.ctx), "the colour menu stays open while its row is out of view"); +} diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 32f22e9cfd..74df52cd36 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -92,7 +92,13 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { crate::chrome_ui::home_button(app, ui); widgets::vline(ui, 22.0); } - let tool_icon = icons::button(ui, icons::tool_icon(app.ui.tool), if t.pro { 26.0 } else { 28.0 }, !t.pro, tl!(app.ui.tool.label())); + // The tool preset picker is greyed while warping, as in the reference (#12503). + let warping = app.ui.transform.as_ref().is_some_and(|s| s.warp.is_some()); + let tool_icon = ui + .add_enabled_ui(!warping, |ui| { + icons::button(ui, icons::tool_icon(app.ui.tool), if t.pro { 26.0 } else { 28.0 }, !t.pro, tl!(app.ui.tool.label())) + }) + .inner; // Photoshop: right-click the tool icon for Reset Tool / Reset All Tools (#2825). let mut reset = None; tool_icon.context_menu(|ui| { @@ -142,19 +148,30 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // Its list has Behind, greyed on the Background (#12879). opt_label(ui, tl!("Mode")); let behind = crate::brush_mode_menu::enabled(app, crate::brush_mode_menu::Item::Behind); - super::brush_controls::pattern_stamp_mode_dropdown(ui, "retouch-mode", &mut brush, behind); + // An Indexed Color document names Normal "Threshold" (#12887); the other + // entries weren't measured there. + let threshold = app.session.active().is_some_and(|st| st.doc.mode == photocraft_doc::ColorMode::Indexed); + super::brush_controls::pattern_stamp_mode_dropdown(ui, "retouch-mode", &mut brush, behind, threshold); } else if let Some(modes) = crate::blend_keys::tool_modes(tool) { opt_label(ui, tl!("Mode")); - if let Some(Some(m)) = - tool_mode_dropdown(ui, "retouch-mode", &modes, Some(crate::blend_keys::brush_tool_mode(tool, brush.mode))) - { + let mode = crate::blend_keys::brush_tool_mode(tool, brush.mode); + // Indexed Color names Normal "Threshold"; the other modes weren't measured. + let threshold = crate::retouch_ui::clone_stamp_indexed(app); + if let Some(Some(m)) = tool_mode_dropdown(ui, "retouch-mode", &modes, Some(mode), threshold) { brush.mode = m; } } - if matches!(tool, Tool::CloneStamp | Tool::HistoryBrush) { + if matches!(tool, Tool::CloneStamp | Tool::PatternStamp | Tool::HistoryBrush) { let width = if t.pro { 62.0 } else { 66.0 }; - percent_field(ui, tl!("Opacity"), &mut brush.opacity, 1.0..=100.0, width); - percent_field(ui, tl!("Flow"), &mut brush.flow, 1.0..=100.0, width); + // The Pattern Stamp's are whole percents as measured; the Brush's tooltips (#12616). + let pattern = tool == Tool::PatternStamp; + let field = if pattern { whole_percent_field } else { percent_field }; + let opacity = field(ui, tl!("Opacity"), &mut brush.opacity, 1.0..=100.0, width); + let flow = field(ui, tl!("Flow"), &mut brush.flow, 1.0..=100.0, width); + if pattern { + opacity.on_hover_text(tl!("Set opacity for stroke")); + flow.on_hover_text(tl!("Set flow rate for stroke")); + } } // Art History has no Mode (the engine paints Normal) and no Flow. if tool == Tool::ArtHistoryBrush { @@ -514,7 +531,7 @@ fn selection_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: if let Some(modes) = crate::blend_keys::tool_modes(tool) { let o = &mut app.ui.tool_options; let current = if o.bucket_clear { None } else { Some(o.bucket_blend_mode) }; - if let Some(m) = tool_mode_dropdown(ui, "bucket-mode", &modes, current) { + if let Some(m) = tool_mode_dropdown(ui, "bucket-mode", &modes, current, false) { o.bucket_clear = m.is_none(); if let Some(m) = m { o.bucket_blend_mode = m; @@ -785,6 +802,13 @@ fn tool_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, } Tool::Eyedropper => crate::eyedropper_ui::options(app, ui), Tool::Zoom => { + // Zoom In / Zoom Out: a pair, exactly one pressed; Zoom Out makes a click step out. + for (zoom_in, icon, tip) in [(true, "zoom-in", tl!("Zoom In")), (false, "zoom-out", tl!("Zoom Out"))] { + if icons::button(ui, icon, 24.0, app.ui.tool_options.zoom_in == zoom_in, tip).clicked() { + app.ui.tool_options.zoom_in = zoom_in; + } + } + widgets::vline(ui, 22.0); // Resize Windows to Fit is Preferences › Zoom Resizes Windows itself, as in // Photoshop: one setting, shown in both places (zoom_window_fit.rs). let mut fit = app.session.prefs().general.zoom_resizes_windows; @@ -1003,7 +1027,7 @@ fn eraser_percent(ui: &mut egui::Ui, label: &str, value: &mut f32) -> bool { } /// Shows one of the range alerts as a modal with OK, once even if more than one pass asks. -fn range_alert(ui_state: &mut crate::state::UiState, text: &str) { +pub(crate) fn range_alert(ui_state: &mut crate::state::UiState, text: &str) { let message = tl!(text).to_owned(); let shown = ui_state.dialogs.iter().any(|d| d.kind == crate::state::DialogKind::Error && d.fields.get("message").and_then(|m| m.as_str()) == Some(&message)); @@ -1044,3 +1068,7 @@ mod sharpen_strength_alert_tests; #[cfg(test)] #[path = "../smudge_strength_alert_tests.rs"] mod smudge_strength_alert_tests; + +#[cfg(test)] +#[path = "../pattern_stamp_opacity_flow_tests.rs"] +mod pattern_stamp_opacity_flow_tests; diff --git a/crates/ui-egui/src/panels/preset_panels.rs b/crates/ui-egui/src/panels/preset_panels.rs index 29b5d85a95..6fc7c4ea7f 100644 --- a/crates/ui-egui/src/panels/preset_panels.rs +++ b/crates/ui-egui/src/panels/preset_panels.rs @@ -18,11 +18,15 @@ use crate::PhotocraftApp; use crate::state::Tool; use crate::theme::Tokens; +mod clone_offsets; mod panels; +pub use clone_offsets::{clone_mapping_at, clone_sample_point}; +pub(crate) use clone_offsets::{clone_offset_edit, clone_offset_readout, remember_clone_cursor}; + pub use panels::{ - clone_sample_point, clone_source_panel, finish_custom_shape, gradients_panel, patterns_panel, select_tool_preset, shape_picker, shapes_panel, styles_panel, - tool_presets_panel, windows, + clone_source_panel, finish_custom_shape, gradients_panel, patterns_panel, select_tool_preset, shape_picker, shapes_panel, styles_panel, tool_presets_panel, + windows, }; #[cfg(test)] use panels::{new_tool_preset_params, tool_id}; @@ -36,6 +40,9 @@ pub struct PresetUi { pub shapes: bool, pub tool_presets: bool, pub clone_source: bool, + /// Last clone preview position in its destination document; never restored into another session. + #[serde(skip)] + pub clone_cursor: Option<(photocraft_doc::DocId, [f64; 2])>, /// Thumbnail size per panel (px; the minimum shows a list). pub sizes: BTreeMap, /// Folders whose open state differs from the default (only the first folder starts open). diff --git a/crates/ui-egui/src/panels/preset_panels/clone_offsets.rs b/crates/ui-egui/src/panels/preset_panels/clone_offsets.rs new file mode 100644 index 0000000000..7c14cebaff --- /dev/null +++ b/crates/ui-egui/src/panels/preset_panels/clone_offsets.rs @@ -0,0 +1,66 @@ +//! Read-only clone geometry shared by the panel, overlay and source marker. + +use photocraft_engine::presets::clone_source::{Mapping, resolve}; + +use super::{PhotocraftApp, Tool, Value, json}; + +/// Remember a document-space preview position when the pointer is over the active canvas. +/// Retain it while the pointer enters the panel so editing X/Y uses the readout's reference. +pub(crate) fn remember_clone_cursor(app: &mut PhotocraftApp, at: [f64; 2]) -> bool { + if !matches!(app.ui.tool, Tool::CloneStamp | Tool::Healing) || !at.into_iter().all(|v| v.is_finite() && v.abs() < 1_000_000.0) { + return false; + } + if let Some(document) = app.session.active().map(|st| st.doc.id) { + let next = Some((document, at)); + if app.ui.presets_ui.clone_cursor != next { + app.ui.presets_ui.clone_cursor = next; + return true; + } + } + false +} + +/// Resolve the exact sampling geometry without storing a painting anchor or changing a source. +pub fn clone_mapping_at(app: &PhotocraftApp, at: Option<[f64; 2]>) -> Option { + let slot = app.session.presets.clone.active(); + let source = slot.source?; + let start = app.drag.as_ref().filter(|d| matches!(d.tool, Tool::CloneStamp | Tool::Healing)).map(|d| d.start); + let first = start.or(at).or(slot.last_anchor).or(slot.anchor).unwrap_or(source); + let params = json!({"aligned": app.ui.tool_options.clone_aligned}); + let (map, _) = resolve(&app.session, ¶ms, (first[0], first[1]), "clone.preview").ok()?; + [map.source.0, map.source.1, map.anchor.0, map.anchor.1].into_iter().chain(map.m).all(|v| v.is_finite() && v.abs() < 1_000_000.0).then_some(map) +} + +/// Pairing currently previewed in this document, or the most recently committed pairing. +fn panel_mapping(app: &PhotocraftApp) -> Option { + let cursor = app + .ui + .presets_ui + .clone_cursor + .filter(|(id, _)| app.session.active().is_some_and(|st| st.doc.id == *id)) + .filter(|_| matches!(app.ui.tool, Tool::CloneStamp | Tool::Healing)) + .map(|(_, at)| at); + clone_mapping_at(app, cursor) +} + +/// Source-minus-destination displacement in document pixels, independent of canvas zoom. +pub(crate) fn clone_offset_readout(app: &PhotocraftApp) -> Option<[f64; 2]> { + let map = panel_mapping(app)?; + Some([map.source.0 - map.anchor.0, map.source.1 - map.anchor.1]) +} + +/// Edit exactly the reference shown in X/Y, including before the first paint or with Aligned off. +pub(crate) fn clone_offset_edit(app: &PhotocraftApp, offset: [f64; 2]) -> Option { + let map = panel_mapping(app)?; + Some(json!({"offset": offset, "anchor": [map.anchor.0, map.anchor.1]})) +} + +/// Where the source marker samples at a canvas point, using the overlay's mapping. +pub fn clone_sample_point(app: &PhotocraftApp, at: Option<[f64; 2]>) -> Option<[f64; 2]> { + let map = clone_mapping_at(app, at)?; + let (x, y) = at.map_or(map.source, |at| map.map(at[0], at[1])); + Some([x, y]) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/panels/preset_panels/clone_offsets/tests.rs b/crates/ui-egui/src/panels/preset_panels/clone_offsets/tests.rs new file mode 100644 index 0000000000..0d2f143ed2 --- /dev/null +++ b/crates/ui-egui/src/panels/preset_panels/clone_offsets/tests.rs @@ -0,0 +1,159 @@ +use super::*; +use crate::canvas::{Drag, ToolEvent, tool_event}; +use photocraft_engine::Session; + +/// Create two distinguishable source colours and an empty layer for real mouse strokes. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + app.run("paint.pencil", json!({"points": [[16,16]], "size": 4, "color": "#ff0000"})).unwrap(); + app.run("paint.pencil", json!({"points": [[20,16]], "size": 4, "color": "#0000ff"})).unwrap(); + app.ui.tool = Tool::CloneStamp; + crate::paint_mouse::sync_tool_brush(&mut app); + app.run("tools.setBrush", json!({"size": 8, "hardness": 1, "opacity": 1, "flow": 1})).unwrap(); + crate::retouch_ui::set_source(&mut app, 16.0, 16.0); + app.run("layer.new.layer", json!({})).unwrap(); + app +} + +/// Exercise the same Down/Up path used by canvas interaction. +fn stamp(app: &mut PhotocraftApp, at: [f64; 2]) { + remember_clone_cursor(app, at); + tool_event(app, ToolEvent::Down { x: at[0], y: at[1], pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: at[0], y: at[1] }, egui::Modifiers::NONE); + assert!(!app.ui.status_error, "{}", app.ui.status); +} + +/// Hover may change a displayed pairing but cannot alter source state or document revision. +#[test] +fn clone_offset_hover_readout_does_not_establish_a_painting_anchor() { + for aligned in [false, true] { + let mut app = app(); + app.ui.tool_options.clone_aligned = aligned; + let before = app.session.presets.clone.clone(); + let revision = app.session.active().unwrap().revision; + for at in [[40.0, 30.0], [50.0, 40.0]] { + remember_clone_cursor(&mut app, at); + assert_eq!(clone_offset_readout(&app), Some([16.0 - at[0], 16.0 - at[1]])); + assert_eq!(app.session.presets.clone, before); + assert_eq!(app.session.active().unwrap().revision, revision); + } + } +} + +/// Entering the panel must retain the last canvas reference for a numeric offset edit. +#[test] +fn clone_offset_edit_before_painting_uses_the_preview_reference_and_matches_pixels() { + for aligned in [false, true] { + let mut app = app(); + app.ui.tool_options.clone_aligned = aligned; + remember_clone_cursor(&mut app, [40.0, 30.0]); + app.hover_doc = None; // The pointer left the canvas to edit the panel. + let edit = clone_offset_edit(&app, [-20.0, -14.0]).unwrap(); + assert_eq!(edit["anchor"], json!([40.0, 30.0])); + app.run("cloneSource.set", edit).unwrap(); + assert_eq!(clone_offset_readout(&app), Some([-20.0, -14.0])); + stamp(&mut app, [40.0, 30.0]); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(40, 30), [0.0, 0.0, 1.0, 1.0]); + assert_eq!(clone_sample_point(&app, Some([40.0, 30.0])), Some([20.0, 16.0])); + } +} + +/// Reporting an unaligned stroke must not discard the established aligned sampling origin. +#[test] +fn clone_offset_readout_tracks_aligned_mode_without_replacing_its_saved_anchor() { + let mut app = app(); + stamp(&mut app, [40.0, 30.0]); + remember_clone_cursor(&mut app, [50.0, 40.0]); + assert_eq!(clone_offset_readout(&app), Some([-24.0, -14.0])); + let original_anchor = app.session.presets.clone.active().anchor; + app.ui.tool_options.clone_aligned = false; + assert_eq!(clone_offset_readout(&app), Some([-34.0, -24.0])); + stamp(&mut app, [50.0, 40.0]); + assert_eq!(app.session.presets.clone.active().anchor, original_anchor); + assert_eq!(clone_offset_readout(&app), Some([-34.0, -24.0])); + app.ui.tool_options.clone_aligned = true; + assert_eq!(clone_offset_readout(&app), Some([-24.0, -14.0])); + assert_eq!(app.session.presets.clone.active().anchor, original_anchor); +} + +/// A slot switch changes the source; a cursor from another destination cannot set its reference. +#[test] +fn clone_offset_readout_uses_the_selected_slot_and_destination_document() { + let mut app = app(); + let source_layer = app.session.presets.clone.active().layer.unwrap(); + remember_clone_cursor(&mut app, [40.0, 30.0]); + app.run("cloneSource.set", json!({"index": 2, "source": [20,16], "layer": source_layer})).unwrap(); + assert_eq!(clone_offset_readout(&app), Some([-20.0, -14.0])); + app.run("cloneSource.select", json!({"index": 0})).unwrap(); + assert_eq!(clone_offset_readout(&app), Some([-24.0, -14.0])); + app.run("cloneSource.select", json!({"index": 1})).unwrap(); + assert!(clone_offset_readout(&app).is_none()); + assert!(clone_offset_edit(&app, [0.0, 0.0]).is_none()); + app.run("cloneSource.select", json!({"index": 0})).unwrap(); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + assert_eq!(clone_offset_readout(&app), Some([0.0, 0.0]), "another destination has no preview position yet"); + remember_clone_cursor(&mut app, [50.0, 40.0]); + assert_eq!(clone_offset_readout(&app), Some([-34.0, -24.0])); + assert!(app.session.set_active(0)); + assert_eq!(clone_offset_readout(&app), Some([0.0, 0.0]), "a cursor from another document cannot become this one's reference"); +} + +/// The marker and readout use the same scaled, rotated or flipped mapping as sampling. +#[test] +fn clone_offsets_share_transformed_sampling_geometry_during_a_stroke() { + for (transform, want) in [ + (json!({"width": 200}), [18.0, 18.0]), + (json!({"rotation": 90}), [14.0, 20.0]), + (json!({"flipH": true}), [12.0, 18.0]), + (json!({"flipV": true}), [20.0, 14.0]), + ] { + let mut app = app(); + app.ui.tool_options.clone_aligned = false; + app.run("cloneSource.set", transform).unwrap(); + app.drag = Some(Drag::new(Tool::CloneStamp, [40.0, 30.0], vec![[44.0, 32.0, 1.0]], egui::Modifiers::NONE, false)); + remember_clone_cursor(&mut app, [44.0, 32.0]); + assert_eq!(clone_offset_readout(&app), Some([-24.0, -14.0]), "offsets describe the transform's origin, not a moving screen-space distance"); + let sample = clone_sample_point(&app, Some([44.0, 32.0])).unwrap(); + for (got, want) in sample.into_iter().zip(want) { + assert!((got - want).abs() < 1e-8); + } + assert!(app.session.presets.clone.active().anchor.is_none()); + } +} + +/// Invalid cursor positions and restored UI state must not invent a preview reference. +#[test] +fn clone_offset_cursor_is_transient_and_rejects_nonfinite_positions() { + let mut app = app(); + remember_clone_cursor(&mut app, [40.0, 30.0]); + let before = app.ui.presets_ui.clone_cursor; + for at in [[f64::NAN, 0.0], [0.0, f64::INFINITY], [1e300, 0.0]] { + remember_clone_cursor(&mut app, at); + assert_eq!(app.ui.presets_ui.clone_cursor, before); + } + let saved = serde_json::to_value(&app.ui.presets_ui).unwrap(); + assert!(saved.get("clone_cursor").is_none()); + let restored: crate::preset_panels::PresetUi = serde_json::from_value(saved).unwrap(); + assert!(restored.clone_cursor.is_none()); +} + +/// View zoom changes screen geometry while document-space displacement remains constant. +#[test] +fn clone_offset_readout_is_in_document_pixels_at_different_canvas_zooms() { + let mut app = app(); + app.last_canvas_rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + for zoom in [1.0, 2.0, 4.0] { + let view = app.ui.views.first_mut().unwrap(); + view.zoom = zoom; + view.center = [32.0, 32.0]; + view.fit_pending = false; + view.doc_size = [64, 64]; + let screen = egui::pos2(400.0 + 8.0 * zoom, 300.0 - 2.0 * zoom); + let at = crate::canvas::doc_point_at(&app, screen).unwrap(); + assert!((at[0] - 40.0).abs() < 1e-6 && (at[1] - 30.0).abs() < 1e-6); + remember_clone_cursor(&mut app, at); + assert_eq!(clone_offset_readout(&app), Some([-24.0, -14.0])); + } +} diff --git a/crates/ui-egui/src/panels/preset_panels/panels.rs b/crates/ui-egui/src/panels/preset_panels/panels.rs index 4b0e05fbd6..287638afbb 100644 --- a/crates/ui-egui/src/panels/preset_panels/panels.rs +++ b/crates/ui-egui/src/panels/preset_panels/panels.rs @@ -549,6 +549,7 @@ pub fn tool_presets_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // ------------------------------------------------------------------ Clone Source +/// Display source identity and edit the resolved pairing/transform through engine commands. pub fn clone_source_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); let cs = app.session.presets.clone.clone(); @@ -577,26 +578,33 @@ pub fn clone_source_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } }); ui.add_space(4.0); - let src_line = - match (slot.source, slot.layer.and_then(|l| app.session.active().and_then(|d| d.doc.layer(photocraft_doc::LayerId(l)).map(|x| x.name.clone())))) { - (Some(_), Some(l)) => format!("Source: {} : {l}", app.session.active().map(|d| d.doc.name.clone()).unwrap_or_default()), - (Some(_), None) => "Source: set".to_string(), - _ => crate::i18n::fmt(tl!("Source: not set ({key}-click with Clone Stamp)"), &[("key", &crate::shortcuts::pretty("Alt"))]), - }; + // The document the source was set in (the active one for slots set before slots remembered it). + let source_doc = match slot.document { + Some(id) => slot.open_document().and_then(|_| app.session.documents().iter().find(|d| d.doc.id == id)), + None => app.session.active(), + }; + let src_line = match (slot.source, source_doc) { + (Some(_), None) => tl!("Source: document closed").to_string(), + (Some(_), Some(d)) => match slot.layer.and_then(|l| d.doc.layer(photocraft_doc::LayerId(l))) { + Some(l) => format!("Source: {} : {}", d.doc.name, l.name), + None => "Source: set".to_string(), + }, + _ => crate::i18n::fmt(tl!("Source: not set ({key}-click with Clone Stamp)"), &[("key", &crate::shortcuts::pretty("Alt"))]), + }; ui.label(egui::RichText::new(src_line).color(t.text_dim).size(11.0)); ui.add_space(4.0); let lbl = |ui: &mut egui::Ui, s: &str| { let label = ui.add_sized(vec2(18.0, 18.0), egui::Label::new(egui::RichText::new(s).color(t.text_dim).size(11.5))); crate::widgets::scrub_option_label(ui, &label); }; - let off = slot.offset().unwrap_or([0.0, 0.0]); + let off = super::clone_offset_readout(app).unwrap_or([0.0, 0.0]); let (mut ox, mut oy) = (off[0] as f32, off[1] as f32); let (mut w, mut h) = (slot.scale[0] as f32, slot.scale[1] as f32); let mut rot = slot.rotation as f32; egui::Grid::new("clone-src-grid").num_columns(5).spacing(vec2(6.0, 4.0)).show(ui, |ui| { lbl(ui, "X:"); - if crate::widgets::value_field(ui, &mut ox, -30000.0..=30000.0, "px", 72.0).changed() && slot.source.is_some() { - action = Some(json!({"offset": [ox, oy]})); + if crate::widgets::value_field(ui, &mut ox, -30000.0..=30000.0, "px", 72.0).accessible_name(tl!("Clone Source X Offset")).changed() { + action = super::clone_offset_edit(app, [f64::from(ox), f64::from(oy)]); } lbl(ui, "W:"); if crate::widgets::value_field(ui, &mut w, -1000.0..=1000.0, "%", 64.0).changed() { @@ -609,8 +617,8 @@ pub fn clone_source_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } ui.end_row(); lbl(ui, "Y:"); - if crate::widgets::value_field(ui, &mut oy, -30000.0..=30000.0, "px", 72.0).changed() && slot.source.is_some() { - action = Some(json!({"offset": [ox, oy]})); + if crate::widgets::value_field(ui, &mut oy, -30000.0..=30000.0, "px", 72.0).accessible_name(tl!("Clone Source Y Offset")).changed() { + action = super::clone_offset_edit(app, [f64::from(ox), f64::from(oy)]); } lbl(ui, "H:"); if crate::widgets::value_field(ui, &mut h, -1000.0..=1000.0, "%", 64.0).changed() { @@ -672,21 +680,3 @@ pub fn clone_source_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ); } } - -/// Where the active clone source samples for document point `at` (for the canvas marker). -/// The first stroke anchors at its press, so the marker follows before the stroke commits. -pub fn clone_sample_point(app: &PhotocraftApp, at: Option<[f64; 2]>) -> Option<[f64; 2]> { - use photocraft_engine::presets::clone_source::{Mapping, transform_matrix}; - let s = app.session.presets.clone.active(); - let src = s.source?; - let stroking = app.drag.as_ref().filter(|d| matches!(d.tool, Tool::CloneStamp | Tool::Healing)).map(|d| d.start); - let anchor = if app.ui.tool_options.clone_aligned { s.anchor.or(stroking) } else { stroking }; - match (anchor, at) { - (Some(a), Some(h)) => { - let m = Mapping { source: (src[0], src[1]), anchor: (a[0], a[1]), m: transform_matrix(s.scale, s.rotation, s.flip_h, s.flip_v) }; - let (x, y) = m.map(h[0], h[1]); - Some([x, y]) - } - _ => Some(src), - } -} diff --git a/crates/ui-egui/src/panels/props_layout.rs b/crates/ui-egui/src/panels/props_layout.rs index 8d604995bc..e74faec053 100644 --- a/crates/ui-egui/src/panels/props_layout.rs +++ b/crates/ui-egui/src/panels/props_layout.rs @@ -35,7 +35,7 @@ pub fn kind_icon(content: &LayerContent) -> &'static str { LayerContent::Group(_) => "folder", LayerContent::Fill(_) => "paint-bucket", LayerContent::Text(_) => "type", - LayerContent::Shape(_) => "pentagon", + LayerContent::Shape(_) => "vector-shape", LayerContent::Smart(_) => "app-window", LayerContent::Raster(_) => "image", } diff --git a/crates/ui-egui/src/panels/props_layout/tests.rs b/crates/ui-egui/src/panels/props_layout/tests.rs index 50e9006875..cc2cd61cee 100644 --- a/crates/ui-egui/src/panels/props_layout/tests.rs +++ b/crates/ui-egui/src/panels/props_layout/tests.rs @@ -363,3 +363,95 @@ fn background_in_a_multiple_selection_keeps_align_and_distribute() { assert_eq!((b.x0 + b.x1) / 2, 150, "centred on the Background, which spans the canvas: {b:?}"); assert_eq!(b.y0, 30, "only horizontally"); } + +/// Shape layers use the registered vector icon; raster and text mappings stay unchanged. +#[test] +fn shape_properties_uses_vector_shape_icon() { + let (session, layers) = kinds(); + let app = PhotocraftApp::new(session, crate::Services::default()); + + assert!(crate::icons::exists("vector-shape")); + + for (kind, id) in layers { + let layer = layer_of(&app, id); + let icon = kind_icon(&layer.content); + + let expected_icon = match kind { + "pixel" => "image", + "shape" => "vector-shape", + "type" => "type", + _ => panic!("Unexpected layer kind: {kind}"), + }; + + assert_eq!(icon, expected_icon, "{kind}: Properties icon"); + } +} + +/// Headers paint the expected 15 px icons, and the shape glyph has four hollow anchors. +#[test] +fn shape_header_paints_correct_icon() { + let (session, layers) = kinds(); + let app = PhotocraftApp::new(session, crate::Services::default()); + + for (kind, id) in layers { + let layer = layer_of(&app, id); + let icon = kind_icon(&layer.content); + let mut ready = false; + let mut h = Harness::new_ui(move |ui| { + if !ready { + crate::theme::install_fonts(ui.ctx()); + egui_extras::install_image_loaders(ui.ctx()); + ready = true; + return; + } + header(ui, &layer); + }); + h.run_steps(4); + + let icon_sizes: Vec<_> = h + .output() + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Rect(rect) if rect.brush.is_some() => Some(rect.rect.size()), + _ => None, + }) + .collect(); + + let expected = 15.0; + + assert_eq!(icon_sizes, vec![vec2(expected, expected)], "{kind}: Properties header icon size"); + + let expected_texture = h + .ctx + .try_load_texture( + &format!("bytes://icons/{icon}.svg"), + Default::default(), + egui::load::SizeHint::Size { width: expected as u32, height: expected as u32, maintain_aspect_ratio: false }, + ) + .unwrap() + .texture_id() + .expect("icon texture loaded"); + + let painted_texture = h.output().shapes.iter().find_map(|shape| match &shape.shape { + egui::Shape::Rect(rect) => rect.brush.as_ref().map(|brush| brush.fill_texture_id), + _ => None, + }); + + assert_eq!(painted_texture, Some(expected_texture), "{kind}: Properties header must paint {icon}"); + + if kind == "shape" { + let image = crate::icons::rasterize_svg(icon, 15, 15).expect("shape icon rasterized"); + assert!(image.pixels.iter().any(|pixel| pixel.a() > 0), "shape icon must have nontransparent pixels"); + + // Native SVG dimensions keep anchor centres clear of antialiased edges. + let anchors = crate::icons::rasterize_svg(icon, 24, 24).expect("shape anchors rasterized"); + for (x, y) in [(6, 6), (18, 6), (6, 18), (18, 18)] { + assert_eq!(anchors[(x, y)].a(), 0, "anchor at ({x}, {y}) must be hollow"); + for (edge_x, edge_y) in [(x - 2, y), (x + 2, y), (x, y - 2), (x, y + 2)] { + assert!(anchors[(edge_x, edge_y)].a() > 0, "anchor at ({x}, {y}) must have four visible sides"); + } + } + } + } +} diff --git a/crates/ui-egui/src/panels/smart_ui.rs b/crates/ui-egui/src/panels/smart_ui.rs index 3c401a95b9..37b93eb891 100644 --- a/crates/ui-egui/src/panels/smart_ui.rs +++ b/crates/ui-egui/src/panels/smart_ui.rs @@ -124,6 +124,12 @@ pub fn filter_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, doc: &Document, l let rows = std::iter::once(None).chain((0..sm.smart_filters.len()).rev().map(Some)); for index in rows { let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), if index.is_none() { header_height } else { SUB_ROW_H }), Sense::click_and_drag()); + // Off screen: keep the row's place but skip its painting, widgets and drop (#13118), as + // effect rows do. The drawn marker below still records `l`, so a selected filter that + // scrolled away stays selected. + if !ui.is_rect_visible(rect) { + continue; + } if let Some((to, action)) = reorder_drop(ui, l, sm.smart_filters.len(), index, rect) { // The moved filter ends up selected, with its smart object active, as after a click. ui.ctx().data_mut(|d| d.insert_temp::(selected_key(doc.id), (l.id.0, Some(to)))); @@ -411,7 +417,9 @@ fn reorder_drop(ui: &egui::Ui, l: &Layer, n: usize, row: Option, rect: Re let ctx = ui.ctx(); let (from, src) = ctx.data(|d| d.get_temp::(drag_key()))?; let (src, p) = (src?, ctx.input(|i| i.pointer.interact_pos())?); - if from != l.id.0 || !rect.contains(p) { + // Only the part of the row the list shows: one half scrolled under the panel's header takes + // no drop there (#13118, as masks since #10485). + if from != l.id.0 || !rect.intersect(ui.clip_rect()).contains(p) { return None; } let above = p.y < rect.center().y; diff --git a/crates/ui-egui/src/panels/swatches_ui.rs b/crates/ui-egui/src/panels/swatches_ui.rs index 09420d4944..6a16751f8f 100644 --- a/crates/ui-egui/src/panels/swatches_ui.rs +++ b/crates/ui-egui/src/panels/swatches_ui.rs @@ -288,7 +288,7 @@ mod tests { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); let mut colors = vec![[10u8, 20, 30]; 256]; colors[0] = [0, 1, 5]; - let bytes = photocraft_psd::act::write(&colors, None, None).unwrap(); + let bytes = craft_psd::act::write(&colors, None, None).unwrap(); let r = import_bytes(&mut app, "Palette.act", &bytes, true).unwrap(); assert_eq!((r["format"].as_str(), r["count"].as_u64()), (Some("act"), Some(256))); } @@ -456,9 +456,7 @@ mod tests { type Written = Arc)>>>; let written: Written = Arc::default(); let w = written.clone(); - let aco = - photocraft_psd::aco::write(&[photocraft_psd::aco::AcoSwatch { name: "Teal".into(), color: photocraft_psd::aco::AcoColor::Rgb([0, 32768, 32768]) }]) - .unwrap(); + let aco = craft_psd::aco::write(&[craft_psd::aco::AcoSwatch { name: "Teal".into(), color: craft_psd::aco::AcoColor::Rgb([0, 32768, 32768]) }]).unwrap(); use crate::file_dialog::FileDialogAnswer; let answers = vec![ Some(FileDialogAnswer::Contents("Ocean.aco".into(), aco.clone())), diff --git a/crates/ui-egui/src/patch_reset_tool_tests.rs b/crates/ui-egui/src/patch_reset_tool_tests.rs new file mode 100644 index 0000000000..39c7d07e62 --- /dev/null +++ b/crates/ui-egui/src/patch_reset_tool_tests.rs @@ -0,0 +1,71 @@ +//! Reset Tool on the Patch tool keeps Structure and Color (#12127), as the reference app does; +//! Reset All Tools still resets them, and a tool preset still stores them. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::{Tool, ToolOptions}; + +fn app() -> PhotocraftApp { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.ui.tool = Tool::Patch; + app +} + +/// Structure 7, Color 5, Destination mode, Content-Aware on. +fn customize(app: &mut PhotocraftApp) { + let o = &mut app.ui.tool_options; + o.patch_structure = 7.0; + o.patch_color = 5.0; + o.patch_mode = "destination".into(); + o.patch_content_aware = true; +} + +#[test] +fn reset_tool_keeps_structure_and_color_and_resets_the_mode() { + let mut app = app(); + customize(&mut app); + app.ui.selection_mode = 2; + crate::menus::invoke(&mut app, &egui::Context::default(), crate::tool_reset::RESET, json!({})).unwrap(); + let o = &app.ui.tool_options; + assert_eq!((o.patch_structure, o.patch_color), (7.0, 5.0)); + assert_eq!(o.patch_mode, "source"); + assert!(!o.patch_content_aware); + assert_eq!(app.ui.selection_mode, 0); +} + +#[test] +fn reset_all_tools_still_gives_structure_4_and_color_0() { + let mut app = app(); + customize(&mut app); + crate::menus::invoke(&mut app, &egui::Context::default(), crate::tool_reset::RESET_ALL, json!({"confirmed": true})).unwrap(); + let o = &app.ui.tool_options; + assert_eq!((o.patch_structure, o.patch_color), (4.0, 0.0)); + assert_eq!(o.patch_mode, "source"); +} + +#[test] +fn content_aware_move_reset_tool_resets_its_own_structure_and_color() { + let mut app = app(); + app.ui.tool = Tool::ContentAwareMove; + app.ui.tool_options.cam_mode = "extend".into(); + app.ui.tool_options.cam_structure = 7.0; + app.ui.tool_options.cam_color = 5.0; + app.ui.tool_options.patch_structure = 7.0; + crate::menus::invoke(&mut app, &egui::Context::default(), crate::tool_reset::RESET, json!({})).unwrap(); + let d = ToolOptions::default(); + let o = &app.ui.tool_options; + assert_eq!((o.cam_structure, o.cam_color), (d.cam_structure, d.cam_color)); + assert_eq!(o.patch_structure, 7.0, "another tool's option stays"); + assert_eq!(o.cam_mode, "extend", "Reset Tool keeps the Content-Aware Move Mode (#12183)"); +} + +#[test] +fn a_patch_tool_preset_still_stores_structure_and_color() { + let keys = crate::tool_reset::option_keys(Tool::Patch); + for k in ["patch_mode", "patch_content_aware", "patch_structure", "patch_color"] { + assert!(keys.contains(&k), "{k}"); + } +} diff --git a/crates/ui-egui/src/pattern_stamp_opacity_flow_tests.rs b/crates/ui-egui/src/pattern_stamp_opacity_flow_tests.rs new file mode 100644 index 0000000000..13cfa73800 --- /dev/null +++ b/crates/ui-egui/src/pattern_stamp_opacity_flow_tests.rs @@ -0,0 +1,177 @@ +//! #12616: the Pattern Stamp's options bar has Opacity and Flow after Mode (whole percents 1..100, +//! default 100, the reference's tooltips, the Brush's silent clamp for a typed value past the +//! range), its strokes paint with them, live and committed alike, and Reset Tool puts both back +//! to 100. + +use std::collections::BTreeSet; + +use egui::accesskit::Role; +use egui::{Modifiers, Rect}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::eraser_range_alert_tests::{alerts, bar, type_into}; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, display_doc, tool_event}; +use crate::state::Tool; + +/// The field named `label` ("Opacity", "Flow"), by its caption's name. +fn field<'a>(h: &'a Harness<'static, PhotocraftApp>, label: &str) -> egui_kittest::Node<'a> { + let label = format!("{label}:"); + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some(label.as_str())).unwrap_or_else(|| panic!("the {label} field")) +} + +/// The live brush's Opacity and Flow in percent. +fn opacity_flow(app: &PhotocraftApp) -> (f32, f32) { + let b = &app.session.tools.brush; + ((b.opacity * 100.0).round(), (b.flow * 100.0).round()) +} + +#[test] +fn the_bar_shows_opacity_and_flow_after_mode_at_100() { + let h = bar(Tool::PatternStamp); + let mode = h.query_all_by_role(Role::ComboBox).find(|n| n.value().as_deref() == Some("Normal")).expect("the Mode dropdown").rect(); + let (opacity, flow) = (field(&h, "Opacity"), field(&h, "Flow")); + assert_eq!((opacity.accesskit_node().numeric_value(), flow.accesskit_node().numeric_value()), (Some(100.0), Some(100.0))); + assert_eq!(opacity.accesskit_node().description().as_deref(), Some("Set opacity for stroke")); + assert_eq!(flow.accesskit_node().description().as_deref(), Some("Set flow rate for stroke")); + let (opacity, flow) = (opacity.rect(), flow.rect()); + assert!(mode.right() <= opacity.left() && opacity.right() <= flow.left(), "Mode, Opacity, Flow: {mode:?} {opacity:?} {flow:?}"); +} + +#[test] +fn typed_values_are_whole_percents_clamped_to_1_100_without_an_alert() { + let mut h = bar(Tool::PatternStamp); + for (opacity, flow, want) in [("50", "10", (50.0, 10.0)), ("37.6", "12.4", (38.0, 12.0)), ("150", "0", (100.0, 1.0))] { + type_into(&mut h, "Opacity", opacity); + type_into(&mut h, "Flow", flow); + assert_eq!(opacity_flow(h.state()), want, "typed {opacity} / {flow}"); + assert!(alerts(&h).is_empty(), "the Brush's fields clamp silently"); + } + let b = &h.state().session.tools.brush; + assert_eq!((b.opacity, b.flow), (1.0, 0.01), "stored as whole percents"); +} + +#[test] +fn reset_tool_puts_opacity_and_flow_back_to_100() { + let mut h = bar(Tool::PatternStamp); + type_into(&mut h, "Opacity", "40"); + type_into(&mut h, "Flow", "25"); + assert_eq!(opacity_flow(h.state()), (40.0, 25.0)); + crate::burn_default_tip_tests::invoke(h.state_mut(), "tool.reset", json!({})); + h.run_steps(3); + assert_eq!(opacity_flow(h.state()), (100.0, 100.0)); + assert_eq!(field(&h, "Opacity").accesskit_node().numeric_value(), Some(100.0)); + assert_eq!(field(&h, "Flow").accesskit_node().numeric_value(), Some(100.0)); +} + +/// The issue's test document: 800 × 600 RGB 8 bit, white with its right half green (40,160,60), +/// a 20 × 20 pattern of 10 px quadrants (red, green / blue, white) and the Pattern Stamp with a +/// 40 px hard tip, Aligned on, at `opacity` and `flow` (fractions). +fn document(opacity: f32, flow: f32) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 20, "height": 20})).unwrap(); + for (x, y, color) in [(0, 0, "#ff0000"), (10, 0, "#00ff00"), (0, 10, "#0000ff"), (10, 10, "#ffffff")] { + app.run("select.rect", json!({"x": x, "y": y, "width": 10, "height": 10})).unwrap(); + app.run("edit.fill", json!({"color": color})).unwrap(); + } + app.run("select.deselect", json!({})).unwrap(); + let pattern = app.run("edit.definePattern", json!({"name": "Quadrants", "rect": [0, 0, 20, 20]})).unwrap()["pattern"].clone(); + app.run("pattern.presets.select", json!({"pattern": pattern})).unwrap(); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.run("select.rect", json!({"x": 400, "y": 0, "width": 400, "height": 600})).unwrap(); + app.run("edit.fill", json!({"color": "#28a03c"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.ui.tool = Tool::PatternStamp; + app.ui.tool_options.pattern_stamp_aligned = true; + crate::paint_mouse::sync_tool_brush(&mut app); + let brush = json!({"size": 40, "hardness": 1.0, "opacity": opacity, "flow": flow, "pressureSize": false, "smoothing": {"amount": 0.0}}); + app.run("tools.setBrush", json!({"brush": brush})).unwrap(); + app +} + +/// The distinct 8-bit colours inside the tip of a click at (600, 300), in `doc`. +fn colours(doc: &photocraft_doc::Document, app: &PhotocraftApp) -> BTreeSet<[u8; 3]> { + let surf = doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap(); + let inside = Rect::from_center_size(egui::pos2(600.0, 300.0), egui::vec2(24.0, 24.0)); + let (x0, y0, x1, y1) = (inside.left() as i32, inside.top() as i32, inside.right() as i32, inside.bottom() as i32); + (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).map(|(x, y)| surf.rgba(x, y)).map(|c| [c[0], c[1], c[2]].map(|v| (v * 255.0).round() as u8)).collect() +} + +/// One click at (600, 300) on the green half: what the canvas showed before the release, and what +/// the release committed. +fn click(app: &mut PhotocraftApp) -> (BTreeSet<[u8; 3]>, BTreeSet<[u8; 3]>) { + tool_event(app, ToolEvent::Down { x: 600.0, y: 300.0, pressure: 1.0 }, Modifiers::NONE); + assert!(app.live_stroke.is_some(), "the stroke draws live"); + // The canvas shows the second document; the first holds the pattern. + let idx = app.session.active_index().unwrap(); + let shown = colours(&display_doc(app, idx).0, app); + tool_event(app, ToolEvent::Up { x: 600.0, y: 300.0 }, Modifiers::NONE); + assert!(!app.ui.status_error, "{}", app.ui.status); + let committed = colours(&app.session.active().unwrap().doc, app); + (shown, committed) +} + +/// The reference's values for Opacity 50, and for Flow 50 (the same): half the pattern over green. +const HALF: [[u8; 3]; 4] = [[148, 80, 30], [20, 208, 30], [20, 80, 158], [148, 208, 158]]; + +#[test] +fn opacity_50_paints_the_reference_values_live_and_committed() { + let mut app = document(0.5, 1.0); + let (shown, committed) = click(&mut app); + assert_eq!(committed, BTreeSet::from(HALF)); + assert_eq!(shown, committed, "the live preview and the commit agree"); + let (_, params) = app.session.journal.iter().rev().find(|(name, _)| name == "paint.patternStamp").unwrap(); + assert_eq!((params["opacity"].as_f64(), params["flow"].as_f64()), (Some(50.0), Some(100.0)), "{params}"); +} + +#[test] +fn flow_50_paints_the_same_values_as_opacity_50() { + let mut app = document(1.0, 0.5); + let (shown, committed) = click(&mut app); + assert_eq!(committed, BTreeSet::from(HALF)); + assert_eq!(shown, committed); +} + +#[test] +fn flow_10_paints_about_10_percent() { + let mut app = document(1.0, 0.1); + let (shown, committed) = click(&mut app); + assert_eq!(shown, committed); + // Red over green: the reference's 62,144,54. + let red = committed.iter().find(|c| c[0] > c[2] && c[1] < 150).copied().expect("the red cells"); + assert!(red.iter().zip([62u8, 144, 54]).all(|(a, b)| a.abs_diff(b) <= 1), "{red:?} in {committed:?}"); +} + +/// A first pick doesn't carry the Brush's Opacity and Flow over: the Pattern Stamp starts at 100. +#[test] +fn a_first_pick_after_a_30_percent_brush_starts_at_100() { + let mut h = bar(Tool::Brush); + h.state_mut().run("tools.setBrush", json!({"brush": {"opacity": 0.3, "flow": 0.4}})).unwrap(); + h.run_steps(3); + h.state_mut().ui.tool = Tool::PatternStamp; + h.run_steps(4); + assert_eq!(field(&h, "Opacity").accesskit_node().numeric_value(), Some(100.0)); + assert_eq!(field(&h, "Flow").accesskit_node().numeric_value(), Some(100.0)); + let app = h.state_mut(); + assert!(crate::retouch_ui::finish_stroke(app, Tool::PatternStamp, &[[40.0, 40.0, 1.0]], Modifiers::NONE, false)); + let (_, params) = app.session.journal.iter().rev().find(|(name, _)| name == "paint.patternStamp").unwrap(); + assert_eq!((params["opacity"].as_f64(), params["flow"].as_f64()), (Some(100.0), Some(100.0)), "{params}"); +} + +/// Impressionist strokes take Opacity too (not measured: only that they paint with it, live and +/// committed alike). +#[test] +fn an_impressionist_stroke_paints_with_opacity_live_and_committed() { + let painted = |opacity: f32| { + let mut app = document(opacity, 1.0); + app.ui.tool_options.pattern_stamp_impressionist = true; + let (shown, committed) = click(&mut app); + assert_eq!(shown, committed, "opacity {opacity}: the live preview and the commit agree"); + let (_, params) = app.session.journal.iter().rev().find(|(name, _)| name == "paint.patternStamp").unwrap(); + assert_eq!(params["opacity"].as_f64(), Some(f64::from(opacity) * 100.0), "{params}"); + committed + }; + assert_ne!(painted(0.5), painted(1.0), "Opacity 50 paints differently from 100"); +} diff --git a/crates/ui-egui/src/pencil_reset_defaults_tests.rs b/crates/ui-egui/src/pencil_reset_defaults_tests.rs new file mode 100644 index 0000000000..37ebd78b4e --- /dev/null +++ b/crates/ui-egui/src/pencil_reset_defaults_tests.rs @@ -0,0 +1,154 @@ +//! #12200: Reset Tool, Reset All Tools and a fresh first pick give the Pencil a 1 px hard round +//! tip (size 1, hardness 100 %, angle 0, roundness 100 %, spacing 25 %, both pressure overrides +//! off, options-bar chip "1"), and a default click at 100.2,100.2 paints only pixel 100,100. + +use egui::{Context, Modifiers, Pos2, RawInput, Rect, Shape, vec2}; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::control::{ControlRequest, handle}; +use crate::state::Tool; + +/// Creates a test app with a 200x200 document. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.sync_views(); + app +} + +/// Dispatches a control request and syncs document views. +fn control(app: &mut PhotocraftApp, method: &str, params: Value) { + let ctx = Context::default(); + let (req, _rx) = ControlRequest::new(method, params); + let _ = handle(app, &ctx, &req); + app.sync_views(); +} + +/// Switches to `tool` and synchronizes its remembered brush. +fn pick(app: &mut PhotocraftApp, tool: Tool) { + app.ui.tool = tool; + crate::paint_mouse::sync_tool_brush(app); + app.sync_views(); +} + +/// Scrambles the active brush tip and pressure overrides away from defaults. +fn scramble(app: &mut PhotocraftApp) { + let b = &mut app.session.tools.brush; + (b.size, b.hardness, b.spacing, b.angle, b.roundness) = (42.0, 0.3, 0.6, 25.0, 0.5); + (b.pressure_size, b.pressure_opacity) = (true, true); +} + +/// Asserts that `brush.get` reports the Pencil's 1 px hard round default tip. +fn assert_pencil_tip(app: &mut PhotocraftApp) { + let b = app.run("brush.get", json!({})).unwrap(); + let tip = ["size", "hardness", "angle", "roundness", "spacing"].map(|k| (b[k].as_f64().unwrap() * 1e4).round() / 1e4); + assert_eq!(tip, [1.0, 1.0, 0.0, 1.0, 0.25], "{b}"); + assert_eq!(b["pressureSize"], json!(false), "{b}"); + assert_eq!(b["pressureOpacity"], json!(false), "{b}"); +} + +/// Renders the options bar and returns whether the brush preset chip displays `"1"`. +fn chip_shows_one(app: &mut PhotocraftApp) -> bool { + fn has_one(shape: &Shape, rect: Rect) -> bool { + match shape { + Shape::Text(t) => rect.contains(t.pos) && t.galley.text() == "1", + Shape::Vec(v) => v.iter().any(|s| has_one(s, rect)), + _ => false, + } + } + let ctx = Context::default(); + PhotocraftApp::setup_context(&ctx, Default::default()); + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 300.0))); + let mut out = ctx.run_ui(RawInput { screen_rect, ..Default::default() }, |ui| crate::panels::options_bar(app, ui)); + out.textures_delta.clear(); + let chip = ctx.read_response(crate::brush_picker::chip_id()).unwrap().rect; + out.shapes.iter().any(|s| has_one(&s.shape, chip)) +} + +/// Verifies that `tool.reset` and `tool.resetAll` give the Pencil its 1 px hard tip and `"1"` chip. +#[test] +fn reset_tool_and_reset_all_give_the_pencil_a_one_pixel_hard_tip() { + let mut a = app(); + pick(&mut a, Tool::Pencil); + scramble(&mut a); + a.session.tools.brush.opacity = 0.4; + control(&mut a, "ui.menu.invoke", json!({"id": "tool.reset"})); + assert_pencil_tip(&mut a); + assert_eq!(a.session.tools.brush.opacity, 1.0); + assert!(chip_shows_one(&mut a)); + + scramble(&mut a); + control(&mut a, "ui.menu.invoke", json!({"id": "tool.resetAll", "params": {"confirmed": true}})); + assert_pencil_tip(&mut a); + assert!(chip_shows_one(&mut a)); +} + +/// Verifies that first selecting the Pencil (including via `tools.select.pencil` before a UI pass) +/// uses its 1 px hard tip while preserving the outgoing brush opacity. +#[test] +fn pencil_starts_with_its_own_tip_whatever_the_brush_had() { + let mut a = app(); + pick(&mut a, Tool::Brush); + scramble(&mut a); + a.session.tools.brush.opacity = 0.4; + control(&mut a, "ui.menu.invoke", json!({"id": "tools.select.pencil"})); + assert_pencil_tip(&mut a); + assert!((a.session.tools.brush.opacity - 0.4).abs() < 1e-5); + assert!(chip_shows_one(&mut a)); +} + +/// Selecting the Brush again by command, before a UI pass, gives back the Brush's own tip: the +/// Pencil's 1 px tip is not left for the next brush command, and the Brush's edit is not saved to +/// the Pencil. +#[test] +fn selecting_back_to_the_brush_by_command_restores_its_tip_at_once() { + let mut a = app(); + pick(&mut a, Tool::Brush); + a.session.tools.brush.size = 42.0; + control(&mut a, "ui.menu.invoke", json!({"id": "tools.select.pencil"})); + assert_pencil_tip(&mut a); + control(&mut a, "ui.menu.invoke", json!({"id": "tools.select.brush"})); + assert_eq!(a.session.tools.brush.size, 42.0, "the Brush's own size, before any frame"); +} + +/// Verifies that a default Pencil click at `(100.2, 100.2)` paints only pixel `(100, 100)`. +#[test] +fn a_default_click_at_100_2_paints_only_pixel_100_100() { + let mut a = app(); + a.run("layer.new.layer", json!({})).unwrap(); + pick(&mut a, Tool::Pencil); + tool_event(&mut a, ToolEvent::Down { x: 100.2, y: 100.2, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut a, ToolEvent::Up { x: 100.2, y: 100.2 }, Modifiers::NONE); + let st = a.session.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + assert_eq!(surf.content_bounds(), photocraft_geom::Rect::new(100, 100, 101, 101)); + assert_eq!(surf.rgba(100, 100)[3], 1.0); +} + +/// Verifies that `tool.resetAll` resets a saved Pencil brush even when invoked from another tool, +/// while preserving the Brush and Eraser reset tips. +#[test] +fn brush_and_other_painting_tools_keep_their_reset_tips() { + let mut a = app(); + pick(&mut a, Tool::Eraser); + scramble(&mut a); + pick(&mut a, Tool::Pencil); + scramble(&mut a); + pick(&mut a, Tool::Brush); + scramble(&mut a); + control(&mut a, "ui.menu.invoke", json!({"id": "tool.resetAll", "params": {"confirmed": true}})); + let b = a.run("brush.get", json!({})).unwrap(); + let brush_tip = ["size", "hardness", "spacing"].map(|k| (b[k].as_f64().unwrap() * 1e4).round() / 1e4); + assert_eq!(brush_tip, [13.0, 0.0, 0.25]); + + pick(&mut a, Tool::Pencil); + assert_pencil_tip(&mut a); + assert!(chip_shows_one(&mut a)); + + pick(&mut a, Tool::Eraser); + let e = a.run("brush.get", json!({})).unwrap(); + let eraser_tip = ["size", "hardness", "spacing"].map(|k| (e[k].as_f64().unwrap() * 1e4).round() / 1e4); + assert_eq!(eraser_tip, [20.0, 1.0, 0.1]); +} diff --git a/crates/ui-egui/src/pencil_tests.rs b/crates/ui-egui/src/pencil_tests.rs index 3223128a17..25ca0a1887 100644 --- a/crates/ui-egui/src/pencil_tests.rs +++ b/crates/ui-egui/src/pencil_tests.rs @@ -13,12 +13,11 @@ fn app() -> PhotocraftApp { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); app.run("file.new", json!({"width": 120, "height": 80, "background": "transparent"})).unwrap(); app.run("tools.setColors", json!({"foreground": "#000000", "background": "#ffffff"})).unwrap(); - app.run("tools.setBrush", json!({"brush": {"size": 3, "hardness": 0.0}})).unwrap(); // Each tool keeps its own brush (#218): switch first, then set the Pencil's options, as the - // options bar does (its first frame takes the Brush's tip at Photoshop's 10 % smoothing). + // options bar does. app.ui.tool = Tool::Pencil; crate::paint_mouse::sync_tool_brush(&mut app); - app.run("tools.setBrush", json!({"brush": {"smoothing": {"amount": 0.0}}})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 3, "hardness": 0.0, "smoothing": {"amount": 0.0}}})).unwrap(); app } diff --git a/crates/ui-egui/src/prefs/prefs_ui.rs b/crates/ui-egui/src/prefs/prefs_ui.rs index 3af37664b2..f57a730544 100644 --- a/crates/ui-egui/src/prefs/prefs_ui.rs +++ b/crates/ui-egui/src/prefs/prefs_ui.rs @@ -52,6 +52,11 @@ pub struct Runtime { show_rulers: Option, /// Tool options as last remembered in the preferences (see `tool_memory`). pub(crate) tool_options: Option, + /// MCP settings the agent connection was last set up for (`agents::sync_agent_link`). + agent_link: Option, + /// When to try again after the agent connection failed to start (a taken port), in seconds of + /// `gpu_canvas::now_ms`; `None` while it runs or is off. + agent_link_retry: Option, pub(crate) selected_tool: Option, pub(crate) tool_colors: Option<[[[f32; 4]; 2]; 2]>, pub(crate) tool_cmyk_picks: crate::tool_memory::CmykPicks, @@ -64,6 +69,7 @@ pub struct Runtime { pub use crate::shortcuts::{default_shortcut, effective_shortcut}; +mod agents; mod appearance; mod dialogs; mod fields; @@ -103,6 +109,8 @@ pub(crate) use startup::{on_recovery_event, remember_rulers}; // Test modules stay after the production code: the prefs_usage test reads each file up to // its first `#[cfg(test)] mod`. #[cfg(test)] +mod agents_tests; +#[cfg(test)] mod recovery_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/prefs/prefs_ui/agents.rs b/crates/ui-egui/src/prefs/prefs_ui/agents.rs new file mode 100644 index 0000000000..0d6feb588e --- /dev/null +++ b/crates/ui-egui/src/prefs/prefs_ui/agents.rs @@ -0,0 +1,141 @@ +//! Preferences › AI Integrations: whether agents can use the open app (one switch for every Craft +//! app, in the ArtCraft Launcher), the port, the folders agents may use, and what +//! `photocraft-cli mcp` does while the app is closed. Changes apply at once, without a restart. +//! Adding PhotoCraft to an MCP client is the launcher's job too, so there is nothing for it here. + +use super::dialogs::is_preferences; +use super::fields::{choice_label, humanize}; +use super::{Map, PhotocraftApp, RichText, Tokens, Value, json, prefs}; + +/// Seconds between tries while the agent connection is on but couldn't start (its port taken). +pub(super) const AGENT_LINK_RETRY_S: f64 = 5.0; + +/// Start, move or stop the agent connection when its settings change +/// ([`crate::Services::agent_link`]); the first frame applies the saved settings. A connection +/// that is on but failed to start is tried again every [`AGENT_LINK_RETRY_S`], so freeing its +/// port is enough, without touching a setting. With the suite's `AI-MCP` flag, the ArtCraft +/// Launcher's switch ([`crate::Services::launcher_agents`]) alone decides whether agents may connect: +/// one switch for every Craft app. Without the flag, as before, a Control Port saved in the +/// preferences (`connectAgents`, set from it when they load). +pub(super) fn sync_agent_link(app: &mut PhotocraftApp, ctx: &egui::Context) { + let launcher = app.services.launcher_agents.as_ref().is_some_and(|on| on()); + let mcp_flag = app.agent_link.mcp_flag; + let Some(link) = app.services.agent_link.as_mut() else { return }; + let mut effective = app.session.prefs().integrations.clone(); + if mcp_flag { + effective.connect_agents = launcher; + } + let current = &effective; + let now = crate::gpu_canvas::now_ms() / 1000.0; + let retry_due = app.prefs_rt.agent_link_retry.is_some_and(|at| now >= at); + if app.prefs_rt.agent_link.as_ref() == Some(current) && !retry_due { + return; + } + let update = link(current, ctx); + let failed_start = current.connect_agents && current.allow_agent_control && update.status.port.is_none(); + app.prefs_rt.agent_link = Some(current.clone()); + app.prefs_rt.agent_link_retry = failed_start.then_some(now + AGENT_LINK_RETRY_S); + if failed_start { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(AGENT_LINK_RETRY_S)); + } + if update.stopped { + app.control_rx = None; + } + if let Some(rx) = update.requests { + app.control_rx = Some(rx); + } + app.services.set_automation(update.automation); + // Actions automation records keep the policy as their gate when the user plays them, as they + // do with `--control` (`PhotocraftApp::new`); the gate stays once agents have connected. + app.session.automation_gate = app.session.automation_gate.or(app.services.automation_authorize); + // The service reports the connection; the feature flag is the app's, set once at launch. + app.agent_link = update.status; + app.agent_link.mcp_flag = mcp_flag; + app.agent_link.launcher = launcher; +} + +/// The rows of the section. A button click is left in `f["__agentAction"]` for [`agent_action`]. +pub(super) fn integration_rows(ui: &mut egui::Ui, obj: &mut Map, f: &mut Map) { + let t = Tokens::get(ui.ctx()); + let status = f.get("__agentLink").cloned().unwrap_or(Value::Null); + let launch_flags = status.get("launchFlags").and_then(Value::as_bool) == Some(true); + // One switch for every Craft app: ArtCraft Launcher › Settings › AI agents. There is none here. + ui.label( + RichText::new(tl!( + "AI apps such as Claude can open, edit and save documents in this window while ArtCraft Launcher › Settings › AI agents › Let AI agents use Craft apps is on. Only programs on this computer can connect." + )) + .color(t.text_dim), + ); + ui.add_space(4.0); + let port = status.get("port").and_then(Value::as_u64); + let error = status.get("error").and_then(Value::as_str); + let (line, color) = match (launch_flags, port, error) { + (true, _, _) => (tl!("Managed by the launch options (--control).").to_string(), t.text_dim), + (false, _, Some(e)) => (e.to_string(), t.danger), + (false, Some(p), None) => (crate::i18n::fmt(tl!("Agents can connect on 127.0.0.1:{port}."), &[("port", &p.to_string())]), t.accent_text), + (false, None, None) => (tl!("Off: turn on AI agents in ArtCraft Launcher › Settings › AI agents.").to_string(), t.text_faint), + }; + ui.label(RichText::new(line).color(color)); + ui.add_space(8.0); + egui::Grid::new("prefs-integrations").num_columns(2).spacing([14.0, 7.0]).show(ui, |ui| { + let port_label = ui.label(RichText::new(tl!(&humanize("controlPort"))).color(t.text_dim)); + ui.horizontal(|ui| { + let mut p = obj.get("controlPort").and_then(Value::as_i64).unwrap_or(0); + ui.add(egui::DragValue::new(&mut p).range(0..=65535).custom_parser(crate::widgets::parse_num)).labelled_by(port_label.id); + obj.insert("controlPort".into(), json!(p)); + ui.label(RichText::new(tl!("0 picks a free port; AI apps find it by themselves")).color(t.text_faint)); + }); + ui.end_row(); + for (key, pick) in [("readRoot", "chooseRead"), ("writeRoot", "chooseWrite")] { + let label = humanize(key); + ui.label(RichText::new(tl!(&label)).color(t.text_dim)); + ui.horizontal(|ui| { + let mut path = obj.get(key).and_then(Value::as_str).unwrap_or("").to_string(); + crate::widgets::text_field(ui, ui.scope_id().with(key), &mut path, tl!("None"), 260.0, false); + obj.insert(key.into(), json!(path)); + if crate::widgets::secondary_button(ui, tl!("Browse…"), 70.0).clicked() { + f.insert("__agentAction".into(), json!(pick)); + } + }); + ui.end_row(); + } + let label = humanize("whenAppClosed"); + ui.label(RichText::new(tl!(&label)).color(t.text_dim)); + let mut cur = obj.get("whenAppClosed").and_then(Value::as_str).unwrap_or("launch").to_string(); + let options = prefs::choices("integrations.whenAppClosed").unwrap_or(&[]); + let labels: Vec = options.iter().map(|o| choice_label(o)).collect(); + let pairs: Vec<(String, &str)> = options.iter().map(|o| o.to_string()).zip(labels.iter().map(String::as_str)).collect(); + crate::widgets::dropdown(ui, "pref-integrations.whenAppClosed", &label, &mut cur, &pairs, 220.0); + obj.insert("whenAppClosed".into(), json!(cur)); + ui.end_row(); + }); + if let Some(result) = f.get("__agentResult").and_then(Value::as_object) { + let ok = result.get("ok").and_then(Value::as_bool) == Some(true); + let text = result.get("message").and_then(Value::as_str).unwrap_or(""); + ui.label(RichText::new(text).color(if ok { t.text_dim } else { t.danger })); + } +} + +/// A button of [`integration_rows`]: choose a folder (into the dialog's working copy). +pub(super) fn agent_action(app: &mut PhotocraftApp, f: &mut Map, action: &str, dialog: u64) { + let key = match action { + "chooseRead" => Some("readRoot"), + "chooseWrite" => Some("writeRoot"), + _ => None, + }; + if let Some(key) = key { + // Into the Preferences dialog that asked: closed meanwhile (or reopened as a new one), the + // answer is dropped rather than landing in another working copy. + let picked = app.ask_folder(move |app, path| { + if let Some(d) = app.ui.dialogs.iter_mut().find(|d| d.id == dialog && is_preferences(&d.fields)) + && let Some(obj) = d.fields.get_mut("values").and_then(|v| v.get_mut("integrations")).and_then(Value::as_object_mut) + { + obj.insert(key.into(), json!(path)); + } + Ok(Value::Null) + }); + if let Err(e) = picked { + f.insert("__agentResult".into(), json!({"ok": false, "message": e})); + } + } +} diff --git a/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs new file mode 100644 index 0000000000..c5a2467663 --- /dev/null +++ b/crates/ui-egui/src/prefs/prefs_ui/agents_tests.rs @@ -0,0 +1,216 @@ +//! Preferences › AI Integrations (`agents.rs`): the live agent connection and its buttons. + +use super::tests::app_with_store; +use super::*; +use std::sync::{Arc, Mutex}; + +#[test] +fn ai_integrations_start_and_stop_the_agent_connection_through_the_service() { + use std::sync::mpsc::channel; + let (mut app, _) = app_with_store(); + let ctx = egui::Context::default(); + let calls: Arc>> = Arc::default(); + let seen = calls.clone(); + let (tx, rx) = channel::(); + let mut rx = Some(rx); + app.services.agent_link = Some(Box::new(move |p: &prefs::Integrations, _: &egui::Context| { + seen.lock().unwrap().push(p.clone()); + let mut out = crate::AgentLink { stopped: !p.connect_agents, ..Default::default() }; + if p.connect_agents { + out.requests = rx.take(); + out.status.port = Some(4321); + out.automation.command = Some(Box::new(|_, _| Err("policy".into()))); + } + out + })); + // The first frame applies the saved settings (off), once. + tick(&mut app, &ctx); + tick(&mut app, &ctx); + assert_eq!(calls.lock().unwrap().len(), 1); + assert!(app.control_rx.is_none() && app.agent_link.port.is_none()); + // On: the request channel and the automation policy are installed, without a restart. + app.run("prefs.set", json!({"values": {"integrations.connectAgents": true, "integrations.readRoot": "/work"}})).unwrap(); + tick(&mut app, &ctx); + assert_eq!(calls.lock().unwrap().last().map(|p| (p.connect_agents, p.read_root.clone())), Some((true, "/work".into()))); + assert!(app.control_rx.is_some()); + assert!(app.services.automation_command.is_some()); + assert_eq!(app.agent_link.port, Some(4321)); + assert!(tx.send(crate::ControlRequest::new("ui.inspect", json!({})).0).is_ok(), "the app holds the receiver"); + // An unrelated preference doesn't touch the connection. + app.run("prefs.set", json!({"values": {"performance.historyStates": 12}})).unwrap(); + tick(&mut app, &ctx); + assert_eq!(calls.lock().unwrap().len(), 2); + // Off: the channel and the policy go. + app.run("prefs.set", json!({"values": {"integrations.connectAgents": false}})).unwrap(); + tick(&mut app, &ctx); + assert_eq!(calls.lock().unwrap().len(), 3); + assert!(app.control_rx.is_none() && app.services.automation_command.is_none()); + assert_eq!(app.agent_link.port, None); + // ui.inspect reports it. + assert!(crate::control::inspect(&app, &ctx).get("agentLink").is_some()); +} + +/// With the AI-MCP flag the ArtCraft Launcher's switch is the one consent: it starts the +/// connection, turning it off there stops it again, and a Control Port saved before (the old, +/// flag-less way) doesn't keep it on. +#[test] +fn with_the_flag_the_launcher_switch_alone_turns_the_agent_connection_on_and_off() { + use std::sync::atomic::{AtomicBool, Ordering}; + let (mut app, _) = app_with_store(); + app.agent_link.mcp_flag = true; + app.run("prefs.set", json!({"values": {"integrations.connectAgents": true}})).unwrap(); + let ctx = egui::Context::default(); + let calls: Arc>> = Arc::default(); + let seen = calls.clone(); + app.services.agent_link = Some(Box::new(move |p: &prefs::Integrations, _: &egui::Context| { + seen.lock().unwrap().push(p.connect_agents); + crate::AgentLink { + stopped: !p.connect_agents, + status: crate::AgentLinkStatus { port: p.connect_agents.then_some(4321), ..Default::default() }, + ..Default::default() + } + })); + let launcher = Arc::new(AtomicBool::new(false)); + let on = launcher.clone(); + app.services.launcher_agents = Some(Box::new(move || on.load(Ordering::Relaxed))); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), [false]); + launcher.store(true, Ordering::Relaxed); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), [false, true], "the launcher's switch alone starts it"); + assert!(app.agent_link.launcher && app.agent_link.port == Some(4321)); + tick(&mut app, &ctx); + assert_eq!(calls.lock().unwrap().len(), 2, "no change, no restart"); + launcher.store(false, Ordering::Relaxed); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), [false, true, false], "off in the launcher stops it"); + assert!(!app.agent_link.launcher && app.agent_link.port.is_none()); +} + +/// Without the AI-MCP flag nothing changes from before: the launcher's switch means nothing, and a +/// Control Port saved in the preferences keeps its connection. +#[test] +fn without_the_flag_the_launcher_switch_means_nothing() { + let (mut app, _) = app_with_store(); + let ctx = egui::Context::default(); + let calls: Arc>> = Arc::default(); + let seen = calls.clone(); + app.services.agent_link = Some(Box::new(move |p: &prefs::Integrations, _: &egui::Context| { + seen.lock().unwrap().push(p.connect_agents); + crate::AgentLink { stopped: !p.connect_agents, ..Default::default() } + })); + app.services.launcher_agents = Some(Box::new(|| true)); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), [false], "the launcher's switch needs the flag"); + app.run("prefs.set", json!({"values": {"integrations.connectAgents": true}})).unwrap(); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), [false, true], "a saved Control Port still counts"); +} + +/// The connection's updates keep the AI-MCP flag the app was started with: losing it would put the +/// page back to the settings it had before the flag after the first frame. +#[test] +fn connection_updates_keep_the_mcp_flag() { + let (mut app, _) = app_with_store(); + let ctx = egui::Context::default(); + app.services.agent_link = Some(Box::new(|_: &prefs::Integrations, _: &egui::Context| crate::AgentLink::default())); + app.agent_link.mcp_flag = true; + tick(&mut app, &ctx); + assert!(app.agent_link.mcp_flag, "first frame"); + app.run("prefs.set", json!({"values": {"integrations.connectAgents": true}})).unwrap(); + tick(&mut app, &ctx); + assert!(app.agent_link.mcp_flag, "after a change"); +} + +/// With the flag the page has no switch of its own and nothing that sets up an MCP client: it says +/// where agents are turned on (the ArtCraft Launcher), and keeps the port, folders and closed-app +/// choice. +#[test] +fn ai_integrations_point_to_the_launcher_and_have_no_switch_or_client_buttons() { + use egui_kittest::{Harness, kittest::Queryable}; + let (mut app, _) = app_with_store(); + app.agent_link.mcp_flag = true; + open_preferences(&mut app, "integrations"); + let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.run_steps(4); + for label in ["Let AI agents connect (MCP)", "Copy Configuration", "Add to Claude Desktop", "Copy Prompt for an Agent"] { + assert!(h.query_by_label(label).is_none(), "{label}"); + } + h.get_by_label_contains("ArtCraft Launcher › Settings › AI agents › Let AI agents use Craft apps"); + h.get_by_label("Off: turn on AI agents in ArtCraft Launcher › Settings › AI agents."); + assert!(h.query_by_label("Folder agents can open from").is_some(), "the folders stay"); +} + +/// Without the suite's AI-MCP feature flag the page shows only the settings it had before. +#[test] +fn ai_integrations_without_the_mcp_flag_show_only_the_earlier_settings() { + use egui_kittest::{Harness, kittest::Queryable}; + let (mut app, _) = app_with_store(); + app.agent_link.mcp_flag = false; + open_preferences(&mut app, "integrations"); + let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + app + }); + h.run_steps(4); + assert!(h.query_by_label("Let AI agents connect (MCP)").is_none(), "the new connection switch waits for the flag"); + assert!(h.query_by_label("Folder agents can open from").is_none()); + assert!(h.query_by_label("Allow agent control").is_some(), "the earlier setting stays"); +} + +#[test] +fn ai_integrations_choices_and_paths_validate_through_prefs_set() { + let (mut app, _) = app_with_store(); + for v in ["launch", "headless", "error"] { + app.run("prefs.set", json!({"values": {"integrations.whenAppClosed": v}})).unwrap(); + assert_eq!(app.session.prefs().integrations.when_app_closed.name(), v); + } + assert!(app.run("prefs.set", json!({"values": {"integrations.whenAppClosed": "sometimes"}})).is_err()); + assert!(app.run("prefs.set", json!({"values": {"integrations.controlPort": 70000}})).is_err()); + app.run("prefs.set", json!({"values": {"integrations.writeRoot": "/tmp/out"}})).unwrap(); + assert_eq!(app.session.prefs().integrations.write_root, "/tmp/out"); +} + +/// A connection that is on but failed to start (its port taken) is tried again by itself, with the +/// same settings, and the automation gate follows the live policy. +#[test] +fn a_failed_start_is_retried_without_a_setting_change() { + let (mut app, _) = app_with_store(); + let ctx = egui::Context::default(); + let calls: Arc> = Arc::default(); + let seen = calls.clone(); + app.services.agent_link = Some(Box::new(move |p: &prefs::Integrations, _: &egui::Context| { + let mut n = seen.lock().unwrap(); + *n += 1; + let mut out = crate::AgentLink::default(); + if p.connect_agents && *n >= 3 { + out.status.port = Some(4321); + out.automation.authorize = Some(|_, _| Ok(())); + } else if p.connect_agents { + out.status.error = Some("Couldn't listen on 127.0.0.1:4321: in use".into()); + } + out + })); + app.run("prefs.set", json!({"values": {"integrations.connectAgents": true}})).unwrap(); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), 1); + assert!(app.agent_link.port.is_none() && app.prefs_rt.agent_link_retry.is_some(), "a retry is scheduled"); + // Not yet due: nothing happens. + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), 1); + // Due: tried again with the same settings, still failing, then started. + app.prefs_rt.agent_link_retry = Some(0.0); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), 2); + app.prefs_rt.agent_link_retry = Some(0.0); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), 3); + assert_eq!(app.agent_link.port, Some(4321)); + assert!(app.prefs_rt.agent_link_retry.is_none(), "running: no more retries"); + assert!(app.session.automation_gate.is_some(), "actions agents record keep the policy"); + tick(&mut app, &ctx); + assert_eq!(*calls.lock().unwrap(), 3); +} diff --git a/crates/ui-egui/src/prefs/prefs_ui/fields.rs b/crates/ui-egui/src/prefs/prefs_ui/fields.rs index 908711341b..c07c304fae 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/fields.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/fields.rs @@ -6,16 +6,20 @@ use super::{Color32, Map, PhotocraftApp, RichText, SECTIONS, Sense, Tokens, Valu // ------------------------------------------------------------------ bodies -/// Render one of our dialogs' bodies. -pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map) { +/// Render one of our dialogs' bodies (`id`: the dialog's, for answers that arrive later). +pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map, id: u64) { match f.get("__prefsui").and_then(Value::as_str).unwrap_or("") { "prefs" => { let mut info = app.perf.gpu_info.lines(); info.extend(gpu_memory_lines(app)); f.insert("__gpuInfo".into(), json!(info)); f.insert("__gpuAdapters".into(), json!(app.perf.gpu_info.adapters)); + f.insert("__agentLink".into(), serde_json::to_value(&app.agent_link).unwrap_or(Value::Null)); let system = system_theme(app, ui.ctx()); prefs_body(ui, f, system); + if let Some(action) = f.remove("__agentAction").and_then(|a| a.as_str().map(str::to_string)) { + super::agents::agent_action(app, f, &action, id); + } } "shortcuts" => shortcuts_body(app, ui, f), "presets" => presets_body(app, ui, f), @@ -49,6 +53,14 @@ pub(super) fn humanize(key: &str) -> String { if key == "notificationAutoHide" { return "Auto Hide Notifications".into(); } + // MCP: the labels its own rows show (`agents::integration_rows`), also for search. + match key { + "connectAgents" => return "Let AI agents connect (MCP)".into(), + "readRoot" => return "Folder agents can open from".into(), + "writeRoot" => return "Folder agents can save to".into(), + "whenAppClosed" => return "When PhotoCraft is closed".into(), + _ => {} + } if key == "notificationDurationSeconds" { return "Notification Duration (seconds)".into(); } @@ -123,6 +135,10 @@ pub(super) fn choice_label(v: &str) -> String { "ahd" => "AHD (adaptive homogeneity)".into(), "mhc" => "Malvar–He–Cutler".into(), "cpu" => "CPU (no GPU acceleration)".into(), + // MCP › When PhotoCraft is closed. + "launch" => "Open PhotoCraft".into(), + "headless" => "Work without a window".into(), + "error" => "Ask to open PhotoCraft".into(), v => humanize(v), } } @@ -250,6 +266,20 @@ fn prefs_body(ui: &mut egui::Ui, f: &mut Map, system: Option = + obj.iter().filter(|(k, _)| LEGACY_INTEGRATIONS.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + section_fields(ui, §ion, &mut shown, &order, lang, system, filter); + obj.extend(shown); } else if let Some(obj) = values.get_mut(§ion).and_then(Value::as_object_mut) { section_fields(ui, §ion, obj, &order, lang, system, filter); if section == "fileHandling" { @@ -370,6 +400,10 @@ fn interface_groups(ui: &mut egui::Ui, obj: &mut Map, keys: &[Str /// Where a clicked colour swatch leaves its preference path and label for the dialog body, which /// holds the fields the Color Picker request goes in. +/// Preferences › AI Integrations without the AI-MCP feature flag: the settings PhotoCraft had +/// before the agent connection page. +const LEGACY_INTEGRATIONS: [&str; 2] = ["allowAgentControl", "controlPort"]; + const PICK_ID: &str = "prefs-pick-color"; /// The colour swatch clicked this frame, if any: (preference path, label). @@ -522,6 +556,11 @@ fn field_rows(ui: &mut egui::Ui, section: &str, obj: &mut Map, ke let mut s = s.clone(); ui.add(egui::TextEdit::singleline(&mut s).desired_width(260.0)).accessible_name(tl!(&label)); obj.insert(k, json!(s)); + if read_at_launch(&path) { + ui.end_row(); + ui.label(""); + ui.label(RichText::new(tl!("Applies at next launch.")).color(t.text_dim)); + } } Value::Number(n) => { let value_label = ui.label(RichText::new(tl!(&label)).color(t.text_dim)); diff --git a/crates/ui-egui/src/prefs/prefs_ui/graphics.rs b/crates/ui-egui/src/prefs/prefs_ui/graphics.rs index 45b2e9ccdb..65c80cd90d 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/graphics.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/graphics.rs @@ -134,8 +134,6 @@ pub(super) fn read_at_launch(path: &str) -> bool { match path { // Only Windows and Linux draw their own title bar. "interface.systemTitleBar" => cfg!(all(not(target_arch = "wasm32"), not(target_os = "macos"))), - // The desktop app decides on the control server before its window opens. - "integrations.allowAgentControl" | "integrations.controlPort" => cfg!(not(target_arch = "wasm32")), // The WinTab context is opened once, when the window starts. "tools.tabletInput" => cfg!(target_os = "windows"), _ => false, diff --git a/crates/ui-egui/src/prefs/prefs_ui/save.rs b/crates/ui-egui/src/prefs/prefs_ui/save.rs index d236af92b4..d960159160 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/save.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/save.rs @@ -15,6 +15,7 @@ pub fn tick(app: &mut PhotocraftApp, ctx: &egui::Context) { presets_store(app); sync_tooltips(app, ctx); app.sync_recent(); + super::agents::sync_agent_link(app, ctx); // Monotonic, not `ctx.input(|i| i.time)`: logic also runs on hidden ticks, where egui's input // time is that of the last UI pass. if let Some(wait) = persist(app, crate::gpu_canvas::now_ms() / 1000.0) { diff --git a/crates/ui-egui/src/prefs/prefs_ui/tests.rs b/crates/ui-egui/src/prefs/prefs_ui/tests.rs index a0ed41a491..4f0d1f1584 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/tests.rs @@ -598,7 +598,7 @@ fn preferences_interface_search_hides_rows_and_skips_empty_groups() { } } -fn app_with_store() -> (PhotocraftApp, Arc>>) { +pub(super) fn app_with_store() -> (PhotocraftApp, Arc>>) { app_with_saved(None) } @@ -1582,10 +1582,13 @@ fn unimplemented_preferences_are_hidden_from_the_dialog() { assert!(has_visible_fields(&values, "fileHandling")); assert!(has_visible_fields(&values, "scratchDisks")); assert!(!prefs::is_hidden("scratchDisks.disks")); - // Allow Agent Control and Control Port are read at launch (apps/photocraft main.rs). + // MCP: the agent connection and its folders apply at once (`agents.rs`). assert!(has_visible_fields(&values, "integrations")); assert!(!prefs::is_hidden("integrations.allowAgentControl")); assert!(!prefs::is_hidden("integrations.controlPort")); + assert!(!prefs::is_hidden("integrations.readRoot")); + assert!(!prefs::is_hidden("integrations.writeRoot")); + assert!(!prefs::is_hidden("integrations.connectAgents")); // "Fill new type layers with placeholder text" and "Use Escape to Commit" are live; other Type rows stay hidden. assert!(has_visible_fields(&values, "type")); assert!(!prefs::is_hidden("type.fillNewTypeLayersWithPlaceholder")); @@ -1830,18 +1833,13 @@ fn rendering_mode_explains_next_launch() { assert!(h.query_by_label("Applies at next launch.").is_none()); } -/// #4097: Allow Agent Control and Control Port are read when the app starts, and say so. +/// Integrations' rows apply at once, so none of them says "Applies at next launch." (it did +/// before the agent connection followed the preferences live). #[test] -fn integrations_explain_next_launch() { - use egui_kittest::{Harness, kittest::Queryable}; - let obj = json!({"allowAgentControl": true, "controlPort": 0}).as_object().unwrap().clone(); - let mut h = Harness::new_ui_state( - |ui, obj: &mut Map| section_fields(ui, "integrations", obj, &[], crate::i18n::Lang::from_pref("en"), None, ""), - obj, - ); - h.run_steps(4); - h.get_by_label("Allow agent control"); - assert_eq!(h.query_all_by_label("Applies at next launch.").count(), 2, "one notice under each row"); +fn integrations_apply_without_a_restart() { + for key in ["allowAgentControl", "connectAgents", "controlPort", "readRoot", "writeRoot", "whenAppClosed"] { + assert!(!graphics::read_at_launch(&format!("integrations.{key}")), "{key}"); + } } #[test] diff --git a/crates/ui-egui/src/preset_files_ui.rs b/crates/ui-egui/src/preset_files_ui.rs index 5ea7b04615..6ba6aee6ca 100644 --- a/crates/ui-egui/src/preset_files_ui.rs +++ b/crates/ui-egui/src/preset_files_ui.rs @@ -181,7 +181,7 @@ mod tests { /// New Group (Enter) keeps it, Cancel imports nothing, Replace deletes it (#10640). #[test] fn reimporting_a_brush_file_asks_before_touching_its_group() { - use photocraft_psd::abr::{LegacyBrush, LegacyTip, write_v12}; + use craft_psd::abr::{LegacyBrush, LegacyTip, write_v12}; let round = |name: &str| LegacyBrush { name: name.into(), spacing: 25, @@ -240,7 +240,7 @@ mod tests { /// 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}; + use craft_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() }; diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index d09d91e9d5..5c7cc44950 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -161,9 +161,9 @@ fn cancelling_one_damaged_open_does_not_open_the_next_damaged_file_without_conse fn damage_confirmation_precedes_the_profile_question() { let mut app = app(); app.run("edit.colorSettings", json!({"askOnMismatch": true, "policyRgb": "preserve"})).unwrap(); - let (mut file, _) = photocraft_psd::PsdFile::from_bytes_and_merged(&recovery_psd::make_psd(true), |_| false).unwrap(); - file.resources.push(photocraft_psd::ImageResource::new( - photocraft_psd::resources::ids::ICC_PROFILE, + let (mut file, _) = craft_psd::PsdFile::from_bytes_and_merged(&recovery_psd::make_psd(true), |_| false).unwrap(); + file.resources.push(craft_psd::ImageResource::new( + craft_psd::resources::ids::ICC_PROFILE, photocraft_cms::Builtin::from_id("adobe-rgb-compat").unwrap().profile().to_bytes().to_vec(), )); app.open_bytes("profile.psd", &file.to_bytes().unwrap()).unwrap(); diff --git a/crates/ui-egui/src/red_eye_context_menu_tests.rs b/crates/ui-egui/src/red_eye_context_menu_tests.rs new file mode 100644 index 0000000000..24623db652 --- /dev/null +++ b/crates/ui-egui/src/red_eye_context_menu_tests.rs @@ -0,0 +1,206 @@ +//! #12577: a right-click on the canvas with the Red Eye tool opens the layer menu, or the +//! selection menu with the pointer inside a selection, as measured in the reference application on +//! a plain one-layer RGB document. The rows grey out like their menu-bar twins and run their +//! commands; the right-click itself corrects no red eye and adds no history state. The cases that +//! weren't measured keep opening nothing. + +use egui::Modifiers; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::canvas_tool_menu::count_tests::{call, listed, right_click}; +use crate::canvas_tool_menu::{entry_enabled, rows}; +use crate::state::Tool; + +/// A 64 × 48 RGB document with its one Background layer red, after a cleared selection (so +/// Reselect has one to restore). The Red Eye tool is the tool. +fn app() -> (PhotocraftApp, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 48, "background": "white"})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#d01818"})).unwrap(); + app.run("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::RedEye; + (app, egui::Context::default()) +} + +/// The open menu's rows as `ui.inspect` lists them: (label, enabled), "―" for separators. +fn entries(app: &mut PhotocraftApp, ctx: &egui::Context) -> Vec<(String, bool)> { + let inspected = call(app, ctx, "ui.inspect", json!({})); + let entries = inspected.pointer("/result/canvasToolMenu/entries").and_then(Value::as_array).cloned().unwrap_or_default(); + entries.iter().map(|e| (e["label"].as_str().unwrap_or("―").to_string(), e["enabled"] != false)).collect() +} + +/// `want` as (label, enabled): the rows named in `grey` disabled, separators as "―". +fn expected(want: &[&str], grey: &[&str]) -> Vec<(String, bool)> { + want.iter().map(|l| (l.to_string(), *l == "―" || !grey.contains(l))).collect() +} + +/// The document's revision, history depth and journal length. +fn state(app: &PhotocraftApp) -> (u64, usize, usize) { + let st = app.session.active().unwrap(); + (st.revision, st.history.past_len(), app.session.journal.len()) +} + +const NO_SELECTION: [&str; 17] = [ + "Blending Options…", + "―", + "Duplicate Layer…", + "Delete Layer", + "Group from Layers…", + "―", + "Convert to Smart Object", + "Convert to Layers", + "―", + "Rasterize Layer", + "Rasterize Layer Style", + "―", + "Free Transform", + "―", + "Color Range…", + "Load Selection…", + "Reselect", +]; + +/// Group from Layers… and Load Selection… follow their menu-bar twins, which grey them for the Background +/// (#12866) and for a lone Background with no saved selection (#13293), as the reference does. +const NO_SELECTION_GREY: [&str; 7] = + ["Blending Options…", "Group from Layers…", "Convert to Layers", "Rasterize Layer", "Rasterize Layer Style", "Free Transform", "Load Selection…"]; + +const IN_SELECTION: [&str; 23] = [ + "Deselect", + "Select Inverse", + "Feather…", + "Select and Mask…", + "―", + "Save Selection…", + "Make Work Path…", + "―", + "Layer Via Copy", + "Layer Via Cut", + "New Layer…", + "―", + "Free Transform", + "Transform Selection", + "―", + "Fill…", + "Stroke…", + "Content-Aware Fill…", + "Delete and Fill Selection", + "―", + "Last Filter", + "―", + "Fade…", +]; + +fn select(app: &mut PhotocraftApp) { + app.run("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); +} + +#[test] +fn without_a_selection_the_layer_menu_opens_in_order_with_the_reference_greys() { + let (mut app, ctx) = app(); + right_click(&mut app, &ctx, 40.0, 30.0); + assert_eq!(entries(&mut app, &ctx), expected(&NO_SELECTION, &NO_SELECTION_GREY)); +} + +#[test] +fn inside_a_selection_the_selection_menu_opens_in_order_with_the_reference_greys() { + let (mut app, ctx) = app(); + select(&mut app); + right_click(&mut app, &ctx, 20.0, 20.0); + assert_eq!(entries(&mut app, &ctx), expected(&IN_SELECTION, &["Last Filter", "Fade…"])); +} + +#[test] +fn rows_grey_out_like_their_menu_bar_twins() { + for selection in [false, true] { + let (mut app, ctx) = app(); + if selection { + select(&mut app); + } + right_click(&mut app, &ctx, 20.0, 20.0); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + for (_, id) in rows(&menu).iter().flatten() { + assert_eq!(entry_enabled(&app, &menu, id), crate::menus::is_enabled(&app, id), "{id} (selection: {selection})"); + } + } +} + +#[test] +fn picking_a_row_runs_its_command() { + let (mut app, ctx) = app(); + select(&mut app); + right_click(&mut app, &ctx, 20.0, 20.0); + assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id": "select.deselect"}))["ok"], true); + assert!(app.session.active().unwrap().doc.selection.is_none(), "Deselect deselected"); + assert!(app.ui.canvas_tool_menu.is_none(), "the pick closes the menu"); + right_click(&mut app, &ctx, 20.0, 20.0); + assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id": "select.reselect"}))["ok"], true); + assert!(app.session.active().unwrap().doc.selection.is_some(), "Reselect brought it back"); + // A row the open menu doesn't have is refused. + right_click(&mut app, &ctx, 20.0, 20.0); + assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id": "select.colorRange"}))["ok"], false); +} + +#[test] +fn the_right_click_corrects_no_red_eye_and_adds_no_history_state() { + for selection in [false, true] { + let (mut app, ctx) = app(); + if selection { + select(&mut app); + } + let before = state(&app); + right_click(&mut app, &ctx, 20.0, 20.0); + assert!(app.ui.canvas_tool_menu.is_some(), "the menu is open (selection: {selection})"); + assert_eq!(state(&app), before, "nothing ran (selection: {selection})"); + } +} + +#[test] +fn a_mouse_right_click_on_the_canvas_opens_the_layer_menu() { + let (app, _) = app(); + let mut h = crate::canvas_tool_menu::tests::harness(app); + let before = state(h.state()); + let center = h.state().last_canvas_rect.center(); + crate::canvas_tool_menu::tests::right_click(&mut h, center, Modifiers::NONE); + let menu = h.state().ui.canvas_tool_menu.clone().expect("the menu opens"); + let labels: Vec<&str> = rows(&menu).iter().map(|r| r.map_or("―", |(l, _)| l)).collect(); + assert_eq!(labels, NO_SELECTION); + assert_eq!(state(h.state()), before, "no correction, no history state"); +} + +#[test] +fn the_cases_not_measured_keep_opening_nothing() { + type Setup = fn(&mut PhotocraftApp); + let cases: [(&str, Setup); 5] = [ + ("outside the selection", |app| app.run("select.rect", json!({"x": 40, "y": 30, "width": 10, "height": 10})).map(drop).unwrap()), + ("a second layer", |app| app.run("layer.new.layer", json!({"name": "Ink"})).map(drop).unwrap()), + ("a smart object", |app| app.run("layer.smartObjects.convertToSmartObject", json!({})).map(drop).unwrap()), + ("a type layer", |app| { + let background = app.session.active().unwrap().doc.layers[0].id.0; + app.run("type.create", json!({"text": "Eyes", "size": 12, "x": 4, "y": 20})).unwrap(); + app.run("layer.select", json!({"layer": background})).unwrap(); + app.run("layer.delete", json!({})).unwrap(); + }), + ("Grayscale", |app| app.run("image.mode.grayscale", json!({})).map(drop).unwrap()), + ]; + for (what, setup) in cases { + let (mut app, ctx) = app(); + setup(&mut app); + let before = state(&app); + right_click(&mut app, &ctx, 20.0, 20.0); + assert!(app.ui.canvas_tool_menu.is_none(), "{what}: no menu"); + assert!(listed(&mut app, &ctx).is_empty(), "{what}"); + assert_eq!(state(&app), before, "{what}: nothing ran"); + } +} + +#[test] +fn outside_the_image_with_a_selection_the_pasteboard_menu_opens_as_before() { + let (mut app, ctx) = app(); + select(&mut app); + right_click(&mut app, &ctx, -10.0, 20.0); + assert!(app.ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "the pasteboard colour menu"); +} diff --git a/crates/ui-egui/src/retouch_mode_refusal_alert_tests.rs b/crates/ui-egui/src/retouch_mode_refusal_alert_tests.rs new file mode 100644 index 0000000000..eba8c7bce4 --- /dev/null +++ b/crates/ui-egui/src/retouch_mode_refusal_alert_tests.rs @@ -0,0 +1,41 @@ +//! #12673, #13033, #12656, #12967: a press with the Burn, Sponge, Blur or Smudge tool in an Indexed +//! Color or Bitmap document opens the reference application's colour-mode alert with OK, once, and +//! paints nothing; in RGB the same press still paints. + +use serde_json::json; + +use super::brush_refusal_alert_tests::{alerts, app, refused, steps, stroke}; +use super::*; + +const TOOLS: [(Tool, &str); 4] = [(Tool::Burn, "burn tool"), (Tool::Sponge, "sponge tool"), (Tool::Blur, "blur tool"), (Tool::Smudge, "smudge tool")]; + +#[test] +fn indexed_color_documents_get_the_mode_alert() { + for (tool, name) in TOOLS { + let mut app = app(tool); + app.run("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap(); + refused(&mut app, &format!("Could not use the {name} because it does not work with Indexed Color images (convert image to RGB Color mode to edit).")); + } +} + +#[test] +fn bitmap_documents_get_the_mode_alert() { + for (tool, name) in TOOLS { + let mut app = app(tool); + app.run("image.mode.grayscale", json!({})).unwrap(); + app.run("image.mode.bitmap", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.mode, photocraft_doc::ColorMode::Bitmap); + refused(&mut app, &format!("Could not use the {name} because it does not work with Bitmap images (convert image to Grayscale mode to edit).")); + } +} + +#[test] +fn rgb_documents_keep_painting() { + for (tool, _) in TOOLS { + let mut app = app(tool); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty(), "{tool:?}: no alert"); + assert_eq!(steps(&app), before + 1, "{tool:?}: the stroke was applied"); + } +} diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 6e28f00938..fc8a37bea1 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -340,6 +340,54 @@ pub type AutomationOpenPcraftFn = Box Result Result<(), String>>; +/// Same policy as [`AutomationCommandFn`] for each step a command runs (`actions.play`). +pub type AutomationAuthorizeFn = fn(&str, &Value) -> photocraft_engine::Result<()>; + +/// The automation half of [`Services`]: what control and MCP requests may read, write and run. +/// Replaced as a whole when Preferences › AI Integrations starts the agent connection or +/// changes its folders ([`Services::set_automation`]). +#[derive(Default)] +pub struct AutomationServices { + pub read: Option, + pub write: Option, + pub open_pcraft: Option, + pub save: Option, + pub command: Option, + pub authorize: Option, +} + +/// Preferences › AI Integrations: the agent connection as the dialog and `ui.inspect` show it. +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentLinkStatus { + /// Loopback port agents reach the app on, while it accepts them. + pub port: Option, + /// Started with `--control`: the launch flags manage the connection, not Preferences. + pub launch_flags: bool, + /// Why the connection, or one of its folders, couldn't be set up. + pub error: Option, + /// The suite's `AI-MCP` feature flag (`craft-flags`): without it the page shows only the + /// connection settings PhotoCraft had before (Allow Agent Control, Control Port). + pub mcp_flag: bool, + /// The ArtCraft Launcher's switch (Settings › AI agents) lets agents use the Craft apps: with + /// the `AI-MCP` flag, the one consent for agents in this window. + pub launcher: bool, +} + +/// What [`Services::agent_link`] did after the MCP settings changed. +#[derive(Default)] +pub struct AgentLink { + /// Requests from agents on a connection that just started (or moved to another port). + pub requests: Option>, + /// The connection stopped: drop the request channel. + pub stopped: bool, + /// What agent requests may read, write and run now. + pub automation: AutomationServices, + pub status: AgentLinkStatus, +} + +/// Starts, moves or stops the agent connection to match Preferences › AI Integrations. +pub type AgentLinkFn = Box AgentLink>; /// Open a URL in the system browser (native) — reliable cross-platform, unlike `ctx.open_url`. pub type OpenUrlFn = Box Result<(), String>>; @@ -534,7 +582,14 @@ pub struct Services { /// Same policy as [`Self::automation_command`], as a function pointer the engine calls for /// each step of `actions.play`. Installed on the session only while a control request or /// an automation-driven [`PhotocraftApp::run`] runs, so a local play of a recorded `file.*` step still works. - pub automation_authorize: Option photocraft_engine::Result<()>>, + pub automation_authorize: Option, + /// Preferences › AI Integrations (desktop): starts, moves or stops the agent connection when + /// its settings change. `None` on the web, and when `--control` manages the connection. + pub agent_link: Option, + /// Whether the ArtCraft Launcher turned agents on for every Craft app, cheap enough to ask every + /// frame (the desktop app watches the launcher's files on its own thread). `None` without the + /// suite's `AI-MCP` flag, on the web, and in tests that don't set it. + pub launcher_agents: Option bool>>, /// Encode an RGBA8 image as PNG (used for screenshots and `ui.render`). pub encode_png: Option, /// Open a URL in the system browser (native). Falls back to `ctx.open_url` (web) when unset. @@ -639,3 +694,15 @@ pub struct Services { /// Without one, eframe closes the window and the app ends with it. pub quit: Option, } + +impl Services { + /// Install the automation services (see [`AutomationServices`]). + pub fn set_automation(&mut self, a: AutomationServices) { + self.automation_read = a.read; + self.automation_write = a.write; + self.automation_open_pcraft = a.open_pcraft; + self.automation_save = a.save; + self.automation_command = a.command; + self.automation_authorize = a.authorize; + } +} diff --git a/crates/ui-egui/src/shape_bounds_box_tests.rs b/crates/ui-egui/src/shape_bounds_box_tests.rs index 9c4d4ff322..fd0ebdd59d 100644 --- a/crates/ui-egui/src/shape_bounds_box_tests.rs +++ b/crates/ui-egui/src/shape_bounds_box_tests.rs @@ -14,7 +14,7 @@ use crate::state::Tool; const NONE: Modifiers = Modifiers::NONE; /// A 1:1 view of the 1000 × 700 document, turned by `rotation` degrees. -fn view(rotation: f32) -> ViewXform { +pub(crate) fn view(rotation: f32) -> ViewXform { ViewXform { rect: egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(1000.0, 700.0)), zoom: 1.0, @@ -54,7 +54,7 @@ fn near(got: (f64, f64, f64, f64), want: [f64; 4]) { assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1.0), "{got:?} vs {want:?}"); } -fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { +pub(crate) fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, NONE); let mid = [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0]; tool_event(app, ToolEvent::Move { x: mid[0], y: mid[1], pressure: 1.0 }, NONE); diff --git a/crates/ui-egui/src/smart_filter_rows_tests.rs b/crates/ui-egui/src/smart_filter_rows_tests.rs index 1d5daf2950..71a2ea4d66 100644 --- a/crates/ui-egui/src/smart_filter_rows_tests.rs +++ b/crates/ui-egui/src/smart_filter_rows_tests.rs @@ -3,7 +3,7 @@ //! removes it, as in Photoshop. use egui::accesskit::{Role, Toggled}; -use egui::{Modifiers, Pos2}; +use egui::{Modifiers, Pos2, pos2}; use egui_kittest::kittest::{NodeT, Queryable}; use photocraft_doc::{LayerContent, LayerId}; use serde_json::json; @@ -399,3 +399,176 @@ fn double_clicking_the_liquify_filter_of_an_inactive_smart_object_edits_it() { let liquify = sm.smart_filters.iter().find(|f| f.command == photocraft_engine::distort_cmds::LIQUIFY).unwrap(); assert_eq!(liquify.params["strokes"].as_array().map(Vec::len), Some(2), "the new stroke was kept"); } + +/// 40 filler layers and the smart object "Smart A" (Gaussian Blur and Offset), at the top of the +/// stack when `smart_on_top` and at its bottom otherwise, in a Layers panel short enough that the +/// list scrolls: (harness, A). +fn scrolling_panel(smart_on_top: bool) -> (egui_kittest::Harness<'static, PhotocraftApp>, u64) { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16})).unwrap(); + let fillers = |s: &mut photocraft_engine::Session| { + for i in 0..40 { + s.execute("layer.new.layer", json!({"name": format!("Filler {i}")})).unwrap(); + } + }; + if smart_on_top { + fillers(&mut s); + } + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"contents": "black"})).unwrap(); + let a = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.setProps", json!({"layer": a, "name": "Smart A"})).unwrap(); + s.execute("filter.blur.gaussianBlur", json!({"radius": 1})).unwrap(); + s.execute("filter.other.offset", json!({"horizontal": 2})).unwrap(); + if !smart_on_top { + fillers(&mut s); + } + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 600.0)).with_max_steps(64).with_step_dt(1.0 / 60.0).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(s, crate::Services::default()) + }); + let ctx = h.ctx.clone(); + let (req, _rx) = crate::control::ControlRequest::new( + "ui.set", + json!({"theme": "promedium", "dockWidth": 290.0, "dockTabs": {"layers": 0}, "dock": {"collapsed": ["color", "properties", "history", "navigator"]}}), + ); + crate::control::handle(h.state_mut(), &ctx, &req); + h.run_steps(8); + (h, a) +} + +/// Scroll the Layers list by `steps` mouse wheel events of `delta` (negative scrolls down), with +/// the pointer at `over`, a point inside the list. +fn scroll_list(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, over: Pos2, steps: usize, unit: egui::MouseWheelUnit, delta: f32) { + h.hover_at(over); + h.run_steps(2); + for _ in 0..steps { + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit, + delta: egui::vec2(0.0, delta), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + }); + h.run_steps(1); + } + h.run_steps(10); +} + +fn scroll_to_bottom(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, over: Pos2) { + scroll_list(h, over, 80, egui::MouseWheelUnit::Line, -1.0); +} + +fn scroll_to_top(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, over: Pos2) { + scroll_list(h, over, 80, egui::MouseWheelUnit::Line, 1.0); +} + +/// The Layers rows' name button labelled `label`, if drawn. +fn button(h: &egui_kittest::Harness<'static, PhotocraftApp>, label: &str) -> Option { + h.query_all_by_label(label).find(|n| n.accesskit_node().role() == Role::Button).map(|n| n.rect()) +} + +/// Every text painted in the last frame. +fn painted_text(h: &egui_kittest::Harness<'static, PhotocraftApp>) -> Vec { + fn collect(shape: &egui::epaint::Shape, out: &mut Vec) { + match shape { + egui::epaint::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::epaint::Shape::Vec(shapes) => shapes.iter().for_each(|s| collect(s, out)), + _ => {} + } + } + let mut out = Vec::new(); + for clipped in &h.output().shapes { + collect(&clipped.shape, &mut out); + } + out +} + +/// #13118: a filter row scrolled out of the Layers list paints no name and carries no button, so +/// a long list of smart filters doesn't lay out every row's widgets each frame. It does once +/// scrolled into view. +#[test] +fn an_off_screen_filter_row_is_not_painted() { + let (mut h, _) = scrolling_panel(false); + let window = h.ctx.content_rect(); + // The smart object is the bottom layer: 40 rows lie above it, far below the window's end. + let filler = h.get_by_label("Filler 0").rect(); + assert!(filler.top() > window.bottom(), "the filters' rows are below the list's visible part: {filler:?} vs {window:?}"); + assert!(button(&h, "Gaussian Blur").is_none(), "no button for a row below the list"); + assert!(!painted_text(&h).iter().any(|t| t.contains("Gaussian Blur")), "no text for a row below the list"); + let top = h.get_by_label("Filler 39").rect().center(); + scroll_to_bottom(&mut h, top); + let fill = h.get_all_by_label("Fill").next().unwrap().rect(); + let row = button(&h, "Gaussian Blur").expect("the row is drawn once scrolled into view"); + assert!(row.center().y > fill.bottom() && row.center().y < window.bottom(), "the row shows in the list: {row:?}"); + assert!(painted_text(&h).iter().any(|t| t.contains("Gaussian Blur")), "the row's name is painted in view"); +} + +/// #13118: a filter selected stays selected while its row is scrolled out of view. +#[test] +fn a_selected_filter_stays_selected_when_scrolled_away() { + let (mut h, _) = scrolling_panel(false); + let top = h.get_by_label("Filler 39").rect().center(); + scroll_to_bottom(&mut h, top); + let blur = button(&h, "Gaussian Blur").expect("the row shows").center(); + click_at(&mut h, blur); + assert!(selected(&h, "Gaussian Blur"), "the click selects the filter"); + scroll_to_top(&mut h, top); + let window = h.ctx.content_rect(); + assert!(h.get_by_label("Filler 0").rect().top() > window.bottom(), "the filter's row scrolled away"); + h.run_steps(4); + scroll_to_bottom(&mut h, top); + assert!(selected(&h, "Gaussian Blur"), "still selected after scrolling away and back"); +} + +/// #13118: a filter dropped over the panel's header doesn't reorder against the row of its own +/// smart object scrolled out of view underneath it. The rows take drops only where the list +/// shows them. +#[test] +fn a_filter_dropped_over_the_header_skips_rows_scrolled_out_of_view() { + let (mut h, a) = scrolling_panel(true); + let (blur, offset) = ("filter.blur.gaussianBlur", "filter.other.offset"); + assert_eq!(filters(&h, a), [blur, offset]); + let fill = h.get_all_by_label("Fill").next().unwrap().rect(); + // Offset (the upper row) lies SUB_ROW_H-plus above Gaussian Blur's. + let (blur_row, offset_row) = (button(&h, "Gaussian Blur").unwrap(), button(&h, "Offset").unwrap()); + let gap = offset_row.center().y - blur_row.center().y; + assert!(gap < 0.0, "Offset is above Gaussian Blur: {gap}"); + // Scroll a little at a time until Offset's row is just above the list while Gaussian Blur's + // is still mostly in it. + let hover = h.get_by_label("Filler 39").rect().center(); + let mut blur_center = None; + for _ in 0..400 { + scroll_list(&mut h, hover, 1, egui::MouseWheelUnit::Point, -2.0); + let Some(row) = button(&h, "Gaussian Blur") else { break }; + let (c, above) = (row.center(), row.center().y + gap); + if above < fill.bottom() - 1.0 { + if c.y > fill.bottom() + 6.0 { + blur_center = Some(c); + } + break; + } + } + let from = blur_center.expect("Gaussian Blur's row is in the list with Offset's scrolled out above it"); + // Offset's row, hidden: the point in its upper half, which a drop would reorder against. + let over = pos2(from.x, from.y + gap - 6.0); + assert!(over.y < fill.bottom(), "the drop point is outside the list: {over:?} vs {fill:?}"); + let doc = h.state().session.active().unwrap().doc.clone(); + h.hover_at(from); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + // Down through the list, clear of its edges (which scroll it), then up over the header and + // released there at once. + let inside = pos2(from.x, from.y + 60.0); + for k in 1..=8 { + h.event(egui::Event::PointerMoved(from + (inside - from) * (k as f32 / 8.0))); + h.run_steps(1); + } + h.event(egui::Event::PointerMoved(over)); + h.event(egui::Event::PointerButton { pos: over, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + assert_eq!(filters(&h, a), [blur, offset], "the row under the header took no drop"); + let st = h.state().session.active().unwrap(); + assert!(st.doc == doc, "the document is unchanged"); + assert!(!h.state().ui.status_error, "{}", h.state().ui.status); +} diff --git a/crates/ui-egui/src/smudge_default_tip_tests.rs b/crates/ui-egui/src/smudge_default_tip_tests.rs new file mode 100644 index 0000000000..3086f52467 --- /dev/null +++ b/crates/ui-egui/src/smudge_default_tip_tests.rs @@ -0,0 +1,84 @@ +//! #12964: the Smudge tool starts, and comes back after Reset Tool, with the reference +//! application's tip: a 13 px soft round (hardness 0 %, angle 0°, roundness 100 %) at 25 % +//! spacing. Other tools' starting tips are unchanged. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::burn_default_tip_tests::{app, invoke, pick}; +use crate::state::Tool; + +/// Size, hardness, spacing, angle and roundness of the live brush, as `brush.get` reports them. +fn tip(app: &mut PhotocraftApp) -> [f64; 5] { + let b = app.run("brush.get", json!({})).unwrap(); + ["size", "hardness", "spacing", "angle", "roundness"].map(|k| (b[k].as_f64().unwrap() * 1e4).round() / 1e4) +} + +/// A tip that is no tool's starting tip, so a reset has something to undo. +fn scramble(app: &mut PhotocraftApp) { + let b = &mut app.session.tools.brush; + (b.size, b.hardness, b.spacing, b.angle, b.roundness) = (57.0, 0.4, 0.6, 30.0, 0.5); +} + +const SMUDGE_TIP: [f64; 5] = [13.0, 0.0, 0.25, 0.0, 1.0]; +const DEFAULT_TIP: [f64; 5] = [20.0, 1.0, 0.1, 0.0, 1.0]; + +#[test] +fn reset_tool_gives_the_smudge_tool_a_13_px_soft_tip() { + let mut app = app(); + pick(&mut app, Tool::Smudge); + scramble(&mut app); + invoke(&mut app, "tool.reset", json!({})); + assert_eq!(tip(&mut app), SMUDGE_TIP); + // The options-bar brush chip reads the live brush's rounded size. + assert_eq!(app.session.tools.brush.size.round(), 13.0); +} + +#[test] +fn a_first_use_starts_with_the_tip() { + // No stored tool brushes, as on a fresh install: the Smudge tool's first pick, after another + // tool's tip. + let mut app = app(); + pick(&mut app, Tool::Pencil); + scramble(&mut app); + pick(&mut app, Tool::Smudge); + assert_eq!(tip(&mut app), SMUDGE_TIP); + // Its own tip is then kept across tool switches. + app.session.tools.brush.size = 42.0; + pick(&mut app, Tool::Pencil); + pick(&mut app, Tool::Smudge); + assert_eq!(tip(&mut app)[0], 42.0); +} + +#[test] +fn reset_all_tools_gives_it_the_tip_active_or_picked_later() { + let mut app = app(); + pick(&mut app, Tool::Smudge); + scramble(&mut app); + invoke(&mut app, "tool.resetAll", json!({"confirmed": true})); + assert_eq!(tip(&mut app), SMUDGE_TIP, "active"); + let mut app = self::app(); + pick(&mut app, Tool::Smudge); + scramble(&mut app); + pick(&mut app, Tool::Pencil); + invoke(&mut app, "tool.resetAll", json!({"confirmed": true})); + pick(&mut app, Tool::Smudge); + assert_eq!(tip(&mut app), SMUDGE_TIP, "picked after the reset"); +} + +#[test] +fn blur_and_sharpen_keep_their_tips() { + for tool in [Tool::Blur, Tool::Sharpen] { + let mut a = app(); + pick(&mut a, tool); + scramble(&mut a); + invoke(&mut a, "tool.reset", json!({})); + assert_eq!(tip(&mut a), DEFAULT_TIP, "{tool:?}"); + // A first use still takes the current tip, as before. + let mut a = app(); + pick(&mut a, Tool::Pencil); + scramble(&mut a); + pick(&mut a, tool); + assert_eq!(tip(&mut a)[0], 57.0, "{tool:?}, first use"); + } +} diff --git a/crates/ui-egui/src/smudge_refusal_alert_tests.rs b/crates/ui-egui/src/smudge_refusal_alert_tests.rs new file mode 100644 index 0000000000..08e1ce8763 --- /dev/null +++ b/crates/ui-egui/src/smudge_refusal_alert_tests.rs @@ -0,0 +1,84 @@ +//! #12965: when the Smudge tool can't work on the layer (a hidden target layer, Lock All, Lock +//! Image Pixels, a group's pixels), a press opens the reference application's alert with OK and +//! changes nothing; Lock position still smudges. The Brush keeps its alerts, the other tools keep +//! today's behaviour. + +use serde_json::json; + +use super::brush_refusal_alert_tests::{active, alerts, app, refused, steps, stroke}; +use super::*; +use crate::control::{ControlRequest, Outcome, handle}; + +#[test] +fn a_hidden_target_layer() { + let mut app = app(Tool::Smudge); + let id = active(&app); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + refused(&mut app, "Could not use the smudge tool because the target layer is hidden."); + assert!(app.ui.status.is_empty() || !app.ui.status_error, "no status-bar error as well: {:?}", app.ui.status); +} + +#[test] +fn lock_all_and_lock_image_pixels() { + // Both are the one "the layer is locked." alert in the reference application. + for lock in ["all", "pixels"] { + let mut app = app(Tool::Smudge); + app.run("layer.lockLayers", json!({ lock: true })).unwrap(); + refused(&mut app, "Could not use the smudge tool because the layer is locked."); + } +} + +#[test] +fn a_group_is_active() { + let mut app = app(Tool::Smudge); + app.run("layer.new.group", json!({})).unwrap(); + refused(&mut app, "Could not use the smudge tool because the pixels in a group cannot be edited without merging the group."); +} + +#[test] +fn lock_position_still_smudges() { + let mut app = app(Tool::Smudge); + app.run("layer.lockLayers", json!({"position": true})).unwrap(); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty(), "Lock position is no refusal: {:?}", alerts(&app)); + assert_eq!(steps(&app), before + 1, "the stroke was applied"); +} + +#[test] +fn the_alert_is_listed_and_confirmed_over_the_control_channel() { + let ctx = egui::Context::default(); + let mut app = app(Tool::Smudge); + app.run("layer.lockLayers", json!({"pixels": true})).unwrap(); + stroke(&mut app); + let mut call = |method: &str, params: serde_json::Value| { + let (req, _rx) = ControlRequest::new(method, params); + match handle(&mut app, &ctx, &req) { + Outcome::Done(v) => v, + _ => panic!("{method}: expected an immediate reply"), + } + }; + let inspect = call("ui.inspect", json!({})); + let dialog = &inspect["result"]["dialogs"][0]; + assert_eq!(dialog["fields"]["message"], "Could not use the smudge tool because the layer is locked.", "{inspect}"); + assert_eq!(call("ui.dialog.confirm", json!({"dialog": dialog["id"]}))["ok"], true); + assert!(alerts(&app).is_empty()); +} + +#[test] +fn the_brush_and_the_other_tools_keep_todays_behaviour() { + // The Brush: no alert for Lock Image Pixels. + let mut app = self::app(Tool::Brush); + app.run("layer.lockLayers", json!({"pixels": true})).unwrap(); + stroke(&mut app); + assert!(alerts(&app).is_empty()); + // The Blur tool, the Smudge tool's neighbour in the toolbar, has no layer alerts yet: the + // status bar says a hidden target. + let mut app = self::app(Tool::Blur); + let id = active(&app); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + stroke(&mut app); + assert!(alerts(&app).is_empty()); + assert_eq!(app.ui.status, photocraft_engine::hidden_target::HIDDEN); + assert_eq!(tool_name(&app, Tool::Blur), None); +} diff --git a/crates/ui-egui/src/sponge_default_tip_tests.rs b/crates/ui-egui/src/sponge_default_tip_tests.rs new file mode 100644 index 0000000000..9d9f6d077b --- /dev/null +++ b/crates/ui-egui/src/sponge_default_tip_tests.rs @@ -0,0 +1,83 @@ +//! #13029: the Sponge tool starts, and comes back after Reset Tool, with the reference +//! application's tip: a 65 px soft round (hardness 0 %, angle 0°, roundness 100 %) at 25 % +//! spacing, the Burn and Dodge tools' tip. Other tools' starting tips are unchanged. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::burn_default_tip_tests::{app, invoke, pick}; +use crate::state::Tool; + +/// Size, hardness, spacing, angle and roundness of the live brush, as `brush.get` reports them. +fn tip(app: &mut PhotocraftApp) -> [f64; 5] { + let b = app.run("brush.get", json!({})).unwrap(); + ["size", "hardness", "spacing", "angle", "roundness"].map(|k| (b[k].as_f64().unwrap() * 1e4).round() / 1e4) +} + +/// A tip that is no tool's starting tip, so a reset has something to undo. +fn scramble(app: &mut PhotocraftApp) { + let b = &mut app.session.tools.brush; + (b.size, b.hardness, b.spacing, b.angle, b.roundness) = (57.0, 0.4, 0.6, 30.0, 0.5); +} + +const SPONGE_TIP: [f64; 5] = [65.0, 0.0, 0.25, 0.0, 1.0]; +const DEFAULT_TIP: [f64; 5] = [20.0, 1.0, 0.1, 0.0, 1.0]; + +#[test] +fn reset_tool_gives_the_sponge_tool_a_65_px_soft_tip() { + let mut app = app(); + pick(&mut app, Tool::Sponge); + scramble(&mut app); + invoke(&mut app, "tool.reset", json!({})); + assert_eq!(tip(&mut app), SPONGE_TIP); + // The options-bar brush chip reads the live brush's rounded size. + assert_eq!(app.session.tools.brush.size.round(), 65.0); +} + +#[test] +fn a_first_use_starts_with_the_tip() { + // No stored tool brushes, as on a fresh install: the Sponge tool's first pick, after another + // tool's tip. + let mut app = app(); + pick(&mut app, Tool::Pencil); + scramble(&mut app); + pick(&mut app, Tool::Sponge); + assert_eq!(tip(&mut app), SPONGE_TIP); + // Its own tip is then kept across tool switches, and the Pencil keeps its own. + app.session.tools.brush.size = 42.0; + pick(&mut app, Tool::Pencil); + assert_eq!(tip(&mut app)[0], 57.0, "Pencil"); + pick(&mut app, Tool::Sponge); + assert_eq!(tip(&mut app)[0], 42.0); +} + +#[test] +fn reset_all_tools_gives_it_the_tip_active_or_picked_later() { + let mut app = app(); + pick(&mut app, Tool::Sponge); + scramble(&mut app); + invoke(&mut app, "tool.resetAll", json!({"confirmed": true})); + assert_eq!(tip(&mut app), SPONGE_TIP, "active"); + let mut app = self::app(); + pick(&mut app, Tool::Sponge); + scramble(&mut app); + pick(&mut app, Tool::Pencil); + invoke(&mut app, "tool.resetAll", json!({"confirmed": true})); + pick(&mut app, Tool::Sponge); + assert_eq!(tip(&mut app), SPONGE_TIP, "picked after the reset"); +} + +#[test] +fn the_blur_tool_keeps_its_tip() { + let mut a = app(); + pick(&mut a, Tool::Blur); + scramble(&mut a); + invoke(&mut a, "tool.reset", json!({})); + assert_eq!(tip(&mut a), DEFAULT_TIP); + // A first use still takes the current tip, as before. + let mut a = app(); + pick(&mut a, Tool::Pencil); + scramble(&mut a); + pick(&mut a, Tool::Blur); + assert_eq!(tip(&mut a)[0], 57.0, "first use"); +} diff --git a/crates/ui-egui/src/sponge_flow_field_tests.rs b/crates/ui-egui/src/sponge_flow_field_tests.rs index 5853d8a85a..fb8dda9d90 100644 --- a/crates/ui-egui/src/sponge_flow_field_tests.rs +++ b/crates/ui-egui/src/sponge_flow_field_tests.rs @@ -155,6 +155,10 @@ fn a_sponge_click_uses_the_bar_flow() { for f in [10.0, 50.0, 100.0] { let mut clicked = red_app(); clicked.ui.tool = Tool::Sponge; + // The Sponge's first pick brings its own soft tip (#13029): give it the 40 px hard one at + // the default 10 % spacing, as `paint.sponge` paints below. + crate::paint_mouse::sync_tool_brush(&mut clicked); + clicked.run("tools.setBrush", json!({"brush": {"size": 40, "hardness": 1.0, "spacing": 0.1}})).unwrap(); clicked.ui.tool_options.sponge_mode = "desaturate".into(); clicked.ui.tool_options.vibrance = true; clicked.ui.tool_options.sponge_flow = f; diff --git a/crates/ui-egui/src/sponge_refusal_alert_tests.rs b/crates/ui-egui/src/sponge_refusal_alert_tests.rs new file mode 100644 index 0000000000..522cc98d00 --- /dev/null +++ b/crates/ui-egui/src/sponge_refusal_alert_tests.rs @@ -0,0 +1,84 @@ +//! #13030: when the Sponge tool can't work on the layer (a hidden target layer, Lock All, Lock +//! Image Pixels, a group's pixels), a press opens the reference application's alert with OK and +//! changes nothing; Lock position still sponges. The Brush keeps its alerts, the other tools keep +//! today's behaviour. + +use serde_json::json; + +use super::brush_refusal_alert_tests::{active, alerts, app, refused, steps, stroke}; +use super::*; +use crate::control::{ControlRequest, Outcome, handle}; + +#[test] +fn a_hidden_target_layer() { + let mut app = app(Tool::Sponge); + let id = active(&app); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + refused(&mut app, "Could not use the sponge tool because the target layer is hidden."); + assert!(app.ui.status.is_empty() || !app.ui.status_error, "no status-bar error as well: {:?}", app.ui.status); +} + +#[test] +fn lock_all_and_lock_image_pixels() { + // Both are the one "the layer is locked." alert in the reference application. + for lock in ["all", "pixels"] { + let mut app = app(Tool::Sponge); + app.run("layer.lockLayers", json!({ lock: true })).unwrap(); + refused(&mut app, "Could not use the sponge tool because the layer is locked."); + } +} + +#[test] +fn a_group_is_active() { + let mut app = app(Tool::Sponge); + app.run("layer.new.group", json!({})).unwrap(); + refused(&mut app, "Could not use the sponge tool because the pixels in a group cannot be edited without merging the group."); +} + +#[test] +fn lock_position_still_sponges() { + let mut app = app(Tool::Sponge); + app.run("layer.lockLayers", json!({"position": true})).unwrap(); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty(), "Lock position is no refusal: {:?}", alerts(&app)); + assert_eq!(steps(&app), before + 1, "the stroke was applied"); +} + +#[test] +fn the_alert_is_listed_and_confirmed_over_the_control_channel() { + let ctx = egui::Context::default(); + let mut app = app(Tool::Sponge); + app.run("layer.lockLayers", json!({"pixels": true})).unwrap(); + stroke(&mut app); + let mut call = |method: &str, params: serde_json::Value| { + let (req, _rx) = ControlRequest::new(method, params); + match handle(&mut app, &ctx, &req) { + Outcome::Done(v) => v, + _ => panic!("{method}: expected an immediate reply"), + } + }; + let inspect = call("ui.inspect", json!({})); + let dialog = &inspect["result"]["dialogs"][0]; + assert_eq!(dialog["fields"]["message"], "Could not use the sponge tool because the layer is locked.", "{inspect}"); + assert_eq!(call("ui.dialog.confirm", json!({"dialog": dialog["id"]}))["ok"], true); + assert!(alerts(&app).is_empty()); +} + +#[test] +fn the_brush_and_the_other_tools_keep_todays_behaviour() { + // The Brush: no alert for Lock Image Pixels. + let mut app = self::app(Tool::Brush); + app.run("layer.lockLayers", json!({"pixels": true})).unwrap(); + stroke(&mut app); + assert!(alerts(&app).is_empty()); + // The Dodge tool keeps its colour-mode alert only: no layer alerts, the status bar says a + // hidden target. + let mut app = self::app(Tool::Dodge); + let id = active(&app); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + stroke(&mut app); + assert!(alerts(&app).is_empty()); + assert_eq!(app.ui.status, photocraft_engine::hidden_target::HIDDEN); + assert_eq!(tool_name(&app, Tool::Dodge), None); +} diff --git a/crates/ui-egui/src/star_tool_tests.rs b/crates/ui-egui/src/star_tool_tests.rs index b83bb15d83..8a476690c8 100644 --- a/crates/ui-egui/src/star_tool_tests.rs +++ b/crates/ui-egui/src/star_tool_tests.rs @@ -109,7 +109,7 @@ fn shift_and_alt_constrain_and_centre_the_star_like_the_polygon_tool() { app.ui.tool = Tool::Star; drag(&mut app, [100.0, 100.0], [140.0, 120.0], Modifiers::SHIFT | Modifiers::ALT); match live_shape(&app) { - Some(LiveShape::Polygon { rect, .. }) => assert_eq!(rect, [60.0, 60.0, 80.0, 80.0], "a square box drawn from the centre"), + Some(LiveShape::Polygon { rect, .. }) => assert_eq!(rect, [80.0, 80.0, 40.0, 40.0], "a square box of the shorter side drawn from the centre (#13222)"), other => panic!("a live star shape, got {other:?}"), } } diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index 0f800645da..874c444d19 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -103,6 +103,11 @@ pub struct ToolOptions { /// draws it as "combine"), "combine", "subtract", "intersect" or "exclude". #[serde(default = "default_pen_path_op")] pub pen_path_op: String, + /// Shape tools › Path operations (#13235): how a drag combines with the active shape layer + /// (Shape mode) or work path (Path mode). Same values as `pen_path_op`; in Path mode "newLayer" + /// means Exclude Overlapping Shapes. + #[serde(default = "default_shape_path_op")] + pub shape_path_op: String, /// Shape tools: "shape" (a shape layer) or "path" (the work path), as Photoshop's tool mode /// (#9453). Shape by default, where the Pen's own mode defaults to Path. pub shape_mode: String, @@ -117,6 +122,9 @@ pub struct ToolOptions { pub shape_fill_gradient: Option, pub shape_stroke_gradient: Option, pub corner_radius: f32, + /// Shape tools' Align Edges: snap the drawn shape's box to whole pixels. On by default; the + /// Triangle tool shows it, enabled in Shape mode only (#13370); the other shape tools always snap. + pub align_edges: bool, pub polygon_sides: u32, pub line_weight: f32, /// Line arrowheads. @@ -251,6 +259,10 @@ pub struct ToolOptions { /// Zoom tool › Scrubby Zoom: dragging left/right zooms continuously (else a zoom rectangle). #[serde(default = "yes")] pub zoom_scrubby: bool, + /// Zoom tool › Zoom In / Zoom Out: which way a click steps (⌥ turns it around). Reset Tool + /// leaves it, as in Photoshop. + #[serde(default = "yes")] + pub zoom_in: bool, /// Hand tool › Scroll All Windows: a Hand drag pans every shown document view, not only the /// one dragged in (`scroll_all_windows.rs`). Shift held while dragging does the same. #[serde(default)] @@ -328,6 +340,10 @@ fn default_pen_path_op() -> String { "newLayer".into() } +fn default_shape_path_op() -> String { + "newLayer".into() +} + fn default_curve_fit() -> f32 { 2.0 } @@ -498,6 +514,7 @@ impl Default for ToolOptions { enhance_edge: false, vector_mode: "path".into(), pen_path_op: default_pen_path_op(), + shape_path_op: default_shape_path_op(), shape_mode: "shape".into(), shape_fill: true, stroke_width: 0.0, @@ -505,12 +522,13 @@ impl Default for ToolOptions { shape_fill_gradient: None, shape_stroke_gradient: None, corner_radius: 0.0, + align_edges: true, polygon_sides: 5, - line_weight: 3.0, + line_weight: 1.0, arrow_start: false, arrow_end: false, - arrow_width: 52.0, - arrow_length: 50.0, + arrow_width: 5.0, + arrow_length: 10.0, arrow_concavity: 0.0, curve_fit: default_curve_fit(), pen_auto_add_delete: true, @@ -557,6 +575,7 @@ impl Default for ToolOptions { cr_tolerance: 30.0, cr_anti_alias: true, zoom_scrubby: true, + zoom_in: true, hand_scroll_all: false, pencil_auto_erase: false, brush_clear: false, diff --git a/crates/ui-egui/src/stroke_timing_tests.rs b/crates/ui-egui/src/stroke_timing_tests.rs index ee9461f6fd..d569f73f11 100644 --- a/crates/ui-egui/src/stroke_timing_tests.rs +++ b/crates/ui-egui/src/stroke_timing_tests.rs @@ -545,8 +545,10 @@ fn a_shift_click_dodge_line_commits_its_live_pixels_unsmoothed() { fn pressure_sized_smudge_release_matches_replay_and_undo_redo() { use crate::stylus::PenSample; + // The spacing is set too: the Smudge tool starts with its own tip (#12964), the replay's + // fresh session with the default brush. let setup = |run: &mut dyn FnMut(&str, Value)| { - run("tools.setBrush", json!({"brush": {"size":40,"hardness":0.7,"pressureSize":true,"smoothing":{"amount":0.4}}})); + run("tools.setBrush", json!({"brush": {"size":40,"hardness":0.7,"spacing":0.1,"pressureSize":true,"smoothing":{"amount":0.4}}})); run("paint.stroke", json!({"points":[[10,20],[190,80]],"size":30,"color":"#2060c0"})); }; let mut h = harness(); diff --git a/crates/ui-egui/src/tool_memory.rs b/crates/ui-egui/src/tool_memory.rs index 4775e15db9..b13a4020ab 100644 --- a/crates/ui-egui/src/tool_memory.rs +++ b/crates/ui-egui/src/tool_memory.rs @@ -361,7 +361,7 @@ pub(crate) fn sanitize(o: &mut ToolOptions) { fit(&mut o.exposure, 1.0, 100.0, d.exposure); fit(&mut o.strength, 1.0, 100.0, d.strength); fit(&mut o.stroke_width, 0.0, 288.0, d.stroke_width); - fit(&mut o.corner_radius, 0.0, 10000.0, d.corner_radius); + fit(&mut o.corner_radius, *crate::shape_options::RADIUS_RANGE.start(), *crate::shape_options::RADIUS_RANGE.end(), d.corner_radius); fit(&mut o.line_weight, 1.0, 1000.0, d.line_weight); fit(&mut o.curve_fit, 0.5, 10.0, d.curve_fit); // The marquee's and the Slice tool's Width and Height are a ratio or a size in px, as their diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 81dafc6bc9..503bbe0a7d 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -63,6 +63,12 @@ pub mod zoom_tool; #[cfg(test)] mod gradient_mode_greyed_tests; +#[cfg(test)] +mod line_live_handles_tests; + +#[cfg(test)] +mod object_selection_mode_tests; + #[cfg(test)] mod count_show_extras_tests; #[cfg(test)] @@ -71,3 +77,15 @@ mod crop_options_labels_tests; mod gradient_options_bar_mode_tests; #[cfg(test)] mod gradient_refusal_messages_tests; +#[cfg(test)] +mod line_tool_defaults_tests; +#[cfg(test)] +mod path_selection_ctrl_direct_tests; +#[cfg(test)] +mod path_selection_shape_over_saved_path_tests; + +#[cfg(test)] +mod remove_default_size_tests; + +#[cfg(test)] +mod ellipse_center_mark_tests; diff --git a/crates/ui-egui/src/tools/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs index 7580ec88c4..6da8b1fe5a 100644 --- a/crates/ui-egui/src/tools/analysis_ui.rs +++ b/crates/ui-egui/src/tools/analysis_ui.rs @@ -22,6 +22,25 @@ use crate::canvas::{ToolEvent, ViewXform}; use crate::state::{DialogKind, Tool}; use crate::theme::Tokens; +#[cfg(test)] +#[path = "count_readout_tests.rs"] +mod count_readout_tests; + +/// The Count tool options bar's number (#11764): with one group (or none), its markers; with two +/// or more, the markers of the visible groups, then the current group's in brackets (0 while it +/// is hidden), as "5 (2)". The single-group case counts a hidden group too (not measured, so it +/// keeps the old total). An out-of-range current index means the last group, as in the Group +/// dropdown and `count.add`. +pub(crate) fn count_readout(m: &photocraft_doc::analysis::Measurement) -> String { + if m.count_groups.len() < 2 { + return m.count_total().to_string(); + } + let visible: usize = m.count_groups.iter().filter(|g| g.visible).map(|g| g.points.len()).sum(); + let gi = m.active_count_group.min(m.count_groups.len().saturating_sub(1)); + let current = m.count_groups.get(gi).filter(|g| g.visible).map_or(0, |g| g.points.len()); + format!("{visible} ({current})") +} + /// What a pointer drag is doing (not serialised). #[derive(Clone, Copy, Debug, PartialEq)] pub enum Drag { @@ -223,6 +242,19 @@ fn dist(a: [f64; 2], b: [f64; 2]) -> f64 { (a[0] - b[0]).hypot(a[1] - b[1]) } +/// Is `p` within the grab radius `tol` of one of `r`'s end points? +fn near_end(r: Ruler, p: [f64; 2], tol: f64) -> bool { + dist(p, r.start) <= tol || dist(p, r.end) <= tol +} + +/// Is the pointer at document point `p` over the ruler's end points? The very hit test a press +/// makes its decision with ([`near_end`], `dist` with [`tolerance`]), so the Ruler tool's ⌥ pointer +/// shows exactly where an ⌥-drag starts the protractor arm (#12037). +pub(crate) fn ruler_end_at(app: &PhotocraftApp, p: [f64; 2]) -> bool { + let tol = tolerance(app); + app.session.active().is_some_and(|d| d.doc.measurement.ruler.is_some_and(|r| near_end(r, p, tol))) +} + /// Shift constrains to 45° steps around `from`, as the reference does (#11985): on a diagonal step /// both legs take the smaller of |dx| and |dy| (signs kept), on a 0° or 90° step the dominant /// component stays and the other becomes 0, so the ruler never gets longer than the pointer's legs. @@ -290,7 +322,7 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> let near = |q: [f64; 2]| dist(p, q) <= tol; match cur { // ⌥-drag from an end point starts the protractor arm at that vertex. - Some(mut r) if mods.alt && (near(r.start) || near(r.end)) => { + Some(mut r) if mods.alt && near_end(r, p, tol) => { if near(r.end) && !near(r.start) { std::mem::swap(&mut r.start, &mut r.end); } @@ -526,7 +558,11 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform } // Color Sampler points (#1046): persistent numbered markers, drawn whatever the active tool is. // While one is dragged its marker follows the pointer, and a new one shows the next number - // there (#11729), unless the limit is reached and the release cannot place it. + // there (#11729), unless the limit is reached and the release cannot place it. View › Extras + // off hides the markers but keeps the points and their Info readouts (#11741). + if !v.extras { + return; + } let mut samplers = app.session.active().map(|d| d.color_samplers.clone()).unwrap_or_default(); match app.ui.analysis.drag { Some(Drag::Sampler(i, at)) if app.ui.tool == Tool::ColorSampler && i < samplers.len() => samplers[i] = at, @@ -610,50 +646,86 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo Tool::Count => { let t = Tokens::get(ui.ctx()); let m = &doc.measurement; - ui.label(RichText::new(crate::i18n::fmt(tl!("Count: {n}"), &[("n", &m.count_total().to_string())])).color(t.text).size(11.0)); + ui.label(RichText::new(crate::i18n::fmt(tl!("Count: {n}"), &[("n", &count_readout(m))])).color(t.text).size(11.0)); crate::widgets::vline(ui, 22.0); - if !m.count_groups.is_empty() { - let mut gi = m.active_count_group.min(m.count_groups.len() - 1); + // Every control from the start, in Photoshop's order (#11765): group, eye, folder, + // trash, Clear, colour, Marker Size, Label Size. With no group yet the swatch and the + // sizes show what the next new group gets; using them, or the eye, changes nothing + // until there is a group (not measured). + let group = (!m.count_groups.is_empty()).then(|| m.active_count_group.min(m.count_groups.len() - 1)); + let next = photocraft_doc::CountGroup::default(); + let g = group.map_or(&next, |gi| &m.count_groups[gi]); + if let Some(mut gi) = group { let opts: Vec<(usize, &str)> = m.count_groups.iter().enumerate().map(|(i, g)| (i, g.name.as_str())).collect(); - if crate::widgets::dropdown(ui, "count-group", tl!("Group"), &mut gi, &opts, 140.0) { + if crate::widgets::dropdown(ui, "count-group", tl!("Group"), &mut gi, &opts, 150.0) { let _ = app.run("count.setGroup", json!({"group": gi, "active": true})); } - let g = &m.count_groups[gi]; - let eye = if g.visible { "eye" } else { "eye-off" }; - if crate::icons::button(ui, eye, 22.0, false, tl!("Toggle count group visibility")).clicked() { - let _ = app.run("count.setGroup", json!({"group": gi, "visible": !g.visible})); - } - let rgb = g.color.to_rgb(); - // PhotoCraft's Color Picker (sRGB), as everywhere else (#2144). - if crate::widgets::color_swatch_button(ui, color32(rgb), tl!("Color")).clicked() { - crate::color_picker_ui::open_for_command( - app, - &crate::color_picker_ui::title_for(tl!("Color")), - rgb, - "count.setGroup", - json!({"group": gi}), - ); - } - if crate::icons::button(ui, "trash", 22.0, false, tl!("Delete count group")).clicked() { - let _ = app.run("count.deleteGroup", json!({"group": gi})); - } + } else { + ui.add_enabled_ui(false, |ui| crate::widgets::dropdown(ui, "count-group", tl!("Group"), &mut 0usize, &[(0, tl!("Count Group"))], 150.0)); + } + let eye = if g.visible { "eye" } else { "eye-off" }; + if crate::icons::button(ui, eye, 22.0, false, tl!("Toggle visibility of count group")).clicked() + && let Some(gi) = group + { + let _ = app.run("count.setGroup", json!({"group": gi, "visible": !g.visible})); } if crate::icons::button(ui, "folder-plus", 22.0, false, tl!("Create a new count group")).clicked() { let _ = app.run("count.newGroup", json!({})); } - if crate::widgets::secondary_button(ui, tl!("Clear"), 0.0).clicked() && m.count_total() > 0 { + // The last group can't be deleted from here (`count.deleteGroup` still can). + let trash = ui.add_enabled_ui(m.count_groups.len() >= 2, |ui| { + crate::icons::button(ui, "trash", 22.0, false, tl!("Delete the currently selected count group")) + }); + if trash.inner.clicked() + && let Some(gi) = group + { + let _ = app.run("count.deleteGroup", json!({"group": gi})); + } + // Clear acts on a visible current group with markers (`count.clear` itself is unchanged). + let clearable = group.is_some() && g.visible && !g.points.is_empty(); + if ui.add_enabled_ui(clearable, |ui| crate::widgets::secondary_button(ui, tl!("Clear"), 0.0)).inner.clicked() { let _ = app.run("count.clear", json!({})); } - if let Some(g) = m.count_groups.get(m.active_count_group) { - crate::widgets::vline(ui, 22.0); - let (mut ms, mut ls) = (g.marker_size as f32, g.label_size as f32); - ui.label(RichText::new(tl!("Marker Size")).color(t.text_dim).size(11.0)); - let a = crate::widgets::value_field(ui, &mut ms, 1.0..=10.0, "", 40.0).accessible_name(tl!("Marker Size")).changed(); - ui.label(RichText::new(tl!("Label Size")).color(t.text_dim).size(11.0)); - let b = crate::widgets::value_field(ui, &mut ls, 8.0..=72.0, "", 44.0).accessible_name(tl!("Label Size")).changed(); - if a || b { - let _ = app.run("count.setGroup", count_size_params(ms, ls)); + let rgb = g.color.to_rgb(); + // PhotoCraft's Color Picker (sRGB), as everywhere else (#2144). + if crate::widgets::color_swatch_button(ui, color32(rgb), tl!("Count group color")).on_hover_text(tl!("Count group color")).clicked() + && let Some(gi) = group + { + crate::color_picker_ui::open_for_command( + app, + &crate::color_picker_ui::title_for(tl!("Count Color")), + rgb, + "count.setGroup", + json!({"group": gi}), + ); + } + crate::widgets::vline(ui, 22.0); + let (mut ms, mut ls) = (g.marker_size as f32, g.label_size as f32); + // Scrubby captions with colons, as in Photoshop: the options bar's own caption, which + // scrubs the field after it when dragged. The catalogs translate the names without + // the colon (main's captions), so the colon follows the translation. + let caption = |ui: &mut egui::Ui, text: &str| crate::panels::opt_label(ui, &format!("{text}:")); + // Each caption names its field (the scrub link), so a screen reader reads what is shown. + caption(ui, tl!("Marker Size")); + let a = crate::widgets::value_field_whole(ui, &mut ms, 1.0..=10.0, "", 40.0); + caption(ui, tl!("Label Size")); + let b = crate::widgets::value_field_whole(ui, &mut ls, 8.0..=72.0, "", 44.0); + // One undo step per scrub (of a field or its caption), as the Gradient tool's Opacity. + let drag = |r: &egui::Response| { + let key = r.id.with("count-size-drag"); + if r.drag_started() { + let n = ui.ctx().cumulative_pass_nr(); + ui.data_mut(|d| d.insert_temp(key, n)); } + if r.changed() && r.dragged() { ui.data(|d| d.get_temp::(key)).map(|n| format!("count-size:{}:{n}", key.value())) } else { None } + }; + let coalesce = drag(&a).or(drag(&b)); + if (a.changed() || b.changed()) && group.is_some() { + let mut p = count_size_params(ms, ls); + if let Some(k) = coalesce { + p["coalesce"] = json!(k); + } + let _ = app.run("count.setGroup", p); } true } @@ -1079,6 +1151,9 @@ pub(crate) mod tests; #[cfg(test)] mod sampler_drag_tests; +#[cfg(test)] +mod sampler_extras_tests; + /// Marks the "Delete this note?" alert (#11788). const DELETE_NOTE_MARK: &str = "__deleteNote"; @@ -1242,3 +1317,7 @@ mod note_clear_all_tests; #[cfg(test)] #[path = "analysis_ruler_escape_tests.rs"] mod analysis_ruler_escape_tests; + +#[cfg(test)] +#[path = "count_options_bar_tests.rs"] +mod count_options_bar_tests; diff --git a/crates/ui-egui/src/tools/analysis_ui/sampler_extras_tests.rs b/crates/ui-egui/src/tools/analysis_ui/sampler_extras_tests.rs new file mode 100644 index 0000000000..9a42350518 --- /dev/null +++ b/crates/ui-egui/src/tools/analysis_ui/sampler_extras_tests.rs @@ -0,0 +1,84 @@ +//! #11741: View › Extras (⌘H) hides the Color Sampler markers on the canvas, as in Photoshop. The +//! points stay in the document and the Info panel keeps reading them; Extras on again draws the +//! markers back at the same places with the same numbers. + +use super::*; + +/// A 200 × 100 document with two samplers and the Color Sampler tool. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + app.ui.tool = Tool::ColorSampler; + app.run("view.colorSamplers.add", json!({"x": 50, "y": 50})).unwrap(); + app.run("view.colorSamplers.add", json!({"x": 120, "y": 30})).unwrap(); + app +} + +fn xf() -> ViewXform { + ViewXform { + rect: egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(200.0, 100.0)), + zoom: 1.0, + center: [100.0, 50.0], + flip: false, + rotation: 0.0, + aspect: 1.0, + } +} + +/// Every shape the overlay paints, and the marker numbers with where they are. +fn painted(app: &PhotocraftApp, ctx: &egui::Context) -> (usize, Vec<(String, egui::Pos2)>) { + let xf = xf(); + let mut o = ctx.run_ui(Default::default(), |ui| draw_overlay(app, ui.painter(), &xf)); + o.textures_delta.clear(); + let numbers = o + .shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Text(t) => Some((t.galley.text().to_owned(), t.pos)), + _ => None, + }) + .collect(); + (o.shapes.len(), numbers) +} + +fn toggle_extras(app: &mut PhotocraftApp, ctx: &egui::Context) { + crate::menus::invoke(app, ctx, "view.extras", json!({})).unwrap(); +} + +/// The Info panel's sampler readouts, read afresh rather than from the per-revision cache. +fn readouts(app: &mut PhotocraftApp) -> Vec { + app.info_samplers = None; + crate::panels::info::sampler_readouts(app).to_vec() +} + +#[test] +fn extras_off_hides_the_sampler_markers_and_keeps_the_points_and_readouts() { + let mut app = app(); + let ctx = egui::Context::default(); + let (shown, numbers) = painted(&app, &ctx); + assert!(shown > 0, "the markers are drawn with Extras on"); + let points = app.session.active().unwrap().color_samplers.clone(); + let info = readouts(&mut app); + assert_eq!(info.len(), 2, "the Info panel lists both samplers: {info:?}"); + + toggle_extras(&mut app, &ctx); + assert!(!app.ui.view.extras); + assert_eq!(painted(&app, &ctx).0, 0, "no marker is drawn with Extras off"); + assert_eq!(app.session.active().unwrap().color_samplers, points, "the samplers stay in the document"); + assert_eq!(readouts(&mut app), info, "the Info panel readouts are unchanged"); + + toggle_extras(&mut app, &ctx); + assert!(app.ui.view.extras); + assert_eq!(painted(&app, &ctx), (shown, numbers), "Extras on again draws the same markers at the same places"); +} + +#[test] +fn extras_off_hides_a_marker_being_dragged() { + let mut app = app(); + let ctx = egui::Context::default(); + toggle_extras(&mut app, &ctx); + app.ui.analysis.drag = Some(Drag::Sampler(0, [80.0, 60.0])); + assert_eq!(painted(&app, &ctx).0, 0, "a dragged marker stays hidden"); + app.ui.analysis.drag = Some(Drag::SamplerNew([30.0, 70.0])); + assert_eq!(painted(&app, &ctx).0, 0, "a new marker stays hidden"); +} diff --git a/crates/ui-egui/src/tools/anchor_tools.rs b/crates/ui-egui/src/tools/anchor_tools.rs index bb4c82d3e3..f36814934c 100644 --- a/crates/ui-egui/src/tools/anchor_tools.rs +++ b/crates/ui-egui/src/tools/anchor_tools.rs @@ -9,13 +9,15 @@ //! direction handles showing, and a drag from the click moves it, as in Photoshop (#8653). //! * Delete Anchor Point: hovering an anchor highlights it; a click removes it //! (`path.deleteAnchor`), joining its neighbours. -//! * ⌥ swaps the two tools and ⌘/Ctrl is Direct Selection (`direct_select`) while held. +//! * ⌥ swaps the two tools and ⌘/Ctrl is Direct Selection (`direct_select`) while held; ⌥-click +//! with Delete Anchor Point on an anchor selects its whole subpath instead. //! * The Pen does both with Auto Add/Delete on (its options bar, on by default, #4144): a click on //! a segment adds, a click on an anchor deletes, except an open subpath's end points; ⇧ turns it //! off while held. It edits the active path, or while a path is being drawn that path (#6140), //! and drawing carries on from its last anchor. //! -//! Each click (or add and drag) is one history step; a click on nothing it can edit does nothing. +//! Each click (or add and drag) is one history step; a click on nothing it can edit does nothing; +//! ⌥-click on an anchor with Delete Anchor Point only selects. use egui::{Color32, Modifiers, Pos2, Stroke}; use photocraft_doc::vector::Path; @@ -25,7 +27,7 @@ use photocraft_vector::edit::{self, Hit}; use crate::PhotocraftApp; use crate::canvas::ToolEvent; -use crate::direct_select::{DirectSelection, PathRef}; +use crate::direct_select::{DirectSelection, Owner, PathRef}; use crate::state::Tool; /// The anchor tool in effect, if the current tool is one: ⌥ swaps Add and Delete. @@ -38,13 +40,9 @@ pub fn effective(tool: Tool, mods: Modifiers) -> Option { } } -/// What a click at `p` would edit with `tool`: the frontmost path under the pointer and the -/// segment (Add) or anchor (Delete) hit on it. An anchor hit with Add, or a segment with Delete, -/// edits nothing. -fn target(app: &PhotocraftApp, tool: Tool, p: [f64; 2]) -> Option<(PathRef, Path, Hit)> { - let (r, path, hit) = crate::direct_select::hit_active(app, p)?; - // The anchor tools ignore a click on a shape with only its own position lock set (#12730, #12825). - if let PathRef::Layer(id) = r +/// The anchor tools ignore a click on a shape with only its own position lock set (#12730, #12825). +pub(crate) fn ignores(app: &PhotocraftApp, r: &PathRef) -> bool { + if let PathRef::Layer(id) = *r && let Some(st) = app.session.active() && let Some(layer) = st.doc.layer(LayerId(id)) && matches!(layer.content, LayerContent::Shape(_)) @@ -52,6 +50,17 @@ fn target(app: &PhotocraftApp, tool: Tool, p: [f64; 2]) -> Option<(PathRef, Path && let Some(at) = st.doc.path_of(layer.id) && at.split_last().is_some_and(|(_, ancestors)| !st.doc.locks_at(ancestors).any()) { + return true; + } + false +} + +/// What a click at `p` would edit with `tool`: the frontmost path under the pointer and the +/// segment (Add) or anchor (Delete) hit on it. An anchor hit with Add, or a segment with Delete, +/// edits nothing. +fn target(app: &PhotocraftApp, tool: Tool, p: [f64; 2]) -> Option<(PathRef, Path, Hit)> { + let (r, path, hit) = crate::direct_select::hit_active(app, p)?; + if ignores(app, &r) { return None; } match (tool, hit) { @@ -60,6 +69,13 @@ fn target(app: &PhotocraftApp, tool: Tool, p: [f64; 2]) -> Option<(PathRef, Path } } +/// Whether a click at `p` with Add Anchor Point (`tool`) would add an anchor: the pointer is over +/// a segment of the targeted path that the tool may edit. Read-only; the cursor and its badge +/// (#12729) ask it, so they show the pen with "+" only where a click does something. +pub(crate) fn adds_anchor_at(app: &PhotocraftApp, tool: Tool, p: [f64; 2]) -> bool { + tool == Tool::AddAnchorPoint && target(app, tool, p).is_some() +} + /// The Pen's Auto Add/Delete (#4144): what a Pen click at `p` does to the active path instead of /// starting a new one, as the anchor tool that does it (Add Anchor Point on a segment, Delete /// Anchor Point on an anchor), the path and the hit. While a path is being drawn it edits that @@ -109,7 +125,7 @@ pub fn pen_auto(app: &PhotocraftApp, tool: Tool, mods: Modifiers, p: [f64; 2]) - /// opposite it (`path.convertPoint` on release, through Direct Selection's drag). Both are one /// History step, Add Anchor Point. False when the press is not that, so ⌥ stays Convert Point. pub fn pen_alt_segment_press(app: &mut PhotocraftApp, mods: Modifiers, p: [f64; 2]) -> bool { - use crate::direct_select::{Drag, Edit, Owner, active_paths}; + use crate::direct_select::{Drag, Edit, active_paths}; if !mods.alt { return false; } @@ -158,21 +174,132 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool return true; } let Some(tool) = effective(app.ui.tool, mods) else { return false }; - if let ToolEvent::Down { x, y, .. } = ev { - click(app, tool, [x, y]); + match ev { + ToolEvent::Down { x, y, .. } => { + app.ui.direct_selection.subpath_press = None; + if app.ui.tool == Tool::DeleteAnchorPoint && mods.alt && subpath_at(app, [x, y]).is_some() { + let owner = Owner::current(app); + let ds = &mut app.ui.direct_selection; + ds.subpath_press = Some([x, y]); + // A stale press is dropped with the selection (`cancel_stale`). + ds.owner = owner; + } else if tool == Tool::DeleteAnchorPoint && start_segment_drag(app, [x, y], mods) { + return true; + } else { + click(app, tool, [x, y]); + } + } + ToolEvent::Up { x, y } => { + if let Some(start) = app.ui.direct_selection.subpath_press.take() + && !crate::direct_select::moved(app, start, [x, y]) + && let Some((r, anchors)) = subpath_at(app, start) + { + let owner = Owner::current(app); + app.ui.direct_selection = DirectSelection { target: Some(r), anchors, owner, ..Default::default() }; + } + } + // Once the pointer has moved off the press it is a drag, even if it comes back. + ToolEvent::Move { x, y, .. } => { + if app.ui.direct_selection.subpath_press.is_some_and(|start| crate::direct_select::moved(app, start, [x, y])) { + app.ui.direct_selection.subpath_press = None; + } + } } true } +/// Delete Anchor Point (#12767): a press on a straight segment of the targeted path starts Direct +/// Selection's segment drag (`Edit::Segment`, `path.bendSegment`, **Drag Segment**); the drag's +/// Move and Up reach `direct_select::pointer` first. A click without movement records nothing. +/// Not measured, so as today (a press on a segment does nothing): a curved segment, ⇧, a segment of +/// a path whose anchors are all selected, and the Pen path being drawn. False when the press is not +/// on such a segment (an anchor press goes on to delete). +fn start_segment_drag(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) -> bool { + if mods.shift { + return false; + } + let Some((r, path, Hit::Segment(k, t))) = crate::direct_select::hit_active(app, p) else { return false }; + let Some(sp) = path.subpaths.get(k[0]) else { return false }; + let end = if k[1] + 1 < sp.knots.len() { k[1] + 1 } else { 0 }; + // Straight as `edit::straight` (and so `bend_segment`) has it: both facing handles within 1e-9 + // of their anchors. + let retracted = |h: Point, a: Point| (h.x - a.x).hypot(h.y - a.y) < 1e-9; + let straight = sp.knots.get(k[1]).zip(sp.knots.get(end)).is_some_and(|(a, b)| retracted(a.out_ctrl, a.anchor) && retracted(b.in_ctrl, b.anchor)); + let ds = &app.ui.direct_selection; + let all_selected = ds.target == Some(r) && (0..path.subpaths.len()).all(|s| edit::subpath_anchors(&path, s).iter().all(|a| ds.anchors.contains(a))); + // A shape with only its own position lock is ignored, as a click on it is (#12730, #12825). + if r == PathRef::Pen || all_selected || !straight || ignores(app, &r) { + return false; + } + let owner = crate::direct_select::Owner::current(app); + let ds = &mut app.ui.direct_selection; + *ds = DirectSelection { target: Some(r), segment: Some(k), owner, ..Default::default() }; + ds.drag = + Some(crate::direct_select::Drag::Edit { target: r, base: path, edit: crate::direct_select::Edit::Segment(k, t), start: p, end: p, preview: None }); + true +} + +/// ⌥-click with Delete Anchor Point on an anchor of a targeted path selects its whole subpath, as +/// in Photoshop (#12770); ⌥ is Add Anchor Point only on a segment. The path and that subpath's +/// anchors, or `None` when the press hits no anchor of a targeted path (a shape in a group that +/// is not active is hit as before but is not targeted). +fn subpath_at(app: &PhotocraftApp, p: [f64; 2]) -> Option<(PathRef, Vec<[usize; 2]>)> { + let (r, path, Hit::Anchor([s, _])) = target(app, Tool::DeleteAnchorPoint, p)? else { return None }; + crate::direct_select::active_paths(app).iter().any(|(a, _)| *a == r).then(|| (r, edit::subpath_anchors(&path, s))) +} + fn click(app: &mut PhotocraftApp, tool: Tool, p: [f64; 2]) { - let Some((r, path, hit)) = target(app, tool, p) else { return }; + let Some((r, path, hit)) = target(app, tool, p) else { + hide_anchors(app, tool, p); + return; + }; if r == PathRef::Pen { edit_pen(app, path, hit, p); return; } + // Only a saved path has the measured behaviour (#12769); a vector mask or the Work Path delete at once. + if let (Tool::DeleteAnchorPoint, PathRef::Saved(_), Hit::Anchor([s, k])) = (tool, r, hit) { + if !crate::direct_select::anchors_shown(app, r, s) { + select_shown(app, r, vec![s], vec![[s, k]]); + return; + } + if apply(app, r, hit, p) { + select_follower(app, r, &path, [s, k]); + } + return; + } apply(app, r, hit, p); } +/// Show the anchors of `subpaths` of `r` only, with `anchors` selected: a view change, no history step. +fn select_shown(app: &mut PhotocraftApp, r: PathRef, subpaths: Vec, anchors: Vec<[usize; 2]>) { + app.ui.direct_selection = + DirectSelection { target: Some(r), anchors, shown: Some(subpaths), owner: crate::direct_select::Owner::current(app), ..Default::default() }; +} + +/// After Delete Anchor Point removed knot `k` of subpath `s` of `before`: select the anchor that +/// followed it and keep only that subpath's anchors drawn (#12769). If a subpath went away the +/// indices moved, so the selection is just cleared. +fn select_follower(app: &mut PhotocraftApp, r: PathRef, before: &Path, [s, k]: [usize; 2]) { + let after = crate::direct_select::path_of(app, &r).and_then(|p| p.subpaths.get(s).cloned().filter(|_| p.subpaths.len() == before.subpaths.len())); + let Some(sp) = after else { + app.ui.direct_selection = DirectSelection { target: Some(r), ..Default::default() }; + return; + }; + let next = if k < sp.knots.len() { Some(k) } else { (sp.closed && !sp.knots.is_empty()).then_some(0) }; + select_shown(app, r, vec![s], next.map(|k| [s, k]).into_iter().collect()); +} + +/// A click on empty canvas hides the saved path's anchors; its outline stays and it stays targeted (#12769). +fn hide_anchors(app: &mut PhotocraftApp, tool: Tool, p: [f64; 2]) { + if tool != Tool::DeleteAnchorPoint || crate::direct_select::hit_active(app, p).is_some() { + return; + } + if let Some((i, _)) = crate::vector_ui::selected_saved_path_index(app) { + select_shown(app, PathRef::Saved(i), Vec::new(), Vec::new()); + } +} + /// Add or delete an anchor of the Pen path being drawn (`path`, from `pen_path`). It isn't in the /// document yet, so it takes the edit directly; drawing carries on from its last anchor. An added /// anchor is selected and follows a drag from the press at `p` ([`crate::direct_select::grab_added`]). @@ -200,20 +327,28 @@ fn edit_pen(app: &mut PhotocraftApp, mut path: Path, hit: Hit, p: [f64; 2]) { /// Add an anchor where `hit` is on a segment of `r`, or delete the anchor it is on: one command. /// An added anchor is selected and follows a drag from the press at `p`; the add and the move are /// one history step. -fn apply(app: &mut PhotocraftApp, r: PathRef, hit: Hit, p: [f64; 2]) { +/// Whether the engine ran the edit: not at a full History (it records a step and evicts the oldest, so +/// the step count does not change), nor when a live-shape prompt or an error stopped it. +fn apply(app: &mut PhotocraftApp, r: PathRef, hit: Hit, p: [f64; 2]) -> bool { let (id, mut params, coalesce) = match hit { Hit::Segment([s, k], t) => { let key = format!("add-anchor-{}", app.ui.alloc_id()); ("path.addAnchor", serde_json::json!({"subpath": s, "knot": k, "t": t, "coalesce": key}), Some(key)) } Hit::Anchor([s, k]) => ("path.deleteAnchor", serde_json::json!({"subpath": s, "knot": k}), None), - Hit::Handle(..) => return, + Hit::Handle(..) => return false, }; // A hit right at a segment's end is an anchor (anchors win the hit test), so `t` is inside. if let (Some(o), Some(t)) = (params.as_object_mut(), r.params(app).as_object()) { o.extend(t.clone()); } - match app.run(id, params) { + // A live shape becomes a regular path: ask first (#12768). + if id == "path.deleteAnchor" && crate::dialogs::live_shape_prompt::ask(app, r, ¶ms) { + return false; + } + let ran = app.run(id, params); + let ok = ran.is_ok(); + match ran { Ok(v) if coalesce.is_some() => { let n = |f: &str| v["anchor"][f].as_u64().and_then(|v| usize::try_from(v).ok()); let base = crate::direct_select::candidates(app).into_iter().find(|(c, _)| *c == r).map(|(_, path)| path); @@ -230,6 +365,7 @@ fn apply(app: &mut PhotocraftApp, r: PathRef, hit: Hit, p: [f64; 2]) { app.ui.status_error = true; } } + ok } /// The hover feedback over the Direct Selection overlay: Add highlights the segment under the @@ -275,14 +411,27 @@ mod add_anchor_lock_tests; #[cfg(test)] mod add_anchor_targeted_path_tests; #[cfg(test)] +mod delete_anchor_drag_segment_tests; +#[cfg(test)] +mod delete_anchor_live_shape_tests; +#[cfg(test)] mod delete_anchor_lock_tests; #[cfg(test)] -mod delete_anchor_targeted_path_tests; +pub(crate) mod delete_anchor_targeted_path_tests; #[cfg(test)] mod tests; #[cfg(test)] mod add_anchor_delete_key_tests; +#[cfg(test)] +mod delete_anchor_delete_key_tests; + #[cfg(test)] mod delete_anchor_escape_tests; + +#[cfg(test)] +mod delete_anchor_shown_anchors_tests; + +#[cfg(test)] +mod delete_anchor_alt_tests; diff --git a/crates/ui-egui/src/tools/anchor_tools/add_anchor_delete_key_tests.rs b/crates/ui-egui/src/tools/anchor_tools/add_anchor_delete_key_tests.rs index 3808174d72..c385841e11 100644 --- a/crates/ui-egui/src/tools/anchor_tools/add_anchor_delete_key_tests.rs +++ b/crates/ui-egui/src/tools/anchor_tools/add_anchor_delete_key_tests.rs @@ -11,7 +11,7 @@ use crate::state::Tool; /// 800 x 600 on white, pixel layer Red active, saved path Path 1 (a closed corner square) /// targeted in the Paths panel, the Add Anchor Point tool on. -fn app() -> PhotocraftApp { +pub(super) fn app() -> PhotocraftApp { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.session.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); app.sync_views(); @@ -23,25 +23,25 @@ fn app() -> PhotocraftApp { app } -fn path1(app: &PhotocraftApp) -> Path { +pub(super) fn path1(app: &PhotocraftApp) -> Path { app.session.active().unwrap().doc.paths.iter().find(|p| p.name == "Path 1").unwrap().path.clone() } -fn layers(app: &PhotocraftApp) -> usize { +pub(super) fn layers(app: &PhotocraftApp) -> usize { app.session.active().unwrap().doc.layers.len() } -fn steps(app: &PhotocraftApp) -> usize { +pub(super) fn steps(app: &PhotocraftApp) -> usize { app.session.active().unwrap().history.past_len() } -fn ctrl_click(app: &mut PhotocraftApp, at: [f64; 2]) { +pub(super) fn ctrl_click(app: &mut PhotocraftApp, at: [f64; 2]) { tool_event(app, ToolEvent::Down { x: at[0], y: at[1], pressure: 1.0 }, Modifiers::COMMAND); tool_event(app, ToolEvent::Up { x: at[0], y: at[1] }, Modifiers::COMMAND); } /// A key through the app's shortcut handling, as the canvas gets it. -fn press(app: &mut PhotocraftApp, key: egui::Key) { +pub(super) fn press(app: &mut PhotocraftApp, key: egui::Key) { let ctx = egui::Context::default(); let m = Modifiers::NONE; let raw = egui::RawInput { @@ -53,7 +53,7 @@ fn press(app: &mut PhotocraftApp, key: egui::Key) { ctx.end_pass().textures_delta.clear(); } -fn anchors(path: &Path) -> Vec<[f64; 2]> { +pub(super) fn anchors(path: &Path) -> Vec<[f64; 2]> { path.subpaths.iter().flat_map(|sp| sp.knots.iter().map(|k| [k.anchor.x, k.anchor.y])).collect() } diff --git a/crates/ui-egui/src/tools/anchor_tools/delete_anchor_alt_tests.rs b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_alt_tests.rs new file mode 100644 index 0000000000..95eb805718 --- /dev/null +++ b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_alt_tests.rs @@ -0,0 +1,95 @@ +//! #12770: ⌥-click with Delete Anchor Point on an anchor of the targeted path selects its whole +//! subpath and edits nothing; on a segment ⌥ still adds an anchor (Add Anchor Point). + +use egui::Modifiers; +use serde_json::json; + +use super::add_anchor_lock_tests::click_with_modifiers; +use super::delete_anchor_targeted_path_tests::{click, group_shape, setup, shape_path, steps}; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::direct_select::PathRef; +use crate::state::Tool; + +/// Delete Anchor Point with the saved path "Path 1", a closed corner square +/// (100,300)(300,300)(300,500)(100,500), targeted in the Paths panel. +fn square() -> PhotocraftApp { + let (mut app, _) = setup(Tool::DeleteAnchorPoint); + let path = json!({"subpaths": [{"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); + app +} + +fn knots(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.paths[0].path.subpaths[0].knots.len() +} + +#[test] +fn alt_click_on_an_anchor_selects_the_whole_subpath_and_records_nothing() { + let mut app = square(); + let n = steps(&app); + click_with_modifiers(&mut app, [300.0, 500.0], Modifiers::ALT); + app.sync_views(); + let ds = &app.ui.direct_selection; + assert_eq!(ds.target, Some(PathRef::Saved(0))); + assert_eq!(ds.anchors, vec![[0, 0], [0, 1], [0, 2], [0, 3]]); + assert_eq!(knots(&app), 4); + assert_eq!(steps(&app), n); +} + +#[test] +fn alt_click_on_a_segment_still_adds_an_anchor() { + let mut app = square(); + let n = steps(&app); + click_with_modifiers(&mut app, [200.0, 300.0], Modifiers::ALT); + assert_eq!(knots(&app), 5); + assert_eq!(steps(&app), n + 1); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Add Anchor Point")); +} + +#[test] +fn a_plain_click_on_an_anchor_still_deletes_it() { + let mut app = square(); + let n = steps(&app); + click(&mut app, [300.0, 500.0]); + assert_eq!(knots(&app), 3); + assert_eq!(steps(&app), n + 1); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Delete Anchor Point")); + // #12769: the anchor that followed the deleted one is selected, not nothing. + assert_eq!(app.ui.direct_selection.anchors.len(), 1); +} + +#[test] +fn alt_drag_from_an_anchor_selects_nothing() { + let mut app = square(); + let n = steps(&app); + tool_event(&mut app, ToolEvent::Down { x: 300.0, y: 500.0, pressure: 1.0 }, Modifiers::ALT); + tool_event(&mut app, ToolEvent::Move { x: 360.0, y: 560.0, pressure: 1.0 }, Modifiers::ALT); + tool_event(&mut app, ToolEvent::Up { x: 360.0, y: 560.0 }, Modifiers::ALT); + assert!(app.ui.direct_selection.anchors.is_empty()); + assert_eq!(knots(&app), 4); + assert_eq!(steps(&app), n); +} + +#[test] +fn alt_drag_that_returns_to_the_press_selects_nothing() { + let mut app = square(); + tool_event(&mut app, ToolEvent::Down { x: 300.0, y: 500.0, pressure: 1.0 }, Modifiers::ALT); + tool_event(&mut app, ToolEvent::Move { x: 360.0, y: 560.0, pressure: 1.0 }, Modifiers::ALT); + tool_event(&mut app, ToolEvent::Move { x: 300.0, y: 500.0, pressure: 1.0 }, Modifiers::ALT); + tool_event(&mut app, ToolEvent::Up { x: 300.0, y: 500.0 }, Modifiers::ALT); + assert!(app.ui.direct_selection.anchors.is_empty()); + assert_eq!(knots(&app), 4); +} + +#[test] +fn alt_click_on_a_shape_in_a_group_that_is_not_active_selects_nothing() { + let (mut app, shape) = setup(Tool::DeleteAnchorPoint); + group_shape(&mut app, shape); + let (before, n) = (shape_path(&mut app, shape), steps(&app)); + click_with_modifiers(&mut app, [650.0, 250.0], Modifiers::ALT); + assert!(app.ui.direct_selection.anchors.is_empty()); + assert_eq!(shape_path(&mut app, shape), before); + assert_eq!(steps(&app), n); +} diff --git a/crates/ui-egui/src/tools/anchor_tools/delete_anchor_delete_key_tests.rs b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_delete_key_tests.rs new file mode 100644 index 0000000000..b77a9dd899 --- /dev/null +++ b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_delete_key_tests.rs @@ -0,0 +1,94 @@ +//! #12761: with the Delete Anchor Point tool, Delete / Backspace on a selected anchor edits the +//! path, never the active layer. The single anchor left of a subpath takes the whole subpath +//! (History: Delete Selection); an anchor of a longer subpath goes as in #12703. + +use egui::Modifiers; +use serde_json::json; + +use super::add_anchor_delete_key_tests::{anchors, app as add_app, ctrl_click, layers, path1, press, steps}; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// The measured document: Path 1 holds a square, the open line B (400,300) to (700,300) and an +/// S-curve; the Delete Anchor Point tool is on. +fn app() -> PhotocraftApp { + let mut app = add_app(); + let path = json!({"subpaths": [ + {"closed": true, "knots": [[100, 100], [200, 100], [200, 200], [100, 200]]}, + {"closed": false, "knots": [[400, 300], [700, 300]]}, + {"closed": false, "knots": [[100, 400], [150, 350], [200, 450], [250, 400]]}, + ]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.tool = Tool::DeleteAnchorPoint; + app +} + +fn click(app: &mut PhotocraftApp, at: [f64; 2]) { + tool_event(app, ToolEvent::Down { x: at[0], y: at[1], pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: at[0], y: at[1] }, Modifiers::NONE); +} + +/// B's end deleted by a click, then B's last anchor selected. +fn with_lone_anchor_selected() -> PhotocraftApp { + let mut app = app(); + click(&mut app, [700.0, 300.0]); + ctrl_click(&mut app, [400.0, 300.0]); + assert_eq!(app.ui.direct_selection.anchors, vec![[1, 0]], "Ctrl+click selects B's last anchor"); + app +} + +#[test] +fn delete_and_backspace_on_a_subpaths_last_anchor_remove_the_subpath_not_the_layer() { + for key in [egui::Key::Delete, egui::Key::Backspace] { + let mut app = with_lone_anchor_selected(); + let (before, n, count) = (path1(&app), steps(&app), layers(&app)); + assert_eq!(before.subpaths.len(), 3, "{key:?}: B is down to one anchor"); + press(&mut app, key); + assert_eq!(layers(&app), count, "{key:?}: every layer is still there"); + assert_eq!(path1(&app).subpaths.len(), 2, "{key:?}: Path 1 keeps the square and the S-curve"); + let st = app.session.active().unwrap(); + assert_eq!((st.history.past_len(), st.history.undo_label()), (n + 1, Some("Delete Selection")), "{key:?}"); + assert!(app.session.undo()); + assert_eq!(path1(&app), before, "{key:?}: Undo brings B back"); + } +} + +#[test] +fn delete_on_an_anchor_of_a_longer_subpath_goes_as_for_add_anchor_point() { + for key in [egui::Key::Delete, egui::Key::Backspace] { + let mut app = app(); + let (before, n, count) = (path1(&app), steps(&app), layers(&app)); + ctrl_click(&mut app, [200.0, 200.0]); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 2]], "{key:?}"); + press(&mut app, key); + assert_eq!(layers(&app), count, "{key:?}: every layer is still there"); + let p = path1(&app); + assert_eq!((p.subpaths.len(), p.subpaths[0].closed), (3, false), "{key:?}: the square opens"); + assert_eq!(anchors(&p).len(), 9, "{key:?}: one anchor fewer"); + let st = app.session.active().unwrap(); + assert_eq!((st.history.past_len(), st.history.undo_label()), (n + 1, Some("Delete Anchor Point")), "{key:?}"); + assert!(app.session.undo()); + assert_eq!(path1(&app), before, "{key:?}: Undo restores the square"); + } +} + +#[test] +fn without_a_selected_anchor_delete_keeps_its_usual_route() { + let mut app = app(); + let before = path1(&app); + press(&mut app, egui::Key::Delete); + assert_eq!(path1(&app), before, "no anchor selected: the path stays"); + assert_ne!(app.session.active().unwrap().history.undo_label(), Some("Delete Selection")); +} + +#[test] +fn other_tools_keep_their_delete() { + for tool in [Tool::Pen, Tool::FreeformPen, Tool::PathSelection] { + let mut app = with_lone_anchor_selected(); + app.ui.tool = tool; + let before = path1(&app); + press(&mut app, egui::Key::Delete); + assert_eq!(path1(&app), before, "{tool:?}: no anchor is deleted"); + } +} diff --git a/crates/ui-egui/src/tools/anchor_tools/delete_anchor_drag_segment_tests.rs b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_drag_segment_tests.rs new file mode 100644 index 0000000000..e43ae68e34 --- /dev/null +++ b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_drag_segment_tests.rs @@ -0,0 +1,110 @@ +//! #12767: with Delete Anchor Point, a drag that starts on a segment moves it as a temporary +//! Direct Selection does (history step **Drag Segment**); an anchor click still deletes. + +use egui::Modifiers; +use serde_json::{Value, json}; + +use super::delete_anchor_targeted_path_tests::{click, select_layer, setup, shape_path, steps}; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// The item's test document: a saved path "Path 1", selected in the Paths panel, with a closed +/// corner square, an open straight line and an open S-curve. +fn document(tool: Tool) -> PhotocraftApp { + let (mut app, _) = setup(tool); + let path = json!({"subpaths": [ + {"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}, + {"closed": false, "knots": [[400, 300], [700, 300]]}, + {"closed": false, "knots": [{"anchor": [400, 450], "out": [500, 350]}, {"anchor": [700, 450], "in": [600, 550]}]}, + ]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); + app +} + +fn knots(app: &mut PhotocraftApp) -> Vec { + app.run("path.info", json!({"name": "Path 1"})).unwrap()["path"]["subpaths"][0]["knots"].as_array().unwrap().clone() +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, Modifiers::NONE); +} + +fn anchors(app: &mut PhotocraftApp) -> Vec<[f64; 2]> { + let anchor = |k: &Value| { + let a = k.get("anchor").unwrap_or(k); + [a[0].as_f64().unwrap(), a[1].as_f64().unwrap()] + }; + knots(app).iter().map(anchor).collect() +} + +#[test] +fn dragging_the_bottom_edge_moves_both_its_anchors_in_one_drag_segment_step() { + let mut app = document(Tool::DeleteAnchorPoint); + let n = steps(&app); + drag(&mut app, [200.0, 500.0], [200.0, 540.0]); + assert_eq!(anchors(&mut app), vec![[100.0, 300.0], [300.0, 300.0], [300.0, 540.0], [100.0, 540.0]]); + assert_eq!(steps(&app), n + 1); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Drag Segment")); +} + +/// A segment whose facing handles sit within the vector edit's straightness tolerance (1e-9) of +/// their anchors counts as straight, as Direct Selection's `bend_segment` treats it. +#[test] +fn a_segment_with_handles_a_hair_off_its_anchors_still_drags() { + let mut app = document(Tool::DeleteAnchorPoint); + let path = json!({"subpaths": [{"closed": true, "knots": [ + [100, 300], [300, 300], + {"anchor": [300, 500], "out": [300.000_000_000_000_1, 500]}, + {"anchor": [100, 500], "in": [100.000_000_000_000_1, 500]}, + ]}]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + drag(&mut app, [200.0, 500.0], [200.0, 540.0]); + let moved = anchors(&mut app); + assert_eq!((moved[2], moved[3]), ([300.0, 540.0], [100.0, 540.0]), "{moved:?}"); +} + +#[test] +fn a_click_on_a_segment_without_movement_does_nothing() { + let mut app = document(Tool::DeleteAnchorPoint); + let (before, n) = (knots(&mut app), steps(&app)); + click(&mut app, [200.0, 500.0]); + assert_eq!(knots(&mut app), before); + assert_eq!(steps(&app), n); +} + +#[test] +fn a_click_on_an_anchor_still_deletes_it_in_one_step() { + let mut app = document(Tool::DeleteAnchorPoint); + let n = steps(&app); + click(&mut app, [300.0, 500.0]); + assert_eq!(knots(&mut app).len(), 3); + assert_eq!(steps(&app), n + 1); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Delete Anchor Point")); +} + +#[test] +fn add_anchor_point_clicks_keep_adding_an_anchor() { + let mut app = document(Tool::AddAnchorPoint); + let n = steps(&app); + click(&mut app, [200.0, 500.0]); + assert_eq!(knots(&mut app).len(), 5); + assert_eq!(steps(&app), n + 1); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Add Anchor Point")); +} + +/// A shape with only its own position lock is left alone by a segment drag, as by an anchor click +/// (#12730, #12825): its bottom edge doesn't move and no history step is added. +#[test] +fn a_position_locked_shape_s_segment_does_not_drag() { + let (mut app, shape) = setup(Tool::DeleteAnchorPoint); + select_layer(&mut app, shape); + app.run("layer.lockLayers", json!({"position": true})).unwrap(); + let (before, n) = (shape_path(&mut app, shape), steps(&app)); + drag(&mut app, [550.0, 250.0], [550.0, 290.0]); + assert_eq!(shape_path(&mut app, shape), before); + assert_eq!(steps(&app), n); +} diff --git a/crates/ui-egui/src/tools/anchor_tools/delete_anchor_escape_tests.rs b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_escape_tests.rs index 2fd81fdbd2..7513898191 100644 --- a/crates/ui-egui/src/tools/anchor_tools/delete_anchor_escape_tests.rs +++ b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_escape_tests.rs @@ -9,7 +9,7 @@ use serde_json::json; use super::tests::{click, steps}; use crate::PhotocraftApp; -use crate::direct_select::{PathRef, active_paths, candidates}; +use crate::direct_select::{Drag, PathRef, active_paths, candidates}; use crate::state::Tool; /// The issue's document: 800 x 600 with the saved path "Path 1", a corner square with an anchor @@ -142,3 +142,43 @@ fn escape_while_renaming_path_1_cancels_the_rename() { assert_eq!(names, ["Path 1"], "Esc cancels the rename"); assert_eq!(h.state().ui.selected_path.as_deref(), Some("Path 1")); } + +#[test] +fn the_first_escape_without_a_selected_anchor_keeps_path_1_targeted() { + let mut app = app(); + let n = steps(&app); + escape(&mut app); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "the first Esc keeps Path 1 targeted"); + assert!(!active_paths(&app).is_empty(), "its outline stays"); + escape(&mut app); + assert_eq!(app.ui.selected_path, None, "the second Esc deselects Path 1"); + assert!(candidates(&app).is_empty(), "no outline or anchors are drawn"); + assert_eq!(steps(&app), n, "Esc adds no History step"); +} + +#[test] +fn an_escape_during_a_direct_selection_drag_keeps_the_anchors() { + let mut app = app(); + // Cmd is Direct Selection while held: it selects the anchor instead of deleting it. + click(&mut app, [300.0, 300.0], Modifiers::COMMAND); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1]]); + app.ui.direct_selection.drag = Some(Drag::Marquee { start: [200.0, 200.0], end: [400.0, 400.0], add: false }); + escape(&mut app); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1]], "the drag's release still moves them"); + assert!(app.ui.direct_selection.drag.is_some(), "and Esc does not end the drag"); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "nor deactivates the path"); +} + +#[test] +fn a_newly_targeted_path_starts_at_the_first_escape_again() { + let mut app = app(); + let line = json!({"subpaths": [{"knots": [[600, 100], [700, 100]]}]}); + app.run("path.set", json!({"name": "Path 2", "path": line})).unwrap(); + escape(&mut app); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "the first Esc keeps Path 1 targeted"); + app.ui.selected_path = Some("Path 2".into()); + escape(&mut app); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 2"), "the first Esc on a new path keeps it targeted"); + escape(&mut app); + assert_eq!(app.ui.selected_path, None, "and the second Esc deselects it"); +} diff --git a/crates/ui-egui/src/tools/anchor_tools/delete_anchor_live_shape_tests.rs b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_live_shape_tests.rs new file mode 100644 index 0000000000..fdccea07e0 --- /dev/null +++ b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_live_shape_tests.rs @@ -0,0 +1,184 @@ +//! #12768: a click with the Delete Anchor Point tool on an anchor of a live shape asks "This +//! operation will turn a live shape into a regular path. Continue?" first: Yes deletes it, No +//! changes nothing, and "Don't show again" skips the question later. + +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; + +use super::delete_anchor_targeted_path_tests::{click, select_layer, select_saved_path, setup_asking, shape_path, steps}; +use crate::PhotocraftApp; +use crate::state::Tool; + +const QUESTION: &str = "This operation will turn a live shape into a regular path. Continue?"; +/// The live rectangle's bottom-right corner. +const CORNER: [f64; 2] = [650.0, 250.0]; + +/// The tool with the live rectangle active. +fn live(tool: Tool) -> (PhotocraftApp, u64) { + let (mut app, shape) = setup_asking(tool); + select_layer(&mut app, shape); + (app, shape) +} + +fn info(app: &mut PhotocraftApp, shape: u64) -> Value { + app.run("shape.info", json!({"layer": shape})).unwrap() +} + +fn question(app: &PhotocraftApp) -> Option { + app.ui.dialogs.iter().find(|d| d.fields.get("__command").and_then(Value::as_str) == Some("path.deleteAnchor")).map(|d| d.id) +} + +fn corners(app: &mut PhotocraftApp, shape: u64) -> usize { + shape_path(app, shape)["subpaths"][0]["knots"].as_array().unwrap().len() +} + +#[test] +fn a_click_on_a_live_shape_anchor_asks_with_yes_no_and_an_unticked_box() { + let (mut app, shape) = live(Tool::DeleteAnchorPoint); + let (before, n) = (info(&mut app, shape), steps(&app)); + click(&mut app, CORNER); + let id = question(&app).expect("the question"); + assert_eq!(info(&mut app, shape), before, "nothing goes before the answer"); + assert_eq!(steps(&app), n); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields["skip"], json!(false)); + // Like the Preferences kittest: the dialog draws in the semibold family, which a build without the fonts lacks. + let has_fonts = |ctx: &egui::Context| ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("semibold".into()))); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_ui_state( + move |ui, app| { + if has_fonts(ui.ctx()) { + crate::dialogs::show(app, ui.ctx()); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(5); + if !has_fonts(&h.ctx) { + return; + } + h.get_by_label(QUESTION); + h.get_by_label("Yes"); + h.get_by_label("No"); + h.get_by_label("Don't show again"); + // Enter is Yes. + h.key_press(egui::Key::Enter); + h.run_steps(5); + let app = h.state_mut(); + assert!(question(app).is_none()); + assert_eq!(info(app, shape)["live"], Value::Null); +} + +#[test] +fn yes_deletes_the_anchor_and_the_layer_is_no_longer_live() { + let (mut app, shape) = live(Tool::DeleteAnchorPoint); + let n = steps(&app); + click(&mut app, CORNER); + let id = question(&app).expect("the question"); + crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(corners(&mut app, shape), 3); + let info = info(&mut app, shape); + assert_eq!((&info["live"], &info["kind"]), (&Value::Null, &json!("path"))); + assert_eq!(steps(&app), n + 1); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Delete Anchor Point")); +} + +/// The question belongs to the document it was asked in: Yes after another document became active +/// is refused and changes nothing there (layer ids are unique in a session, so this guards the +/// binding the way the Color Picker's `__document` does), and the question's own document keeps +/// its shape. +#[test] +fn yes_after_another_document_became_active_deletes_nothing() { + let (mut app, shape) = live(Tool::DeleteAnchorPoint); + click(&mut app, CORNER); + let id = question(&app).expect("the question"); + let first = app.session.active_index(); + app.session.execute("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.sync_views(); + let other = app.run("shape.create", json!({"kind": "rect", "rect": [450, 100, 200, 150], "fill": "#3070c0"})).unwrap()["layer"].as_u64().unwrap(); + assert_ne!(app.session.active_index(), first, "the new document is active"); + let (before, n) = (shape_path(&mut app, other), steps(&app)); + assert!(crate::dialogs::confirm(&mut app, id).is_err()); + assert_eq!((shape_path(&mut app, other), steps(&app)), (before, n)); + assert!(app.session.set_active(first.unwrap())); + app.sync_views(); + assert_eq!(corners(&mut app, shape), 4, "the first document's shape keeps its corner"); +} + +/// The question's knot index belongs to the path as it was asked: an anchor added before the +/// corner meanwhile (through the control channel; the question is modal on screen) shifts it, so Yes +/// is refused instead of deleting another anchor. +#[test] +fn yes_after_the_path_changed_deletes_nothing() { + let (mut app, shape) = live(Tool::DeleteAnchorPoint); + click(&mut app, CORNER); + let id = question(&app).expect("the question"); + app.run("path.addAnchor", json!({"name": "layer", "layer": shape, "subpath": 0, "knot": 0, "t": 0.5})).unwrap(); + let (before, n) = (shape_path(&mut app, shape), steps(&app)); + assert!(crate::dialogs::confirm(&mut app, id).is_err()); + assert_eq!((shape_path(&mut app, shape), steps(&app)), (before, n)); +} + +#[test] +fn no_leaves_the_shape_its_parameters_and_history_unchanged() { + let (mut app, shape) = live(Tool::DeleteAnchorPoint); + let (before, n) = (info(&mut app, shape), steps(&app)); + click(&mut app, CORNER); + let id = question(&app).expect("the question"); + crate::dialogs::cancel(&mut app, id).unwrap(); + assert_eq!(info(&mut app, shape), before); + assert_ne!(before["live"], Value::Null); + assert_eq!(steps(&app), n); + // Not recorded: the next click asks again. + click(&mut app, CORNER); + assert!(question(&app).is_some()); +} + +#[test] +fn yes_with_dont_show_again_deletes_later_clicks_at_once() { + let (mut app, shape) = live(Tool::DeleteAnchorPoint); + click(&mut app, CORNER); + let id = question(&app).expect("the question"); + app.ui.dialog_mut(id).unwrap().fields.insert("skip".into(), json!(true)); + crate::dialogs::confirm(&mut app, id).unwrap(); + // A second live shape: its anchor goes at once. + let other = app.run("shape.create", json!({"kind": "rect", "rect": [100, 100, 100, 100], "fill": "#c03030"})).unwrap()["layer"].as_u64().unwrap(); + assert_ne!(info(&mut app, other)["live"], Value::Null); + let n = steps(&app); + click(&mut app, [200.0, 200.0]); + assert!(question(&app).is_none()); + assert_eq!(corners(&mut app, other), 3); + assert_eq!(info(&mut app, other)["live"], Value::Null); + assert_eq!(steps(&app), n + 1); + assert_eq!(corners(&mut app, shape), 3); +} + +#[test] +fn a_shape_that_is_not_live_or_a_saved_path_deletes_without_the_question() { + let (mut app, shape) = live(Tool::DeleteAnchorPoint); + let path = json!({"subpaths": [{"closed": true, "knots": [[450, 100], [650, 100], [650, 250], [450, 250]]}]}); + app.run("shape.edit", json!({"layer": shape, "path": path})).unwrap(); + assert_eq!(info(&mut app, shape)["live"], Value::Null); + let n = steps(&app); + click(&mut app, CORNER); + assert!(question(&app).is_none()); + assert_eq!(corners(&mut app, shape), 3); + assert_eq!(steps(&app), n + 1); + // A saved path. + let (mut app, _) = live(Tool::DeleteAnchorPoint); + select_saved_path(&mut app); + let n = steps(&app); + click(&mut app, [150.0, 550.0]); + assert!(question(&app).is_none()); + assert_eq!(steps(&app), n + 1); +} + +#[test] +fn add_anchor_point_on_a_live_shape_converts_it_without_the_question() { + let (mut app, shape) = live(Tool::AddAnchorPoint); + let n = steps(&app); + click(&mut app, [550.0, 100.0]); + assert!(question(&app).is_none()); + assert_eq!(corners(&mut app, shape), 5); + assert_eq!(info(&mut app, shape)["live"], Value::Null); + assert_eq!(steps(&app), n + 1); +} diff --git a/crates/ui-egui/src/tools/anchor_tools/delete_anchor_shown_anchors_tests.rs b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_shown_anchors_tests.rs new file mode 100644 index 0000000000..23234540d7 --- /dev/null +++ b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_shown_anchors_tests.rs @@ -0,0 +1,98 @@ +//! #12769: Delete Anchor Point deletes only an anchor that is drawn. A click on one that is not +//! drawn selects it first. + +use serde_json::json; + +use super::delete_anchor_targeted_path_tests::{click, setup, steps}; +use crate::PhotocraftApp; +use crate::direct_select::{PathRef, anchors_shown}; +use crate::state::Tool; + +/// Saved path "Path 1", targeted in the Paths panel: A a closed square, B an open straight line, C an open S-curve. +fn target_path_1(app: &mut PhotocraftApp) { + let path = json!({"subpaths": [ + {"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}, + {"closed": false, "knots": [[400, 300], [700, 300]]}, + {"closed": false, "knots": [ + {"anchor": [400, 450], "in": [400, 450], "out": [500, 350], "smooth": false}, + {"anchor": [700, 450], "in": [600, 550], "out": [700, 450], "smooth": false}]}, + ]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); +} + +fn knots(app: &PhotocraftApp, subpath: usize) -> usize { + app.session.active().unwrap().doc.paths[0].path.subpaths[subpath].knots.len() +} + +fn drawn(app: &PhotocraftApp) -> [bool; 3] { + [0, 1, 2].map(|s| anchors_shown(app, PathRef::Saved(0), s)) +} + +#[test] +fn right_after_targeting_all_anchors_are_drawn_and_the_first_click_deletes() { + let (mut app, _) = setup(Tool::DeleteAnchorPoint); + target_path_1(&mut app); + assert_eq!(drawn(&app), [true; 3]); + let n = steps(&app); + click(&mut app, [700.0, 300.0]); + assert_eq!(steps(&app), n + 1); + assert_eq!(knots(&app, 1), 1); +} + +#[test] +fn after_a_deletion_the_following_anchor_is_selected_and_only_that_subpath_is_drawn() { + let (mut app, _) = setup(Tool::DeleteAnchorPoint); + target_path_1(&mut app); + click(&mut app, [300.0, 300.0]); + assert_eq!(knots(&app, 0), 3); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1]]); + assert_eq!(drawn(&app), [true, false, false]); +} + +#[test] +fn a_click_on_an_anchor_that_is_not_drawn_selects_it_and_a_second_click_deletes_it() { + let (mut app, _) = setup(Tool::DeleteAnchorPoint); + target_path_1(&mut app); + click(&mut app, [300.0, 300.0]); + let n = steps(&app); + click(&mut app, [700.0, 300.0]); + assert_eq!(steps(&app), n); + assert_eq!(knots(&app, 1), 2); + assert_eq!(app.ui.direct_selection.anchors, vec![[1, 1]]); + assert_eq!(drawn(&app), [false, true, false]); + click(&mut app, [700.0, 300.0]); + assert_eq!(steps(&app), n + 1); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Delete Anchor Point")); +} + +#[test] +fn a_click_on_empty_canvas_hides_the_anchors_and_the_next_anchor_click_only_selects() { + let (mut app, _) = setup(Tool::DeleteAnchorPoint); + target_path_1(&mut app); + click(&mut app, [300.0, 300.0]); + let n = steps(&app); + click(&mut app, [50.0, 50.0]); + assert_eq!(steps(&app), n); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1")); + assert_eq!(drawn(&app), [false; 3]); + click(&mut app, [300.0, 500.0]); + assert_eq!(steps(&app), n); + assert_eq!(knots(&app, 0), 3); + assert_eq!(drawn(&app), [true, false, false]); +} + +#[test] +fn at_the_history_limit_the_following_anchor_is_still_selected() { + let (mut app, _) = setup(Tool::DeleteAnchorPoint); + target_path_1(&mut app); + // At the limit a new step evicts the oldest, so the step count does not change. + let st = app.session.active_mut().unwrap(); + st.history.max_states = st.history.past_len(); + let n = steps(&app); + click(&mut app, [300.0, 300.0]); + assert_eq!(steps(&app), n, "the step count stays at the limit"); + assert_eq!(knots(&app, 0), 3); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1]]); + assert_eq!(drawn(&app), [true, false, false]); +} diff --git a/crates/ui-egui/src/tools/anchor_tools/delete_anchor_targeted_path_tests.rs b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_targeted_path_tests.rs index bd086ec450..156e3b9dad 100644 --- a/crates/ui-egui/src/tools/anchor_tools/delete_anchor_targeted_path_tests.rs +++ b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_targeted_path_tests.rs @@ -11,7 +11,15 @@ use crate::state::Tool; /// 800 x 600, white Background, pixel layer "Red" active, and a shape layer from (450,100) to /// (650,250) below it in the stack's activity (Red stays the active layer). -pub(super) fn setup(tool: Tool) -> (PhotocraftApp, u64) { +pub(crate) fn setup(tool: Tool) -> (PhotocraftApp, u64) { + let (mut app, shape) = setup_asking(tool); + // These tests predate the live-shape question (#12768) and keep testing targeting and locks. + crate::dialogs::dont_show_again::remember(&mut app, crate::dialogs::live_shape_prompt::PREF); + (app, shape) +} + +/// [`setup`] with the live-shape question still on. +pub(super) fn setup_asking(tool: Tool) -> (PhotocraftApp, u64) { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.session.execute("file.new", json!({"width": 800, "height": 600})).unwrap(); app.sync_views(); @@ -23,11 +31,11 @@ pub(super) fn setup(tool: Tool) -> (PhotocraftApp, u64) { (app, shape) } -pub(super) fn shape_path(app: &mut PhotocraftApp, id: u64) -> Value { +pub(crate) fn shape_path(app: &mut PhotocraftApp, id: u64) -> Value { app.run("shape.info", json!({"layer": id})).unwrap()["path"].clone() } -pub(super) fn steps(app: &PhotocraftApp) -> usize { +pub(crate) fn steps(app: &PhotocraftApp) -> usize { app.session.active().unwrap().history.entries().len() } @@ -36,18 +44,18 @@ pub(super) fn click(app: &mut PhotocraftApp, at: [f64; 2]) { tool_event(app, ToolEvent::Up { x: at[0], y: at[1] }, Modifiers::NONE); } -pub(super) fn select_saved_path(app: &mut PhotocraftApp) { +pub(crate) fn select_saved_path(app: &mut PhotocraftApp) { let path = json!({"subpaths": [{"closed": true, "knots": [[50, 450], [150, 450], [150, 550], [50, 550]]}]}); app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); app.ui.selected_path = Some("Path 1".into()); } -pub(super) fn select_layer(app: &mut PhotocraftApp, id: u64) { +pub(crate) fn select_layer(app: &mut PhotocraftApp, id: u64) { app.run("layer.select", json!({"layer": id})).unwrap(); } /// Moves `shape` into a new group and makes Red the active layer again; returns the group's id. -pub(super) fn group_shape(app: &mut PhotocraftApp, shape: u64) -> u64 { +pub(crate) fn group_shape(app: &mut PhotocraftApp, shape: u64) -> u64 { let red = app.session.active().unwrap().active_layer.unwrap(); let group = app.run("layer.groupLayers", json!({"layer": shape})).unwrap()["layer"].as_u64().unwrap(); select_layer(app, red.0); diff --git a/crates/ui-egui/src/tools/anchor_tools/tests.rs b/crates/ui-egui/src/tools/anchor_tools/tests.rs index d04b5aa1a2..ae58b9b611 100644 --- a/crates/ui-egui/src/tools/anchor_tools/tests.rs +++ b/crates/ui-egui/src/tools/anchor_tools/tests.rs @@ -53,7 +53,7 @@ fn the_anchor_tools_have_no_letter() { } #[test] -fn add_on_a_straight_segment_inserts_a_corner_in_one_step() { +fn add_on_a_straight_segment_inserts_a_smooth_anchor_in_one_step() { let mut app = app(Tool::AddAnchorPoint); with_path(&mut app); let (before, n) = (work(&app), steps(&app)); @@ -61,7 +61,11 @@ fn add_on_a_straight_segment_inserts_a_corner_in_one_step() { let p = work(&app); assert_eq!(p.subpaths[0].knots.len(), 5); let k = p.subpaths[0].knots[3]; - assert!(!k.smooth && (k.anchor.y - 120.0).abs() < 1e-9 && (k.anchor.x - 80.0).abs() < 1.0, "a corner on the bottom edge: {k:?}"); + assert!(k.smooth && (k.anchor.y - 120.0).abs() < 1e-9 && (k.anchor.x - 80.0).abs() < 1.0, "a smooth anchor on the bottom edge: {k:?}"); + assert!( + (k.in_ctrl.y - 120.0).abs() < 1e-9 && (k.out_ctrl.y - 120.0).abs() < 1e-9 && k.in_ctrl.x != k.anchor.x && k.out_ctrl.x != k.anchor.x, + "with handles along the edge: {k:?}" + ); assert_eq!(steps(&app), n + 1); assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Add Anchor Point")); assert!(app.session.undo()); @@ -144,7 +148,13 @@ fn shape_layer_paths_are_edited_and_the_added_anchor_replaces_the_selection() { #[test] fn the_cursor_shows_plus_or_minus() { use crate::tool_feedback::{Badge, badge}; - let app = app(Tool::AddAnchorPoint); + let mut app = app(Tool::AddAnchorPoint); + assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::NONE), None, "no path targeted, no segment under the pointer (#12729)"); + with_path(&mut app); + app.ui.selected_path = Some("work".into()); + app.hover_doc = Some([80.0, 80.0]); + assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::NONE), None, "off the path's segments"); + app.hover_doc = Some([80.0, 120.0]); assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::NONE), Some(Badge::Add)); assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::ALT), Some(Badge::Subtract)); assert_eq!(badge(&app, Tool::DeleteAnchorPoint, Modifiers::NONE), Some(Badge::Subtract)); diff --git a/crates/ui-egui/src/tools/brush_refusal.rs b/crates/ui-egui/src/tools/brush_refusal.rs index e0a76d4d47..18f48b01e0 100644 --- a/crates/ui-egui/src/tools/brush_refusal.rs +++ b/crates/ui-egui/src/tools/brush_refusal.rs @@ -2,7 +2,8 @@ //! layer, on a layer with Lock All, or with a group active (its pixels, not its mask) opens a //! modal alert with OK instead of a status-bar message, and paints nothing. Only the tools whose //! wording was measured have a name here ([`tool_name`]); the others keep today's status bar. The -//! Classic gradient has the same three alerts (#12017); the live Gradient keeps today's. +//! Classic gradient has the same three alerts (#12017); the live Gradient keeps today's. The Remove +//! tool has one alert, without the tool's name: Lock All on a pixel layer (#12552). use serde_json::json; @@ -13,30 +14,38 @@ use crate::state::{DialogKind, Tool}; pub const HIDDEN: &str = "Could not use the {tool} because the target layer is hidden."; pub const LOCKED: &str = "Could not use the {tool} because the layer is locked."; pub const GROUP: &str = "Could not use the {tool} because the pixels in a group cannot be edited without merging the group."; +/// The Remove tool's one measured alert, Lock All (#12552): it doesn't name the tool. +pub const REMOVE_LOCKED: &str = "Can't use the tool because the layer is locked."; /// The colour-mode alerts (#12686); `{tool}` is [`mode_tool_name`]. The engine refuses the /// command with the same words. pub const INDEXED: &str = "Could not use the {tool} because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; pub const BITMAP: &str = "Could not use the {tool} because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; -/// The tool's name in the colour-mode alerts, for the tools whose wording was measured: the Dodge -/// and Sharpen tools. Kept apart from [`tool_name`]: the layer alerts aren't wired for the Dodge -/// tool yet (#12685). +/// The tool's name in the colour-mode alerts, for the tools whose wording was measured: the Dodge, +/// Burn, Sponge, Blur, Sharpen and Smudge tools. Kept apart from [`tool_name`]: the layer alerts +/// aren't wired for all of them yet (#12685). fn mode_tool_name(tool: Tool) -> Option<&'static str> { match tool { Tool::Dodge => Some(tl!("dodge tool")), + Tool::Burn => Some(tl!("burn tool")), + Tool::Sponge => Some(tl!("sponge tool")), + Tool::Blur => Some(tl!("blur tool")), Tool::Sharpen => Some(tl!("sharpen tool")), + Tool::Smudge => Some(tl!("smudge tool")), _ => None, } } /// The tool's name in the alerts, for the tools whose wording was measured: the Brush, the -/// Sharpen tool (#12952) and the Classic gradient (the live Gradient makes a fill layer and isn't -/// measured, #12017). +/// Sharpen tool (#12952), the Sponge (#13030), the Smudge tool (#12965) and the Classic gradient +/// (the live Gradient makes a fill layer and isn't measured, #12017). pub fn tool_name(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { match tool { Tool::Brush => Some(tl!("brush tool")), Tool::Sharpen => Some(tl!("sharpen tool")), + Tool::Sponge => Some(tl!("sponge tool")), + Tool::Smudge => Some(tl!("smudge tool")), Tool::Gradient if app.ui.tool_options.gradient_classic => Some(tl!("gradient tool")), _ => None, } @@ -45,8 +54,15 @@ pub fn tool_name(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { /// The alert a press with `tool` gets, if any. `hidden` is the press-time hidden-target refusal /// (`canvas::tool_input`), which this only words; the lock and the group are checked here. Lock /// transparent pixels is no refusal, and a group's targeted mask paints. A tool with a -/// [`mode_tool_name`] gets its colour-mode alert first, in an Indexed Color or Bitmap document. +/// [`mode_tool_name`] gets its colour-mode alert first, in an Indexed Color or Bitmap document; the +/// Pattern Stamp only the engine's, for any pattern in an Indexed Color document. pub fn alert(app: &PhotocraftApp, tool: Tool, hidden: bool) -> Option { + // The Pattern Stamp's colour-mode alert depends on its pattern too (#12887). + if tool == Tool::PatternStamp { + use photocraft_engine::retouch_cmds::{PATTERN_STAMP_INDEXED_REFUSAL, pattern_stamp_press_refusal}; + let p = crate::retouch_ui::pattern_stamp_params(app, &[]); + return pattern_stamp_press_refusal(&app.session, &p).is_some().then(|| tl!(PATTERN_STAMP_INDEXED_REFUSAL).to_owned()); + } if let Some(name) = mode_tool_name(tool) && let Some(template) = match app.session.active()?.doc.mode { photocraft_doc::ColorMode::Indexed => Some(INDEXED), @@ -56,30 +72,37 @@ pub fn alert(app: &PhotocraftApp, tool: Tool, hidden: bool) -> Option { { return Some(crate::i18n::fmt(tl!(template), &[("tool", name)])); } - let name = tool_name(app, tool)?; - let template = if hidden { - HIDDEN - } else { + if tool == Tool::Remove { + // Measured on a pixel layer only: a hidden target, a group, a type, shape, Smart Object or + // fill layer keep today's behaviour. let st = app.session.active()?; - let layer = st.active_layer.and_then(|id| st.doc.layer(id))?; - if crate::canvas::paint_target(app) != json!("pixels") { - return None; - } - if layer.is_group() { - GROUP - } else if locked(st.doc.effective_locks(layer.id), tool) { - LOCKED - } else { - return None; - } - }; + let pixel_layer = st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| matches!(l.content, photocraft_doc::LayerContent::Raster(_))); + return (!hidden && pixel_layer && layer_refusal(app, tool) == Some(LOCKED)).then(|| tl!(REMOVE_LOCKED).to_string()); + } + let name = tool_name(app, tool)?; + let template = if hidden { HIDDEN } else { layer_refusal(app, tool)? }; Some(crate::i18n::fmt(tl!(template), &[("tool", name)])) } -/// Whether `locks` refuse `tool`: Lock All, and for the Sharpen tool Lock Image Pixels as well -/// (measured for it; the Brush keeps today's behaviour there). +/// [`GROUP`] or [`LOCKED`] when `tool` can't paint the active layer's pixels. +fn layer_refusal(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> { + let st = app.session.active()?; + let layer = st.active_layer.and_then(|id| st.doc.layer(id))?; + if crate::canvas::paint_target(app) != json!("pixels") { + None + } else if layer.is_group() { + Some(GROUP) + } else if locked(st.doc.effective_locks(layer.id), tool) { + Some(LOCKED) + } else { + None + } +} + +/// Whether `locks` refuse `tool`: Lock All, and for the Sharpen, Sponge and Smudge tools Lock Image +/// Pixels as well (measured for them; the Brush keeps today's behaviour there). fn locked(locks: photocraft_doc::Locks, tool: Tool) -> bool { - locks.all || (tool == Tool::Sharpen && locks.pixels) + locks.all || (matches!(tool, Tool::Sharpen | Tool::Sponge | Tool::Smudge) && locks.pixels) } /// Opens the alert: ordinary dialog state, listed by `ui.inspect` and closed by `ui.dialog.confirm`. @@ -89,8 +112,32 @@ pub fn prompt(app: &mut PhotocraftApp, message: &str) { #[cfg(test)] #[path = "../brush_refusal_alert_tests.rs"] -mod brush_refusal_alert_tests; +pub(super) mod brush_refusal_alert_tests; #[cfg(test)] #[path = "../sharpen_refusal_alert_tests.rs"] mod sharpen_refusal_alert_tests; + +#[cfg(test)] +#[path = "../sponge_refusal_alert_tests.rs"] +mod sponge_refusal_alert_tests; + +#[cfg(test)] +#[path = "../retouch_mode_refusal_alert_tests.rs"] +mod retouch_mode_refusal_alert_tests; + +#[cfg(test)] +#[path = "../smudge_refusal_alert_tests.rs"] +mod smudge_refusal_alert_tests; + +#[cfg(test)] +#[path = "../bucket_bitmap_alert_tests.rs"] +mod bucket_bitmap_alert_tests; + +#[cfg(test)] +#[path = "remove_locked_alert_tests.rs"] +mod remove_locked_alert_tests; + +#[cfg(test)] +#[path = "remove_hidden_layer_tests.rs"] +mod remove_hidden_layer_tests; diff --git a/crates/ui-egui/src/tools/brush_resize.rs b/crates/ui-egui/src/tools/brush_resize.rs index e22faf2347..075c06b579 100644 --- a/crates/ui-egui/src/tools/brush_resize.rs +++ b/crates/ui-egui/src/tools/brush_resize.rs @@ -19,8 +19,12 @@ use crate::PhotocraftApp; use crate::canvas::{ToolEvent, ViewXform}; use crate::state::Tool; -/// Screen points of vertical drag that take the hardness from 0 % to 100 %. -pub const HARDNESS_TRAVEL: f32 = 200.0; +/// Screen points of vertical drag that take the hardness from 0 % to 100 %: Photoshop's rate, +/// where 50 points down from 0 % give 13 % (#11891). +pub const HARDNESS_TRAVEL: f32 = 385.0; +/// Screen points of vertical drag that take the opacity from 0 % to 100 % when "Vary Round Brush +/// Hardness on HUD" is off: the rate it had before the hardness rate was measured (#11891). +pub const OPACITY_TRAVEL: f32 = 200.0; /// The brush size range (`tools.setBrush` accepts the same). const SIZE: std::ops::RangeInclusive = 1.0..=MAX_BRUSH_SIZE; @@ -122,10 +126,11 @@ fn update(app: &mut PhotocraftApp, r: Resize, x: f64, y: f64) { // No view: document axes, mirrored by View › Flip Horizontal. _ => ((x - r.anchor[0]) * if app.ui.view.flip_horizontal { -1.0 } else { 1.0 }, y - r.anchor[1], app.point_zoom()), }; - let (size, v) = resized(r.start, dx, dy, zoom); // "Vary Round Brush Hardness on HUD" (Preferences ▸ Tools, on by default): off, the vertical - // movement takes the opacity instead of the hardness, as in Photoshop. + // movement takes the opacity instead of the hardness, as in Photoshop, at its own rate. let vary = app.session.prefs().tools.vary_round_brush_hardness_on_hud; + let dy = if vary { dy } else { dy * f64::from(HARDNESS_TRAVEL / OPACITY_TRAVEL) }; + let (size, v) = resized(r.start, dx, dy, zoom); let b = &app.session.tools.brush; if b.size == size && if vary { b.hardness == v } else { b.opacity == v } { return; @@ -151,15 +156,22 @@ pub fn draw(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) -> boo // Photoshop hides the pointer while the circle stays put. painter.ctx().set_cursor_icon(egui::CursorIcon::None); let at = painter.ctx().pointer_latest_pos().unwrap_or(c); - let (label, value) = if app.session.prefs().tools.vary_round_brush_hardness_on_hud { - (tl!("Hardness:"), format!("{}%", (b.hardness * 100.0).round() as i64)) - } else { - (tl!("Opacity:"), format!("{}%", (b.opacity * 100.0).round() as i64)) - }; - crate::canvas::draw_readout(painter.ctx(), "brush-resize-readout", at, [tl!("Diameter:"), label], [format!("{} px", b.size.round() as i64), value]); + let percent = |v: f32| format!("{}%", (v * 100.0).round() as i64); + let labels = [readout_label(tl!("Diameter:")), readout_label(tl!("Hardness:")), readout_label(tl!("Opacity:"))]; + let values = [format!("{} px", b.size.round() as i64), percent(b.hardness), percent(b.opacity)]; + crate::canvas::draw_readout(painter.ctx(), "brush-resize-readout", at, labels.each_ref().map(String::as_str), values); true } +/// A readout label as Photoshop's HUD shows it, with a space before the colon ("Diameter :", +/// #11891). A translation that already has one keeps it. +pub(crate) fn readout_label(label: &str) -> String { + match label.strip_suffix(':') { + Some(head) if !head.ends_with(char::is_whitespace) => format!("{head} :"), + _ => label.to_owned(), + } +} + /// The tip preview's tint: Preferences ▸ Cursors ▸ Brush Preview colour (red by default, as in /// Photoshop), at the overlay's alpha. Unreadable values keep the red. fn preview_tint(app: &PhotocraftApp) -> Color32 { diff --git a/crates/ui-egui/src/tools/brush_resize/tests.rs b/crates/ui-egui/src/tools/brush_resize/tests.rs index 3cba8bef99..b2e5790b68 100644 --- a/crates/ui-egui/src/tools/brush_resize/tests.rs +++ b/crates/ui-egui/src/tools/brush_resize/tests.rs @@ -22,7 +22,7 @@ fn history(app: &PhotocraftApp) -> usize { #[test] fn mapping_is_bounded() { assert_eq!(resized((40.0, 0.5), 10.0, 0.0, 1.0), (60.0, 0.5), "the edge follows the pointer"); - assert_eq!(resized((40.0, 0.5), 0.0, 50.0, 2.0), (40.0, 1.0), "down is harder, in screen points"); + assert_eq!(resized((40.0, 0.5), 0.0, f64::from(HARDNESS_TRAVEL / 4.0), 2.0), (40.0, 1.0), "down is harder, in screen points"); assert_eq!(resized((40.0, 0.5), -1e9, -1e9, 1.0), (1.0, 0.0)); assert_eq!(resized((40.0, 0.5), 1e9, 1e9, 1.0), (MAX_BRUSH_SIZE, 1.0)); assert_eq!(resized((40.0, 0.5), f64::NAN, f64::INFINITY, f32::NAN), (40.0, 0.5)); @@ -41,11 +41,11 @@ fn ctrl_alt_drag_resizes_every_brush_tool_without_painting_or_history() { // Right grows the size. tool_event(&mut app, ToolEvent::Move { x: 130.0, y: 100.0, pressure: 1.0 }, CTRL_ALT); assert_eq!(app.session.tools.brush.size, 100.0, "{tool:?}"); - // Down raises the hardness (at 100 %, 200 points take it from 0 to 100 %). - tool_event(&mut app, ToolEvent::Move { x: 130.0, y: 160.0, pressure: 1.0 }, CTRL_ALT); + // Down raises the hardness (at 100 %, 385 points take it from 0 to 100 %, #11891). + tool_event(&mut app, ToolEvent::Move { x: 130.0, y: 215.5, pressure: 1.0 }, CTRL_ALT); assert_eq!(app.session.tools.brush.hardness, 0.5, "{tool:?}"); // Letting go of the keys mid-drag keeps resizing until the button is released. - tool_event(&mut app, ToolEvent::Up { x: 120.0, y: 180.0 }, Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 120.0, y: 254.0 }, Modifiers::NONE); let b = &app.session.tools.brush; assert_eq!((b.size, b.hardness), (80.0, 0.6), "{tool:?}"); assert!(app.brush_resize.is_none() && app.drag.is_none()); @@ -297,9 +297,11 @@ fn vary_round_brush_hardness_on_hud_switches_the_vertical_target() { app.run("prefs.set", json!({"path": "tools.varyRoundBrushHardnessOnHud", "value": false})).unwrap(); } let (h0, o0) = (app.session.tools.brush.hardness, app.session.tools.brush.opacity); + // 20 % of each travel: 77 points for the hardness, 40 for the opacity, which keeps its rate. + let y = if vary { 177.0 } else { 140.0 }; tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 100.0, pressure: 1.0 }, CTRL_ALT); - tool_event(&mut app, ToolEvent::Move { x: 100.0, y: 140.0, pressure: 1.0 }, CTRL_ALT); - tool_event(&mut app, ToolEvent::Up { x: 100.0, y: 140.0 }, CTRL_ALT); + tool_event(&mut app, ToolEvent::Move { x: 100.0, y, pressure: 1.0 }, CTRL_ALT); + tool_event(&mut app, ToolEvent::Up { x: 100.0, y }, CTRL_ALT); let b = &app.session.tools.brush; if vary { assert_eq!((b.hardness, b.opacity), (h0 + 0.2, o0), "hardness moves with the drag"); @@ -330,16 +332,16 @@ fn drag_in_view(rotation: f32, flip: bool, dx: f64, dy: f64) -> (f32, f32) { fn a_rotated_view_keeps_horizontal_for_size_and_vertical_for_hardness() { // Unrotated, with and without View › Flip Horizontal: unchanged. assert_eq!(drag_in_view(0.0, false, 30.0, 0.0), (100.0, 0.2), "right grows"); - assert_eq!(drag_in_view(0.0, false, 0.0, 40.0), (40.0, 0.4), "down hardens"); + assert_eq!(drag_in_view(0.0, false, 0.0, 77.0), (40.0, 0.4), "down hardens"); assert_eq!(drag_in_view(0.0, true, -30.0, 0.0), (100.0, 0.2), "flipped: screen right grows"); - assert_eq!(drag_in_view(0.0, true, 0.0, 40.0), (40.0, 0.4), "flipped: down hardens"); + assert_eq!(drag_in_view(0.0, true, 0.0, 77.0), (40.0, 0.4), "flipped: down hardens"); // 90° clockwise: document +y points screen-left and document +x screen-down. assert_eq!(drag_in_view(90.0, false, 0.0, 10.0), (20.0, 0.2), "screen-left shrinks, the hardness stays"); assert_eq!(drag_in_view(90.0, false, 0.0, -30.0), (100.0, 0.2), "screen-right grows"); - assert_eq!(drag_in_view(90.0, false, 40.0, 0.0), (40.0, 0.4), "screen-down hardens, the size stays"); + assert_eq!(drag_in_view(90.0, false, 77.0, 0.0), (40.0, 0.4), "screen-down hardens, the size stays"); // 180°: document -x is screen right. assert_eq!(drag_in_view(180.0, false, -30.0, 0.0), (100.0, 0.2), "screen right still grows"); - assert_eq!(drag_in_view(180.0, false, 0.0, -40.0), (40.0, 0.4), "screen down still hardens"); + assert_eq!(drag_in_view(180.0, false, 0.0, -77.0), (40.0, 0.4), "screen down still hardens"); // 90° and flipped: document +y points screen-right. assert_eq!(drag_in_view(90.0, true, 0.0, 30.0), (100.0, 0.2), "rotated and flipped: screen right grows"); } diff --git a/crates/ui-egui/src/tools/corner_radius.rs b/crates/ui-egui/src/tools/corner_radius.rs index f5ec3192e9..534e7108bd 100644 --- a/crates/ui-egui/src/tools/corner_radius.rs +++ b/crates/ui-egui/src/tools/corner_radius.rs @@ -5,7 +5,7 @@ //! of every selected shape to the same radius; ⌥/Alt changes that corner only on rectangles //! (a triangle or polygon has one radius for all its corners, as in Photoshop). The drag previews //! the new outlines and commits one `shape.edit` per changed layer on release (`radii` for a -//! rectangle, `cornerRadius` for a polygon), as one history step; a click without movement +//! rectangle, `cornerRadius` for a polygon or a triangle), as one history step; a click without movement //! changes nothing. use egui::{Color32, Modifiers, Pos2, Stroke}; @@ -26,8 +26,9 @@ const MIN_INSET: f64 = 10.0; enum Geom { /// `[x, y, w, h]` with a positive size. Rect([f64; 4]), - /// The polygon's parameters and its sharp vertices, in path order. - Polygon { rect: [f64; 4], sides: u32, star_ratio: f64, vertices: Vec<[f64; 2]> }, + /// A polygon, star or triangle: its live shape, its sharp vertices in path order, and the + /// indices of those that take the radius (a star's outer points only). + Polygon { live: LiveShape, vertices: Vec<[f64; 2]>, rounded: Vec }, } /// A selected live shape with corners: its layer, its geometry, and its radii (a rectangle's four @@ -52,7 +53,7 @@ impl Target { fn corners(&self) -> usize { match &self.geom { Geom::Rect(_) => 4, - Geom::Polygon { vertices, .. } => vertices.len(), + Geom::Polygon { rounded, .. } => rounded.len(), } } @@ -72,27 +73,29 @@ impl Target { }; Some(Corner { vertex, step: d }) } - Geom::Polygon { vertices, .. } => { + Geom::Polygon { vertices, rounded, .. } => { let f = self.fillet(i, 1.0)?; let sin = f.half_angle.sin(); - (sin > 1e-9).then(|| Corner { vertex: vertices.get(i).copied().unwrap_or(f.centre), step: [f.bisector[0] / sin, f.bisector[1] / sin] }) + let vertex = rounded.get(i).and_then(|&v| vertices.get(v)).copied().unwrap_or(f.centre); + (sin > 1e-9).then(|| Corner { vertex, step: [f.bisector[0] / sin, f.bisector[1] / sin] }) } } } - /// A polygon vertex's rounding with radius `r`. + /// Corner `i`'s rounding with radius `r` (a polygon's). fn fillet(&self, i: usize, r: f64) -> Option { - let Geom::Polygon { vertices, .. } = &self.geom else { return None }; + let Geom::Polygon { vertices, rounded, .. } = &self.geom else { return None }; let n = vertices.len(); + let v = *rounded.get(i)?; let at = |k: usize| vertices.get(k % n).copied(); - shapes::fillet(at(i + n - 1)?, at(i)?, at(i + 1)?, r) + shapes::fillet(at(v + n - 1)?, at(v)?, at(v + 1)?, r) } /// The largest radius every corner of the shape can take. fn max_radius(&self) -> f64 { match &self.geom { Geom::Rect(r) => r[2].min(r[3]) / 2.0, - Geom::Polygon { vertices, .. } => (0..vertices.len()).filter_map(|i| self.fillet(i, 1.0e12)).map(|f| f.radius).fold(f64::INFINITY, f64::min), + Geom::Polygon { rounded, .. } => (0..rounded.len()).filter_map(|i| self.fillet(i, 1.0e12)).map(|f| f.radius).fold(f64::INFINITY, f64::min), } } @@ -123,8 +126,12 @@ impl Target { fn path(&self, radii: [f64; 4]) -> photocraft_doc::Path { match &self.geom { Geom::Rect([x, y, w, h]) => shapes::rounded_rect(*x, *y, *w, *h, radii), - Geom::Polygon { rect, sides, star_ratio, .. } => { - shapes::live_path(&LiveShape::Polygon { rect: *rect, sides: *sides, star_ratio: *star_ratio, corner_radius: radii[0] }) + Geom::Polygon { live, .. } => { + let mut live = live.clone(); + if let LiveShape::Polygon { corner_radius, .. } | LiveShape::Triangle { corner_radius, .. } = &mut live { + *corner_radius = radii[0]; + } + shapes::live_path(&live) } } } @@ -175,13 +182,28 @@ fn target(layer: u64, live: &LiveShape) -> Option { return None; } let sharp = shapes::polygon(rect[0], rect[1], rect[2], rect[3], sides, star_ratio); - 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] }) + polygon_target(layer, live, &sharp, corner_radius, |i| shapes::polygon_rounds_vertex(star_ratio, i)) + } + LiveShape::Triangle { rect, corner_radius } => { + positive(rect)?; + if !finite(&[corner_radius]) { + return None; + } + let sharp = shapes::triangle(rect[0], rect[1], rect[2], rect[3]); + polygon_target(layer, live, &sharp, corner_radius, |_| true) } LiveShape::Ellipse { .. } | LiveShape::Line { .. } | LiveShape::ArrowLine { .. } => None, } } +/// A polygon, star or triangle as a target: the vertices of its sharp outline, and which of them +/// take the radius. +fn polygon_target(layer: u64, live: &LiveShape, sharp: &photocraft_doc::Path, corner_radius: f64, rounds: impl Fn(usize) -> bool) -> Option { + let vertices: Vec<[f64; 2]> = sharp.subpaths.first()?.knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); + let rounded = (0..vertices.len()).filter(|&i| rounds(i)).collect(); + Some(Target { layer, geom: Geom::Polygon { live: live.clone(), vertices, rounded }, radii: [corner_radius.max(0.0); 4] }) +} + /// The selected layers that are live shapes with corners, front first. fn targets(app: &PhotocraftApp) -> Vec { if !shows(app) { diff --git a/crates/ui-egui/src/tools/corner_radius/tests.rs b/crates/ui-egui/src/tools/corner_radius/tests.rs index 252e9ce587..904eb9ff59 100644 --- a/crates/ui-egui/src/tools/corner_radius/tests.rs +++ b/crates/ui-egui/src/tools/corner_radius/tests.rs @@ -267,3 +267,27 @@ fn rectangles_and_triangles_selected_together_take_the_same_radius() { assert_eq!(rr, [4.0; 4]); assert!((corner_radius_of(&app, tri) - 4.0).abs() < 1e-9); } + +#[test] +fn a_star_shows_widgets_at_its_outer_points_only() { + // #13308: a star's inner points stay sharp, so they have no widget. + let live = LiveShape::Polygon { rect: [40.0, 40.0, 120.0, 100.0], sides: 5, star_ratio: 0.5, corner_radius: 6.0 }; + let t = super::target(1, &live).unwrap(); + assert_eq!(t.corners(), 5); + let sharp = &photocraft_vector::shapes::polygon(40.0, 40.0, 120.0, 100.0, 5, 0.5).subpaths[0].knots; + for i in 0..5 { + let v = sharp[2 * i].anchor; + assert_eq!(t.corner(i).unwrap().vertex, [v.x, v.y], "corner {i} is outer point {i}"); + } + // The widgets preview the outline `shape.create` makes with the same radius. + assert_eq!(t.path(t.radii), photocraft_vector::shapes::live_path(&live)); + // The largest radius is the one every outer point can take. + let outer_most = (0..5).filter_map(|i| t.fillet(i, 1.0e12)).map(|f| f.radius).fold(f64::INFINITY, f64::min); + assert!(outer_most.is_finite() && t.max_radius() == outer_most); +} + +#[test] +fn a_plain_polygon_shows_a_widget_at_every_vertex() { + let live = LiveShape::Polygon { rect: [40.0, 40.0, 120.0, 100.0], sides: 6, star_ratio: 1.0, corner_radius: 6.0 }; + assert_eq!(super::target(1, &live).unwrap().corners(), 6); +} diff --git a/crates/ui-egui/src/tools/count_options_bar_tests.rs b/crates/ui-egui/src/tools/count_options_bar_tests.rs new file mode 100644 index 0000000000..3a2e9c1f20 --- /dev/null +++ b/crates/ui-egui/src/tools/count_options_bar_tests.rs @@ -0,0 +1,234 @@ +//! #11765: the Count tool's options bar shows every control from the start, in Photoshop's order, +//! with its tooltips, and greys what can't act: the group dropdown until there is a group, the +//! trash with fewer than two groups, Clear while the current group is empty or hidden. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +const EYE: &str = "Toggle visibility of count group"; +const FOLDER: &str = "Create a new count group"; +const TRASH: &str = "Delete the currently selected count group"; +const SWATCH: &str = "Count group color"; + +/// A 100 × 100 document with the Count tool and `groups` count groups (the first with a marker). +fn app(groups: usize) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.ui.tool = Tool::Count; + if groups > 0 { + app.run("count.add", json!({"x": 10, "y": 10})).unwrap(); + } + for _ in 1..groups { + app.run("count.newGroup", json!({})).unwrap(); + } + if groups > 0 { + app.run("count.setGroup", json!({"group": 0, "active": true})).unwrap(); + } + app +} + +fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1400.0, 120.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::panels::options_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(4); + h +} + +fn disabled(h: &Harness<'static, PhotocraftApp>, label: &str) -> bool { + h.get_by_label(label).accesskit_node().is_disabled() +} + +fn combo_disabled(h: &Harness<'static, PhotocraftApp>) -> bool { + h.get_all_by_role(egui::accesskit::Role::ComboBox).next().expect("the group dropdown").accesskit_node().is_disabled() +} + +#[test] +fn the_controls_are_in_the_reference_order_in_every_state() { + for groups in [0, 1, 2] { + let h = harness(app(groups)); + let x = |label: &str| h.get_by_label(label).rect().left(); + let combo = h.get_all_by_role(egui::accesskit::Role::ComboBox).next().expect("the group dropdown").rect().left(); + let order = [combo, x(EYE), x(FOLDER), x(TRASH), x("Clear"), x(SWATCH), x("Marker Size:"), x("Label Size:")]; + assert!(order.windows(2).all(|w| w[0] < w[1]), "{groups} groups: left edges {order:?}"); + let count = h.get_all_by_label_contains("Count: ").next().expect("the Count: readout").rect().left(); + assert!(count < combo, "{groups} groups: the readout comes first"); + } +} + +#[test] +fn with_no_group_the_dropdown_trash_and_clear_are_greyed_and_the_next_groups_values_show() { + let h = harness(app(0)); + assert!(combo_disabled(&h), "the dropdown is greyed"); + let combo = h.get_all_by_role(egui::accesskit::Role::ComboBox).next().unwrap(); + let node = combo.accesskit_node(); + assert_eq!(node.value().as_deref(), Some("Count Group"), "with the placeholder"); + assert!(disabled(&h, TRASH) && disabled(&h, "Clear")); + assert!(!disabled(&h, EYE) && !disabled(&h, FOLDER)); + // The sizes the next new group gets today. + let next = photocraft_doc::CountGroup::default(); + assert!(h.query_by_value(&next.marker_size.to_string()).is_some(), "Marker Size {}", next.marker_size); + assert!(h.query_by_value(&next.label_size.to_string()).is_some(), "Label Size {}", next.label_size); +} + +#[test] +fn using_the_eye_with_no_group_changes_nothing() { + let mut h = harness(app(0)); + let steps = h.state().session.active().unwrap().history.past_len(); + h.get_by_label(EYE).click(); + h.run_steps(3); + let st = h.state().session.active().unwrap(); + assert!(st.doc.measurement.count_groups.is_empty()); + assert_eq!(st.history.past_len(), steps); +} + +#[test] +fn the_trash_needs_two_groups() { + assert!(disabled(&harness(app(1)), TRASH), "one group"); + let mut h = harness(app(2)); + assert!(!disabled(&h, TRASH), "two groups"); + h.get_by_label(TRASH).click(); + h.run_steps(3); + assert_eq!(h.state().session.active().unwrap().doc.measurement.count_groups.len(), 1); + assert!(disabled(&h, TRASH), "back to one group"); +} + +#[test] +fn clear_needs_a_visible_current_group_with_markers() { + let h = harness(app(1)); + assert!(!disabled(&h, "Clear"), "one marker, visible"); + let mut hidden = app(1); + hidden.run("count.setGroup", json!({"visible": false})).unwrap(); + assert!(disabled(&harness(hidden), "Clear"), "hidden"); + let mut empty = app(2); + empty.run("count.setGroup", json!({"group": 1, "active": true})).unwrap(); + assert!(disabled(&harness(empty), "Clear"), "the current group has no markers"); +} + +#[test] +fn the_swatch_opens_the_count_color_picker() { + let mut h = harness(app(1)); + h.get_by_label(SWATCH).click(); + h.run_steps(3); + let want = crate::color_picker_ui::title_for("Count Color"); + assert_eq!(want, "Color Picker (Count Color)"); + assert!(h.state().ui.dialogs.iter().any(|d| crate::dialogs::title(d) == want), "a picker titled {want}"); +} + +#[test] +fn the_size_captions_scrub_their_fields() { + let mut h = harness(app(1)); + // The visible caption, not the field it names (`get_by_label` returns the labelled field). + let from = h + .query_all(egui_kittest::kittest::by().label("Marker Size:").include_labels()) + .find(|n| n.accesskit_node().role() == egui::accesskit::Role::Label) + .expect("the Marker Size: caption") + .rect() + .center(); + // As the Brush options' scrub test drives a caption (options_hit_area_tests): hover, press, + // move in steps, release, letting each step settle. + h.hover_at(from); + h.run(); + h.drag_at(from); + h.run(); + for i in 1..=4 { + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.hover_at(from + vec2(12.0 * i as f32, 0.0)); + h.run(); + } + h.drop_at(from + vec2(48.0, 0.0)); + h.run_steps(2); + let g = &h.state().session.active().unwrap().doc.measurement.count_groups[0]; + assert!(g.marker_size > 1, "dragging the caption right raised Marker Size: {}", g.marker_size); + assert!(g.marker_size <= 10, "within its range"); +} + +/// Drags the visible "Marker Size:" caption `dx` points right in four moves. +fn scrub_marker_size(h: &mut Harness<'static, PhotocraftApp>, dx: f32) { + let from = h + .query_all(egui_kittest::kittest::by().label("Marker Size:").include_labels()) + .find(|n| n.accesskit_node().role() == egui::accesskit::Role::Label) + .expect("the Marker Size: caption") + .rect() + .center(); + h.hover_at(from); + h.run(); + h.drag_at(from); + h.run(); + for i in 1..=4 { + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.hover_at(from + vec2(dx / 4.0 * i as f32, 0.0)); + h.run(); + } + h.drop_at(from + vec2(dx, 0.0)); + h.run_steps(2); +} + +#[test] +fn one_size_scrub_is_one_history_step() { + let mut h = harness(app(1)); + let steps = |h: &Harness<'static, PhotocraftApp>| h.state().session.active().unwrap().history.past_len(); + let before = steps(&h); + scrub_marker_size(&mut h, 24.0); + let size = h.state().session.active().unwrap().doc.measurement.count_groups[0].marker_size; + assert!(size > 2, "the scrub moved Marker Size several steps: {size}"); + assert_eq!(steps(&h), before + 1, "one scrub, one Undo step"); + // Back left, as the first may have reached the top of the range. + scrub_marker_size(&mut h, -24.0); + let back = h.state().session.active().unwrap().doc.measurement.count_groups[0].marker_size; + assert!(back < size, "the second scrub moved it back: {size} -> {back}"); + assert_eq!(steps(&h), before + 2, "a second scrub is a step of its own"); +} + +#[test] +fn automation_delete_and_clear_work_as_today() { + // The greying is the options bar's: the commands still delete the last group and clear a + // hidden one. + let mut app = app(1); + app.run("count.setGroup", json!({"visible": false})).unwrap(); + app.run("count.clear", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.measurement.count_total(), 0); + app.run("count.deleteGroup", json!({})).unwrap(); + assert!(app.session.active().unwrap().doc.measurement.count_groups.is_empty()); +} + +/// The visible caption node (a `Role::Label`) reading `text`, if any. +fn caption_node(h: &Harness<'static, PhotocraftApp>, text: &str) -> bool { + h.query_all(egui_kittest::kittest::by().label(text).include_labels()).any(|n| n.accesskit_node().role() == egui::accesskit::Role::Label) +} + +#[test] +fn the_size_captions_are_translated() { + // The catalogs translate "Marker Size" and "Label Size" (main's captions); the colon follows. + // A missing catalog row shows the English, so the test doesn't require the translation. + if !crate::i18n::needs_catalogs() { + return; + } + let _de = crate::i18n::language_scope(crate::i18n::Lang::from_code("de").expect("German")); + let h = harness(app(1)); + for key in ["Marker Size", "Label Size"] { + let want = format!("{}:", crate::i18n::t(key)); + assert!(caption_node(&h, &want), "the caption reads {want}"); + } +} + +#[test] +fn the_size_fields_are_named_by_their_visible_captions() { + let h = harness(app(1)); + for caption in ["Marker Size:", "Label Size:"] { + let fields = h.query_all(egui_kittest::kittest::by().label(caption).predicate(|n| n.role() != egui::accesskit::Role::Label)).count(); + assert_eq!(fields, 1, "one field named {caption}, as its caption reads"); + } +} diff --git a/crates/ui-egui/src/tools/count_readout_tests.rs b/crates/ui-egui/src/tools/count_readout_tests.rs new file mode 100644 index 0000000000..509b3e92c7 --- /dev/null +++ b/crates/ui-egui/src/tools/count_readout_tests.rs @@ -0,0 +1,61 @@ +//! #11764: the Count tool's options-bar readout: "N" for one group (or none), "V (C)" for two or +//! more, V the visible groups' markers and C the current group's (0 while it is hidden). + +use serde_json::json; + +use super::count_readout; + +fn session(groups: &[usize]) -> photocraft_engine::Session { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 100, "height": 100})).unwrap(); + for (g, n) in groups.iter().enumerate() { + s.execute("count.newGroup", json!({"name": format!("G{g}")})).unwrap(); + for i in 0..*n { + s.execute("count.add", json!({"x": 10 + 5 * i, "y": 10 + 10 * g})).unwrap(); + } + } + s +} + +fn readout(s: &photocraft_engine::Session) -> String { + count_readout(&s.active().unwrap().doc.measurement) +} + +#[test] +fn no_group_or_one_group_reads_its_markers() { + assert_eq!(readout(&session(&[])), "0"); + let mut s = session(&[3]); + assert_eq!(readout(&s), "3"); + s.execute("count.setGroup", json!({"visible": false})).unwrap(); + assert_eq!(readout(&s), "3", "a single hidden group keeps today's count"); +} + +#[test] +fn two_groups_read_the_visible_total_and_the_current_group() { + let mut s = session(&[3, 2]); + // The 2-marker group (made last) is current. + assert_eq!(readout(&s), "5 (2)"); + s.execute("count.setGroup", json!({"visible": false})).unwrap(); + assert_eq!(readout(&s), "3 (0)"); + // count_total() keeps its meaning: every group. + assert_eq!(s.active().unwrap().doc.measurement.count_total(), 5); +} + +#[test] +fn hiding_another_group_or_switching_the_current_one() { + let mut s = session(&[3, 2]); + s.execute("count.setGroup", json!({"group": 0, "visible": false})).unwrap(); + assert_eq!(readout(&s), "2 (2)", "a hidden other group leaves the total only"); + s.execute("count.setGroup", json!({"group": 0, "visible": true, "active": true})).unwrap(); + assert_eq!(readout(&s), "5 (3)"); + assert_eq!(readout(&session(&[3, 2, 4])), "9 (4)"); + assert_eq!(readout(&session(&[0, 0])), "0 (0)"); +} + +#[test] +fn an_out_of_range_current_group_reads_the_last_one() { + // The Group dropdown and `count.add` treat a stale index as the last group; the readout too. + let mut m = session(&[3, 2]).active().unwrap().doc.measurement.clone(); + m.active_count_group = 9; + assert_eq!(count_readout(&m), "5 (2)"); +} diff --git a/crates/ui-egui/src/tools/crop_size.rs b/crates/ui-egui/src/tools/crop_size.rs index 68b0714190..6477c280e4 100644 --- a/crates/ui-egui/src/tools/crop_size.rs +++ b/crates/ui-egui/src/tools/crop_size.rs @@ -33,6 +33,15 @@ pub const PX_PER_CM: &str = "px/cm"; /// The largest number a length or resolution field keeps (well past any canvas or ppi limit, /// which `image.crop` enforces with its own message). const MAX_FIELD: f64 = 1e9; +/// Perspective Crop's W and H take 1 to 300000 px, its resolution 1 to 29999.999 px/in (#11977). +pub const PCROP_MAX_PX: f64 = 300_000.0; +pub const PCROP_MAX_PPI: f64 = 29_999.999; +/// Perspective Crop's alerts for a W or H, and a resolution, out of range; `{min}` and `{max}` +/// with three decimals and the system's decimal separator. +pub const LENGTH_RANGE_ALERT: &str = "A value between {min} {unit} and {max} {unit} is required. Closest value inserted."; +pub const RESOLUTION_RANGE_ALERT: &str = "A number between {min} and {max} is required. Closest value inserted."; +/// Perspective Crop's alert for a field that doesn't hold a number. +pub const INVALID_ENTRY_ALERT: &str = "Invalid numeric entry. Restored last valid value."; /// Photoshop's built-in crop presets: (dropdown key, label, width, height, resolution in px/in). pub const PRESETS: &[(&str, &str, &str, &str, &str)] = &[ @@ -69,6 +78,12 @@ fn unit_of(suffix: &str) -> Option { /// A typed length: a positive number and an optional unit ("4 in", "4in", "10,5 cm", "1024"). /// A bare number takes `fallback`. `None` for anything else (empty, zero, negative, unknown unit). pub fn parse_length(text: &str, fallback: Unit) -> Option<(f64, Unit)> { + let (v, unit) = parse_number(text, fallback)?; + (v > 0.0 && v <= MAX_FIELD).then_some((v, unit)) +} + +/// A typed number of any sign with an optional unit, as [`parse_length`] reads it. +fn parse_number(text: &str, fallback: Unit) -> Option<(f64, Unit)> { let text = text.trim(); if text.is_empty() || text.len() > 64 { return None; @@ -77,7 +92,80 @@ pub fn parse_length(text: &str, fallback: Unit) -> Option<(f64, Unit)> { let (num, suffix) = (text.get(..split)?.trim(), text.get(split..)?.trim()); let v = crate::widgets::parse_num(&num.replace(',', "."))?; let unit = if suffix.is_empty() { fallback } else { unit_of(suffix)? }; - (v.is_finite() && v > 0.0 && v <= MAX_FIELD).then_some((v, unit)) + v.is_finite().then_some((v, unit)) +} + +/// A limit in an alert: three decimals with the system's decimal separator ("300000.000"). +fn alert_number(v: f64) -> String { + let text = format!("{v:.3}"); + match crate::i18n::decimal_separator() { + Some(',') => text.replace('.', ","), + _ => text, + } +} + +fn unit_name(unit: Unit) -> &'static str { + match unit { + Unit::Pixels => tl!("Pixels"), + Unit::Inches => tl!("Inches"), + Unit::Centimeters => tl!("Centimeters"), + Unit::Millimeters => tl!("Millimeters"), + Unit::Points => tl!("Points"), + Unit::Picas => tl!("Picas"), + Unit::Percent => tl!("Percent"), + } +} + +/// What a Perspective Crop W or H field keeps once typed, and the alert to show (#11977): a length +/// out of 1 to 300000 px gets the closest one (the limits converted into its unit at `dpi` and +/// `pt_per_in`), text that isn't a number the previous value, empty stays empty. +pub fn clamp_length(typed: &str, previous: &str, dpi: f64, pt_per_in: f64) -> (String, Option) { + if typed.trim().is_empty() { + return (String::new(), None); + } + let Some((v, unit)) = parse_number(typed, field_unit(previous)) else { + return (previous.to_string(), Some(tl!(INVALID_ENTRY_ALERT).to_string())); + }; + let (lo, hi) = (unit.from_px(1.0, dpi, 0.0, pt_per_in), unit.from_px(PCROP_MAX_PX, dpi, 0.0, pt_per_in)); + if !(lo.is_finite() && hi.is_finite() && lo <= hi) { + return (previous.to_string(), Some(tl!(INVALID_ENTRY_ALERT).to_string())); + } + if (lo..=hi).contains(&v) { + return (format_length(v, unit), None); + } + let alert = crate::i18n::fmt(tl!(LENGTH_RANGE_ALERT), &[("min", &alert_number(lo)), ("max", &alert_number(hi)), ("unit", unit_name(unit))]); + (format_length(v.clamp(lo, hi), unit), Some(alert)) +} + +/// What the Perspective Crop resolution field keeps once typed, and the alert to show (#11977): +/// 1 to 29999.999 px/in (divided by 2.54 for px/cm), the closest limit outside it. +pub fn clamp_resolution(typed: &str, previous: &str, per_cm: bool) -> (String, Option) { + if typed.trim().is_empty() { + return (String::new(), None); + } + let Some(v) = crate::widgets::parse_num(&typed.trim().replace(',', ".")).filter(|v| v.is_finite()) else { + return (previous.to_string(), Some(tl!(INVALID_ENTRY_ALERT).to_string())); + }; + let (lo, hi) = resolution_limits(per_cm); + if (lo..=hi).contains(&v) { + return (fit_resolution(v, per_cm), None); + } + let alert = crate::i18n::fmt(tl!(RESOLUTION_RANGE_ALERT), &[("min", &alert_number(lo)), ("max", &alert_number(hi))]); + (fit_resolution(v, per_cm), Some(alert)) +} + +/// Perspective Crop's resolution range in px/in, or in px/cm (the per-inch limits divided by 2.54). +fn resolution_limits(per_cm: bool) -> (f64, f64) { + if per_cm { (1.0 / 2.54, PCROP_MAX_PPI / 2.54) } else { (1.0, PCROP_MAX_PPI) } +} + +/// A resolution as the Perspective Crop field keeps it: three decimals, so the top limit is kept as +/// it is, and clamped to the limits rounded inwards, so the stored text never converts past them +/// (Front Image on a 30000 ppi document keeps 29999.999). +pub fn fit_resolution(v: f64, per_cm: bool) -> String { + let (lo, hi) = resolution_limits(per_cm); + let (lo, hi) = ((lo * 1000.0).ceil() / 1000.0, (hi * 1000.0).floor() / 1000.0); + crate::widgets::fmt_num_prec(((v * 1000.0).round() / 1000.0).clamp(lo, hi), 3) } /// "4 in", "1024 px", "8.5 in", "2.54 cm": the number (up to its unit's decimals) and the unit. @@ -286,7 +374,7 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { /// A text field for a length or the resolution: what is typed is kept while it has focus and /// normalised into `value` (by `normalize(typed, previous)`) when it loses it. Returns true then. -fn text_field(ui: &mut egui::Ui, id: &str, value: &mut String, hint: &str, width: f32, normalize: fn(&str, &str) -> String) -> bool { +fn text_field(ui: &mut egui::Ui, id: &str, value: &mut String, hint: &str, width: f32, normalize: impl Fn(&str, &str) -> String) -> bool { let t = Tokens::get(ui.ctx()); let id = ui.scope_id().with(id); let mut buf = ui.data(|d| d.get_temp::(id)).unwrap_or_else(|| value.clone()); @@ -317,15 +405,50 @@ fn text_field(ui: &mut egui::Ui, id: &str, value: &mut String, hint: &str, width /// The W x H x Resolution fields of the options bar: W, ⇄, H, the resolution and its unit. /// Returns true when ⇄ swapped W and H, so the Crop tool turns its frame with them. pub fn fields(o: &mut ToolOptions, ui: &mut egui::Ui) -> bool { - text_field(ui, "crop-width", &mut o.crop_width, tl!("Width"), 64.0, normalize_length); + fields_with(o, ui, None).0 +} + +/// The same fields for Perspective Crop, with its limits and alerts (#11977): lengths convert at +/// the typed resolution or `doc_dpi`, points and picas at `pt_per_in`. Returns the alert to show. +pub fn perspective_fields(o: &mut ToolOptions, ui: &mut egui::Ui, doc_dpi: f64, pt_per_in: f64) -> Option { + fields_with(o, ui, Some((doc_dpi, pt_per_in))).1 +} + +/// The fields; with `limits` (Perspective Crop's document resolution and point size) they clamp +/// and return an alert. +fn fields_with(o: &mut ToolOptions, ui: &mut egui::Ui, limits: Option<(f64, f64)>) -> (bool, Option) { + let alert = std::cell::Cell::new(None); + let dpi = limits.map(|(doc_dpi, ppi)| (resolution_ppi(o).unwrap_or(doc_dpi), ppi)); + let per_cm = o.crop_resolution_unit == PX_PER_CM; + let length = |typed: &str, previous: &str| match dpi { + Some((dpi, ppi)) => { + let (kept, a) = clamp_length(typed, previous, dpi, ppi); + if a.is_some() { + alert.set(a); + } + kept + } + None => normalize_length(typed, previous), + }; + let resolution = |typed: &str, previous: &str| match limits { + Some(_) => { + let (kept, a) = clamp_resolution(typed, previous, per_cm); + if a.is_some() { + alert.set(a); + } + kept + } + None => normalize_resolution(typed, previous), + }; + text_field(ui, "crop-width", &mut o.crop_width, tl!("Width"), 64.0, length); // Always swaps (Perspective Crop shows the fields without the mode); true in W x H x Resolution // mode, where the Crop tool turns its frame with W and H. let swapped = crate::icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked() && { swap_fields(o); o.crop_ratio == WHR }; - text_field(ui, "crop-height", &mut o.crop_height, tl!("Height"), 64.0, normalize_length); - text_field(ui, "crop-resolution", &mut o.crop_resolution, tl!("Resolution"), 64.0, normalize_resolution); + text_field(ui, "crop-height", &mut o.crop_height, tl!("Height"), 64.0, length); + text_field(ui, "crop-resolution", &mut o.crop_resolution, tl!("Resolution"), 64.0, resolution); let units = [(PX_PER_IN.to_string(), "px/in"), (PX_PER_CM.to_string(), "px/cm")]; let before = o.crop_resolution_unit.clone(); if crate::widgets::dropdown(ui, "crop-resolution-unit", tl!("Resolution"), &mut o.crop_resolution_unit, &units, 64.0) && before != o.crop_resolution_unit { @@ -335,7 +458,7 @@ pub fn fields(o: &mut ToolOptions, ui: &mut egui::Ui) -> bool { o.crop_resolution = crate::widgets::fmt_num2(v); } } - swapped + (swapped, alert.take()) } #[cfg(test)] diff --git a/crates/ui-egui/src/tools/direct_select.rs b/crates/ui-egui/src/tools/direct_select.rs index 9d684816bf..1673ee9fbd 100644 --- a/crates/ui-egui/src/tools/direct_select.rs +++ b/crates/ui-egui/src/tools/direct_select.rs @@ -10,8 +10,9 @@ //! The arrow keys nudge the selected anchors 1 px (⇧ 10 px), one history step per press. //! * Convert Point (the tool, or Pen + ⌥): click an anchor to make it a corner, drag from it to //! pull out smooth handles, drag a handle to move it alone. The tool selects the anchor it -//! converts, so its handles show; a press on empty canvas or a segment does nothing, and ⌘/Ctrl -//! is Direct Selection, as with the Pen. +//! converts, so its handles show; a press on empty canvas does nothing, and ⌘/Ctrl is Direct +//! Selection, as with the Pen. The tool drags a straight segment with nothing selected, or the +//! whole path when all of it is selected, as Direct Selection would (#12741). //! * While a Pen path is being drawn, ⌘/Ctrl edits it in place (its anchors, handles and //! segments) and the Pen carries on drawing from its last anchor once ⌘/Ctrl is let go; a //! ⌘/Ctrl-press anywhere else ends it, as in Photoshop (#4022). @@ -75,6 +76,9 @@ pub struct DirectSelection { pub anchors: Vec<[usize; 2]>, /// A clicked segment (`[subpath, knot]` it leaves): its two handles show. pub segment: Option<[usize; 2]>, + /// The subpaths of `target` whose anchors are drawn (Delete Anchor Point on a saved path, #12769); + /// `None` draws all of them, as right after the path is targeted. + pub shown: Option>, #[serde(skip)] pub drag: Option, /// The history step the drag's commit joins (`coalesce`): a Curvature Pen click on a segment @@ -85,12 +89,20 @@ pub struct DirectSelection { pub(crate) owner: Option, #[serde(skip)] pub(crate) cancelled_drag: bool, + /// The saved path whose anchors the first Escape hid (#13072): the next Escape deactivates it, + /// and targeting another path starts at the first Escape again. + #[serde(skip)] + pub(crate) escape_hidden: Option, /// Path Selection only: the target path's [`crate::path_components::SelectionSignature`] when /// the selection was made — a structural identity that survives history revisions (a click /// activates the layer, colours change, components move), so the component selection lives /// until the path's structure changes (#10854). #[serde(skip)] pub(crate) signature: Option, + /// Where a ⌥-press with Delete Anchor Point hit an anchor: its release without a drag selects + /// the anchor's subpath (`anchor_tools`). + #[serde(skip)] + pub(crate) subpath_press: Option<[f64; 2]>, } /// The cached structural check for one document revision. Type Paths are generated only when @@ -263,26 +275,33 @@ pub enum Edit { /// A handle, where it was at the press, and whether it moves alone (⌥). Handle([usize; 2], Handle, Point, bool), Segment([usize; 2], f64), + /// The Convert Point tool dragging a whole selected path by a segment: its anchors, all of them. + Path(Vec<[usize; 2]>), /// Pen + ⌥ on an anchor: a click makes a corner, a drag pulls out smooth handles. Convert([usize; 2]), } impl Edit { - /// The drag's end with ⇧ held: moving anchors locks to multiples of 45°, as in Photoshop (#5475). + /// The drag's end with ⇧ held: moving anchors locks to multiples of 45°, as in Photoshop (#5475), + /// with the measured (+60, -25) drag kept on the axis (#13207). fn constrain(&self, start: [f64; 2], p: [f64; 2], shift: bool) -> [f64; 2] { - if shift && matches!(self, Edit::Anchors(_)) { crate::stroke_constraint::snap45(start, p) } else { p } + if shift && matches!(self, Edit::Anchors(_)) { crate::stroke_constraint::snap45_anchor(start, p) } else { p } } /// The edit for a drag from `start` to `end`, as a command and its params (without target). fn command(&self, start: [f64; 2], end: [f64; 2]) -> (&'static str, Value) { let d = [end[0] - start[0], end[1] - start[1]]; match self { + // One anchor is "Drag Anchor Point" in History, two or more the default "Drag Anchor + // Points", as in Photoshop (#13205). + Edit::Anchors(a) if a.len() == 1 => ("path.moveAnchors", json!({"anchors": a, "move": d, "stepName": "Drag Anchor Point"})), Edit::Anchors(a) => ("path.moveAnchors", json!({"anchors": a, "move": d})), Edit::Curvature(a) => ("path.moveAnchors", json!({"anchors": a, "move": d, "curvature": true})), Edit::Handle([s, k], h, from, independent) => { ("path.moveHandle", json!({"subpath": s, "knot": k, "handle": h.name(), "to": [from.x + d[0], from.y + d[1]], "independent": independent})) } Edit::Segment([s, k], t) => ("path.bendSegment", json!({"subpath": s, "knot": k, "t": t, "move": d})), + Edit::Path(a) => ("path.moveAnchors", json!({"anchors": a, "move": d, "stepName": "Drag Path"})), Edit::Convert([s, k]) => ("path.convertPoint", json!({"subpath": s, "knot": k, "out": end})), } } @@ -292,7 +311,7 @@ impl Edit { let d = [end[0] - start[0], end[1] - start[1]]; let mut p = base.clone(); match self { - Edit::Anchors(a) => edit::move_anchors(&mut p, a, d), + Edit::Anchors(a) | Edit::Path(a) => edit::move_anchors(&mut p, a, d), Edit::Curvature(a) => edit::move_anchors_curvature(&mut p, a, d), Edit::Handle(k, h, from, independent) => edit::move_handle(&mut p, *k, *h, Point::new(from.x + d[0], from.y + d[1]), *independent), Edit::Segment(k, t) => edit::bend_segment(&mut p, *k, *t, d), @@ -304,9 +323,11 @@ impl Edit { } /// Is Direct Selection what the pointer does now: its own tool, or a Pen (the Pen, Freeform Pen -/// or Curvature Pen), an anchor point tool or Convert Point with ⌘/Ctrl held. +/// or Curvature Pen), an anchor point tool or Convert Point with ⌘/Ctrl held, or Path Selection +/// with ⌘/Ctrl alone (#13284; with ⌥ or ⇧ too, the reference was not measured, so as today). fn direct(tool: Tool, mods: Modifiers) -> bool { tool == Tool::DirectSelection + || (tool == Tool::PathSelection && mods.command && !mods.alt && !mods.shift) || (matches!(tool, Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint) && mods.command) } @@ -352,6 +373,15 @@ pub fn shows(app: &PhotocraftApp, mods: Modifiers) -> bool { || (app.ui.tool == Tool::Pen && app.ui.pen.is_none() && !ds.anchors.is_empty() && still_valid(app, ds)) } +/// Are the anchors of subpath `s` of `r` drawn now (#12769)? +pub(crate) fn anchors_shown(app: &PhotocraftApp, r: PathRef, s: usize) -> bool { + let ds = &app.ui.direct_selection; + if ds.target != Some(r) || !still_valid(app, ds) { + return true; + } + ds.shown.as_ref().is_none_or(|shown| shown.contains(&s)) +} + /// The active paths, front first: the targeted vector mask, the active shape layer's path or the /// active type layer's Type Path (#9114), then the work path. The Pen's Auto Add/Delete edits these /// (`anchor_tools::pen_auto`). @@ -433,37 +463,12 @@ pub(crate) fn hit_target(app: &PhotocraftApp, p: [f64; 2], handles: bool) -> Opt pub(crate) fn hit_active(app: &PhotocraftApp, p: [f64; 2]) -> Option<(PathRef, Path, Hit)> { let tol = 6.0 / f64::from(app.point_zoom().max(0.01)); let st = app.session.active()?; - // A path selected in the Paths panel (saved or Work Path) is the only target; otherwise the Pen draft first (as - // `candidates` builds it), then the active paths. The draft's destination is private to - // `vector_ui`, so it is not filtered here. + // A path selected in the Paths panel (saved or Work Path) is the only target; otherwise `targeted`. let targets: Vec<(PathRef, Path)> = match crate::vector_ui::selected_saved_path_index(app) { Some((i, path)) => Some((PathRef::Saved(i), path)).filter(|(r, _)| writable(app, r)).into_iter().collect(), // The Work Path selected in the Paths panel is the only target too, as for Path Selection. None if app.ui.selected_path.as_deref() == Some("work") => active_paths(app).into_iter().filter(|(r, _)| *r == PathRef::Work).collect(), - None => { - let pen = app - .ui - .pen - .as_ref() - .filter(|_| app.ui.pen_doc.is_none_or(|owner| Some(owner) == Some(st.doc.id))) - .filter(|p| !p.dragging && !p.knots.is_empty()) - .map(|p| (PathRef::Pen, crate::vector_ui::pen_path(p))); - let mut out: Vec<(PathRef, Path)> = pen.into_iter().chain(active_paths(app)).collect(); - // Not measured (#12762, #12705): a shape layer inside a group keeps today's behaviour. Every shown, - // unlocked one stays a target after the targeted paths, front first, as `candidates` lists it. - // A top-level shape layer (depth 0) is a target only as the active layer. - let layers = st.doc.walk(); - let grouped = layers.iter().rev().filter(|(at, depth, _)| *depth > 0 && st.doc.shown_at(at)).filter_map(|(_, _, l)| match &l.content { - photocraft_doc::LayerContent::Shape(sh) => Some((PathRef::Layer(l.id.0), sh.path.clone())), - _ => None, - }); - for (r, path) in grouped { - if writable(app, &r) && !out.iter().any(|(have, _)| *have == r) { - out.push((r, path)); - } - } - out - } + None => targeted(app), }; targets .into_iter() @@ -471,6 +476,67 @@ pub(crate) fn hit_active(app: &PhotocraftApp, p: [f64; 2]) -> Option<(PathRef, P .find_map(|(r, path)| edit::hit(&path, Point::new(p[0], p[1]), tol, &[]).map(|h| (r, path, h))) } +/// The Pen draft (as `candidates` builds it), then the active paths, then (not measured, so as today, +/// #12762, #12705) every shown, unlocked shape layer inside a group, front first. A top-level shape +/// layer is a target only as the active layer. +fn targeted(app: &PhotocraftApp) -> Vec<(PathRef, Path)> { + let Some(st) = app.session.active() else { + return Vec::new(); + }; + // The draft's destination is private to `vector_ui`, so it is not filtered here. + let pen = app + .ui + .pen + .as_ref() + .filter(|_| app.ui.pen_doc.is_none_or(|owner| Some(owner) == Some(st.doc.id))) + .filter(|p| !p.dragging && !p.knots.is_empty()) + .map(|p| (PathRef::Pen, crate::vector_ui::pen_path(p))); + let mut out: Vec<(PathRef, Path)> = pen.into_iter().chain(active_paths(app)).collect(); + let layers = st.doc.walk(); + let grouped = layers.iter().rev().filter(|(at, depth, _)| *depth > 0 && st.doc.shown_at(at)).filter_map(|(_, _, l)| match &l.content { + photocraft_doc::LayerContent::Shape(sh) => Some((PathRef::Layer(l.id.0), sh.path.clone())), + _ => None, + }); + for (r, path) in grouped { + if writable(app, &r) && !out.iter().any(|(have, _)| *have == r) { + out.push((r, path)); + } + } + out +} + +/// What a Convert Point tool press at `p` works on: `hit_target` over the targeted paths only, so a +/// top-level shape layer that is not active is left alone (#12735). Not measured, so as today: a +/// shape layer inside a group, a hidden active layer, the active layer's path behind a path +/// selected in the Paths panel, and a Work Path hidden after ⌘↩ or Load as Selection (#8459). +fn hit_converting(app: &PhotocraftApp, p: [f64; 2]) -> Option<(PathRef, Path, Hit)> { + let zoom = f64::from(app.point_zoom().max(0.01)); + let tol = 6.0 / zoom; + // An anchor is in reach within 5 points (5 screen px at display scale 1, as measured, #12748); + // other display scales weren't measured and keep the points unit, like every canvas tolerance. + // The 0.01 point covers the f32 screen-to-document mapping, so a press 5 px away always hits. + // Shown handles and segments weren't measured and keep `tol`. + let reach = 5.01 / zoom; + let beyond = |path: &Path, k: [usize; 2]| { + path.subpaths.get(k[0]).and_then(|s| s.knots.get(k[1])).is_some_and(|kn| (kn.anchor.x - p[0]).hypot(kn.anchor.y - p[1]) > reach) + }; + let ds = &app.ui.direct_selection; + let valid = still_valid(app, ds); + let mut paths = targeted(app); + if !paths.iter().any(|(r, _)| *r == PathRef::Work) { + paths.extend(app.session.active().and_then(|st| st.doc.work_path.clone()).map(|p| (PathRef::Work, p))); + } + paths + .into_iter() + .find_map(|(r, path)| { + let shown = if valid && ds.target.as_ref() == Some(&r) { shown_handles(ds, &path) } else { Vec::new() }; + edit::hit(&path, Point::new(p[0], p[1]), tol.max(reach), &shown).map(|h| (r, path, h)) + }) + // The front path's anchor out of reach swallows the press, as today, rather than handing it + // to a path behind. + .filter(|(_, path, h)| !matches!(h, Hit::Anchor(k) if beyond(path, *k))) +} + fn retracted(k: &photocraft_doc::Knot, h: Handle) -> bool { let c = if h == Handle::In { k.in_ctrl } else { k.out_ctrl }; (c.x - k.anchor.x).abs() < 1e-9 && (c.y - k.anchor.y).abs() < 1e-9 @@ -576,7 +642,9 @@ fn hits_pen(app: &PhotocraftApp, p: [f64; 2]) -> bool { /// that hit nothing; the Convert Point tool has nothing else to do, so it keeps the press. fn press(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers, convert: bool) -> bool { let own_tool = app.ui.tool == Tool::ConvertPoint; - let Some((target, base, hit)) = hit_target(app, p, true) else { + // The tool's ⌘ is Direct Selection, which still reaches every visible shape layer. + let hit = if own_tool && convert { hit_converting(app, p) } else { hit_target(app, p, true) }; + let Some((target, base, hit)) = hit else { if convert { return own_tool; } @@ -592,6 +660,7 @@ fn press(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers, convert: bool) - let _ = app.run("layer.select", json!({"layer": id})); } let owner = Owner::current(app); + let tool_is_path_selection = app.ui.tool == Tool::PathSelection; let ds = &mut app.ui.direct_selection; if ds.target.as_ref() != Some(&target) { *ds = DirectSelection { target: Some(target), ..Default::default() }; @@ -612,8 +681,21 @@ fn press(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers, convert: bool) - } Edit::Convert(k) } - // Pen + ⌥ on a segment does nothing. - Hit::Segment(..) if convert => return true, + // Pen + ⌥ on a segment does nothing; so does the tool where the reference was not + // measured: with ⇧ or ⌥, on a curve, or with part of the path selected. + Hit::Segment(k, t) if convert => { + if !own_tool || mods.alt || mods.shift || !straight(&base, k) { + return true; + } + let all: Vec<[usize; 2]> = (0..base.subpaths.len()).flat_map(|s| edit::subpath_anchors(&base, s)).collect(); + if ds.anchors.is_empty() { + Edit::Segment(k, t) + } else if all.iter().all(|a| ds.anchors.contains(a)) { + Edit::Path(all) + } else { + return true; + } + } Hit::Anchor(k) => { ds.segment = None; if mods.alt { @@ -625,7 +707,9 @@ fn press(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers, convert: bool) - return true; } ds.anchors.push(k); - } else if !ds.anchors.contains(&k) { + } else if !ds.anchors.contains(&k) || tool_is_path_selection { + // Path Selection's ⌘/Ctrl moves the anchor pressed alone, not the selected + // component it belongs to (#13284). ds.anchors = vec![k]; } Edit::Anchors(ds.anchors.clone()) @@ -645,6 +729,18 @@ fn press(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers, convert: bool) - true } +/// Is the segment leaving knot `k` straight: both of its handles retracted? The distance test is +/// the one `edit::bend_segment` uses, so a segment counted straight here moves as straight there. +fn straight(path: &Path, [s, k]: [usize; 2]) -> bool { + let Some(sub) = path.subpaths.get(s) else { return false }; + let next = if k + 1 < sub.knots.len() { k + 1 } else { 0 }; + let near = |c: Point, a: Point| (c.x - a.x).hypot(c.y - a.y) < 1e-9; + match (sub.knots.get(k), sub.knots.get(next)) { + (Some(a), Some(b)) => near(a.out_ctrl, a.anchor) && near(b.in_ctrl, b.anchor), + _ => false, + } +} + /// What the idle Curvature Pen has under document point `p` on the active paths: an anchor or a /// segment, with the path it is on. Handles don't count. fn curvature_target(app: &PhotocraftApp, p: [f64; 2]) -> Option<(PathRef, Path, Hit)> { @@ -730,10 +826,15 @@ pub(crate) fn grab_added(app: &mut PhotocraftApp, target: PathRef, base: Path, k app.ui.direct_selection.drag = Some(Drag::Edit { target, base, edit: Edit::Anchors(vec![k]), start: p, end: p, preview: None }); } +/// Did the pointer move between `start` and `end` (document points): a screen pixel or more? +pub(crate) fn moved(app: &PhotocraftApp, start: [f64; 2], end: [f64; 2]) -> bool { + (end[0] - start[0]).hypot(end[1] - start[1]) * f64::from(app.point_zoom()) >= 1.0 +} + /// End of an edit drag: commit it as one command. A click (no movement) commits nothing, except /// Pen + ⌥ on an anchor, which makes it a corner. The Pen path being drawn takes the edit directly. fn release(app: &mut PhotocraftApp, target: PathRef, base: &Path, edit: &Edit, start: [f64; 2], end: [f64; 2], mods: Modifiers) { - let moved = (end[0] - start[0]).hypot(end[1] - start[1]) * f64::from(app.point_zoom()) >= 1.0; + let moved = moved(app, start, end); if target == PathRef::Pen { let edited = match edit { Edit::Convert(k) if !moved => { @@ -882,7 +983,7 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, to_scr: &dyn F crate::vector_ui::draw_handle(painter, to_scr([kn.anchor.x, kn.anchor.y]), to_scr([c.x, c.y]), accent); } } - for (s, sp) in path.subpaths.iter().enumerate() { + for (s, sp) in path.subpaths.iter().enumerate().filter(|(s, _)| !ours || anchors_shown(app, r, *s)) { for (k, kn) in sp.knots.iter().enumerate() { crate::vector_ui::draw_anchor(painter, to_scr([kn.anchor.x, kn.anchor.y]), ours && ds.anchors.contains(&[s, k]), accent); } @@ -900,6 +1001,21 @@ mod tests; #[cfg(test)] mod convert_point_history_tests; +#[cfg(test)] +mod convert_point_targeted_path_tests; + +#[cfg(test)] +mod convert_point_tolerance_tests; + +#[cfg(test)] +mod convert_point_drag_segment_tests; + +#[cfg(test)] +mod history_names_tests; + +#[cfg(test)] +mod shift_angle_tests; + #[cfg(test)] mod freeform_command_tests { use super::*; diff --git a/crates/ui-egui/src/tools/direct_select/convert_point_drag_segment_tests.rs b/crates/ui-egui/src/tools/direct_select/convert_point_drag_segment_tests.rs new file mode 100644 index 0000000000..33290ed703 --- /dev/null +++ b/crates/ui-egui/src/tools/direct_select/convert_point_drag_segment_tests.rs @@ -0,0 +1,172 @@ +//! #12741: a drag that starts on a segment with the Convert Point tool works as a temporary +//! Direct Selection, as in the reference: with nothing selected the straight segment moves +//! ("Drag Segment"), with the whole path selected the whole path moves ("Drag Path"). A click, +//! and the cases the reference was not measured on, do nothing. + +use egui::Modifiers; +use photocraft_doc::vector::Path; +use photocraft_geom::Point; +use serde_json::json; + +use super::convert_point_history_tests::{added, click, drag}; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +const BOTTOM_EDGE: [f64; 2] = [200.0, 500.0]; + +/// The reference document: 800×600 px with a saved path, targeted in the Paths panel: a closed +/// corner square, an open straight line and an open S-curve of two smooth points. +fn app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 800, "height": 600})).unwrap(); + let path = json!({"subpaths": [ + {"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}, + {"knots": [[400, 300], [700, 300]]}, + {"knots": [ + {"anchor": [400, 450], "in": [300, 550], "out": [500, 350], "smooth": true}, + {"anchor": [700, 450], "in": [600, 550], "out": [800, 350], "smooth": true}, + ]}, + ]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); + app.sync_views(); + app.ui.tool = tool; + app +} + +fn path(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths[0].path.clone() +} + +/// `p` with knots `which` (all when `None`) moved by `d`, handles included. +fn moved(p: &Path, which: Option<&[[usize; 2]]>, d: [f64; 2]) -> Path { + let mut p = p.clone(); + for (s, sub) in p.subpaths.iter_mut().enumerate() { + for (k, kn) in sub.knots.iter_mut().enumerate() { + if which.is_none_or(|w| w.contains(&[s, k])) { + for q in [&mut kn.anchor, &mut kn.in_ctrl, &mut kn.out_ctrl] { + *q = Point::new(q.x + d[0], q.y + d[1]); + } + } + } + } + p +} + +/// Every anchor of the path selected, by a ⌘-marquee (Direct Selection in this tool). +fn select_all(app: &mut PhotocraftApp) { + drag(app, [0.0, 0.0], [800.0, 600.0], Modifiers::COMMAND); + assert_eq!(app.ui.direct_selection.anchors.len(), 8); +} + +#[test] +fn with_nothing_selected_a_segment_drag_moves_only_that_segment() { + let mut app = app(Tool::ConvertPoint); + let before = path(&app); + let steps = added(&mut app, |a| drag(a, BOTTOM_EDGE, [200.0, 540.0], Modifiers::NONE)); + assert_eq!(steps, ["Drag Segment"]); + let after = path(&app); + assert_eq!(after.subpaths[0].knots[2].anchor, Point::new(300.0, 540.0)); + assert_eq!(after.subpaths[0].knots[3].anchor, Point::new(100.0, 540.0)); + assert_eq!(after, moved(&before, Some(&[[0, 2], [0, 3]]), [0.0, 40.0]), "the other anchors stay"); + assert!(app.session.undo()); + assert_eq!(path(&app), before); +} + +#[test] +fn the_closing_segment_of_a_closed_subpath_moves_too() { + let mut app = app(Tool::ConvertPoint); + let before = path(&app); + assert_eq!(added(&mut app, |a| drag(a, [100.0, 400.0], [60.0, 400.0], Modifiers::NONE)), ["Drag Segment"]); + assert_eq!(path(&app), moved(&before, Some(&[[0, 3], [0, 0]]), [-40.0, 0.0])); +} + +#[test] +fn with_the_whole_path_selected_a_segment_drag_moves_the_whole_path() { + let mut app = app(Tool::ConvertPoint); + select_all(&mut app); + let before = path(&app); + let steps = added(&mut app, |a| drag(a, BOTTOM_EDGE, [200.0, 540.0], Modifiers::NONE)); + assert_eq!(steps, ["Drag Path"]); + assert_eq!(path(&app), moved(&before, None, [0.0, 40.0]), "all three subpaths moved"); + assert_eq!(app.ui.direct_selection.anchors.len(), 8, "the selection stays"); +} + +#[test] +fn a_click_on_a_segment_does_nothing() { + for all in [false, true] { + let mut app = app(Tool::ConvertPoint); + if all { + select_all(&mut app); + } + let (before, selection) = (path(&app), app.ui.direct_selection.anchors.clone()); + assert!(added(&mut app, |a| click(a, BOTTOM_EDGE, Modifiers::NONE)).is_empty(), "all selected: {all}"); + assert_eq!((path(&app), &app.ui.direct_selection.anchors), (before, &selection)); + assert!(app.ui.direct_selection.drag.is_none()); + } +} + +#[test] +fn unmeasured_segment_drags_still_do_nothing() { + let nothing = |mut app: PhotocraftApp, from: [f64; 2], mods: Modifiers, what: &str| { + let before = path(&app); + let steps = added(&mut app, |a| drag(a, from, [from[0], from[1] + 40.0], mods)); + assert!(steps.is_empty(), "{what}: {steps:?}"); + assert_eq!(path(&app), before, "{what}"); + }; + nothing(app(Tool::ConvertPoint), [550.0, 450.0], Modifiers::NONE, "a curved segment"); + let mut all = app(Tool::ConvertPoint); + select_all(&mut all); + nothing(all, [550.0, 450.0], Modifiers::NONE, "a curved segment, the whole path selected"); + nothing(app(Tool::ConvertPoint), BOTTOM_EDGE, Modifiers::SHIFT, "⇧"); + nothing(app(Tool::ConvertPoint), BOTTOM_EDGE, Modifiers::ALT, "⌥"); + let mut some = app(Tool::ConvertPoint); + click(&mut some, [100.0, 300.0], Modifiers::COMMAND); + assert_eq!(some.ui.direct_selection.anchors, vec![[0, 0]]); + nothing(some, BOTTOM_EDGE, Modifiers::NONE, "part of the path selected"); + + // Pen + ⌥ on a segment is the Pen's own: it adds an anchor there, and the segment stays. + let mut pen = app(Tool::Pen); + assert_eq!(added(&mut pen, |a| drag(a, BOTTOM_EDGE, [200.0, 540.0], Modifiers::ALT)), ["Add Anchor Point"]); + let bottom = &path(&pen).subpaths[0].knots; + assert!(bottom.iter().all(|k| k.anchor.y <= 500.0), "the segment did not move: {bottom:?}"); +} + +#[test] +fn direct_selection_segment_drags_keep_their_behaviour() { + for all in [false, true] { + let mut app = app(Tool::DirectSelection); + if all { + select_all(&mut app); + } + let before = path(&app); + assert_eq!(added(&mut app, |a| drag(a, BOTTOM_EDGE, [200.0, 540.0], Modifiers::NONE)), ["Drag Segment"]); + assert_eq!(path(&app), moved(&before, Some(&[[0, 2], [0, 3]]), [0.0, 40.0]), "all selected: {all}"); + } +} + +#[test] +fn a_command_anchor_drag_released_without_command_keeps_its_own_step_name() { + let mut app = app(Tool::ConvertPoint); + select_all(&mut app); + tool_event(&mut app, ToolEvent::Down { x: 300.0, y: 300.0, pressure: 1.0 }, Modifiers::COMMAND); + tool_event(&mut app, ToolEvent::Move { x: 320.0, y: 300.0, pressure: 1.0 }, Modifiers::COMMAND); + let steps = added(&mut app, |a| { + tool_event(a, ToolEvent::Up { x: 320.0, y: 300.0 }, Modifiers::NONE); + }); + assert_eq!(steps, ["Drag Anchor Points"]); +} + +#[test] +fn move_anchors_takes_the_drag_path_step_name_and_refuses_any_other() { + let mut app = app(Tool::ConvertPoint); + let params = |name: serde_json::Value| json!({"name": "Path 1", "anchors": [[0, 0]], "move": [1, 1], "stepName": name}); + assert_eq!(added(&mut app, |a| a.run("path.moveAnchors", params(json!("Drag Path"))).map(|_| ()).unwrap()), ["Drag Path"]); + let before = path(&app); + for bad in [json!("Drag Segment"), json!("Drag Path "), json!(1)] { + let e = app.run("path.moveAnchors", params(bad.clone())).unwrap_err(); + assert!(e.contains("stepName"), "{bad}: {e}"); + } + assert_eq!(path(&app), before); +} diff --git a/crates/ui-egui/src/tools/direct_select/convert_point_history_tests.rs b/crates/ui-egui/src/tools/direct_select/convert_point_history_tests.rs index 7bdabd5dbc..a9e3752975 100644 --- a/crates/ui-egui/src/tools/direct_select/convert_point_history_tests.rs +++ b/crates/ui-egui/src/tools/direct_select/convert_point_history_tests.rs @@ -29,13 +29,13 @@ fn with_path(app: &mut PhotocraftApp) { app.run("path.set", json!({"name": "work", "path": path})).unwrap(); } -fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { +pub(super) fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods); tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods); tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods); } -fn click(app: &mut PhotocraftApp, at: [f64; 2], mods: Modifiers) { +pub(super) fn click(app: &mut PhotocraftApp, at: [f64; 2], mods: Modifiers) { drag(app, at, at, mods); } @@ -44,7 +44,7 @@ fn names(app: &PhotocraftApp) -> Vec { } /// Runs `gesture` and returns the History steps it added. -fn added(app: &mut PhotocraftApp, gesture: impl FnOnce(&mut PhotocraftApp)) -> Vec { +pub(super) fn added(app: &mut PhotocraftApp, gesture: impl FnOnce(&mut PhotocraftApp)) -> Vec { let n = names(app).len(); gesture(app); names(app).split_off(n) @@ -128,7 +128,7 @@ fn mask_corner(app: &PhotocraftApp) -> photocraft_doc::Knot { #[test] fn other_tools_keep_their_step_names() { - let direct = vec!["Drag Direction Point".to_string()]; + let direct = vec!["Drag Control Point".to_string()]; for mods in [Modifiers::NONE, Modifiers::ALT] { let mut ds = with_shown_handles(Tool::DirectSelection); assert_eq!(added(&mut ds, |a| drag(a, [140.0, 40.0], [140.0, 70.0], mods)), direct, "Direct Selection {mods:?}"); @@ -157,7 +157,7 @@ fn the_commands_take_the_step_name_and_refuse_any_other() { let handle = json!({"subpath": 0, "knot": 1, "handle": "out", "to": [150, 60], "independent": true}); let mut run = |id: &str, params: &serde_json::Value| added(&mut app, |a| a.run(id, params.clone()).map(|_| ()).unwrap()); assert_eq!(run("path.convertPoint", &convert), ["Convert Point"]); - assert_eq!(run("path.moveHandle", &handle), ["Drag Direction Point"]); + assert_eq!(run("path.moveHandle", &handle), ["Drag Control Point"]); let named = |p: &serde_json::Value, n: &str| { let mut p = p.clone(); p["stepName"] = json!(n); @@ -179,7 +179,7 @@ fn a_bad_step_name_is_an_error_and_changes_nothing() { let e = app.run("path.convertPoint", json!({"subpath": 0, "knot": 1, "stepName": bad})).unwrap_err(); assert!(e.contains("stepName"), "{bad}: {e}"); } - for bad in [json!("Change Anchor Point"), json!("Drag Direction Point"), json!(0), json!({})] { + for bad in [json!("Change Anchor Point"), json!("Drag Control Point"), json!(0), json!({})] { let e = app.run("path.moveHandle", json!({"subpath": 0, "knot": 1, "handle": "out", "to": [150, 60], "stepName": bad})).unwrap_err(); assert!(e.contains("stepName"), "{bad}: {e}"); } diff --git a/crates/ui-egui/src/tools/direct_select/convert_point_targeted_path_tests.rs b/crates/ui-egui/src/tools/direct_select/convert_point_targeted_path_tests.rs new file mode 100644 index 0000000000..07189ea4bd --- /dev/null +++ b/crates/ui-egui/src/tools/direct_select/convert_point_targeted_path_tests.rs @@ -0,0 +1,101 @@ +//! #12735: the Convert Point tool converts anchors on the targeted path only: the path selected in +//! the Paths panel or the active shape layer's. A shape layer that is not active is left alone. + +use egui::Modifiers; +use serde_json::{Value, json}; + +use super::PathRef; +use super::convert_point_history_tests::drag; +use crate::PhotocraftApp; +use crate::anchor_tools::delete_anchor_targeted_path_tests::{group_shape, select_layer, select_saved_path, setup, shape_path, steps}; +use crate::state::Tool; + +const CORNER: [f64; 2] = [450.0, 100.0]; +const PULLED: [f64; 2] = [490.0, 70.0]; + +fn active(app: &PhotocraftApp) -> Option { + app.session.active().unwrap().active_layer.map(|l| l.0) +} + +/// The shape's knot at `CORNER`. +fn corner(app: &mut PhotocraftApp, shape: u64) -> Value { + let path = shape_path(app, shape); + let knots = path["subpaths"][0]["knots"].as_array().unwrap(); + knots.iter().find(|k| k["anchor"] == json!([450.0, 100.0])).unwrap().clone() +} + +/// The gesture leaves the shape, the active layer and History as they were. +fn changes_nothing(app: &mut PhotocraftApp, shape: u64, gesture: impl FnOnce(&mut PhotocraftApp)) { + let (before, layer, n) = (shape_path(app, shape), active(app), steps(app)); + gesture(app); + assert_eq!(shape_path(app, shape), before); + assert_eq!(active(app), layer); + assert_eq!(steps(app), n); +} + +#[test] +fn a_drag_from_the_corner_of_a_shape_that_is_not_active_changes_nothing() { + let (mut app, shape) = setup(Tool::ConvertPoint); + changes_nothing(&mut app, shape, |app| drag(app, CORNER, PULLED, Modifiers::NONE)); +} + +#[test] +fn a_drag_from_the_corner_of_the_active_shape_converts_it() { + let (mut app, shape) = setup(Tool::ConvertPoint); + select_layer(&mut app, shape); + let n = steps(&app); + drag(&mut app, CORNER, PULLED, Modifiers::NONE); + let knot = corner(&mut app, shape); + assert_eq!(knot["out"], json!([490.0, 70.0])); + assert_eq!(knot["in"], json!([410.0, 130.0])); + assert_eq!(steps(&app), n + 1); + assert_eq!(active(&app), Some(shape)); +} + +#[test] +fn with_a_saved_path_selected_a_press_on_the_corner_of_a_shape_that_is_not_active_does_nothing() { + let (mut app, shape) = setup(Tool::ConvertPoint); + select_saved_path(&mut app); + changes_nothing(&mut app, shape, |app| drag(app, CORNER, CORNER, Modifiers::NONE)); + changes_nothing(&mut app, shape, |app| drag(app, CORNER, PULLED, Modifiers::NONE)); +} + +#[test] +fn command_is_still_direct_selection_on_a_shape_that_is_not_active() { + let (mut app, shape) = setup(Tool::ConvertPoint); + drag(&mut app, CORNER, CORNER, Modifiers::COMMAND); + assert_eq!(app.ui.direct_selection.target, Some(PathRef::Layer(shape))); +} + +#[test] +fn direct_selection_still_edits_a_shape_layer_that_is_not_active() { + let (mut app, shape) = setup(Tool::DirectSelection); + drag(&mut app, CORNER, CORNER, Modifiers::NONE); + assert_eq!(app.ui.direct_selection.target, Some(PathRef::Layer(shape))); +} + +#[test] +fn a_shape_inside_a_group_that_is_not_active_keeps_todays_behaviour() { + let (mut app, shape) = setup(Tool::ConvertPoint); + group_shape(&mut app, shape); + let n = steps(&app); + drag(&mut app, CORNER, PULLED, Modifiers::NONE); + assert_eq!(corner(&mut app, shape)["out"], json!([490.0, 70.0])); + assert_eq!(steps(&app), n + 1); +} + +#[test] +fn a_work_path_that_is_not_shown_still_converts_as_today() { + let (mut app, _) = setup(Tool::ConvertPoint); + let path = json!({"subpaths": [{"closed": true, "knots": [[50, 450], [150, 450], [150, 550], [50, 550]]}]}); + app.run("path.set", json!({"path": path})).unwrap(); + // As after ⌘↩ or Load as Selection on the Work Path (#8459). + crate::vector_ui::deselect_loaded_path(&mut app, "work"); + assert!(!crate::vector_ui::work_path_shown(&app)); + let n = steps(&app); + drag(&mut app, [50.0, 450.0], [90.0, 420.0], Modifiers::NONE); + assert_eq!(steps(&app), n + 1); + let work = app.session.active().unwrap().doc.work_path.clone().unwrap(); + let knot = &work.subpaths[0].knots[0]; + assert_eq!((knot.out_ctrl.x, knot.out_ctrl.y), (90.0, 420.0)); +} diff --git a/crates/ui-egui/src/tools/direct_select/convert_point_tolerance_tests.rs b/crates/ui-egui/src/tools/direct_select/convert_point_tolerance_tests.rs new file mode 100644 index 0000000000..1b84d71c43 --- /dev/null +++ b/crates/ui-egui/src/tools/direct_select/convert_point_tolerance_tests.rs @@ -0,0 +1,158 @@ +//! #12748: the Convert Point tool hits an anchor within 5 points, as measured at display scale 1: +//! at 100 % a press 5 px from an anchor converts it and one 6 px away does nothing; at 200 % that +//! is 2.5 document px. Other display scales weren't measured and scale it as every canvas +//! tolerance. Direct Selection, the Pen's ⌥ and the tool's shown handles keep their 6 points. + +use egui::{Modifiers, Pos2, Rect, vec2}; +use photocraft_doc::Knot; +use photocraft_doc::vector::Path; +use serde_json::json; + +use super::convert_point_history_tests::drag; +use crate::PhotocraftApp; +use crate::anchor_tools::delete_anchor_targeted_path_tests::{group_shape, setup, shape_path, steps}; +use crate::canvas::ViewXform; +use crate::state::Tool; + +/// The measured document: 800 × 600 px with a closed corner square as the Work Path, shown at +/// `zoom` (device pixels per document pixel) on a display of `ppp` device pixels per point. +fn app(tool: Tool, zoom: f32, ppp: f32) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = zoom; + app.ppp = ppp; + app.ui.tool = tool; + let path = json!({"subpaths": [{"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}]}); + app.run("path.set", json!({"name": "work", "path": path})).unwrap(); + app +} + +fn work(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.work_path.clone().unwrap() +} + +/// Does a drag that starts `dx` document px left of the corner (100, 300) pull out its handles, +/// in one History step? +fn converts_from(app: &mut PhotocraftApp, dx: f64) -> bool { + let n = steps(app); + drag(app, [100.0 - dx, 300.0], [100.0 - dx, 340.0], Modifiers::NONE); + let corner = work(app).subpaths[0].knots[0]; + if corner == Knot::corner(100.0, 300.0) { + assert_eq!(steps(app), n, "a press that converts nothing adds no step"); + return false; + } + assert_eq!(steps(app), n + 1); + true +} + +#[test] +fn at_100_percent_a_press_5_px_from_an_anchor_converts_it_and_6_px_does_nothing() { + assert!(converts_from(&mut app(Tool::ConvertPoint, 1.0, 1.0), 5.0)); + assert!(!converts_from(&mut app(Tool::ConvertPoint, 1.0, 1.0), 6.0)); +} + +/// Not measured: the reach stays in points, so 5 points are 6.25 px at display scale 1.25 and +/// 10 px at 2 (6 points were 7.5 and 12 px). +#[test] +fn the_reach_is_5_points_on_any_display_scale() { + for (ppp, inside, outside) in [(1.25, 6.25, 6.5), (2.0, 10.0, 11.0)] { + assert!(converts_from(&mut app(Tool::ConvertPoint, 1.0, ppp), inside), "{inside} px at display scale {ppp}"); + assert!(!converts_from(&mut app(Tool::ConvertPoint, 1.0, ppp), outside), "{outside} px at display scale {ppp}"); + } +} + +/// A press 5 or 6 points left of the corner, mapped to the document as the canvas maps it, on views +/// panned to fractional centres: the f32 mapping never moves the 5-point press out of reach. +#[test] +fn a_press_mapped_from_the_screen_5_points_away_converts_and_6_does_nothing() { + for ppp in [1.0, 1.25] { + for i in 0..40u8 { + let center = [100.0 + f32::from(i) * 7.31, 300.0 - f32::from(i) * 3.17]; + for (pt, converts) in [(5.0, true), (6.0, false)] { + let mut app = app(Tool::ConvertPoint, 1.0, ppp); + app.last_canvas_rect = Rect::from_min_size(Pos2::new(37.3, 61.9), vec2(1013.7, 707.1)); + app.ui.views[0].center = center; + let xf = ViewXform::active(&app).unwrap(); + let at = xf.to_doc(xf.to_screen(100.0, 300.0) - vec2(pt, 0.0)); + let n = steps(&app); + drag(&mut app, at, [at[0], at[1] + 40.0], Modifiers::NONE); + let changed = work(&app).subpaths[0].knots[0] != Knot::corner(100.0, 300.0); + assert_eq!(changed, converts, "{pt} points at display scale {ppp}, centre {center:?}, press at {at:?}"); + assert_eq!(steps(&app), n + usize::from(converts)); + } + } + } +} + +/// As today: the front path takes the press even when its anchor is just out of reach, so a path +/// behind with an anchor in reach (a shape inside a group) is not converted either. +#[test] +fn an_anchor_just_out_of_reach_swallows_the_press() { + let (mut app, shape) = setup(Tool::ConvertPoint); + group_shape(&mut app, shape); + let front = json!({"subpaths": [{"closed": false, "knots": [[441.5, 100], [441.5, 40]]}]}); + app.run("path.set", json!({"name": "work", "path": front})).unwrap(); + let (before, n) = (shape_path(&mut app, shape), steps(&app)); + // 5.5 px from the Work Path's anchor (441.5, 100), 3 px from the shape's corner (450, 100). + drag(&mut app, [447.0, 100.0], [447.0, 140.0], Modifiers::NONE); + assert_eq!(shape_path(&mut app, shape), before); + assert_eq!(work(&app).subpaths[0].knots[0], Knot::corner(441.5, 100.0)); + assert_eq!(steps(&app), n); +} + +#[test] +fn at_200_percent_the_reach_is_2_5_document_pixels() { + assert!(converts_from(&mut app(Tool::ConvertPoint, 2.0, 1.0), 2.5)); + assert!(!converts_from(&mut app(Tool::ConvertPoint, 2.0, 1.0), 3.0)); +} + +/// Not measured, so as today: the anchor's shown handles keep 6 points (12 px at display scale 2). +#[test] +fn a_shown_handle_keeps_its_6_points() { + let mut app = app(Tool::ConvertPoint, 1.0, 2.0); + drag(&mut app, [100.0, 300.0], [100.0, 340.0], Modifiers::NONE); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 0]], "the converted anchor's handles show"); + let n = steps(&app); + drag(&mut app, [111.0, 340.0], [140.0, 340.0], Modifiers::NONE); + let k = work(&app).subpaths[0].knots[0]; + assert_eq!((k.out_ctrl.x, k.out_ctrl.y), (129.0, 340.0), "the handle moved with the drag"); + assert_eq!((k.in_ctrl.x, k.in_ctrl.y), (100.0, 260.0), "alone"); + assert_eq!(steps(&app), n + 1); +} + +#[test] +fn direct_selection_keeps_its_6_points() { + for (ppp, dx) in [(1.0, 6.0), (2.0, 12.0)] { + let mut app = app(Tool::DirectSelection, 1.0, ppp); + drag(&mut app, [100.0 - dx, 300.0], [100.0 - dx, 300.0], Modifiers::NONE); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 0]], "{dx} px at display scale {ppp}"); + } +} + +#[test] +fn the_pens_alt_keeps_its_6_points() { + for (ppp, dx) in [(1.0, 6.0), (2.0, 12.0)] { + assert!(converts_from_with_alt(&mut app(Tool::Pen, 1.0, ppp), dx), "{dx} px at display scale {ppp}"); + } +} + +fn converts_from_with_alt(app: &mut PhotocraftApp, dx: f64) -> bool { + drag(app, [100.0 - dx, 300.0], [100.0 - dx, 340.0], Modifiers::ALT); + app.ui.pen.is_none() && work(app).subpaths[0].knots[0] != Knot::corner(100.0, 300.0) +} + +/// While drawing, ⌥ on the last anchor breaks its outgoing handle within 6 points (the Pen's reach +/// is strict, so 11.5 px at display scale 2). +#[test] +fn the_pens_alt_on_the_last_anchor_while_drawing_keeps_its_6_points() { + let mut app = app(Tool::Pen, 1.0, 2.0); + drag(&mut app, [500.0, 100.0], [500.0, 100.0], Modifiers::NONE); + drag(&mut app, [700.0, 100.0], [740.0, 100.0], Modifiers::NONE); + assert_eq!(app.ui.pen.as_ref().unwrap().knots[1][2], [740.0, 100.0]); + drag(&mut app, [688.5, 100.0], [688.5, 100.0], Modifiers::ALT); + let knots = app.ui.pen.as_ref().unwrap().knots.clone(); + assert_eq!(knots.len(), 2, "the press was on the last anchor: no anchor was added"); + assert_eq!(knots[1][0], [700.0, 100.0]); + assert_ne!(knots[1][2], [740.0, 100.0], "its outgoing handle was taken over"); +} diff --git a/crates/ui-egui/src/tools/direct_select/history_names_tests.rs b/crates/ui-egui/src/tools/direct_select/history_names_tests.rs new file mode 100644 index 0000000000..9c7b98bfad --- /dev/null +++ b/crates/ui-egui/src/tools/direct_select/history_names_tests.rs @@ -0,0 +1,57 @@ +//! #13205: a Direct Selection drag of one anchor is one History step "Drag Anchor Point", of two +//! or more "Drag Anchor Points"; a handle drag (with or without ⌥) is "Drag Control Point" and a +//! segment drag "Drag Segment". An arrow-key nudge of one anchor keeps today's name. + +use egui::Modifiers; +use serde_json::json; + +use super::convert_point_history_tests::{added, click, drag}; +use crate::PhotocraftApp; +use crate::state::Tool; + +/// A square work path; knot 1 at (120, 40) is smooth with handles at (100, 40) and (140, 40). +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::DirectSelection; + let path = json!({"subpaths": [{"closed": true, "knots": [ + [40, 40], + {"anchor": [120, 40], "in": [100, 40], "out": [140, 40], "smooth": true}, + [120, 120], + [40, 120], + ]}]}); + app.run("path.set", json!({"name": "work", "path": path})).unwrap(); + app +} + +#[test] +fn a_one_anchor_drag_is_drag_anchor_point() { + let mut app = app(); + assert_eq!(added(&mut app, |a| drag(a, [120.0, 120.0], [130.0, 130.0], Modifiers::NONE)), ["Drag Anchor Point"]); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 2]]); +} + +#[test] +fn a_drag_of_two_anchors_is_drag_anchor_points() { + let mut app = app(); + click(&mut app, [40.0, 120.0], Modifiers::NONE); + click(&mut app, [120.0, 120.0], Modifiers::SHIFT); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 3], [0, 2]]); + assert_eq!(added(&mut app, |a| drag(a, [120.0, 120.0], [120.0, 140.0], Modifiers::NONE)), ["Drag Anchor Points"]); +} + +#[test] +fn a_handle_drag_is_drag_control_point() { + for mods in [Modifiers::NONE, Modifiers::ALT] { + let mut app = app(); + click(&mut app, [120.0, 40.0], Modifiers::NONE); + assert_eq!(added(&mut app, |a| drag(a, [140.0, 40.0], [140.0, 70.0], mods)), ["Drag Control Point"], "{mods:?}"); + } +} + +#[test] +fn a_segment_drag_stays_drag_segment() { + let mut app = app(); + assert_eq!(added(&mut app, |a| drag(a, [80.0, 120.0], [80.0, 150.0], Modifiers::NONE)), ["Drag Segment"]); +} diff --git a/crates/ui-egui/src/tools/direct_select/shift_angle_tests.rs b/crates/ui-egui/src/tools/direct_select/shift_angle_tests.rs new file mode 100644 index 0000000000..302dbe902f --- /dev/null +++ b/crates/ui-egui/src/tools/direct_select/shift_angle_tests.rs @@ -0,0 +1,81 @@ +//! #13207: ⇧ during a Direct Selection anchor drag, as measured in the reference application on +//! the corner anchor (300, 300): a (+60, -25) drag stays on the horizontal at (360, 300), and a +//! (+50, -50) drag ends on the diagonal at (350, 250). Other angles weren't measured and keep the +//! 45° snap of #5475. + +use egui::Modifiers; +use photocraft_geom::Point; +use serde_json::json; + +use super::Drag; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::DirectSelection; + let path = json!({"subpaths": [{"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}]}); + app.run("path.set", json!({"name": "work", "path": path})).unwrap(); + app +} + +/// Drags the corner (300, 300) by `by` with ⇧ held once the drag is under way (⇧ at the press +/// would toggle the anchor's selection) and returns where the preview and the result put it. +fn shift_drag(by: [f64; 2]) -> (Point, Point) { + let mut app = app(); + let to = [300.0 + by[0], 300.0 + by[1]]; + tool_event(&mut app, ToolEvent::Down { x: 300.0, y: 300.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, Modifiers::SHIFT); + let Some(Drag::Edit { preview: Some(p), .. }) = &app.ui.direct_selection.drag else { panic!("dragging") }; + let preview = p.subpaths[0].knots[1].anchor; + tool_event(&mut app, ToolEvent::Up { x: to[0], y: to[1] }, Modifiers::SHIFT); + (preview, app.session.active().unwrap().doc.work_path.as_ref().unwrap().subpaths[0].knots[1].anchor) +} + +fn near(a: Point, want: [f64; 2]) -> bool { + (a.x - want[0]).abs() < 1e-9 && (a.y - want[1]).abs() < 1e-9 +} + +#[test] +fn a_shallow_shift_drag_stays_horizontal() { + let (preview, end) = shift_drag([60.0, -25.0]); + assert_eq!(preview, Point::new(360.0, 300.0), "the preview is locked too"); + assert_eq!(end, Point::new(360.0, 300.0)); +} + +#[test] +fn the_measured_drag_stays_horizontal_with_f32_pointer_noise() { + // The screen-to-document mapping runs in f32, so the measured pointer lands a hair off (-25). + let (preview, end) = shift_drag([60.0, -25.0 - 5e-5]); + assert_eq!((preview, end), (Point::new(360.0, 300.0), Point::new(360.0, 300.0))); +} + +#[test] +fn the_mirrored_vertical_drag_stays_vertical() { + let (preview, end) = shift_drag([25.0, -60.0]); + assert_eq!((preview, end), (Point::new(300.0, 240.0), Point::new(300.0, 240.0))); +} + +#[test] +fn a_diagonal_shift_drag_still_snaps_to_45_degrees() { + let (preview, end) = shift_drag([50.0, -50.0]); + for a in [preview, end] { + assert!(near(a, [350.0, 250.0]), "{a:?}"); + } +} + +#[test] +fn unmeasured_angles_keep_the_45_degree_snap() { + // (+60, -26) is 23.4°, just steeper than the measured drag; (+60, -30) is 26.6°. + for by in [[60.0, -26.0], [60.0, -30.0]] { + let want = crate::stroke_constraint::snap45([300.0, 300.0], [300.0 + by[0], 300.0 + by[1]]); + assert!(want[0] > 340.0 && (want[0] - 300.0 + want[1] - 300.0).abs() < 1e-9, "on the diagonal: {want:?}"); + let (preview, end) = shift_drag(by); + for a in [preview, end] { + assert!(near(a, want), "{by:?}: {a:?} vs {want:?}"); + } + } +} diff --git a/crates/ui-egui/src/tools/ellipse_center_mark_tests.rs b/crates/ui-egui/src/tools/ellipse_center_mark_tests.rs new file mode 100644 index 0000000000..e101758ed2 --- /dev/null +++ b/crates/ui-egui/src/tools/ellipse_center_mark_tests.rs @@ -0,0 +1,150 @@ +//! #13239: with the Ellipse tool, the box round the active ellipse shows a centre mark (a +//! crosshair in a small circle) as well as its eight handles, measured against the reference +//! application: a drag from 400,300 to 600,400 makes Ellipse 1, box 399,299 to 600,400. + +use egui::epaint::ColorMode; +use egui::{Color32, Modifiers, Pos2, Shape}; +use photocraft_doc::LayerContent; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, ViewXform, tool_event}; +use crate::state::Tool; + +const NONE: Modifiers = Modifiers::NONE; + +/// An 800 × 600 document with Ellipse 1 drawn by the measured drag, the Ellipse tool current. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::EllipseShape; + tool_event(&mut app, ToolEvent::Down { x: 400.0, y: 300.0, pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Move { x: 500.0, y: 350.0, pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Move { x: 600.0, y: 400.0, pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Up { x: 600.0, y: 400.0 }, NONE); + app +} + +/// The active shape's box `[x0, y0, x1, y1]`. +fn bounds(app: &PhotocraftApp) -> [f64; 4] { + let st = app.session.active().unwrap(); + let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("a shape layer") }; + let (x0, y0, x1, y1) = sh.path.control_bounds().unwrap(); + [x0, y0, x1, y1] +} + +/// A view at `zoom` screen px per document px, the document centred. +fn view(zoom: f32) -> ViewXform { + let rect = egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(1000.0, 700.0)); + ViewXform { rect, zoom, center: [500.0, 350.0], flip: false, rotation: 0.0, aspect: 1.0 } +} + +/// What the canvas's vector overlay paints in a frame: the hollow circles, the line segments and +/// the colours of the box's outline and handles. +struct Painted { + circles: Vec<(Pos2, f32, Color32)>, + lines: Vec<([Pos2; 2], Color32)>, + box_colours: Vec, +} + +fn painted(app: &PhotocraftApp, xf: &ViewXform) -> Painted { + let ctx = egui::Context::default(); + let doc = &app.session.active().unwrap().doc; + let mut o = ctx.run_ui(Default::default(), |ui| crate::vector_ui::draw_overlay(app, ui.painter(), xf, doc)); + o.textures_delta.clear(); + let mut p = Painted { circles: Vec::new(), lines: Vec::new(), box_colours: Vec::new() }; + for c in &o.shapes { + match &c.shape { + Shape::Circle(c) if c.fill == Color32::TRANSPARENT => p.circles.push((c.center, c.radius, c.stroke.color)), + Shape::LineSegment { points, stroke } => p.lines.push((*points, stroke.color)), + // The box outline is the only four-point closed path; each 7 × 7 handle is a white + // square under a hollow one that carries its stroke. + Shape::Path(path) if path.closed && path.points.len() == 4 => { + if let ColorMode::Solid(c) = path.stroke.color { + p.box_colours.push(c); + } + } + Shape::Rect(r) if r.fill == Color32::TRANSPARENT && r.rect.size() == egui::vec2(7.0, 7.0) => p.box_colours.push(r.stroke.color), + _ => {} + } + } + p +} + +/// The centre mark's radius on screen and colour if one is painted at screen point `c`: a hollow +/// circle there with a horizontal and a vertical line through it, all in one colour. +fn mark_at(app: &PhotocraftApp, xf: &ViewXform, c: Pos2) -> Option<(f32, Color32)> { + let p = painted(app, xf); + let near = |q: Pos2| q.distance(c) < 0.5; + let (_, radius, colour) = p.circles.into_iter().find(|(at, ..)| near(*at))?; + let through = |[a, b]: [Pos2; 2]| near(Pos2::new((a.x + b.x) / 2.0, (a.y + b.y) / 2.0)); + let horizontal = p.lines.iter().any(|&(l, lc)| through(l) && lc == colour && (l[0].y - l[1].y).abs() < 1e-3); + let vertical = p.lines.iter().any(|&(l, lc)| through(l) && lc == colour && (l[0].x - l[1].x).abs() < 1e-3); + (horizontal && vertical).then_some((radius, colour)) +} + +fn centre(r: [f64; 4]) -> [f32; 2] { + [((r[0] + r[2]) / 2.0) as f32, ((r[1] + r[3]) / 2.0) as f32] +} + +#[test] +fn the_ellipse_tool_marks_the_box_centre() { + let app = app(); + let r = bounds(&app); + assert!(r.iter().zip([399.0, 299.0, 600.0, 400.0]).all(|(g, w)| (g - w).abs() <= 1.0), "Ellipse 1's box: {r:?}"); + let [cx, cy] = centre(r); + assert!((cx - 500.0).abs() <= 1.0 && (cy - 350.0).abs() <= 1.0, "about 500,350: {cx},{cy}"); + let xf = view(1.0); + let (_, colour) = mark_at(&app, &xf, xf.to_screen(cx, cy)).expect("a crosshair in a circle at the box centre"); + let box_colours = painted(&app, &xf).box_colours; + assert_eq!(box_colours.len(), 9, "the outline and its eight handles"); + assert!(box_colours.iter().all(|c| *c == colour), "the mark has the box's colour: {colour:?} vs {box_colours:?}"); +} + +#[test] +fn the_mark_keeps_its_screen_size_at_every_zoom() { + let app = app(); + let [cx, cy] = centre(bounds(&app)); + let sizes: Vec> = [0.25, 1.0, 4.0].into_iter().map(|z| mark_at(&app, &view(z), view(z).to_screen(cx, cy)).map(|(r, _)| r)).collect(); + assert!(sizes[0].is_some(), "{sizes:?}"); + assert!(sizes.iter().all(|s| *s == sizes[0]), "the same radius on screen: {sizes:?}"); +} + +#[test] +fn the_mark_follows_the_box_while_a_handle_is_dragged() { + let mut app = app(); + let r = bounds(&app); + let right = [r[2], (r[1] + r[3]) / 2.0]; + tool_event(&mut app, ToolEvent::Down { x: right[0], y: right[1], pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Move { x: right[0] + 100.0, y: right[1], pressure: 1.0 }, NONE); + assert!(app.ui.shape_box.is_some(), "the right handle is dragged"); + let xf = view(1.0); + let [cx, cy] = centre([r[0], r[1], r[2] + 100.0, r[3]]); + assert!(mark_at(&app, &xf, xf.to_screen(cx, cy)).is_some(), "at the centre of the scaled box"); + let [ox, oy] = centre(r); + assert!(mark_at(&app, &xf, xf.to_screen(ox, oy)).is_none(), "not where the box was"); +} + +/// A drag by (+40, +30) from document point `from` with the Ellipse tool over Ellipse 1: whether +/// the box took the press, the layer count, the History length and the new active shape's size. +fn drag_from(from: [f64; 2]) -> (bool, usize, usize, [f64; 2]) { + let mut app = app(); + tool_event(&mut app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, NONE); + let boxed = app.ui.shape_box.is_some(); + tool_event(&mut app, ToolEvent::Move { x: from[0] + 20.0, y: from[1] + 15.0, pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Move { x: from[0] + 40.0, y: from[1] + 30.0, pressure: 1.0 }, NONE); + tool_event(&mut app, ToolEvent::Up { x: from[0] + 40.0, y: from[1] + 30.0 }, NONE); + let st = app.session.active().unwrap(); + let r = bounds(&app); + (boxed, st.doc.walk().len(), st.history.past_len(), [r[2] - r[0], r[3] - r[1]]) +} + +#[test] +fn a_press_on_the_mark_does_what_a_press_elsewhere_on_the_shape_does() { + let r = bounds(&app()); + let [cx, cy] = centre(r); + let on_mark = drag_from([f64::from(cx), f64::from(cy)]); + assert!(!on_mark.0, "the box takes no press at its centre"); + assert_eq!(on_mark, drag_from([r[0] + 50.0, f64::from(cy)]), "the same as a press elsewhere on Ellipse 1"); +} diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index 9d4bf194af..3a88440a52 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -1,10 +1,14 @@ //! UI for the Eraser group's colour-aware tools: Magic Eraser (click → `paint.magicEraser`) and //! Background Eraser (stroke → `paint.backgroundEraser`), with their options bars. +//! +//! A Magic Eraser press in an Indexed Color or Bitmap document shows the reference's alert (message +//! + OK) and runs nothing: the document keeps its pixels and its History (#12032). +use photocraft_engine::eraser_cmds::{MAGIC_ERASER_BITMAP_ERROR, MAGIC_ERASER_INDEXED_ERROR}; use serde_json::{Value, json}; use crate::PhotocraftApp; -use crate::state::Tool; +use crate::state::{DialogKind, Tool}; use crate::theme::Tokens; use crate::{icons, widgets}; @@ -15,11 +19,50 @@ fn report(app: &mut PhotocraftApp, r: Result) { } } +/// The alert this document gets instead of a Magic Eraser click (#12032): `Some(text)` means the +/// click is refused. The check is the engine's, so the press and `paint.magicEraser` can never +/// disagree about what is erased. +fn document_alert(app: &PhotocraftApp) -> Option<&'static str> { + app.session.active().and_then(|st| photocraft_engine::eraser_cmds::magic_eraser_refusal(&st.doc)) +} + +/// A `paint.magicEraser` error as the alert it was meant to be (#12032), so a click that reaches +/// the command shows the same dialog the press shows rather than only the status bar. +fn error_alert(error: &str) -> Option<&'static str> { + [MAGIC_ERASER_INDEXED_ERROR, MAGIC_ERASER_BITMAP_ERROR].into_iter().find(|text| *text == error) +} + +/// Opens the alert: the message and one OK button, as a refused Move press does +/// (`move_lock::prompt`). +fn refuse(app: &mut PhotocraftApp, message: &str) { + app.ui.open_dialog(DialogKind::Error, json!({"message": alert_text(message)}).as_object().cloned().unwrap_or_default()); +} + +/// The alert in the UI language. Literal keys, so the translation report lists both alerts for the +/// translators; `alert_keys_match_the_engine_texts` keeps them equal to the engine's texts. +fn alert_text(message: &str) -> &str { + match message { + MAGIC_ERASER_INDEXED_ERROR => { + tl!("Could not use the magic eraser because it does not work with Indexed Color images (convert image to RGB Color mode to edit).") + } + MAGIC_ERASER_BITMAP_ERROR => { + tl!("Could not use the magic eraser because it does not work with Bitmap images (convert image to Grayscale mode to edit).") + } + other => tl!(other), + } +} + /// Magic Eraser click at document `(x, y)`. Returns false for other tools. pub fn click(app: &mut PhotocraftApp, tool: Tool, x: f64, y: f64) -> bool { if tool != Tool::MagicEraser { return false; } + // An Indexed Color or Bitmap document (#12032): the reference answers the click with its alert + // and erases nothing, so the command is never reached - and the document keeps its History. + if let Some(message) = document_alert(app) { + refuse(app, message); + return true; + } let o = &app.ui.tool_options; let p = json!({ "x": x.floor(), @@ -31,6 +74,11 @@ pub fn click(app: &mut PhotocraftApp, tool: Tool, x: f64, y: f64) -> bool { "opacity": o.magic_eraser_opacity, }); let r = app.run("paint.magicEraser", p); + if let Err(e) = &r + && let Some(message) = error_alert(e) + { + refuse(app, message); + } report(app, r); true } @@ -327,3 +375,89 @@ pub(crate) fn open_range_alert(app: &mut PhotocraftApp) { app.ui.open_dialog(crate::state::DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default()); } } + +#[cfg(test)] +mod tests { + use super::*; + use photocraft_doc::{Color, ColorMode, Document, SampleType, Size}; + + /// #12032: the literal translation keys are the engine's alert texts, so an English UI shows + /// exactly what `paint.magicEraser` answers and the catalogs translate the right string. + #[test] + fn alert_keys_match_the_engine_texts() { + crate::i18n::with_language(crate::i18n::Lang::EN, || { + for text in [MAGIC_ERASER_INDEXED_ERROR, MAGIC_ERASER_BITMAP_ERROR] { + assert_eq!(alert_text(text), text); + } + }); + } + + /// The message of every open error dialog, in the order they were opened. + fn alerts(app: &PhotocraftApp) -> Vec<&str> { + app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message").and_then(|m| m.as_str())).collect() + } + + /// The app with a white 64x48 document in `mode` open and the Magic Eraser picked: a click on + /// it would wipe the flat canvas out. + fn app_in(mode: ColorMode) -> PhotocraftApp { + let mut s = photocraft_engine::Session::new(); + s.add_document(Document::with_background("p", Size::new(64, 48), mode, SampleType::U8, Color::WHITE), None); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.ui.tool = Tool::MagicEraser; + app + } + + /// #12032: the press in an Indexed Color or a Bitmap document shows the reference's alert - the + /// measured text and an OK button - and runs nothing: no History step, no erase, the Background + /// stays a Background, and the alert rather than the status bar carries the message. + #[test] + fn a_press_in_an_indexed_or_bitmap_document_shows_the_alert_and_erases_nothing() { + for (case, mode, want) in [("Indexed", ColorMode::Indexed, MAGIC_ERASER_INDEXED_ERROR), ("Bitmap", ColorMode::Bitmap, MAGIC_ERASER_BITMAP_ERROR)] { + let mut app = app_in(mode); + let st = app.session.active().unwrap(); + let (doc, steps) = (st.doc.clone(), st.history.past_len()); + let id = st.active_layer.unwrap(); + assert!(click(&mut app, Tool::MagicEraser, 2.0, 2.0), "{case}: the Magic Eraser takes the click"); + assert_eq!(alerts(&app), [want], "{case}: one alert with the reference's text"); + let st = app.session.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&doc, &st.doc), "{case}: the command never ran"); + assert_eq!(st.history.past_len(), steps, "{case}: no History step"); + assert_eq!(st.doc.layer(id).unwrap().name, "Background", "{case}: still a Background"); + assert!(st.doc.layer(id).unwrap().surface().unwrap().rgba(2, 2)[3] > 0.0, "{case}: nothing erased"); + assert!(!app.ui.status_error, "{case}: the alert is the answer, not the status bar"); + // OK closes it (`DialogKind::Error` asks for nothing else), and the next press answers + // the same way: the document is no more erasable than it was. + let open: Vec = app.ui.dialogs.iter().map(|d| d.id).collect(); + for dialog in open { + app.ui.close_dialog(dialog); + } + click(&mut app, Tool::MagicEraser, 10.0, 10.0); + assert_eq!(alerts(&app), [want], "{case}: the next press is refused too"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps, "{case}: still no History step"); + } + } + + /// #12032: the new press check leaves every document the tool can edit exactly as it was: the + /// click erases, no alert opens. + #[test] + fn a_press_in_an_editable_document_still_erases() { + for (case, mode) in [ + ("RGB", ColorMode::Rgb), + ("Grayscale", ColorMode::Grayscale), + ("CMYK", ColorMode::Cmyk), + ("Lab", ColorMode::Lab), + ("Duotone", ColorMode::Duotone), + ("Multichannel", ColorMode::Multichannel), + ] { + let mut app = app_in(mode); + let steps = app.session.active().unwrap().history.past_len(); + assert!(click(&mut app, Tool::MagicEraser, 2.0, 2.0), "{case}"); + assert!(app.ui.dialogs.iter().all(|d| d.kind != DialogKind::Error), "{case}: no alert"); + let st = app.session.active().unwrap(); + let id = st.active_layer.unwrap(); + assert_eq!(st.doc.layer(id).unwrap().name, "Layer 0", "{case}: the Background became a layer"); + assert_eq!(st.doc.layer(id).unwrap().surface().unwrap().rgba(2, 2)[3], 0.0, "{case}: erased to transparency"); + assert_eq!(st.history.past_len(), steps + 1, "{case}: one undo step"); + } + } +} diff --git a/crates/ui-egui/src/tools/frame_tool.rs b/crates/ui-egui/src/tools/frame_tool.rs index 190b0509c2..d5639b9af5 100644 --- a/crates/ui-egui/src/tools/frame_tool.rs +++ b/crates/ui-egui/src/tools/frame_tool.rs @@ -63,13 +63,16 @@ fn drawn(start: [f64; 2], cur: [f64; 2], square: bool, centred: bool) -> [i64; 4 let [x, y] = cur; let (mut dx, mut dy) = (x - sx, y - sy); if square { - let side = dx.abs().max(dy.abs()); + // Shift squares from the drag's shorter side, as the reference application does (#13865). + let side = dx.abs().min(dy.abs()); dx = side.copysign(dx); dy = side.copysign(dy); } let (a, b) = if centred { ([sx - dx, sy - dy], [sx + dx, sy + dy]) } else { (start, [sx + dx, sy + dy]) }; [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])].map(|v| v.round() as i64) } +#[cfg(test)] +mod shift_square_tests; pub fn selected(app: &PhotocraftApp) -> Option<&Layer> { let st = app.session.active()?; let id = photocraft_engine::frame_cmds::frame_of(&st.doc, st.active_layer?)?; @@ -340,6 +343,43 @@ pub fn cancel(app: &mut PhotocraftApp) { app.ui.frame_tool.drag = None; app.frame_preview = None; } +/// Escape during a drag. A frame being drawn is made at the pointer, as the reference application +/// does (#13866); the mouse movement and release after it change nothing. Moving, resizing or +/// rotating an existing frame is cancelled. +pub fn escape(app: &mut PhotocraftApp) { + let Some(FrameDrag::New { start, cur, square, centred, doc, revision }) = app.ui.frame_tool.drag.clone() else { + cancel(app); + return; + }; + cancel(app); + if app.session.active().is_some_and(|st| st.doc.id == doc && st.revision == revision) { + commit_new(app, start, cur, square, centred); + } +} +/// Make the frame drawn from `start` to `cur`, unless the drag was a click or drew nothing. +fn commit_new(app: &mut PhotocraftApp, start: [f64; 2], cur: [f64; 2], square: bool, centred: bool) { + if (cur[0] - start[0]).hypot(cur[1] - start[1]) * f64::from(app.point_zoom()) < CLICK_PX { + return; + } + let r = drawn(start, cur, square, centred); + if r[2] <= r[0] || r[3] <= r[1] { + return; + } + let mut p = shape_params(app, r); + if let Some(id) = content_layer(app, r) { + p["layer"] = json!(id); + } + match app.run("layer.new.frame", p) { + Ok(v) => { + if let Some(id) = v.get("layer").and_then(Value::as_u64) { + select(app, LayerId(id), Target::Frame); + } + } + Err(e) => report(app, Err(e)), + } +} +#[cfg(test)] +mod escape_commit_tests; /// A native double click (also driven by ui.click count=2) toggles content-only selection. pub fn double_click(app: &mut PhotocraftApp, p: [f64; 2]) { let Some(id) = frame_at(app, p) else { return }; @@ -463,31 +503,18 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> return true; } match d { - FrameDrag::New { start, .. } => { - if (x - start[0]).hypot(y - start[1]) * f64::from(app.point_zoom()) < CLICK_PX { - return true; - } - let r = drawn(start, [x, y], mods.shift, mods.alt); - if r[2] <= r[0] || r[3] <= r[1] { - return true; - } - let mut p = shape_params(app, r); - if let Some(id) = content_layer(app, r) { - p["layer"] = json!(id); - } - match app.run("layer.new.frame", p) { - Ok(v) => { - if let Some(id) = v.get("layer").and_then(Value::as_u64) { - select(app, LayerId(id), Target::Frame); - } - } - Err(e) => report(app, Err(e)), - } - } + FrameDrag::New { start, .. } => commit_new(app, start, [x, y], mods.shift, mods.alt), FrameDrag::Edit { layer, original, start, mode, .. } => { let transform = edit_transform(&original, mode, start, [x, y], mods); if transform != original.transform { - let r = app.run("layer.frame.set", json!({"layer":layer.0,"transform":transform.m})); + let mut p = json!({"layer":layer.0,"transform":transform.m}); + // Moving an empty frame is a "Move" step (#13880). Handle drags, and a + // frame with an image (not measured yet), keep "Frame Properties". + let empty = app.session.active().and_then(|st| st.doc.layer(layer)).is_some_and(|l| l.children().is_none_or(<[Layer]>::is_empty)); + if mode == EditMode::Move && empty { + p["historyName"] = json!("Move"); + } + let r = app.run("layer.frame.set", p); report(app, r); } } @@ -868,3 +895,5 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { } false } +#[cfg(test)] +mod move_history_tests; diff --git a/crates/ui-egui/src/tools/frame_tool/escape_commit_tests.rs b/crates/ui-egui/src/tools/frame_tool/escape_commit_tests.rs new file mode 100644 index 0000000000..f89988ba2f --- /dev/null +++ b/crates/ui-egui/src/tools/frame_tool/escape_commit_tests.rs @@ -0,0 +1,75 @@ +//! Escape during a frame drag makes the frame at the pointer (#13866). +use super::*; +use crate::canvas::tool_event; + +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(); + app.sync_views(); + app.ui.extras.snap = false; + app.ui.tool = Tool::Frame; + app +} + +fn escape(app: &mut PhotocraftApp) { + let ctx = egui::Context::default(); + ctx.begin_pass(egui::RawInput { + events: vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ..Default::default() + }); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); +} + +fn entries(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().history.entries() +} + +fn frames(app: &PhotocraftApp) -> Vec<[f64; 6]> { + let st = app.session.active().unwrap(); + st.doc.walk().into_iter().filter_map(|(_, _, l)| l.frame.as_ref().map(|f| f.transform.m)).collect() +} + +#[test] +fn escape_during_a_drag_makes_the_frame_at_the_pointer_in_one_new_frame_step() { + let mut app = app(); + let before = entries(&app); + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 50., y: 50., pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 122., y: 120., pressure: 1.0 }, m); + escape(&mut app); + assert!(app.ui.frame_tool.drag.is_none()); + assert_eq!(frames(&app), vec![[72., 0., 0., 70., 50., 50.]], "50..122 x 50..120"); + let after = entries(&app); + assert_eq!(after.len(), before.len() + 1); + assert_eq!(after.last().map(String::as_str), Some("New Frame")); + + // The movement and release after Escape change nothing more. + tool_event(&mut app, ToolEvent::Move { x: 300., y: 250., pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 300., y: 250. }, m); + assert_eq!(frames(&app), vec![[72., 0., 0., 70., 50., 50.]]); + assert_eq!(entries(&app), after); +} + +#[test] +fn escape_after_a_click_sized_drag_makes_nothing() { + let mut app = app(); + let before = entries(&app); + tool_event(&mut app, ToolEvent::Down { x: 50., y: 50., pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 51., y: 51., pressure: 1.0 }, egui::Modifiers::NONE); + escape(&mut app); + assert!(app.ui.frame_tool.drag.is_none()); + assert!(frames(&app).is_empty()); + assert_eq!(entries(&app), before); +} + +#[test] +fn escape_with_no_frame_drag_changes_nothing() { + let mut app = app(); + tool_event(&mut app, ToolEvent::Down { x: 50., y: 50., pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 122., y: 120. }, egui::Modifiers::NONE); + let (before, made) = (entries(&app), frames(&app)); + escape(&mut app); + assert_eq!(entries(&app), before); + assert_eq!(frames(&app), made); +} diff --git a/crates/ui-egui/src/tools/frame_tool/move_history_tests.rs b/crates/ui-egui/src/tools/frame_tool/move_history_tests.rs new file mode 100644 index 0000000000..a632c5f3c6 --- /dev/null +++ b/crates/ui-egui/src/tools/frame_tool/move_history_tests.rs @@ -0,0 +1,102 @@ +//! Moving an empty frame with the Frame tool records "Move" (#13880). +use super::*; +use crate::canvas::tool_event; + +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(); + app.sync_views(); + app.ui.extras.snap = false; + app.ui.tool = Tool::Frame; + app +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + let m = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, m); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, m); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, m); +} + +fn entries(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().history.entries() +} + +fn transform(app: &PhotocraftApp, id: LayerId) -> [f64; 6] { + app.session.active().unwrap().doc.layer(id).unwrap().frame.as_ref().unwrap().transform.m +} + +/// An empty 100 x 80 frame at 20,30, drawn with the Frame tool. +fn empty_frame(app: &mut PhotocraftApp) -> LayerId { + drag(app, [20., 30.], [120., 110.]); + selected(app).unwrap().id +} + +#[test] +fn dragging_an_empty_frame_records_one_move_step_that_undoes_in_one() { + let mut app = app(); + let id = empty_frame(&mut app); + let before = entries(&app); + drag(&mut app, [70., 70.], [90., 80.]); + assert_eq!(transform(&app, id), [100., 0., 0., 80., 40., 40.], "moved +20,+10"); + let after = entries(&app); + assert_eq!(after.len(), before.len() + 1); + assert_eq!(after.last().map(String::as_str), Some("Move")); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(transform(&app, id), [100., 0., 0., 80., 20., 30.]); + assert_eq!(entries(&app), before); +} + +#[test] +fn property_changes_and_handle_drags_keep_frame_properties() { + let mut app = app(); + let id = empty_frame(&mut app); + app.run("layer.frame.set", json!({"layer":id.0,"stroke":{"color":"#ff0000","width":2}})).unwrap(); + assert_eq!(entries(&app).last().map(String::as_str), Some("Frame Properties")); + app.run("layer.frame.set", json!({"layer":id.0,"transform":[120,0,0,80,20,30]})).unwrap(); + assert_eq!(entries(&app).last().map(String::as_str), Some("Frame Properties")); + let steps = entries(&app).len(); + // The bottom-right resize handle. + drag(&mut app, [140., 110.], [160., 130.]); + assert_eq!(transform(&app, id).map(f64::round), [140., 0., 0., 100., 20., 30.], "resized, not moved"); + assert_eq!(entries(&app).len(), steps + 1); + assert_eq!(entries(&app).last().map(String::as_str), Some("Frame Properties")); +} + +#[test] +fn a_bad_history_name_is_refused_and_changes_nothing() { + let mut app = app(); + let id = empty_frame(&mut app); + let before = entries(&app); + for bad in [json!(5), json!("Rotate"), json!(""), json!(["Move"]), json!({"name":"Move"}), json!("move")] { + assert!(app.run("layer.frame.set", json!({"layer":id.0,"transform":[100,0,0,80,40,40],"historyName":bad})).is_err(), "{bad}"); + assert_eq!(entries(&app), before); + assert_eq!(transform(&app, id), [100., 0., 0., 80., 20., 30.]); + } + app.run("layer.frame.set", json!({"layer":id.0,"transform":[100,0,0,80,40,40],"historyName":null})).unwrap(); + assert_eq!(entries(&app).last().map(String::as_str), Some("Frame Properties")); + app.run("layer.frame.set", json!({"layer":id.0,"transform":[100,0,0,80,20,30],"historyName":"Move"})).unwrap(); + assert_eq!(entries(&app).last().map(String::as_str), Some("Move")); +} + +/// A frame with an image is not what #13880 measured: its border drag keeps today's step name. +#[test] +fn dragging_the_border_of_a_frame_with_an_image_keeps_frame_properties() { + let mut app = app(); + let id = empty_frame(&mut app); + let content = app + .session + .edit("Image", |doc, _| { + let mut l = Layer::raster("Photo", doc.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(20, 30, 120, 110), &[1., 0., 0., 1.]); + let id = l.id; + doc.layers.push(l); + Ok(id) + }) + .unwrap(); + app.run("layer.frame.setContent", json!({"layer":id.0,"content":content.0})).unwrap(); + select(&mut app, id, Target::Frame); + drag(&mut app, [45., 30.], [65., 40.]); + assert_eq!(transform(&app, id), [100., 0., 0., 80., 40., 40.]); + assert_eq!(entries(&app).last().map(String::as_str), Some("Frame Properties")); +} diff --git a/crates/ui-egui/src/tools/frame_tool/shift_square_tests.rs b/crates/ui-egui/src/tools/frame_tool/shift_square_tests.rs new file mode 100644 index 0000000000..2007331e36 --- /dev/null +++ b/crates/ui-egui/src/tools/frame_tool/shift_square_tests.rs @@ -0,0 +1,61 @@ +//! Shift while drawing a frame squares from the drag's shorter side (#13865). +use super::*; +use crate::canvas::tool_event; + +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(); + app.sync_views(); + app.ui.extras.snap = false; + app.ui.tool = Tool::Frame; + app +} + +const SHIFT: egui::Modifiers = egui::Modifiers { shift: true, ..egui::Modifiers::NONE }; +const ALT: egui::Modifiers = egui::Modifiers { alt: true, ..egui::Modifiers::NONE }; +const SHIFT_ALT: egui::Modifiers = egui::Modifiers { shift: true, alt: true, ..egui::Modifiers::NONE }; + +/// Press at `from` with `down`, move to `to` with `held`, and return the outline being drawn +/// (`left, top, right, bottom`) before releasing there and returning the new frame's transform. +fn draw(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], down: egui::Modifiers, held: egui::Modifiers) -> ([i64; 4], [f64; 6]) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, down); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, held); + let Some(FrameDrag::New { start, cur, square, centred, .. }) = app.ui.frame_tool.drag.clone() else { panic!("a frame is being drawn") }; + let live = drawn(start, cur, square, centred); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, held); + (live, selected(app).unwrap().frame.as_ref().unwrap().transform.m) +} + +#[test] +fn shift_squares_a_rectangle_from_the_shorter_side_at_the_start_corner() { + let mut app = app(); + let (live, m) = draw(&mut app, [400., 50.], [500., 110.], SHIFT, SHIFT); + assert_eq!(m, [60., 0., 0., 60., 400., 50.], "400..460 x 50..110"); + assert_eq!(live, [400, 50, 460, 110], "the live outline shows the committed square"); + assert_eq!(app.session.active().unwrap().history.entries().last().map(String::as_str), Some("New Frame")); +} + +#[test] +fn shift_squares_a_polygon_from_the_shorter_side() { + let mut app = app(); + app.ui.frame_tool.shape = "polygon".into(); + let (live, m) = draw(&mut app, [100., 100.], [260., 180.], SHIFT, SHIFT); + assert_eq!(m, [80., 0., 0., 80., 100., 100.], "a 160 x 80 drag gives 80 x 80"); + assert_eq!(live, [100, 100, 180, 180]); +} + +#[test] +fn shift_alt_squares_the_shorter_half_extent_around_the_start() { + let mut app = app(); + let (live, m) = draw(&mut app, [150., 300.], [210., 330.], SHIFT_ALT, SHIFT_ALT); + assert_eq!(m, [60., 0., 0., 60., 120., 270.], "120..180 x 270..330"); + assert_eq!(live, [120, 270, 180, 330]); +} + +#[test] +fn alt_alone_draws_from_the_centre_without_squaring() { + let mut app = app(); + let (live, m) = draw(&mut app, [450., 300.], [500., 330.], egui::Modifiers::NONE, ALT); + assert_eq!(m, [100., 0., 0., 60., 400., 270.], "400..500 x 270..330"); + assert_eq!(live, [400, 270, 500, 330]); +} diff --git a/crates/ui-egui/src/tools/frame_tool/tests.rs b/crates/ui-egui/src/tools/frame_tool/tests.rs index f0be9a649f..7fa4778347 100644 --- a/crates/ui-egui/src/tools/frame_tool/tests.rs +++ b/crates/ui-egui/src/tools/frame_tool/tests.rs @@ -174,8 +174,9 @@ fn modifiers_shape_selection_and_invalid_control_params_are_consistent() { pointer(&mut app, ToolEvent::Down { x: 100., y: 100., pressure: 1. }, mods); pointer(&mut app, ToolEvent::Up { x: 130., y: 120. }, mods); let f = selected(&app).unwrap().frame.as_ref().unwrap(); - assert_eq!(f.bounds(), Rect::new(70, 70, 130, 130)); - assert_eq!(TestMask(f.outline()).value(70, 70), 0.0, "triangle rather than bounding rectangle"); + // Shift squares from the shorter side (#13865): 20 px each way around the start. + assert_eq!(f.bounds(), Rect::new(80, 80, 120, 120)); + assert_eq!(TestMask(f.outline()).value(80, 80), 0.0, "triangle rather than bounding rectangle"); let frame = selected(&app).unwrap().id; let content = app .session diff --git a/crates/ui-egui/src/tools/lasso_ui/tests.rs b/crates/ui-egui/src/tools/lasso_ui/tests.rs index a568d102ae..a96c0c89c6 100644 --- a/crates/ui-egui/src/tools/lasso_ui/tests.rs +++ b/crates/ui-egui/src/tools/lasso_ui/tests.rs @@ -170,6 +170,38 @@ fn mouse(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, kind: &str, x: f h.run_steps(2); } +#[test] +fn pasteboard_click_deselects_only_in_new_mode_and_is_undoable() { + for mods in [Modifiers::NONE, Modifiers::SHIFT, Modifiers::ALT, Modifiers::SHIFT | Modifiers::ALT] { + let mut h = harness(); + h.state_mut().run("select.rect", json!({"x": 20, "y": 20, "width": 80, "height": 80})).unwrap(); + let history = h.state().session.active().unwrap().history.past_len(); + mouse(&mut h, "down", -20.0, 100.0, mods); + mouse(&mut h, "up", -20.0, 100.0, mods); + let state = h.state().session.active().unwrap(); + if mods == Modifiers::NONE { + assert!(state.doc.selection.is_none(), "New-mode click deselects"); + assert_eq!(state.history.past_len(), history + 1); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert!(h.state().session.active().unwrap().doc.selection.is_some(), "undo restores the selection"); + } else { + assert!(state.doc.selection.is_some(), "modified selection mode keeps the selection"); + assert_eq!(state.history.past_len(), history); + } + } +} + +#[test] +fn lasso_drag_from_pasteboard_still_creates_a_selection() { + let mut h = harness(); + mouse(&mut h, "down", -20.0, 80.0, Modifiers::NONE); + mouse(&mut h, "move", 100.0, 80.0, Modifiers::NONE); + mouse(&mut h, "move", 100.0, 160.0, Modifiers::NONE); + mouse(&mut h, "up", -20.0, 160.0, Modifiers::NONE); + let selection = h.state().session.active().unwrap().doc.selection.as_ref().expect("a drag still selects"); + assert!(selection.sample_channel(50, 120, 0) > 0.5); +} + fn freeform_harness() -> egui_kittest::Harness<'static, PhotocraftApp> { let mut h = harness(); let app = h.state_mut(); diff --git a/crates/ui-egui/src/tools/line_live_handles_tests.rs b/crates/ui-egui/src/tools/line_live_handles_tests.rs new file mode 100644 index 0000000000..255ebfc5a0 --- /dev/null +++ b/crates/ui-egui/src/tools/line_live_handles_tests.rs @@ -0,0 +1,209 @@ +//! #13263: with the Line tool, the active live line shows a handle at each end and a round widget +//! at its midpoint instead of the shape tools' box, measured against the reference application: a +//! line drawn 400,300 -> 600,400 has handles there and the widget at 500,350; with an arrowhead it +//! also shows its box aligned with the segment, with side handles. Dragging the ends is not +//! measured, so they keep scaling the line as the box's corner handles there did. + +use egui::{Color32, Pos2, Shape}; +use photocraft_doc::LayerContent; +use photocraft_doc::vector::LiveShape; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::ViewXform; +use crate::shape_bounds_box_tests::{drag, view}; +use crate::state::Tool; + +/// An 800 × 600 document with the measured line drawn by the Line tool, arrowheads as given. +fn app(arrows: bool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Line; + app.ui.tool_options.arrow_start = arrows; + app.ui.tool_options.arrow_end = arrows; + drag(&mut app, [400.0, 300.0], [600.0, 400.0]); + app +} + +/// The active layer's live line ends. +fn ends(app: &PhotocraftApp) -> ([f64; 2], [f64; 2]) { + let st = app.session.active().unwrap(); + let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("a shape layer") }; + match sh.live.as_ref() { + Some(LiveShape::Line { from, to, .. } | LiveShape::ArrowLine { from, to, .. }) => (*from, *to), + other => panic!("a live line: {other:?}"), + } +} + +/// What the canvas's vector overlay paints in a frame: the centres of the white square handles, +/// the centres of the white round widgets and the closed outlines' points. +struct Painted { + squares: Vec, + widgets: Vec, + closed: Vec>, +} + +fn painted(app: &PhotocraftApp, xf: &ViewXform) -> Painted { + let ctx = egui::Context::default(); + let doc = &app.session.active().unwrap().doc; + let mut o = ctx.run_ui(Default::default(), |ui| crate::vector_ui::draw_overlay(app, ui.painter(), xf, doc)); + o.textures_delta.clear(); + let mut p = Painted { squares: Vec::new(), widgets: Vec::new(), closed: Vec::new() }; + for c in &o.shapes { + match &c.shape { + // 7 px squares: the anchors Path Selection adds are 6 px. + Shape::Rect(r) if r.fill == Color32::WHITE && (r.rect.width() - 7.0).abs() < 0.01 => p.squares.push(r.rect.center()), + Shape::Circle(c) if c.fill == Color32::WHITE => p.widgets.push(c.center), + Shape::Path(path) if path.closed => p.closed.push(path.points.clone()), + _ => {} + } + } + p +} + +fn scr(xf: &ViewXform, p: [f64; 2]) -> Pos2 { + xf.to_screen(p[0] as f32, p[1] as f32) +} + +fn has(points: &[Pos2], p: Pos2) -> bool { + points.iter().any(|q| q.distance(p) < 0.5) +} + +/// The active layer's id, the document's layer count and its History: the past steps and the last +/// one's name. +fn state(app: &PhotocraftApp) -> (u64, usize, usize, Option) { + let st = app.session.active().unwrap(); + (st.active_layer.unwrap().0, st.doc.walk().len(), st.history.past_len(), st.history.entries().last().cloned()) +} + +fn bounds(app: &PhotocraftApp) -> [f64; 4] { + let st = app.session.active().unwrap(); + let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("a shape layer") }; + let (x0, y0, x1, y1) = sh.path.control_bounds().unwrap(); + [x0, y0, x1, y1] +} + +#[test] +fn a_live_line_shows_its_end_handles_and_a_midpoint_widget_and_no_box() { + let app = app(false); + let (from, to) = ends(&app); + assert!(from.iter().chain(&to).zip([400.0, 300.0, 600.0, 400.0]).all(|(g, w)| (g - w).abs() <= 1.0), "the measured line: {from:?} {to:?}"); + let xf = view(0.0); + let p = painted(&app, &xf); + assert_eq!(p.squares.len(), 2, "a handle at each end, not the box's eight: {:?}", p.squares); + assert!(has(&p.squares, scr(&xf, from)) && has(&p.squares, scr(&xf, to)), "at the ends: {:?}", p.squares); + let mid = [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0]; + assert_eq!(p.widgets.len(), 1, "{:?}", p.widgets); + assert!(has(&p.widgets, scr(&xf, mid)), "the round widget at about 500,350: {:?}", p.widgets); + let axis_box = [[400.0, 300.0], [600.0, 300.0], [600.0, 400.0], [400.0, 400.0]].map(|c| scr(&xf, c)); + let near_box = |pts: &Vec| pts.len() == 4 && axis_box.iter().all(|c| pts.iter().any(|q| q.distance(*c) <= 1.0)); + assert!(!p.closed.iter().any(near_box), "no axis-aligned box: {:?}", p.closed); + // The hidden box's other corners take no press and show no cursor. + for corner in [[600.0, 300.0], [400.0, 400.0]] { + assert!(crate::shape_bounds_box::cursor(&app, &xf, corner).is_none(), "no box handle at {corner:?}"); + } +} + +#[test] +fn dragging_an_end_scales_the_line_as_the_box_corner_did() { + for (handle, from, to) in [([1, 1], [600.0, 400.0], [700.0, 450.0]), ([-1, -1], [400.0, 300.0], [300.0, 250.0])] { + let mut app = app(false); + let (id, layers, steps, _) = state(&app); + let r = bounds(&app); + assert!(crate::shape_bounds_box::cursor(&app, &view(0.0), from).is_some(), "{from:?}: the corner's cursor"); + drag(&mut app, from, to); + assert_eq!(state(&app), (id, layers, steps + 1, Some("Transform Path".to_string())), "{from:?}: one Transform Path step, no new layer"); + // About the opposite corner of the box, as that corner handle scaled it. + let s = crate::shape_bounds_box::scale_for(r, handle, [to[0] - from[0], to[1] - from[1]]); + let (fx, fy) = if handle[0] > 0 { (r[0], r[1]) } else { (r[2], r[3]) }; + let at = |v: f64, f: f64, s: f64| f + (v - f) * s; + let (xs, ys) = ([at(r[0], fx, s[0]), at(r[2], fx, s[0])], [at(r[1], fy, s[1]), at(r[3], fy, s[1])]); + let want = [xs[0].min(xs[1]), ys[0].min(ys[1]), xs[0].max(xs[1]), ys[0].max(ys[1])]; + let got = bounds(&app); + assert!(s[0] > 1.0 && got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1e-6), "{from:?}: {got:?} vs {want:?}"); + } +} + +#[test] +fn a_press_where_the_box_corner_was_draws_a_new_line() { + let mut app = app(false); + let (id, layers, ..) = state(&app); + drag(&mut app, [600.0, 300.0], [650.0, 320.0]); + let (now, count, _, last) = state(&app); + assert!(now != id && count == layers + 1, "the Line tool draws a new line there"); + assert_ne!(last.as_deref(), Some("Transform Path")); +} + +#[test] +fn an_arrowhead_adds_the_box_aligned_with_the_segment_and_its_side_handles() { + let app = app(true); + let (from, to) = ends(&app); + let xf = view(0.0); + let p = painted(&app, &xf); + // Heads at both ends, so the box runs from end to end and is as wide as a head. + let half = f64::from(app.ui.tool_options.arrow_width) / 2.0; + let len = (to[0] - from[0]).hypot(to[1] - from[1]); + let n = [(from[1] - to[1]) / len * half, (to[0] - from[0]) / len * half]; + let corners = [[from[0] + n[0], from[1] + n[1]], [to[0] + n[0], to[1] + n[1]], [to[0] - n[0], to[1] - n[1]], [from[0] - n[0], from[1] - n[1]]]; + let boxed = p.closed.iter().find(|pts| pts.len() == 4 && corners.iter().all(|c| has(pts, scr(&xf, *c)))); + assert!(boxed.is_some(), "a box along the segment, corners {corners:?}: {:?}", p.closed); + let side = |a: [f64; 2], b: [f64; 2]| scr(&xf, [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]); + for (i, a) in corners.iter().enumerate() { + let b = corners[(i + 1) % 4]; + assert!(has(&p.squares, side(*a, b)), "a handle in the middle of side {i}: {:?}", p.squares); + } + assert!(has(&p.squares, scr(&xf, from)) && has(&p.squares, scr(&xf, to)), "the end handles stay: {:?}", p.squares); + assert_eq!(p.widgets.len(), 1, "the midpoint widget stays: {:?}", p.widgets); +} + +#[test] +fn the_other_shape_tools_still_show_the_box_round_the_line() { + for tool in [Tool::PathSelection, Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Star] { + let mut app = app(false); + app.ui.tool = tool; + let xf = view(0.0); + let p = painted(&app, &xf); + assert_eq!(p.squares.len(), 8, "{tool:?}: the box's eight handles"); + assert!(p.widgets.is_empty(), "{tool:?}: no midpoint widget"); + assert!(crate::shape_bounds_box::cursor(&app, &xf, [600.5, 300.0]).is_some(), "{tool:?}: a box corner"); + } +} + +/// The Line tool keeps today's box, and no line controls, round its selection. +fn assert_box(app: &PhotocraftApp, what: &str) { + let p = painted(app, &view(0.0)); + assert_eq!(p.squares.len(), 8, "{what}: the box's eight handles: {:?}", p.squares); + assert!(p.widgets.is_empty(), "{what}: no midpoint widget"); +} + +#[test] +fn the_line_tool_keeps_the_box_round_other_shapes() { + let mut app = app(false); + app.run("shape.create", json!({"kind": "rect", "rect": [100, 100, 200, 100], "fill": "#e02020"})).unwrap(); + app.ui.tool = Tool::Line; + assert_box(&app, "a rectangle"); +} + +#[test] +fn the_line_tool_keeps_the_box_round_several_selected_layers() { + let mut app = app(false); + let (line, ..) = state(&app); + app.run("shape.create", json!({"kind": "rect", "rect": [100, 100, 200, 100], "fill": "#e02020"})).unwrap(); + app.run("layer.select", json!({"layer": line, "mode": "toggle"})).unwrap(); + app.ui.tool = Tool::Line; + assert_eq!(app.session.active().unwrap().selected_layers().len(), 2); + assert_box(&app, "a live line and a rectangle"); +} + +#[test] +fn the_line_tool_keeps_the_box_round_a_line_that_is_no_longer_live() { + let mut app = app(false); + let (line, ..) = state(&app); + // A skew, unlike a rotation, leaves no line the live parameters could describe. + app.run("edit.transform", json!({"layer": line, "matrix": [1.0, 0.0, 0.5, 1.0, 0.0, 0.0], "stepName": "Transform Path"})).unwrap(); + let st = app.session.active().unwrap(); + let LayerContent::Shape(sh) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("a shape layer") }; + assert!(sh.live.is_none(), "a skew leaves a plain path: {:?}", sh.live); + assert_box(&app, "a skewed line"); +} diff --git a/crates/ui-egui/src/tools/line_tool_defaults_tests.rs b/crates/ui-egui/src/tools/line_tool_defaults_tests.rs new file mode 100644 index 0000000000..60ceea5f96 --- /dev/null +++ b/crates/ui-egui/src/tools/line_tool_defaults_tests.rs @@ -0,0 +1,79 @@ +//! #13241: the Line tool starts, and resets to, Weight 1 px with arrowheads 5 px wide and 10 px +//! long (Start and End off, Concavity 0 %), as the reference application does. + +use egui::Modifiers; +use photocraft_doc::LayerContent; +use photocraft_doc::vector::LiveShape; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::{Tool, ToolOptions}; + +fn assert_line_defaults(o: &ToolOptions) { + assert_eq!(o.line_weight, 1.0, "Weight"); + assert!(!o.arrow_start && !o.arrow_end, "Start and End off"); + assert_eq!(o.arrow_width, 5.0, "arrowhead Width"); + assert_eq!(o.arrow_length, 10.0, "arrowhead Length"); + assert_eq!(o.arrow_concavity, 0.0, "arrowhead Concavity"); +} + +#[test] +fn fresh_settings_give_the_reference_line_defaults() { + assert_line_defaults(&ToolOptions::default()); +} + +#[test] +fn reset_tool_gives_the_reference_line_defaults() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.tool = Tool::Line; + let o = &mut app.ui.tool_options; + (o.line_weight, o.arrow_start, o.arrow_end, o.arrow_width, o.arrow_length, o.arrow_concavity) = (3.0, true, true, 52.0, 50.0, 40.0); + crate::menus::invoke(&mut app, &egui::Context::default(), crate::tools::tool_reset::RESET, json!({})).unwrap(); + assert_line_defaults(&app.ui.tool_options); +} + +#[test] +fn a_default_drag_with_end_on_makes_a_1_px_shaft_and_a_10_by_5_px_head() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.ui.tool = Tool::Line; + app.ui.tool_options.arrow_end = true; + let none = Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 400.0, y: 300.0, pressure: 1.0 }, none); + tool_event(&mut app, ToolEvent::Move { x: 600.0, y: 300.0, pressure: 1.0 }, none); + tool_event(&mut app, ToolEvent::Up { x: 600.0, y: 300.0 }, none); + + let st = app.session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + let LayerContent::Shape(shape) = &layer.content else { panic!("a shape layer: {:?}", layer.content) }; + let Some(LiveShape::ArrowLine { from, to, weight, start, end, width, length, concavity }) = shape.live.clone() else { + panic!("a live arrow line: {:?}", shape.live) + }; + assert_eq!((weight, start, end, width, length, concavity), (1.0, false, true, 5.0, 10.0, 0.0)); + assert_eq!(to[0], 600.0, "the head's tip is at the drag's end"); + assert_eq!(from[1], to[1], "a horizontal line"); + + // The shaft, then the head: its tip at 600, 10 px long and 5 px wide. + let [shaft, head] = &shape.path.subpaths[..] else { panic!("a shaft and one head: {:?}", shape.path) }; + let bounds = |sp: &photocraft_doc::vector::Subpath| photocraft_doc::vector::Path::new(vec![sp.clone()]).control_bounds().unwrap(); + let (_, sy0, _, sy1) = bounds(shaft); + assert_eq!(sy1 - sy0, 1.0, "a 1 px shaft"); + let (hx0, hy0, hx1, hy1) = bounds(head); + assert_eq!((hx0, hx1), (590.0, 600.0), "a head 10 px long ending at the tip"); + assert_eq!(hy1 - hy0, 5.0, "a head 5 px wide"); +} + +#[test] +fn line_options_saved_before_the_new_defaults_keep_their_values() { + let saved = json!({"line_weight": 3.0, "arrow_end": true, "arrow_width": 52.0, "arrow_length": 50.0, "arrow_concavity": 25.0}); + let o: ToolOptions = serde_json::from_value(saved).unwrap(); + assert_eq!((o.line_weight, o.arrow_end, o.arrow_width, o.arrow_length, o.arrow_concavity), (3.0, true, 52.0, 50.0, 25.0)); + assert!(!o.arrow_start, "a field the file lacks takes its default"); +} + +#[test] +fn line_options_missing_from_a_saved_file_take_the_new_defaults() { + let o: ToolOptions = serde_json::from_value(json!({"tolerance": 10.0})).unwrap(); + assert_line_defaults(&o); +} diff --git a/crates/ui-egui/src/tools/move_distance.rs b/crates/ui-egui/src/tools/move_distance.rs index e57af527c9..c872a2462b 100644 --- a/crates/ui-egui/src/tools/move_distance.rs +++ b/crates/ui-egui/src/tools/move_distance.rs @@ -11,8 +11,8 @@ //! so a pointer resting on the canvas costs nothing per frame. use egui::{Color32, Pos2, Stroke, pos2, vec2}; -use photocraft_doc::{DocId, Document, LayerId}; -use photocraft_engine::snap::{layer_rect, union}; +use photocraft_doc::{DocId, LayerId}; +use photocraft_engine::snap::union; use crate::PhotocraftApp; use crate::canvas::ViewXform; @@ -82,14 +82,6 @@ pub(crate) fn measure(a: [f64; 4], b: [f64; 4]) -> Overlay { out } -/// The bounds of layer `id` and, for a group, of the layers in it (`snap::layer_rect`: what the -/// Move tool moves and snaps). -fn tree_rect(doc: &Document, id: LayerId) -> Option<[f64; 4]> { - let rows = doc.walk(); - let (prefix, _, _) = rows.iter().find(|(_, _, l)| l.id == id)?; - union(rows.iter().filter(|(p, _, _)| p.starts_with(prefix)).filter_map(|(_, _, l)| layer_rect(doc, l.id))) -} - /// The last answer: the boxes measured with the pointer at `at` on that revision and selection. pub(crate) struct Cache { doc: DocId, @@ -115,13 +107,13 @@ fn boxes(app: &mut PhotocraftApp, at: [f64; 2]) -> Option<([f64; 4], [f64; 4])> return c.boxes; } let d = &st.doc; - let a = union(selected.iter().filter(|id| !d.is_background(**id)).filter_map(|id| tree_rect(d, *id))); + let a = union(selected.iter().filter(|id| !d.is_background(**id)).filter_map(|id| crate::snap_ui::tree_rect(d, *id))); let canvas = [0.0, 0.0, d.size.width as f64, d.size.height as f64]; let hovered = photocraft_engine::pick_cmds::move_auto_select_target(d, at[0], at[1], group).filter(|id| { // The selection itself (or a layer in a selected group) isn't another layer. !d.is_background(*id) && !selected.iter().any(|s| *s == *id || d.path_of(*id).zip(d.path_of(*s)).is_some_and(|(p, q)| p.starts_with(&q))) }); - let boxes = a.map(|a| (a, hovered.and_then(|id| tree_rect(d, id)).unwrap_or(canvas))); + let boxes = a.map(|a| (a, hovered.and_then(|id| crate::snap_ui::tree_rect(d, id)).unwrap_or(canvas))); app.move_distance = Some(Cache { doc, revision, at, group, selected, boxes }); boxes } diff --git a/crates/ui-egui/src/tools/object_selection_mode_tests.rs b/crates/ui-egui/src/tools/object_selection_mode_tests.rs new file mode 100644 index 0000000000..53be1b163f --- /dev/null +++ b/crates/ui-egui/src/tools/object_selection_mode_tests.rs @@ -0,0 +1,230 @@ +//! Object Selection's New / Add / Subtract / Intersect buttons (#12853), as measured in the +//! reference application: the bar's mode (or ⇧ / ⌥ / ⇧⌥) combines each Object Finder click and +//! rectangle drag with the selection; in New mode a press inside the selection deselects (click) +//! or moves the outline (drag); ⌘ moves the pixels. + +use egui::Modifiers; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; +use crate::tool_feedback::{Badge, badge}; + +const RED: [f64; 2] = [200.0, 180.0]; +const BLUE: [f64; 2] = [560.0, 300.0]; + +/// An 800 x 600 document with an opaque red block (80,80–320,280) and a blue disc (centre +/// 560,300, radius 120) on one layer, nothing selected, Object Selection with Object Finder on. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.sync_views(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 80, "y": 80, "width": 240, "height": 200})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + app.run("select.rect", json!({"x": 440, "y": 180, "width": 240, "height": 240, "ellipse": true})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#0000ff"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.ui.tool = Tool::ObjectSelection; + app.ui.tool_options.object_finder = true; + app +} + +fn click(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) { + tool_event(app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: p[0], y: p[1] }, mods); +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: (from[0] + to[0]) / 2.0, y: (from[1] + to[1]) / 2.0, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods); +} + +fn selected(app: &PhotocraftApp, p: [f64; 2]) -> bool { + app.session.active().and_then(|st| st.doc.selection.as_ref()).is_some_and(|s| s.sample_channel(p[0] as i32, p[1] as i32, 0) >= 0.5) +} + +fn any_selection(app: &PhotocraftApp) -> bool { + app.session.active().and_then(|st| st.doc.selection.as_ref()).is_some_and(|s| !s.content_bounds().is_empty()) +} + +fn last_step(app: &PhotocraftApp) -> Option { + app.session.active()?.history.entries().last().map(ToString::to_string) +} + +fn alpha_at(app: &PhotocraftApp, x: i32, y: i32) -> f32 { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)[3] +} + +#[test] +fn add_mode_clicks_accumulate() { + let mut app = app(); + app.ui.selection_mode = 1; + click(&mut app, RED, Modifiers::NONE); + click(&mut app, BLUE, Modifiers::NONE); + assert!(selected(&app, RED) && selected(&app, BLUE)); +} + +#[test] +fn subtract_mode_removes_the_clicked_object() { + let mut app = app(); + app.ui.selection_mode = 1; + click(&mut app, RED, Modifiers::NONE); + click(&mut app, BLUE, Modifiers::NONE); + app.ui.selection_mode = 2; + click(&mut app, RED, Modifiers::NONE); + assert!(!selected(&app, RED), "red is removed"); + assert!(selected(&app, BLUE), "blue stays"); +} + +#[test] +fn intersect_mode_keeps_only_the_overlap() { + let mut app = app(); + click(&mut app, RED, Modifiers::NONE); + app.ui.selection_mode = 3; + click(&mut app, RED, Modifiers::NONE); + assert!(selected(&app, RED), "red with red is red"); + click(&mut app, BLUE, Modifiers::NONE); + assert!(!any_selection(&app), "red with blue is empty"); + assert!(!app.ui.status_error && app.ui.dialogs.is_empty(), "an empty intersection is not an error"); +} + +#[test] +fn new_mode_press_inside_the_selection_deselects_or_moves_the_outline() { + let mut app = app(); + click(&mut app, RED, Modifiers::NONE); + assert!(selected(&app, RED)); + click(&mut app, RED, Modifiers::NONE); + assert!(!any_selection(&app)); + assert_eq!(last_step(&app).as_deref(), Some("Deselect")); + + click(&mut app, RED, Modifiers::NONE); + drag(&mut app, RED, [250.0, 220.0], Modifiers::NONE); + assert_eq!(last_step(&app).as_deref(), Some("Move Selection")); + assert!(selected(&app, [340.0, 300.0]) && !selected(&app, [100.0, 100.0]), "the outline moved by +50,+40"); + assert_eq!(alpha_at(&app, 100, 100), 1.0, "the pixels stay"); + assert_eq!(alpha_at(&app, 340, 300), 0.0); + + // Outside the selection a click replaces it. + click(&mut app, BLUE, Modifiers::NONE); + assert!(selected(&app, BLUE) && !selected(&app, [340.0, 300.0])); +} + +#[test] +fn the_mode_stays_new_after_a_selection() { + let mut app = app(); + click(&mut app, RED, Modifiers::NONE); + assert_eq!(app.ui.selection_mode, 0); +} + +#[test] +fn modifiers_override_the_bar() { + let mut app = app(); + click(&mut app, RED, Modifiers::NONE); + click(&mut app, BLUE, Modifiers::SHIFT); + assert!(selected(&app, RED) && selected(&app, BLUE), "Shift adds"); + click(&mut app, RED, Modifiers::ALT); + assert!(!selected(&app, RED) && selected(&app, BLUE), "Alt subtracts"); + + // Shift inside the selection in New mode adds rather than deselecting. + click(&mut app, BLUE, Modifiers::SHIFT); + assert!(selected(&app, BLUE)); + + // Shift+Alt rectangle drag intersects: both selected, a rectangle around red leaves red. + click(&mut app, RED, Modifiers::SHIFT); + assert!(selected(&app, RED) && selected(&app, BLUE)); + let both = Modifiers { shift: true, alt: true, ..Default::default() }; + drag(&mut app, [60.0, 60.0], [340.0, 300.0], both); + assert!(selected(&app, RED), "red is in both"); + assert!(!selected(&app, BLUE), "blue is outside the rectangle"); +} + +#[test] +fn the_badge_follows_the_bar_and_modifiers() { + let mut app = app(); + let both = Modifiers { shift: true, alt: true, ..Default::default() }; + for (mode, want) in [(0, None), (1, Some(Badge::Add)), (2, Some(Badge::Subtract)), (3, Some(Badge::Intersect))] { + app.ui.selection_mode = mode; + assert_eq!(badge(&app, Tool::ObjectSelection, Modifiers::NONE), want, "bar mode {mode}"); + } + app.ui.selection_mode = 0; + assert_eq!(badge(&app, Tool::ObjectSelection, both), Some(Badge::Intersect)); +} + +#[test] +fn command_drag_inside_the_selection_moves_the_pixels() { + let mut app = app(); + click(&mut app, RED, Modifiers::NONE); + drag(&mut app, RED, [250.0, 220.0], Modifiers::COMMAND); + // The pixels float at the pointer (as with a marquee's ⌘-drag) and land as "Move" on the drop. + let offset = photocraft_engine::float_cmds::floating(app.session.active().unwrap()).map(|f| f.offset); + assert_eq!(offset, Some((50, 40)), "the selected pixels follow the drag"); + crate::menus::invoke(&mut app, &egui::Context::default(), "select.deselect", json!({})).unwrap(); + let labels: Vec = app.session.active().unwrap().history.entries().into_iter().map(|e| e.to_string()).collect(); + assert!(labels.iter().any(|l| l == "Move"), "{labels:?}"); + assert_eq!(alpha_at(&app, 100, 100), 0.0, "the pixels moved away"); + assert_eq!(alpha_at(&app, 340, 300), 1.0); +} + +#[test] +fn reset_tool_sets_the_mode_back_to_new() { + let ctx = egui::Context::default(); + let mut app = app(); + app.ui.selection_mode = 3; + crate::menus::invoke(&mut app, &ctx, "tool.reset", json!({})).unwrap(); + assert_eq!(app.ui.selection_mode, 0); +} + +#[test] +fn object_finder_off_keeps_quick_selection_and_the_rectangle_inside_the_selection() { + let mut app = app(); + click(&mut app, RED, Modifiers::NONE); + app.ui.tool_options.object_finder = false; + // A New-mode click inside the selection is still a Quick Selection dab, not Deselect. + click(&mut app, RED, Modifiers::NONE); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("select.quick")); + assert!(selected(&app, RED)); + // A drag inside it is still a rectangle Object Selection, not Move Selection. + drag(&mut app, [100.0, 100.0], [300.0, 260.0], Modifiers::NONE); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("select.object")); + assert_ne!(last_step(&app).as_deref(), Some("Move Selection")); +} + +#[test] +fn object_finder_off_dab_subtracts_with_alt_and_in_subtract_mode() { + let mut app = app(); + app.ui.tool_options.object_finder = false; + let shift_alt = Modifiers { shift: true, alt: true, ..Default::default() }; + for (bar, mods) in [(0, Modifiers::ALT), (0, shift_alt), (2, Modifiers::NONE)] { + app.run("select.all", json!({})).unwrap(); + app.ui.selection_mode = bar; + click(&mut app, RED, mods); + assert!(!selected(&app, RED), "bar mode {bar}, {mods:?} subtracts"); + assert!(selected(&app, [20.0, 20.0]), "bar mode {bar}, {mods:?} keeps the rest"); + } +} + +#[test] +fn indexed_color_alerts_instead_of_deselecting_or_moving_the_outline() { + let mut app = app(); + click(&mut app, RED, Modifiers::NONE); + app.run("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none"})).unwrap(); + assert!(selected(&app, RED)); + let steps = app.session.active().unwrap().history.past_len(); + let errors = |app: &PhotocraftApp| app.ui.dialogs.iter().filter(|d| d.kind == crate::state::DialogKind::Error).count(); + for gesture in 0..2 { + if gesture == 0 { + click(&mut app, RED, Modifiers::NONE); + } else { + drag(&mut app, RED, [250.0, 220.0], Modifiers::NONE); + } + assert_eq!(errors(&app), 1, "gesture {gesture}: the tool's alert"); + assert!(selected(&app, RED) && !selected(&app, [340.0, 300.0]), "gesture {gesture}: the selection stays"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps, "gesture {gesture}: no history step"); + app.ui.dialogs.clear(); + } +} diff --git a/crates/ui-egui/src/tools/path_components.rs b/crates/ui-egui/src/tools/path_components.rs index 74f866c624..09534432ef 100644 --- a/crates/ui-egui/src/tools/path_components.rs +++ b/crates/ui-egui/src/tools/path_components.rs @@ -32,6 +32,17 @@ fn target(app: &PhotocraftApp) -> Option<(PathRef, Path)> { active_paths(app).into_iter().next() } +/// A Path Selection press on a shape layer, off every component of the targeted saved path: +/// the saved path is no longer the target, so the press and drag act on the shape (#13270). +/// A press on one of the saved path's components keeps it targeted. +pub(crate) fn untarget_saved_path_off(app: &mut PhotocraftApp, at: [f64; 2], tol: f64) { + if let Some((PathRef::Saved(_), path)) = target(app) + && component_at(&path, at, tol).is_none() + { + app.ui.selected_path = None; + } +} + /// The selected components: their path and the first subpath of each, in order. `None` with /// nothing selected, a selection on a path that is not an active one any more, or a tool other /// than Path Selection (the only one that shows it, so the only one that acts on it). @@ -52,6 +63,12 @@ pub(crate) fn selected(app: &PhotocraftApp) -> Option<(PathRef, Path, Vec (!heads.is_empty()).then_some((r, path, heads)) } +/// Deselects every component (and anchor), leaving the path itself as it is. Shared with Direct +/// Selection's Enter (#13208). +pub(crate) fn deselect_components(app: &mut PhotocraftApp) { + app.ui.direct_selection = DirectSelection::default(); +} + /// The operation every selected component has, for the menu's icon; `None` when they differ. pub(crate) fn selected_op(app: &PhotocraftApp) -> Option<&'static str> { let (_, path, heads) = selected(app)?; @@ -64,7 +81,7 @@ pub(crate) fn selected_op(app: &PhotocraftApp) -> Option<&'static str> { /// for the next path. New Layer is not an operation a component can have: it only sets the tool. /// The first component always combines (it is what the others act on), so it keeps its operation. pub(crate) fn set_op(app: &mut PhotocraftApp, op: &str) -> Result<(), String> { - app.ui.tool_options.pen_path_op = op.into(); + *crate::vector_ui::path_op_field(app) = op.into(); if op == "newLayer" { return Ok(()); } @@ -272,3 +289,7 @@ pub fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "path_selection_enter_escape_tests.rs"] +mod path_selection_enter_escape_tests; diff --git a/crates/ui-egui/src/tools/path_selection_ctrl_direct_tests.rs b/crates/ui-egui/src/tools/path_selection_ctrl_direct_tests.rs new file mode 100644 index 0000000000..3803b84fd3 --- /dev/null +++ b/crates/ui-egui/src/tools/path_selection_ctrl_direct_tests.rs @@ -0,0 +1,92 @@ +//! #13284: with Path Selection and ⌘/Ctrl held, a press on an anchor acts as Direct Selection, as in +//! the reference application: only that anchor moves, in one History step. Without ⌘/Ctrl the tool +//! drags the whole component, and releasing ⌘/Ctrl goes back to that. + +use egui::Modifiers; +use photocraft_doc::Path; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +const SAVED: &str = "Path 1"; +const SQUARE: [[f64; 2]; 4] = [[100.0, 300.0], [300.0, 300.0], [300.0, 500.0], [100.0, 500.0]]; + +/// The closed square 100,300–300,500 saved as "Path 1", targeted, with Path Selection. +fn setup() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + let square = json!({"subpaths": [{"closed": true, "knots": SQUARE}]}); + app.run("path.set", json!({"name": SAVED, "path": square})).unwrap(); + app.ui.selected_path = Some(SAVED.into()); + app.ui.tool = Tool::PathSelection; + app +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods); + let mid = [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0]; + tool_event(app, ToolEvent::Move { x: mid[0], y: mid[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods); +} + +fn saved(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths.iter().find(|p| p.name == SAVED).unwrap().path.clone() +} + +fn anchors(app: &PhotocraftApp) -> Vec<[f64; 2]> { + saved(app).subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect() +} + +fn undo_label(app: &PhotocraftApp) -> Option { + app.session.active()?.history.undo_label().map(str::to_string) +} + +fn moved_by(d: [f64; 2]) -> Vec<[f64; 2]> { + SQUARE.iter().map(|p| [p[0] + d[0], p[1] + d[1]]).collect() +} + +/// "Drag Anchor Points" today; PR #13541 renames a one-anchor drag to the singular. +fn is_anchor_drag_label(label: Option<&str>) -> bool { + matches!(label, Some("Drag Anchor Points" | "Drag Anchor Point")) +} + +#[test] +fn ctrl_drag_on_an_anchor_moves_only_that_anchor_in_one_step() { + let mut app = setup(); + let before = undo_label(&app); + drag(&mut app, [100.0, 300.0], [80.0, 280.0], Modifiers::COMMAND); + assert_eq!(anchors(&app), vec![[80.0, 280.0], SQUARE[1], SQUARE[2], SQUARE[3]], "only the pressed anchor moved"); + assert!(is_anchor_drag_label(undo_label(&app).as_deref()), "one anchor-drag step: {:?}", undo_label(&app)); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(anchors(&app), SQUARE.to_vec(), "one undo restores the square"); + assert_eq!(undo_label(&app), before, "the drag was a single History step"); +} + +#[test] +fn ctrl_drag_on_an_anchor_of_a_selected_component_moves_only_that_anchor() { + let mut app = setup(); + // A plain click selects the whole component first. + drag(&mut app, [200.0, 300.0], [200.0, 300.0], Modifiers::NONE); + drag(&mut app, [100.0, 300.0], [80.0, 280.0], Modifiers::COMMAND); + assert_eq!(anchors(&app), vec![[80.0, 280.0], SQUARE[1], SQUARE[2], SQUARE[3]]); +} + +#[test] +fn a_drag_without_ctrl_still_moves_every_anchor() { + let mut app = setup(); + drag(&mut app, [100.0, 300.0], [80.0, 280.0], Modifiers::NONE); + assert_eq!(anchors(&app), moved_by([-20.0, -20.0]), "the whole component moved"); +} + +#[test] +fn releasing_ctrl_returns_to_moving_the_whole_component() { + let mut app = setup(); + drag(&mut app, [100.0, 300.0], [80.0, 280.0], Modifiers::COMMAND); + let after_ctrl = anchors(&app); + drag(&mut app, [200.0, 400.0], [210.0, 410.0], Modifiers::NONE); + let expected: Vec<[f64; 2]> = after_ctrl.iter().map(|p| [p[0] + 10.0, p[1] + 10.0]).collect(); + assert_eq!(anchors(&app), expected, "a plain drag moves the whole component again"); +} diff --git a/crates/ui-egui/src/tools/path_selection_enter_escape_tests.rs b/crates/ui-egui/src/tools/path_selection_enter_escape_tests.rs new file mode 100644 index 0000000000..9a3b174af5 --- /dev/null +++ b/crates/ui-egui/src/tools/path_selection_enter_escape_tests.rs @@ -0,0 +1,156 @@ +//! #13287: with Path Selection and components of the saved path targeted in the Paths panel +//! selected, Esc deselects the components and keeps the path targeted, and Enter deselects them and +//! untargets the path. Neither adds a History step or moves a point. + +use egui::{Key, Modifiers}; +use photocraft_doc::vector::Path; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::direct_select::{DirectSelection, PathRef, active_paths}; +use crate::state::Tool; + +/// 800 x 600 with the saved path "Path 1" (a square and a triangle) targeted, and the square +/// selected as a component. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + let path = json!({"subpaths": [ + {"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}, + {"closed": true, "knots": [[400, 300], [600, 300], [500, 500]]} + ]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::PathSelection; + app.ui.selected_path = Some("Path 1".into()); + crate::path_components::press(&mut app, [300.0, 300.0], false); + let (target, ..) = crate::path_components::selected(&app).expect("the square is selected"); + assert_eq!(target, PathRef::Saved(0)); + app +} + +fn press(app: &mut PhotocraftApp, key: Key, modifiers: Modifiers) { + let ctx = egui::Context::default(); + let ev = egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + ctx.begin_pass(egui::RawInput { events: vec![ev], ..Default::default() }); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); +} + +fn path_1(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths.iter().find(|p| p.name == "Path 1").unwrap().path.clone() +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.entries().len() +} + +fn nothing_selected(app: &PhotocraftApp) { + assert!(crate::path_components::selected(app).is_none(), "no component is selected"); + assert_eq!(app.ui.direct_selection, DirectSelection::default()); +} + +/// Until Path Selection has its own arrow-key nudge (#10920), an arrow key must move nothing once +/// the components are deselected. +fn arrow_moves_nothing(app: &mut PhotocraftApp) { + let (before, n) = (path_1(app), steps(app)); + press(app, Key::ArrowRight, Modifiers::NONE); + assert_eq!(path_1(app), before, "the arrow key moves no point"); + assert_eq!(steps(app), n, "and adds no History step"); +} + +#[test] +fn enter_deselects_the_components_and_untargets_the_path() { + let mut app = app(); + let (before, n) = (path_1(&app), steps(&app)); + press(&mut app, Key::Enter, Modifiers::NONE); + nothing_selected(&app); + assert_eq!(app.ui.selected_path, None, "Path 1 is no longer targeted"); + assert!(!active_paths(&app).iter().any(|(r, _)| *r == PathRef::Saved(0)), "its outline is gone"); + assert_eq!(path_1(&app), before); + assert_eq!(steps(&app), n, "Enter adds no History step"); + arrow_moves_nothing(&mut app); +} + +#[test] +fn escape_deselects_the_components_and_keeps_the_path_targeted() { + let mut app = app(); + let (before, n) = (path_1(&app), steps(&app)); + press(&mut app, Key::Escape, Modifiers::NONE); + nothing_selected(&app); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1")); + assert!(active_paths(&app).iter().any(|(r, _)| *r == PathRef::Saved(0)), "its outline stays"); + assert_eq!(path_1(&app), before); + assert_eq!(steps(&app), n, "Esc adds no History step"); + arrow_moves_nothing(&mut app); +} + +#[test] +fn enter_with_a_work_path_present_does_not_make_the_work_path_the_drawn_path() { + let mut app = app(); + let line = json!({"subpaths": [{"knots": [[100, 100], [200, 100]]}]}); + app.run("path.set", json!({"name": "work", "path": line})).unwrap(); + // `path.set` of the Work Path changes the panel's target: target Path 1 and its component again. + app.ui.selected_path = Some("Path 1".into()); + crate::path_components::press(&mut app, [300.0, 300.0], false); + assert!(crate::path_components::selected(&app).is_some()); + press(&mut app, Key::Enter, Modifiers::NONE); + assert_eq!(app.ui.selected_path, None); + assert!(!crate::vector_ui::work_path_shown(&app), "the Work Path stays hidden"); + assert!(active_paths(&app).is_empty(), "no path is drawn"); +} + +#[test] +fn escape_with_a_pixel_selection_deselects_the_pixels_and_keeps_the_components() { + let mut app = app(); + app.run("select.all", json!({})).unwrap(); + press(&mut app, Key::Escape, Modifiers::NONE); + assert!(app.session.active().unwrap().doc.selection.is_none(), "Esc deselects the pixels"); + assert!(crate::path_components::selected(&app).is_some(), "the components stay selected"); +} + +#[test] +fn shift_or_alt_with_enter_or_escape_keeps_the_components_and_the_path() { + for key in [Key::Enter, Key::Escape] { + for modifiers in [Modifiers::SHIFT, Modifiers::ALT] { + let mut app = app(); + press(&mut app, key, modifiers); + assert!(crate::path_components::selected(&app).is_some(), "{key:?} {modifiers:?}"); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "{key:?} {modifiers:?}"); + } + } +} + +#[test] +fn enter_and_escape_with_no_component_selected_keep_the_path_targeted() { + for key in [Key::Enter, Key::Escape] { + let mut app = app(); + crate::path_components::deselect_components(&mut app); + press(&mut app, key, Modifiers::NONE); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "{key:?}"); + } +} + +#[test] +fn free_transform_path_still_owns_enter_and_escape() { + let ctx = egui::Context::default(); + let mut app = app(); + let (before, n) = (path_1(&app), steps(&app)); + crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); + assert!(app.ui.transform.is_some()); + press(&mut app, Key::Escape, Modifiers::NONE); + assert!(app.ui.transform.is_none(), "Esc cancels the transform"); + assert_eq!(path_1(&app), before); + assert_eq!(steps(&app), n, "cancelling adds no History step"); + + let mut app = self::app(); + let n = steps(&app); + crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap(); + // 5 px down: an unchanged box commits nothing. + let t = app.ui.transform.as_mut().unwrap(); + let [x0, y0, x1, y1] = t.rect; + t.quad = [[x0, y0 + 5.0], [x1, y0 + 5.0], [x1, y1 + 5.0], [x0, y1 + 5.0]]; + press(&mut app, Key::Enter, Modifiers::NONE); + assert!(app.ui.transform.is_none(), "Enter commits the transform"); + assert_eq!(steps(&app), n + 1, "one History step"); +} diff --git a/crates/ui-egui/src/tools/path_selection_shape_over_saved_path_tests.rs b/crates/ui-egui/src/tools/path_selection_shape_over_saved_path_tests.rs new file mode 100644 index 0000000000..4590657480 --- /dev/null +++ b/crates/ui-egui/src/tools/path_selection_shape_over_saved_path_tests.rs @@ -0,0 +1,70 @@ +//! #13270: with a saved path targeted in the Paths panel, a Path Selection drag on a shape layer +//! targets and moves the shape, as in the reference application; the saved path keeps its points. +//! A drag on a component of the saved path still moves that component. + +use egui::Modifiers; +use photocraft_doc::{LayerContent, LayerId, Path}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +const SAVED: &str = "Path 1"; + +/// A rectangle shape at 500,100–700,200, a pixel layer "Red" above it, active, and the saved +/// path "Path 1" (a square 100,300–200,400) selected in the Paths panel, with Path Selection. +fn setup() -> (PhotocraftApp, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [500, 100, 200, 100], "fill": "#2050c0"})).unwrap(); + let shape = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.new.layer", json!({"name": "Red"})).unwrap(); + let square = json!({"subpaths": [{"closed": true, "knots": [[100, 300], [200, 300], [200, 400], [100, 400]]}]}); + app.run("path.set", json!({"name": SAVED, "path": square})).unwrap(); + app.ui.selected_path = Some(SAVED.into()); + app.ui.tool = Tool::PathSelection; + (app, shape) +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, Modifiers::NONE); + let mid = [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0]; + tool_event(app, ToolEvent::Move { x: mid[0], y: mid[1], pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, Modifiers::NONE); +} + +fn saved(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths.iter().find(|p| p.name == SAVED).unwrap().path.clone() +} + +fn shape_bounds(app: &PhotocraftApp, id: LayerId) -> Option<(f64, f64, f64, f64)> { + let doc = &app.session.active().unwrap().doc; + doc.walk().iter().find(|(_, _, l)| l.id == id).and_then(|(_, _, l)| match &l.content { + LayerContent::Shape(sh) => sh.path.control_bounds(), + _ => None, + }) +} + +#[test] +fn a_drag_on_a_shape_moves_the_shape_not_the_targeted_saved_path() { + let (mut app, shape) = setup(); + let (path_before, shape_before) = (saved(&app), shape_bounds(&app, shape).unwrap()); + drag(&mut app, [600.0, 150.0], [650.0, 200.0]); + assert_eq!(app.session.active().unwrap().active_layer, Some(shape), "the shape is the active layer"); + assert_eq!(saved(&app), path_before, "the saved path keeps its points"); + let (x0, y0, x1, y1) = shape_before; + assert_eq!(shape_bounds(&app, shape), Some((x0 + 50.0, y0 + 50.0, x1 + 50.0, y1 + 50.0)), "the shape moved by the drag"); + assert_eq!(app.ui.selected_path, None, "the saved path is no longer the target"); +} + +#[test] +fn a_drag_on_a_component_of_the_saved_path_still_moves_it() { + let (mut app, shape) = setup(); + let shape_before = shape_bounds(&app, shape); + drag(&mut app, [150.0, 350.0], [180.0, 370.0]); + assert_eq!(saved(&app).control_bounds(), Some((130.0, 320.0, 230.0, 420.0)), "the saved path moved"); + assert_eq!(shape_bounds(&app, shape), shape_before, "the shape stays"); + assert_eq!(app.ui.selected_path.as_deref(), Some(SAVED)); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_click_preview_tests.rs b/crates/ui-egui/src/tools/perspective_crop_click_preview_tests.rs index aef086e406..395498c0a3 100644 --- a/crates/ui-egui/src/tools/perspective_crop_click_preview_tests.rs +++ b/crates/ui-egui/src/tools/perspective_crop_click_preview_tests.rs @@ -188,3 +188,22 @@ fn hover_over_the_canvas_moves_the_preview() { assert!((q[2][0] - 110.0).abs() < 0.5 && (q[2][1] - 100.0).abs() < 0.5, "{q:?}"); assert_eq!(q[2], q[3]); } + +/// #13065: a drag that builds no box, which is what a start the snap moved onto its release +/// point gives, keeps the corners clicked so far, so the next click still finishes the quad. +#[test] +fn a_drag_that_makes_no_box_keeps_the_clicked_corners() { + let mut app = app(); + for p in [A, B, C] { + click(&mut app, p); + } + // A straight drag has no area, so `new_box` returns None and no quad replaces the clicks. + pointer(&mut app, ToolEvent::Down { x: 60.0, y: 70.0, pressure: 1.0 }, egui::Modifiers::NONE); + pointer(&mut app, ToolEvent::Move { x: 120.0, y: 70.0, pressure: 1.0 }, egui::Modifiers::NONE); + pointer(&mut app, ToolEvent::Up { x: 120.0, y: 70.0 }, egui::Modifiers::NONE); + assert_eq!(app.ui.perspective_crop, None, "a drag with no area builds no box"); + assert_eq!(app.pcrop.clicks, vec![A, B, C], "the three clicks stay"); + click(&mut app, D); + assert!(app.pcrop.clicks.is_empty(), "the fourth click still finishes the quad"); + assert_eq!(app.ui.perspective_crop, Some([A, B, C, D])); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_fields_tests.rs b/crates/ui-egui/src/tools/perspective_crop_fields_tests.rs new file mode 100644 index 0000000000..4d3e7c0209 --- /dev/null +++ b/crates/ui-egui/src/tools/perspective_crop_fields_tests.rs @@ -0,0 +1,182 @@ +//! #11977: Perspective Crop's W, H and Resolution clamp to the reference application's ranges with +//! its alerts, text that isn't a number restores the last value with an alert, Clear also resets +//! the resolution unit, and the Crop tool's fields keep today's behaviour. + +use egui_kittest::kittest::Queryable; + +use super::*; +use crate::crop_size::{clamp_length, clamp_resolution, normalize_length, normalize_resolution}; + +const PX_ALERT: &str = "A value between 1.000 Pixels and 300000.000 Pixels is required. Closest value inserted."; +const RES_ALERT: &str = "A number between 1.000 and 29999.999 is required. Closest value inserted."; +const INVALID: &str = "Invalid numeric entry. Restored last valid value."; + +fn length(typed: &str, previous: &str) -> (String, Option) { + crate::i18n::with_decimal_separator(Some('.'), || clamp_length(typed, previous, 72.0, 72.0)) +} + +fn resolution(typed: &str, previous: &str, per_cm: bool) -> (String, Option) { + crate::i18n::with_decimal_separator(Some('.'), || clamp_resolution(typed, previous, per_cm)) +} + +#[test] +fn w_and_h_clamp_to_1_and_300000_px_with_the_alert() { + assert_eq!(length("-5", "100 px"), ("1 px".to_string(), Some(PX_ALERT.to_string()))); + assert_eq!(length("0", "100 px"), ("1 px".to_string(), Some(PX_ALERT.to_string()))); + assert_eq!(length("999999", "100 px"), ("300000 px".to_string(), Some(PX_ALERT.to_string()))); + assert_eq!(length("1", "100 px"), ("1 px".to_string(), None)); + assert_eq!(length("300000", ""), ("300000 px".to_string(), None)); + assert_eq!(length("640", "100 px"), ("640 px".to_string(), None)); + assert_eq!(length("", "100 px"), (String::new(), None), "empty stays empty, no alert"); +} + +#[test] +fn other_units_clamp_to_the_converted_limits() { + // At 72 ppi, 300000 px is 4166.667 in; 1 px is 0.014 in. + let (kept, alert) = length("9999 in", "100 px"); + assert_eq!(kept, "4166.667 in"); + assert_eq!(alert.as_deref(), Some("A value between 0.014 Inches and 4166.667 Inches is required. Closest value inserted.")); + assert_eq!(length("4 in", "100 px"), ("4 in".to_string(), None)); +} + +#[test] +fn text_that_isnt_a_number_restores_the_last_value() { + assert_eq!(length("abc", "120 px"), ("120 px".to_string(), Some(INVALID.to_string()))); + assert_eq!(length("12 parsecs", "120 px"), ("120 px".to_string(), Some(INVALID.to_string()))); + assert_eq!(resolution("lots", "300", false), ("300".to_string(), Some(INVALID.to_string()))); +} + +#[test] +fn the_resolution_clamps_to_1_and_29999_999_with_its_alert() { + assert_eq!(resolution("0", "300", false), ("1".to_string(), Some(RES_ALERT.to_string()))); + assert_eq!(resolution("99999", "300", false), ("29999.999".to_string(), Some(RES_ALERT.to_string()))); + assert_eq!(resolution("20000", "300", false), ("20000".to_string(), None), "20000 is kept, and commits (below)"); + assert_eq!(resolution("72", "", false), ("72".to_string(), None)); + // px/cm: the per-inch limits divided by 2.54 (not measured beyond that conversion). + let (kept, alert) = resolution("99999", "100", true); + assert_eq!(kept, "11811.023"); + assert_eq!(alert.as_deref(), Some("A number between 0.394 and 11811.023 is required. Closest value inserted.")); + assert_eq!(resolution("0", "100", true).0, "0.394"); +} + +#[test] +fn the_alerts_use_the_system_decimal_separator() { + let (_, alert) = crate::i18n::with_decimal_separator(Some(','), || clamp_length("0", "100 px", 72.0, 72.0)); + assert_eq!(alert.as_deref(), Some("A value between 1,000 Pixels and 300000,000 Pixels is required. Closest value inserted.")); + let (_, alert) = crate::i18n::with_decimal_separator(Some(','), || clamp_resolution("99999", "300", false)); + assert_eq!(alert.as_deref(), Some("A number between 1,000 and 29999,999 is required. Closest value inserted.")); +} + +#[test] +fn the_crop_tools_fields_keep_todays_behaviour() { + assert_eq!(normalize_length("-5", "100 px"), "100 px"); + assert_eq!(normalize_length("999999", "100 px"), "999999 px"); + assert_eq!(normalize_length("abc", "100 px"), "100 px"); + assert_eq!(normalize_resolution("99999", "300"), "99999"); + assert_eq!(normalize_resolution("0", "300"), "300"); +} + +/// A 200 × 150 document with the Perspective Crop tool and a pending quad. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::PerspectiveCrop; + app +} + +fn crop(app: &mut PhotocraftApp, resolution: f64) -> Result { + let corners = [[10.0, 10.0], [190.0, 10.0], [190.0, 140.0], [10.0, 140.0]]; + app.run("image.perspectiveCrop", json!({"corners": corners, "resolution": resolution})).map_err(|e| e.to_string()) +} + +#[test] +fn the_crop_accepts_up_to_29999_999_ppi() { + let mut app = app(); + assert!(crop(&mut app, 20000.0).is_ok(), "20000 ppi typed into the field commits"); + let mut app2 = self::app(); + assert!(crop(&mut app2, 29_999.999).is_ok()); + let mut app3 = self::app(); + let err = crop(&mut app3, 30_000.0).unwrap_err(); + assert!(err.contains("29999.999"), "{err}"); +} + +/// The options bar in a harness with the app's fonts and theme. +fn harness(app: PhotocraftApp) -> egui_kittest::Harness<'static, PhotocraftApp> { + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 80.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::panels::options_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(4); + h +} + +/// The options bar in a harness, with `typed` committed (Enter) into its `nth` text field (0 = W). +fn type_into(app: PhotocraftApp, nth: usize, typed: &str) -> PhotocraftApp { + use egui::accesskit::Role; + let mut h = harness(app); + h.get_all_by_role(Role::TextInput).nth(nth).expect("the field").click(); + h.run(); + h.get_all_by_role(Role::TextInput).nth(nth).expect("the field").type_text(typed); + h.run(); + h.key_press(egui::Key::Enter); + h.run(); + h.run(); + h.into_state() +} + +#[test] +fn an_out_of_range_width_in_the_options_bar_opens_the_alert() { + let app = crate::i18n::with_decimal_separator(Some('.'), || type_into(app(), 0, "999999")); + assert_eq!(app.ui.tool_options.crop_width, "300000 px"); + let messages: Vec<&str> = + app.ui.dialogs.iter().filter(|d| d.kind == crate::state::DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str()).collect(); + assert_eq!(messages, [PX_ALERT]); +} + +#[test] +fn clear_also_resets_the_resolution_unit() { + let mut app = app(); + let o = &mut app.ui.tool_options; + o.crop_width = "4 in".into(); + o.crop_height = "5 in".into(); + o.crop_resolution = "118.11".into(); + o.crop_resolution_unit = crate::crop_size::PX_PER_CM.into(); + let mut h = harness(app); + h.get_by_label("Clear").click(); + h.run(); + let o = &h.state().ui.tool_options; + assert!(o.crop_width.is_empty() && o.crop_height.is_empty() && o.crop_resolution.is_empty()); + assert_eq!(o.crop_resolution_unit, crate::crop_size::PX_PER_IN); +} + +#[test] +fn the_resolution_never_rounds_past_the_limit() { + // The px/cm limit is 11811.0232…: just below it keeps 11811.023, just above it is out of range. + assert_eq!(resolution("11811.0232", "100", true), ("11811.023".to_string(), None)); + assert_eq!(resolution("11811.0236", "100", true).0, "11811.023"); + assert_eq!(crate::crop_size::fit_resolution(29_999.999_5, false), "29999.999"); + assert_eq!(crate::crop_size::fit_resolution(118.110_236, true), "118.11"); +} + +#[test] +fn front_image_keeps_a_30000_ppi_documents_resolution_within_the_limit() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150, "resolution": 30000})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::PerspectiveCrop; + let mut h = harness(app); + h.get_by_label("Front Image").click(); + h.run(); + let app = h.into_state(); + assert_eq!(app.ui.tool_options.crop_resolution, "29999.999"); + let ppi = crate::crop_size::resolution_ppi(&app.ui.tool_options).unwrap(); + let mut app = app; + assert!(crop(&mut app, ppi).is_ok()); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_mirrored_tests.rs b/crates/ui-egui/src/tools/perspective_crop_mirrored_tests.rs new file mode 100644 index 0000000000..e01e64387c --- /dev/null +++ b/crates/ui-egui/src/tools/perspective_crop_mirrored_tests.rs @@ -0,0 +1,138 @@ +//! #12489: a Perspective Crop box flipped on one axis (⌥ dragging a corner past the opposite one +//! along x only) is wound counter-clockwise. It is drawn valid and commits mirrored, each corner +//! mapped as it lies, as in the reference application; `image.perspectiveCrop` takes the same +//! corners. Clicked corners still commit upright, a box turned 180° still commits upside down, and +//! self-crossing and degenerate quads stay invalid. + +use std::sync::Arc; + +use egui::{Modifiers, Pos2, Rect, vec2}; +use serde_json::json; + +use super::*; + +const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; +const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; +const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; +const YELLOW: [f32; 4] = [1.0, 1.0, 0.0, 1.0]; + +/// The measured test document: 800 x 500, red (top left), green (top right), blue (bottom left) +/// and yellow (bottom right) quadrants with a black square in the middle; the Perspective Crop tool. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 500})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::PerspectiveCrop; + let surf = Arc::make_mut(&mut app.session.active_mut().unwrap().doc).layers[0].surface_mut().unwrap(); + for (x, y, c) in [(0, 0, RED), (400, 0, GREEN), (0, 250, BLUE), (400, 250, YELLOW)] { + surf.fill_rect(photocraft_geom::Rect::from_xywh(x, y, 400, 250), &c); + } + surf.fill_rect(photocraft_geom::Rect::from_xywh(395, 245, 10, 10), &[0.0, 0.0, 0.0, 1.0]); + app +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + assert!(pointer(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods)); + let mid = [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0]; + assert!(pointer(app, ToolEvent::Move { x: mid[0], y: mid[1], pressure: 1.0 }, mods)); + assert!(pointer(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods)); + assert!(pointer(app, ToolEvent::Up { x: to[0], y: to[1] }, mods)); +} + +fn click(app: &mut PhotocraftApp, p: [f64; 2]) { + drag(app, p, p, Modifiers::NONE); +} + +/// The overlay `draw_overlay` paints: (shield polygons, whether the frame is red). +fn overlay(app: &PhotocraftApp) -> (usize, bool) { + let ctx = egui::Context::default(); + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)), zoom: 1.0, center: [400.0, 250.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let mut o = ctx.run_ui(Default::default(), |ui| draw_overlay(app, ui.painter(), &xf)); + o.textures_delta.clear(); + let shield = o.shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Path(p) if p.fill == SHIELD)).count(); + let red = Color32::from_rgb(0xe5, 0x3e, 0x3e); + let frame_red = o.shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Path(p) if p.closed && p.stroke.color == egui::epaint::ColorMode::Solid(red))); + (shield, frame_red) +} + +/// The committed canvas's size and the colours at its four corners (TL, TR, BL, BR). +fn corners(app: &PhotocraftApp) -> ((u32, u32), [[f32; 4]; 4]) { + let doc = &app.session.active().unwrap().doc; + let (w, h) = (doc.size.width as i32, doc.size.height as i32); + let surf = doc.layers[0].surface().unwrap(); + ((doc.size.width, doc.size.height), [surf.rgba(3, 3), surf.rgba(w - 4, 3), surf.rgba(3, h - 4), surf.rgba(w - 4, h - 4)]) +} + +#[test] +fn alt_corner_drag_past_the_opposite_corner_on_one_axis_commits_mirrored() { + let mut app = app(); + // A fresh 100 x 100 box, its bottom right corner ⌥ dragged past the fixed top left one on x only. + drag(&mut app, [450.0, 220.0], [550.0, 320.0], Modifiers::NONE); + drag(&mut app, [550.0, 320.0], [350.0, 300.0], Modifiers::ALT); + assert_eq!(app.ui.perspective_crop, Some([[450.0, 220.0], [350.0, 220.0], [350.0, 300.0], [450.0, 300.0]]), "flipped left to right"); + let (shield, red) = overlay(&app); + assert!(shield > 0 && !red, "drawn as a valid quad: accent frame and shield, not red"); + commit(&mut app); + assert!(app.ui.perspective_crop.is_none(), "committed"); + let (size, [tl, tr, bl, br]) = corners(&app); + assert_eq!(size, (100, 80)); + assert_eq!([tl, tr, bl, br], [GREEN, RED, YELLOW, BLUE], "mirrored left to right, top stays on top"); +} + +#[test] +fn the_command_takes_counter_clockwise_corners_and_mirrors() { + let mut app = app(); + let r = app.run("image.perspectiveCrop", json!({"corners": [[450, 220], [350, 220], [350, 300], [450, 300]]})).unwrap(); + assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(100), Some(80))); + assert_eq!(corners(&app).1, [GREEN, RED, YELLOW, BLUE]); + // Mirrored top to bottom the other way round. + let mut app = self::app(); + app.run("image.perspectiveCrop", json!({"corners": [[350, 300], [450, 300], [450, 220], [350, 220]]})).unwrap(); + assert_eq!(corners(&app).1, [BLUE, YELLOW, RED, GREEN]); +} + +#[test] +fn clicked_corners_commit_upright_in_any_order() { + let mut app = app(); + // Counter-clockwise clicks from the top left. + for p in [[350.0, 220.0], [350.0, 300.0], [450.0, 300.0], [450.0, 220.0]] { + click(&mut app, p); + } + assert_eq!(app.ui.perspective_crop, Some([[350.0, 220.0], [450.0, 220.0], [450.0, 300.0], [350.0, 300.0]]), "sorted clockwise"); + commit(&mut app); + assert_eq!(corners(&app), ((100, 80), [RED, GREEN, BLUE, YELLOW])); +} + +#[test] +fn a_box_turned_180_degrees_commits_upside_down() { + let mut app = app(); + drag(&mut app, [450.0, 300.0], [550.0, 400.0], Modifiers::NONE); + drag(&mut app, [550.0, 400.0], [350.0, 200.0], Modifiers::ALT); + assert_eq!(app.ui.perspective_crop, Some([[450.0, 300.0], [350.0, 300.0], [350.0, 200.0], [450.0, 200.0]])); + commit(&mut app); + assert_eq!(corners(&app), ((100, 100), [YELLOW, BLUE, GREEN, RED])); +} + +#[test] +fn self_crossing_and_degenerate_quads_stay_invalid() { + for q in [ + // Self-crossing (a bow tie), each way round. + [[350.0, 220.0], [450.0, 220.0], [350.0, 300.0], [450.0, 300.0]], + [[450.0, 220.0], [350.0, 220.0], [450.0, 300.0], [350.0, 300.0]], + // Three corners on a line, and no area. + [[350.0, 220.0], [400.0, 220.0], [450.0, 220.0], [350.0, 300.0]], + [[400.0, 250.0]; 4], + ] { + let mut app = app(); + app.ui.perspective_crop = Some(q); + let (shield, red) = overlay(&app); + assert!(shield == 0 && red, "{q:?} is drawn red without the shield"); + assert!(app.run("image.perspectiveCrop", json!({ "corners": q })).is_err(), "{q:?}"); + commit(&mut app); + assert_eq!(app.ui.perspective_crop, Some(q), "{q:?} stays for fixing"); + assert_eq!(app.session.active().unwrap().doc.size.width, 800); + } + let mut app = app(); + assert!(app.run("image.perspectiveCrop", json!({"corners": [[350, 220], [f64::NAN, 220], [450, 300], [350, 300]]})).is_err()); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_modifiers_tests.rs b/crates/ui-egui/src/tools/perspective_crop_modifiers_tests.rs index 1a95a885ad..2ed163575f 100644 --- a/crates/ui-egui/src/tools/perspective_crop_modifiers_tests.rs +++ b/crates/ui-egui/src/tools/perspective_crop_modifiers_tests.rs @@ -1,6 +1,8 @@ //! #11802: ⇧ and ⌥ constrain the Perspective Crop's new drag (a square, from the centre) and its //! corner drags (one axis, stays a rectangle). Ctrl, and no modifier, keep today's behaviour. +use std::sync::Arc; + use egui::Modifiers; use super::*; @@ -90,6 +92,41 @@ fn alt_corner_drag_keeps_a_rectangle() { assert_eq!(app.ui.perspective_crop, rect(50.0, 160.0, 740.0, 430.0)); } +/// #11802: ⌥ dragging a corner past the opposite one on both axes keeps today's result: the +/// rectangle turned 180° (the corners keep their order, so it commits upside down). Crossing on +/// one axis only is a separate item. +#[test] +fn alt_corner_drag_past_the_opposite_corner_on_both_axes_turns_the_rectangle_180_degrees() { + let mut app = app(); + app.ui.perspective_crop = Some([[100.0, 100.0], [500.0, 100.0], [500.0, 400.0], [100.0, 400.0]]); + // Where the turned rectangle will lie (40,60 to 100,100): a red patch in its bottom right and + // a green one in its top left. + let patch = |app: &mut PhotocraftApp, x: i32, y: i32, c: [f32; 4]| { + Arc::make_mut(&mut app.session.active_mut().unwrap().doc).layers[0] + .surface_mut() + .unwrap() + .fill_rect(photocraft_geom::Rect::from_xywh(x, y, 10, 10), &c); + }; + patch(&mut app, 90, 90, [1.0, 0.0, 0.0, 1.0]); + patch(&mut app, 40, 60, [0.0, 1.0, 0.0, 1.0]); + // The bottom right corner goes above and to the left of the fixed top left one. + drag(&mut app, [500.0, 400.0], [40.0, 60.0], ALT); + assert_eq!( + app.ui.perspective_crop, + Some([[100.0, 100.0], [40.0, 100.0], [40.0, 60.0], [100.0, 60.0]]), + "the opposite corner stays, the neighbours follow, the corners keep their order: the rectangle turned 180 degrees" + ); + // Committing keeps that: a 60 x 40 canvas upside down, the red patch (the old bottom right) + // at the top left and the green one (the old top left) at the bottom right. + commit(&mut app); + assert!(app.ui.perspective_crop.is_none(), "committed"); + let doc = &app.session.active().unwrap().doc; + assert_eq!((doc.size.width, doc.size.height), (60, 40)); + let surf = doc.layers[0].surface().unwrap(); + assert_eq!(surf.rgba(3, 3), [1.0, 0.0, 0.0, 1.0], "upside down: the red patch is at the top left"); + assert_eq!(surf.rgba(56, 36), [0.0, 1.0, 0.0, 1.0], "upside down: the green patch is at the bottom right"); +} + #[test] fn alt_corner_drag_on_a_skewed_quad_moves_the_corner_alone() { // Not measured: today's single-corner drag. diff --git a/crates/ui-egui/src/tools/perspective_crop_shield_tests.rs b/crates/ui-egui/src/tools/perspective_crop_shield_tests.rs index c210a46095..edf4466931 100644 --- a/crates/ui-egui/src/tools/perspective_crop_shield_tests.rs +++ b/crates/ui-egui/src/tools/perspective_crop_shield_tests.rs @@ -95,3 +95,49 @@ fn the_shield_shows_with_a_quad_follows_a_drag_and_goes_away() { cancel(&mut app); assert_eq!(painted(&app), 0, "gone after cancel"); } + +/// The shield polygons `draw_overlay` paints, in screen px (the same as document px here). +fn shield_polygons(app: &PhotocraftApp) -> Vec> { + let ctx = egui::Context::default(); + let xf = ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(200.0, 150.0)), zoom: 1.0, center: [100.0, 75.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let mut o = ctx.run_ui(Default::default(), |ui| draw_overlay(app, ui.painter(), &xf)); + o.textures_delta.clear(); + o.shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Path(p) if p.fill == SHIELD => Some(p.points.iter().map(|v| [f64::from(v.x), f64::from(v.y)]).collect()), + _ => None, + }) + .collect() +} + +fn dimmed(app: &PhotocraftApp, p: [f64; 2]) -> bool { + shield_polygons(app).iter().any(|poly| contains(poly, p)) +} + +#[test] +fn the_shield_follows_a_corner_drag_and_a_move_drag() { + let mut app = app(); + let ev = |app: &mut PhotocraftApp, e| assert!(pointer(app, e, egui::Modifiers::NONE)); + app.ui.perspective_crop = Some([[20.0, 20.0], [180.0, 20.0], [180.0, 130.0], [20.0, 130.0]]); + let covered = |app: &PhotocraftApp| shield_polygons(app).iter().map(|p| area(p)).sum::(); + assert!((covered(&app) - (area(&CANVAS) - 160.0 * 110.0)).abs() < 0.5, "{}", covered(&app)); + + // The bottom right corner dragged to (150, 100), the button still held. + ev(&mut app, ToolEvent::Down { x: 180.0, y: 130.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 150.0, y: 100.0, pressure: 1.0 }); + assert!(matches!(app.pcrop.drag, Some(Drag::Corner { index: 2, .. })), "{:?}", app.pcrop.drag); + let q = [[20.0, 20.0], [180.0, 20.0], [150.0, 100.0], [20.0, 130.0]]; + assert!((covered(&app) - (area(&CANVAS) - area(&q))).abs() < 0.5, "the shield follows the corner: {}", covered(&app)); + assert!(dimmed(&app, [170.0, 120.0]), "the corner's old place is dimmed during the drag"); + ev(&mut app, ToolEvent::Up { x: 150.0, y: 100.0 }); + + // The whole quad moved by (10, 5), the button still held. + ev(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 70.0, y: 65.0, pressure: 1.0 }); + assert!(matches!(app.pcrop.drag, Some(Drag::Move { .. })), "{:?}", app.pcrop.drag); + assert!(dimmed(&app, [22.0, 60.0]), "left of the moved quad is dimmed during the move"); + assert!(!dimmed(&app, [185.0, 30.0]), "inside the moved quad is not dimmed during the move"); + ev(&mut app, ToolEvent::Up { x: 70.0, y: 65.0 }); + assert!(!dimmed(&app, [185.0, 30.0]) && dimmed(&app, [22.0, 60.0]), "and after it"); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_ui.rs b/crates/ui-egui/src/tools/perspective_crop_ui.rs index 2906dcdcce..aad099ee2c 100644 --- a/crates/ui-egui/src/tools/perspective_crop_ui.rs +++ b/crates/ui-egui/src/tools/perspective_crop_ui.rs @@ -4,8 +4,8 @@ //! BL in document px; clicked corners are put in that order); //! - drag a corner to move it alone, onto an edge of a skewed object (a photographed page, a //! facade); drag inside the quad to move it; -//! - the quad shows its perspective grid (Show Grid) and turns red while it isn't a convex quad -//! wound like its box, which can't be committed; +//! - the quad shows its perspective grid (Show Grid) and turns red while it isn't a convex quad, +//! which can't be committed; one flipped on one axis (wound the other way) commits mirrored; //! - ↵ (or ✓) commits: `image.perspectiveCrop` maps the quad onto an upright rectangle, the whole //! document in one undo step. Its size comes from the options bar's W x H (and the resolution), //! which are the Crop tool's fields (`crop_size`), or with them empty from the rectangle the @@ -14,7 +14,7 @@ //! A pending quad belongs to the document it was drawn on, like the Crop tool's frame. use egui::{Color32, Pos2, Stroke}; -use photocraft_algo::transform::{Homography, convex_quad}; +use photocraft_algo::transform::{Homography, convex_quad, convex_quad_any_winding}; use photocraft_engine::prefs::Unit; use serde_json::{Value, json}; @@ -109,6 +109,47 @@ fn inside(q: &[[f64; 2]; 4], p: [f64; 2]) -> bool { }) } +/// What a press at a point does, which the hover cursor shows (#11974). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Zone { + /// No quad yet: a press starts a box or places a corner. + Idle, + /// Within the corner tolerance: a press drags that corner. + Corner(usize), + /// Inside the quad: a press moves it. + Inside, + /// Elsewhere with a quad: a press does nothing yet (edge handles and rotate are #11801). + Outside, +} + +/// The zone at `p` (document px): the hit-testing of a press in [`pointer`]. +pub fn zone(app: &PhotocraftApp, p: [f64; 2]) -> Zone { + let Some(q) = app.ui.perspective_crop else { + return Zone::Idle; + }; + let tol = crate::distort_ui::tolerance(app); + let dist = |i: usize| (q[i][0] - p[0]).hypot(q[i][1] - p[1]); + match (0..4).filter(|&i| dist(i) <= tol).min_by(|&i, &j| dist(i).total_cmp(&dist(j))) { + Some(index) => Zone::Corner(index), + None if inside(&q, p) => Zone::Inside, + None => Zone::Outside, + } +} + +/// The hover cursor's zone at `p`: what a press there does. While a drag is held it stays the +/// zone the drag started in, as the Crop tool keeps its drag's cursor (not measured). +pub fn cursor(app: &PhotocraftApp, p: [f64; 2]) -> Option { + if !active(app) || !p[0].is_finite() || !p[1].is_finite() { + return None; + } + Some(match app.pcrop.drag { + Some(Drag::New { .. }) => Zone::Idle, + Some(Drag::Corner { index, .. }) => Zone::Corner(index), + Some(Drag::Move { .. }) => Zone::Inside, + None => zone(app, p), + }) +} + /// The box a new drag from `start` to `cur` draws (document px, x0, y0, x1, y1): ⇧ makes it a /// square of the shorter drag side in the drag's direction, ⌥ centres it on `start` at twice the /// drag, both together a centred square (#11802). `None` without area. @@ -148,7 +189,6 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> return true; } cancel_stale(app); - let tol = crate::distort_ui::tolerance(app); match ev { ToolEvent::Down { .. } => { // A new quad's first press drops an active selection as its own "Deselect" step, as in @@ -161,18 +201,11 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> { return true; } - app.pcrop.drag = match app.ui.perspective_crop { - Some(q) => { - let near = (0..4) - .filter(|&i| (q[i][0] - p[0]).hypot(q[i][1] - p[1]) <= tol) - .min_by(|&i, &j| (q[i][0] - p[0]).hypot(q[i][1] - p[1]).total_cmp(&(q[j][0] - p[0]).hypot(q[j][1] - p[1]))); - match near { - Some(index) => Some(Drag::Corner { index, offset: [p[0] - q[index][0], p[1] - q[index][1]], press: p, quad: q }), - None if inside(&q, p) => Some(Drag::Move { start: p, quad: q }), - None => None, - } - } - None => Some(Drag::New { start: p, cur: p, square: mods.shift, centred: mods.alt }), + app.pcrop.drag = match (zone(app, p), app.ui.perspective_crop) { + (Zone::Corner(index), Some(q)) => Some(Drag::Corner { index, offset: [p[0] - q[index][0], p[1] - q[index][1]], press: p, quad: q }), + (Zone::Inside, Some(q)) => Some(Drag::Move { start: p, quad: q }), + (Zone::Idle, _) => Some(Drag::New { start: p, cur: p, square: mods.shift, centred: mods.alt }), + _ => None, }; } ToolEvent::Move { .. } => { @@ -189,9 +222,12 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> app.ui.perspective_crop = Some(ordered([a, b, c, d])); app.pcrop.clicks.clear(); } - } else { + } else if let Some(quad) = new_box(start, cur, square, centred) { + // Only a drag that built a box replaces the corners clicked so far. One that + // made none (a start the snap moved onto its release point) leaves them, so the + // next click still finishes the quad (#13065). app.pcrop.clicks.clear(); - app.ui.perspective_crop = new_box(start, cur, square, centred); + app.ui.perspective_crop = Some(quad); } } app.pcrop.drag = None; @@ -390,7 +426,8 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform _ => app.ui.perspective_crop, }; if let Some(q) = quad.filter(|q| q.iter().flatten().all(|v| v.is_finite())) { - let ok = convex_quad(&q); + // A quad flipped on one axis is wound counter-clockwise and commits mirrored (#12489). + let ok = convex_quad_any_winding(&q); let color = if ok { accent } else { Color32::from_rgb(0xe5, 0x3e, 0x3e) }; // The image outside the quad is dimmed (#11972), following the quad while it is dragged. if ok && let Some(size) = app.session.active().map(|d| d.doc.size) { @@ -456,18 +493,26 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform /// Options bar: W, ⇄, H, the resolution (the Crop tool's fields), Front Image, Clear, Show Grid, /// and cancel / commit. pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - crate::crop_size::fields(&mut app.ui.tool_options, ui); + let doc_dpi = app.session.active().map_or(72.0, |st| f64::from(st.doc.resolution_dpi)); + let pt_per_in = app.session.prefs().units_and_rulers.point_size.per_inch(); + // Out-of-range numbers and text get the reference application's alerts (#11977). + if let Some(message) = crate::crop_size::perspective_fields(&mut app.ui.tool_options, ui, doc_dpi, pt_per_in) { + app.ui.open_dialog(crate::state::DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default()); + } if crate::widgets::secondary_button(ui, tl!("Front Image"), 0.0).clicked() && let Some((size, dpi)) = app.session.active().map(|st| (st.doc.size, f64::from(st.doc.resolution_dpi))) { let o = &mut app.ui.tool_options; o.crop_width = crate::crop_size::format_length(f64::from(size.width), Unit::Pixels); o.crop_height = crate::crop_size::format_length(f64::from(size.height), Unit::Pixels); - let res = if o.crop_resolution_unit == crate::crop_size::PX_PER_CM { dpi / 2.54 } else { dpi }; - o.crop_resolution = crate::widgets::fmt_num2(res); + let per_cm = o.crop_resolution_unit == crate::crop_size::PX_PER_CM; + // Within the field's limits, so a 30000 ppi document's resolution still commits. + o.crop_resolution = crate::crop_size::fit_resolution(if per_cm { dpi / 2.54 } else { dpi }, per_cm); } if crate::widgets::secondary_button(ui, tl!("Clear"), 0.0).clicked() { crate::crop_size::clear(&mut app.ui.tool_options); + // Clear also puts the resolution unit back to px/in (#11977). + app.ui.tool_options.crop_resolution_unit = crate::crop_size::PX_PER_IN.into(); } crate::widgets::vline(ui, 22.0); crate::widgets::checkbox(ui, &mut app.ui.tool_options.perspective_crop_grid, tl!("Show Grid")); @@ -486,6 +531,10 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { }); } +#[cfg(test)] +#[path = "perspective_crop_fields_tests.rs"] +mod perspective_crop_fields_tests; + #[cfg(test)] #[path = "perspective_crop_click_preview_tests.rs"] mod perspective_crop_click_preview_tests; @@ -506,6 +555,10 @@ mod perspective_crop_shield_tests; #[path = "perspective_crop_deselect_tests.rs"] mod perspective_crop_deselect_tests; +#[cfg(test)] +#[path = "perspective_crop_mirrored_tests.rs"] +mod perspective_crop_mirrored_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/tools/polygon_sides_alert_tests.rs b/crates/ui-egui/src/tools/polygon_sides_alert_tests.rs new file mode 100644 index 0000000000..5d94f034b4 --- /dev/null +++ b/crates/ui-egui/src/tools/polygon_sides_alert_tests.rs @@ -0,0 +1,186 @@ +//! #13304: the Polygon tool's Sides takes whole numbers 3..100; a value typed past the range becomes +//! the closest one and, once the field is left, the reference's "Closest value inserted" alert with +//! OK says so. A scrub, arrow-key or wheel step past either end stops there without one. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::SIDES_RANGE_ALERT; +use crate::PhotocraftApp; +use crate::state::{DialogKind, Tool}; + +/// The options bar with the Polygon tool active. +fn bar() -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = Tool::Polygon; + let mut h = Harness::builder().with_size(vec2(1800.0, 300.0)).build_ui_state( + |ui, app| { + // As the app's frame does: the wheel goes to the focused field. + crate::field_wheel::begin_frame(ui.ctx()); + crate::panels::options_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +/// Clicks into Sides and gives back where it sits. +fn click_sides(h: &mut Harness<'static, PhotocraftApp>) -> egui::Rect { + let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Sides:")).expect("the Sides field"); + let rect = field.rect(); + field.click(); + h.run_steps(1); + rect +} + +/// Types `text` into Sides, then Tabs out of it. +fn type_sides(h: &mut Harness<'static, PhotocraftApp>, text: &str) { + click_sides(h); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn alerts(h: &Harness<'static, PhotocraftApp>) -> Vec { + h.state().ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(str::to_owned)).collect() +} + +/// OK on the alert, as `ui.dialog.confirm` presses it (this harness draws only the bar). +fn ok(h: &mut Harness<'static, PhotocraftApp>) { + let id = h.state().ui.dialogs.iter().find(|d| d.kind == DialogKind::Error).map(|d| d.id).expect("an alert"); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + h.run_steps(3); +} + +fn sides(h: &Harness<'static, PhotocraftApp>) -> u32 { + h.state().ui.tool_options.polygon_sides +} + +#[test] +fn sides_past_the_range_takes_the_closest_value_and_alerts() { + for (typed, want) in [("0", 3), ("2", 3), ("-5", 3), ("101", 100), ("1000", 100)] { + let mut h = bar(); + type_sides(&mut h, typed); + assert_eq!(sides(&h), want, "{typed}"); + assert_eq!(alerts(&h), vec![SIDES_RANGE_ALERT.to_string()], "{typed}: one alert"); + ok(&mut h); + assert!(alerts(&h).is_empty(), "{typed}: OK closes the alert"); + assert_eq!(sides(&h), want, "{typed}: the closest value is kept"); + } +} + +#[test] +fn sides_in_range_are_stored_without_an_alert() { + for (typed, want) in [("3", 3), ("7", 7), ("100", 100)] { + let mut h = bar(); + type_sides(&mut h, typed); + assert_eq!(sides(&h), want, "{typed}"); + assert!(alerts(&h).is_empty(), "{typed} is in range"); + } +} + +#[test] +fn sides_that_are_no_number_keep_the_value_without_an_alert() { + let mut h = bar(); + type_sides(&mut h, "abc"); + assert_eq!(sides(&h), 5, "the previous value stays"); + assert!(alerts(&h).is_empty(), "no number, no alert"); +} + +#[test] +fn arrow_steps_past_either_end_stop_there_without_an_alert() { + for (start, key, want) in [("99", egui::Key::ArrowUp, 100), ("4", egui::Key::ArrowDown, 3)] { + let mut h = bar(); + type_sides(&mut h, start); + click_sides(&mut h); + for _ in 0..3 { + h.key_press(key); + h.run_steps(1); + } + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(sides(&h), want, "{start}: the steps reached the end"); + assert!(alerts(&h).is_empty(), "{start}: an arrow step stops at the end without an alert"); + } +} + +#[test] +fn a_caption_scrub_past_either_end_does_not_alert() { + for (start, dx, want) in [("95", 50.0, 100), ("8", -50.0, 3)] { + let mut h = bar(); + type_sides(&mut h, start); + // The field keeps the keyboard while its caption is scrubbed past the end. + let rect = click_sides(&mut h); + // The caption sits just left of the field. + let from = egui::pos2(rect.left() - 20.0, rect.center().y); + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.run_steps(1); + for k in 1..=6 { + h.event(egui::Event::PointerMoved(from + vec2(dx * k as f32, 0.0))); + h.run_steps(1); + } + let to = from + vec2(dx * 6.0, 0.0); + h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(3); + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(sides(&h), want, "{start}: the scrub reached the end"); + assert!(alerts(&h).is_empty(), "{start}: a scrub stops at the end without an alert"); + } +} + +fn wheel_event(unit: egui::MouseWheelUnit, dy: f32) -> egui::Event { + egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit, + delta: vec2(0.0, dy), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + } +} + +#[test] +fn wheel_steps_past_either_end_stop_there_without_an_alert() { + for (start, lines, want) in [("99", 1.0, 100), ("4", -1.0, 3)] { + let mut h = bar(); + type_sides(&mut h, start); + click_sides(&mut h); + for _ in 0..3 { + h.event(wheel_event(egui::MouseWheelUnit::Line, lines)); + h.run_steps(1); + } + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(sides(&h), want, "{start}: the wheel reached the end"); + assert!(alerts(&h).is_empty(), "{start}: a wheel step stops at the end without an alert"); + } +} + +/// A wheel event that steps nothing (a trackpad's zero-delta start, or less than a notch) in the +/// frame a value is typed leaves it typed: it still alerts on the way out. +#[test] +fn a_wheel_event_that_steps_nothing_does_not_hide_a_typed_value() { + for (unit, dy) in [(egui::MouseWheelUnit::Point, 0.0), (egui::MouseWheelUnit::Point, 2.0)] { + let mut h = bar(); + click_sides(&mut h); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + // Both in one pass, as a trackpad can deliver them (`event` hands the app one per pass). + h.input_mut().events.extend([egui::Event::Text("101".into()), wheel_event(unit, dy)]); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(sides(&h), 100, "{dy} pt"); + assert_eq!(alerts(&h), vec![SIDES_RANGE_ALERT.to_string()], "{dy} pt: the typed 101 alerts"); + } +} diff --git a/crates/ui-egui/src/tools/rectangle_radius_range_tests.rs b/crates/ui-egui/src/tools/rectangle_radius_range_tests.rs new file mode 100644 index 0000000000..57de138e47 --- /dev/null +++ b/crates/ui-egui/src/tools/rectangle_radius_range_tests.rs @@ -0,0 +1,162 @@ +//! #13336: the Rectangle tool's Radius takes 0..150000 px, decimals included; a value typed past +//! the range becomes the closest end and, once the field is left, the reference's "Closest value +//! inserted" alert with OK says so. The Path Selection / Direct Selection Radius is not this field. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::RADIUS_RANGE_ALERT; +use crate::PhotocraftApp; +use crate::state::{DialogKind, Tool}; + +/// The options bar with `tool` active. +fn bar_with(app: PhotocraftApp, tool: Tool) -> Harness<'static, PhotocraftApp> { + let mut app = app; + app.ui.tool = tool; + let mut h = Harness::builder().with_size(vec2(1800.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +fn new_app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app +} + +/// The options bar with the Rectangle tool active and a pixel layer targeted. +fn bar() -> Harness<'static, PhotocraftApp> { + bar_with(new_app(), Tool::Rectangle) +} + +/// Types `text` into Radius, then Tabs out of it. +fn type_radius(h: &mut Harness<'static, PhotocraftApp>, text: &str) { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Radius:")).expect("the Radius field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn alerts(h: &Harness<'static, PhotocraftApp>) -> Vec { + h.state().ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(str::to_owned)).collect() +} + +/// OK on the alert, as `ui.dialog.confirm` presses it (this harness draws only the bar). +fn ok(h: &mut Harness<'static, PhotocraftApp>) { + let id = h.state().ui.dialogs.iter().find(|d| d.kind == DialogKind::Error).map(|d| d.id).expect("an alert"); + crate::dialogs::confirm(h.state_mut(), id).unwrap(); + h.run_steps(3); +} + +fn radius(h: &Harness<'static, PhotocraftApp>) -> f32 { + h.state().ui.tool_options.corner_radius +} + +#[test] +fn radius_in_range_is_stored_without_an_alert() { + for (typed, want) in [("0", 0.0), ("12.5", 12.5), ("5000", 5000.0), ("150000", 150_000.0)] { + let mut h = bar(); + type_radius(&mut h, typed); + assert_eq!(radius(&h), want, "{typed}"); + assert!(alerts(&h).is_empty(), "{typed} is in range"); + } +} + +#[test] +fn radius_past_the_range_takes_the_closest_value_and_alerts() { + for (typed, want) in [("-5", 0.0), ("200000", 150_000.0)] { + let mut h = bar(); + type_radius(&mut h, typed); + assert_eq!(radius(&h), want, "{typed}"); + assert_eq!(alerts(&h), vec![RADIUS_RANGE_ALERT.to_string()], "{typed}: one alert"); + ok(&mut h); + assert!(alerts(&h).is_empty(), "{typed}: OK closes the alert"); + assert_eq!(radius(&h), want, "{typed}: the closest value is kept"); + } +} + +#[test] +fn path_selection_radius_keeps_its_own_range_without_an_alert() { + for tool in [Tool::PathSelection, Tool::DirectSelection] { + let mut app = new_app(); + app.run("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 20], "fill": "#ff0000"})).unwrap(); + let mut h = bar_with(app, tool); + type_radius(&mut h, "20000"); + assert_eq!(radius(&h), 10_000.0, "{tool:?}: today's 0..10000 clamp"); + assert!(alerts(&h).is_empty(), "{tool:?}: no alert"); + } +} + +/// Focuses Radius, presses `key` `n` times, then Tabs out. +fn step_radius(h: &mut Harness<'static, PhotocraftApp>, key: egui::Key, n: usize) { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Radius:")).expect("the Radius field").click(); + h.run_steps(1); + for _ in 0..n { + h.key_press(key); + h.run_steps(1); + } + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +#[test] +fn arrow_steps_stop_at_the_ends_without_the_alert() { + let mut h = bar(); + type_radius(&mut h, "149998"); + step_radius(&mut h, egui::Key::ArrowUp, 5); + assert_eq!(radius(&h), 150_000.0); + type_radius(&mut h, "2"); + step_radius(&mut h, egui::Key::ArrowDown, 5); + assert_eq!(radius(&h), 0.0); + assert!(alerts(&h).is_empty(), "stepping is not typing: {:?}", alerts(&h)); +} + +#[test] +fn wheel_steps_with_the_focus_stop_at_the_end_without_the_alert() { + // As in the app: the focused field takes the wheel before the bar is laid out. + let mut app = new_app(); + app.ui.tool = Tool::Rectangle; + let mut h = Harness::builder().with_size(vec2(1800.0, 300.0)).build_ui_state( + |ui, app| { + crate::field_wheel::begin_frame(ui.ctx()); + crate::panels::options_bar(app, ui) + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + type_radius(&mut h, "149998"); + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Radius:")).expect("the Radius field").click(); + h.run_steps(1); + for _ in 0..5 { + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, 1.0), + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(1); + } + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(radius(&h), 150_000.0); + assert!(alerts(&h).is_empty(), "a wheel step is not typing: {:?}", alerts(&h)); +} + +#[test] +fn a_saved_radius_up_to_the_range_end_is_restored() { + let mut o = crate::state::ToolOptions { corner_radius: 150_000.0, ..Default::default() }; + crate::tool_memory::sanitize(&mut o); + assert_eq!(o.corner_radius, 150_000.0); + o.corner_radius = 200_000.0; + crate::tool_memory::sanitize(&mut o); + assert_eq!(o.corner_radius, 150_000.0, "past the range takes the end"); +} diff --git a/crates/ui-egui/src/tools/rectangle_radius_target_tests.rs b/crates/ui-egui/src/tools/rectangle_radius_target_tests.rs new file mode 100644 index 0000000000..9c9a5bf46d --- /dev/null +++ b/crates/ui-egui/src/tools/rectangle_radius_target_tests.rs @@ -0,0 +1,111 @@ +//! #13338: the Rectangle tool's options-bar Radius sets the next rectangle, not the active shape. +//! It shows the tool's own radius. The Path Selection / Direct Selection Radius still edits the +//! active shape. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::{LayerContent, LiveShape}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// A document with Rectangle 1 (radius 20) as the active layer, and `tool` current. +fn bar_with(tool: Tool) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.create", json!({"kind": "roundedRect", "rect": [10, 10, 80, 60], "radii": [20, 20, 20, 20], "fill": "#ff0000"})).unwrap(); + app.sync_views(); + app.ui.tool = tool; + let mut h = Harness::builder().with_size(vec2(1800.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +fn type_radius(h: &mut Harness<'static, PhotocraftApp>, text: &str) { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Radius:")).expect("the Radius field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn history_len(h: &Harness<'static, PhotocraftApp>) -> usize { + h.state().session.active().unwrap().history.past_len() +} + +/// The first radius of every rectangle shape layer, bottom to top. +fn radii(h: &Harness<'static, PhotocraftApp>) -> Vec { + let st = h.state().session.active().unwrap(); + st.doc + .walk() + .into_iter() + .filter_map(|(_, _, l)| match &l.content { + LayerContent::Shape(sh) => match &sh.live { + Some(LiveShape::Rect { radii, .. }) => Some(radii[0]), + _ => None, + }, + _ => None, + }) + .collect() +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + let mods = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: (from[0] + to[0]) / 2.0, y: (from[1] + to[1]) / 2.0, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods); +} + +#[test] +fn the_rectangle_tools_radius_field_leaves_the_active_shape_alone() { + let mut h = bar_with(Tool::Rectangle); + let before = history_len(&h); + type_radius(&mut h, "5000"); + assert_eq!(radii(&h), vec![20.0], "Rectangle 1 keeps its radius"); + assert_eq!(history_len(&h), before, "no History state"); + assert_eq!(h.state().ui.tool_options.corner_radius, 5000.0); +} + +#[test] +fn the_next_rectangle_takes_the_typed_radius() { + let mut h = bar_with(Tool::Rectangle); + type_radius(&mut h, "5000"); + drag(h.state_mut(), [100.0, 100.0], [180.0, 170.0]); + let all = radii(&h); + assert_eq!(all.len(), 2, "a second rectangle was drawn: {all:?}"); + assert_eq!(all[0], 20.0); + assert_eq!(all[1], 5000.0); +} + +#[test] +fn the_rectangle_tools_radius_field_shows_the_tools_radius() { + let mut h = bar_with(Tool::Rectangle); + h.state_mut().ui.tool_options.corner_radius = 0.0; + h.run_steps(3); + let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Radius:")).expect("the Radius field"); + let shown = field + .accesskit_node() + .numeric_value() + .map(|v| v as f32) + .or_else(|| field.accesskit_node().value().and_then(|v| v.trim_end_matches(" px").trim().parse().ok())); + assert_eq!(shown, Some(0.0), "the tool's radius, not the shape's 20"); +} + +#[test] +fn the_path_selection_radius_field_still_edits_the_active_shape() { + for tool in [Tool::PathSelection, Tool::DirectSelection] { + let mut h = bar_with(tool); + let before = history_len(&h); + type_radius(&mut h, "30"); + assert_eq!(radii(&h), vec![30.0], "{tool:?}: the active shape takes it"); + assert_eq!(history_len(&h), before + 1, "{tool:?}: one History state"); + } +} diff --git a/crates/ui-egui/src/tools/remove_default_size_tests.rs b/crates/ui-egui/src/tools/remove_default_size_tests.rs new file mode 100644 index 0000000000..5bcd0b5dc0 --- /dev/null +++ b/crates/ui-egui/src/tools/remove_default_size_tests.rs @@ -0,0 +1,87 @@ +//! #12548: the Remove tool starts, and comes back after Reset Tool, with the reference +//! application's 19 px brush. Its hardness and spacing are not measured and keep today's values: +//! the default brush's after a reset, the current brush's on a first use. Other tools' starting +//! sizes are unchanged. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::burn_default_tip_tests::{app, invoke, pick}; +use crate::state::Tool; + +/// Size, hardness and spacing of the live brush, as `brush.get` reports them. +fn tip(app: &mut PhotocraftApp) -> [f64; 3] { + let b = app.run("brush.get", json!({})).unwrap(); + ["size", "hardness", "spacing"].map(|k| (b[k].as_f64().unwrap() * 1e4).round() / 1e4) +} + +/// A brush no tool starts with, so a reset or a first use has something to change. +fn scramble(app: &mut PhotocraftApp) { + let b = &mut app.session.tools.brush; + (b.size, b.hardness, b.spacing) = (57.0, 0.4, 0.6); +} + +/// 19 px, with the default brush's hardness and spacing (what Reset Tool gave it before). +const REMOVE_TIP: [f64; 3] = [19.0, 1.0, 0.1]; + +#[test] +fn reset_tool_gives_the_remove_tool_a_19_px_brush() { + let mut app = app(); + pick(&mut app, Tool::Remove); + scramble(&mut app); + invoke(&mut app, "tool.reset", json!({})); + assert_eq!(tip(&mut app), REMOVE_TIP); +} + +#[test] +fn a_first_use_starts_at_19_px() { + // No stored tool brushes, as on a fresh install: the Remove tool's first pick, after another + // tool's brush. + let mut app = app(); + pick(&mut app, Tool::Pencil); + scramble(&mut app); + pick(&mut app, Tool::Remove); + // Only the size is measured: the hardness and spacing are still the previous tool's. + assert_eq!(tip(&mut app), [19.0, 0.4, 0.6]); + // Its own size is then kept across tool switches. + app.session.tools.brush.size = 42.0; + pick(&mut app, Tool::Pencil); + pick(&mut app, Tool::Remove); + assert_eq!(tip(&mut app)[0], 42.0); +} + +#[test] +fn reset_all_tools_gives_it_19_px_active_or_picked_later() { + let mut app = app(); + pick(&mut app, Tool::Remove); + scramble(&mut app); + invoke(&mut app, "tool.resetAll", json!({"confirmed": true})); + assert_eq!(tip(&mut app), REMOVE_TIP, "active"); + let mut app = self::app(); + pick(&mut app, Tool::Remove); + scramble(&mut app); + pick(&mut app, Tool::Pencil); + invoke(&mut app, "tool.resetAll", json!({"confirmed": true})); + pick(&mut app, Tool::Remove); + assert_eq!(tip(&mut app), REMOVE_TIP, "picked after the reset"); +} + +/// The Pencil resets to its 1 px hard round (#12200). +#[test] +fn other_tools_keep_their_reset_sizes() { + for (tool, want) in + [(Tool::Brush, 13.0), (Tool::Pencil, 1.0), (Tool::Eraser, 20.0), (Tool::SpotHealing, 20.0), (Tool::Healing, 19.0), (Tool::CloneStamp, 21.0)] + { + let mut a = app(); + pick(&mut a, tool); + scramble(&mut a); + invoke(&mut a, "tool.reset", json!({})); + assert_eq!(tip(&mut a)[0], want, "{tool:?}"); + } + // The Spot Healing Brush's first use still takes the current brush, as before. + let mut a = app(); + pick(&mut a, Tool::Pencil); + scramble(&mut a); + pick(&mut a, Tool::SpotHealing); + assert_eq!(tip(&mut a)[0], 57.0, "Spot Healing Brush, first use"); +} diff --git a/crates/ui-egui/src/tools/remove_hidden_layer_tests.rs b/crates/ui-egui/src/tools/remove_hidden_layer_tests.rs new file mode 100644 index 0000000000..eb662f2fdc --- /dev/null +++ b/crates/ui-egui/src/tools/remove_hidden_layer_tests.rs @@ -0,0 +1,90 @@ +//! #12554: a Remove stroke on a hidden active layer does nothing, as in the reference +//! application: no message, no alert, no stroke overlay, no job, no History state. The other +//! painting tools keep their alert or status-bar error, and the unmeasured cases keep today's. + +use egui::Modifiers; +use serde_json::json; + +use super::brush_refusal_alert_tests::{active, alerts, app, refused, steps, stroke}; +use super::*; +use crate::canvas::{ToolEvent, tool_event}; + +const ERROR: &str = photocraft_engine::hidden_target::HIDDEN; + +/// [`app`] with its active layer hidden. +fn hidden(tool: Tool) -> PhotocraftApp { + let mut app = app(tool); + let id = active(&app); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + app +} + +/// Both Remove modes: filled at each release, and collected for ↩; and the Background, where the +/// reference application was measured. +#[test] +fn a_hidden_active_layer_is_quiet() { + for (after_each, background) in [(true, false), (false, false), (true, true)] { + let mut app = if background { self::app(Tool::Remove) } else { hidden(Tool::Remove) }; + if background { + let id = app.session.active().unwrap().doc.layers[0].id.0; + app.run("layer.select", json!({"layer": id})).unwrap(); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + } + app.ui.tool_options.remove_after_each_stroke = after_each; + let (journal, before, status) = (app.session.journal.len(), steps(&app), app.ui.status.clone()); + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 32.0, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 44.0, y: 32.0, pressure: 1.0 }, Modifiers::NONE); + assert!(app.drag.is_none() && app.trail.is_none() && app.live_stroke.is_none(), "{after_each}: no stroke overlay"); + tool_event(&mut app, ToolEvent::Up { x: 44.0, y: 32.0 }, Modifiers::NONE); + assert!(app.remove_pending.is_empty(), "{after_each}: no stroke collected"); + assert!(app.ui.dialogs.is_empty(), "{after_each}: no dialog"); + assert_eq!((app.ui.status.as_str(), app.ui.status_error), (status.as_str(), false), "{after_each}: no message"); + assert_eq!(app.session.journal.len(), journal, "{after_each}: no job ran"); + assert_eq!(steps(&app), before, "{after_each}: no History state"); + } +} + +#[test] +fn the_other_tools_keep_their_message() { + refused(&mut hidden(Tool::Brush), "Could not use the brush tool because the target layer is hidden."); + refused(&mut hidden(Tool::Smudge), "Could not use the smudge tool because the target layer is hidden."); + for tool in [Tool::Pencil, Tool::Eraser, Tool::SpotHealing, Tool::Healing, Tool::CloneStamp] { + let mut app = hidden(tool); + let before = steps(&app); + stroke(&mut app); + assert_eq!((app.ui.status.as_str(), app.ui.status_error), (ERROR, true), "{tool:?}"); + assert!(alerts(&app).is_empty(), "{tool:?}: {:?}", alerts(&app)); + assert_eq!(steps(&app), before, "{tool:?}"); + } +} + +/// Not measured: a hidden layer inside a hidden group, a hidden layer with its mask targeted, +/// Sample All Layers on and a hidden type layer keep today's status-bar error. +#[test] +fn unmeasured_cases_keep_the_status_error() { + for case in ["hidden group", "mask", "Sample All Layers", "type layer"] { + let mut app = hidden(Tool::Remove); + match case { + "hidden group" => { + let id = active(&app); + let group = app.run("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap(); + app.run("layer.setProps", json!({"layer": group, "visible": false})).unwrap(); + app.run("layer.select", json!({"layer": id})).unwrap(); + } + "mask" => { + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + assert_eq!(crate::canvas::paint_target(&app), json!("mask"), "the new mask is the target"); + } + "Sample All Layers" => app.ui.tool_options.sample_all.remove = true, + _ => { + let id = app.run("type.create", json!({"x": 10, "y": 32, "text": "Hello"})).unwrap()["layer"].as_u64().unwrap(); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + } + } + let before = steps(&app); + stroke(&mut app); + assert_eq!((app.ui.status.as_str(), app.ui.status_error), (ERROR, true), "{case}"); + assert!(app.ui.dialogs.is_empty(), "{case}: no dialog"); + assert_eq!(steps(&app), before, "{case}"); + } +} diff --git a/crates/ui-egui/src/tools/remove_locked_alert_tests.rs b/crates/ui-egui/src/tools/remove_locked_alert_tests.rs new file mode 100644 index 0000000000..e0c6b34c4d --- /dev/null +++ b/crates/ui-egui/src/tools/remove_locked_alert_tests.rs @@ -0,0 +1,109 @@ +//! #12552: a Remove press on a layer with Lock All opens the reference application's alert with +//! OK at once and changes nothing: no stroke overlay, no job, no History state. Lock transparent +//! pixels still removes, and the Brush keeps its own wording. + +use egui::Modifiers; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::brush_refusal_alert_tests::{active, alerts, app, refused, steps, stroke}; +use super::*; +use crate::canvas::{ToolEvent, tool_event}; + +const WANT: &str = "Can't use the tool because the layer is locked."; + +/// Both Remove modes: filled at each release, and collected for ↩. +#[test] +fn lock_all_opens_the_alert_at_the_press() { + for after_each in [true, false] { + let mut app = app(Tool::Remove); + app.ui.tool_options.remove_after_each_stroke = after_each; + app.run("layer.lockLayers", json!({"all": true})).unwrap(); + let journal = app.session.journal.len(); + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 32.0, pressure: 1.0 }, Modifiers::NONE); + assert_eq!(alerts(&app), [WANT], "{after_each}: the alert at the press"); + tool_event(&mut app, ToolEvent::Move { x: 44.0, y: 32.0, pressure: 1.0 }, Modifiers::NONE); + assert!(app.drag.is_none() && app.trail.is_none() && app.live_stroke.is_none(), "{after_each}: no stroke overlay"); + tool_event(&mut app, ToolEvent::Up { x: 44.0, y: 32.0 }, Modifiers::NONE); + assert!(app.remove_pending.is_empty(), "{after_each}: no stroke collected"); + assert_eq!(app.session.journal.len(), journal, "{after_each}: no job ran"); + assert!(!app.ui.status_error, "{after_each}: no error notice as well: {}", app.ui.status); + let id = app.ui.dialogs.iter().find(|d| d.kind == DialogKind::Error).map(|d| d.id).unwrap(); + crate::dialogs::confirm(&mut app, id).unwrap(); + // `refused` repeats the whole press: the alert once, no History state. + refused(&mut app, WANT); + } +} + +#[test] +fn the_alert_has_one_button_ok() { + let mut app = app(Tool::Remove); + app.run("layer.lockLayers", json!({"all": true})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 600.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + // The press after the fonts are set up: the harness draws its first frame at build. + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + stroke(h.state_mut()); + h.run_steps(2); + assert!(h.query_by_label(WANT).is_some(), "the message is shown"); + let buttons: Vec = h.query_all_by_role(egui::accesskit::Role::Button).filter_map(|n| n.accesskit_node().label()).collect(); + // Off macOS the title bar also has its close box. + let want: &[&str] = if crate::dialogs::CLOSE_BOX { &["Close", "OK"] } else { &["OK"] }; + assert_eq!(buttons, want); + h.get_by_label("OK").click(); + h.run_steps(2); + assert!(h.state().ui.dialogs.is_empty(), "OK closes it"); +} + +#[test] +fn lock_transparent_pixels_still_removes() { + let mut app = app(Tool::Remove); + app.run("layer.lockLayers", json!({"transparency": true})).unwrap(); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty()); + assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("paint.remove")); + assert_eq!(steps(&app), before + 1, "the stroke was removed"); +} + +#[test] +fn the_brush_keeps_its_wording() { + let mut app = app(Tool::Brush); + app.run("layer.lockLayers", json!({"all": true})).unwrap(); + refused(&mut app, "Could not use the brush tool because the layer is locked."); +} + +/// Not this alert: a hidden target is quiet (#12554), a group keeps its own alert (#10074) and +/// Lock Image Pixels alone doesn't refuse the press. +#[test] +fn unmeasured_cases_keep_todays_behaviour() { + let mut app = app(Tool::Remove); + let id = active(&app); + app.run("layer.lockLayers", json!({"all": true})).unwrap(); + app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap(); + stroke(&mut app); + assert!(alerts(&app).is_empty(), "hidden: {:?}", alerts(&app)); + assert!(!app.ui.status_error, "hidden: {}", app.ui.status); + let mut app = self::app(Tool::Remove); + app.run("layer.new.group", json!({})).unwrap(); + app.run("layer.lockLayers", json!({"all": true})).unwrap(); + stroke(&mut app); + assert_eq!(alerts(&app), ["Could not use the Remove Tool because the target layer is a group."]); + let mut app = self::app(Tool::Remove); + app.run("layer.lockLayers", json!({"pixels": true})).unwrap(); + stroke(&mut app); + assert!(alerts(&app).is_empty(), "Lock Image Pixels: {:?}", alerts(&app)); +} + +/// A type layer with Lock All: no alert, and today's status-bar error at the release (#12553 drops +/// only an unlocked type layer's press). +#[test] +fn a_locked_type_layer_keeps_todays_error() { + let mut app = app(Tool::Remove); + app.run("type.create", json!({"x": 10, "y": 32, "text": "Hello"})).unwrap(); + app.run("layer.lockLayers", json!({"all": true})).unwrap(); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty(), "{:?}", alerts(&app)); + assert!(app.ui.status_error && app.ui.status.contains("not a pixel layer"), "{}", app.ui.status); + assert_eq!(steps(&app), before); +} diff --git a/crates/ui-egui/src/tools/remove_options_bar_labels_tests.rs b/crates/ui-egui/src/tools/remove_options_bar_labels_tests.rs new file mode 100644 index 0000000000..9a7587a691 --- /dev/null +++ b/crates/ui-egui/src/tools/remove_options_bar_labels_tests.rs @@ -0,0 +1,104 @@ +//! #12546: the Remove tool's checkboxes read "Sample all layers", "Remove after each stroke", +//! "Create new layer", left to right, each with the reference tooltip. + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::burn_bar_tooltips_tests::{bar, control, hover}; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::i18n::Lang; +use crate::state::Tool; + +const BOXES: [(&str, &str); 3] = [ + ("Sample all layers", "Sample content from all visible layers"), + ("Remove after each stroke", "Remove area after a single stroke"), + ("Create new layer", "Create new layer with results"), +]; + +fn remove_bar() -> Harness<'static, PhotocraftApp> { + bar(Tool::Remove, Lang::EN, 1600.0, 1.0, false) +} + +fn checked(h: &Harness<'static, PhotocraftApp>, label: &str) -> bool { + control(h, Role::CheckBox, label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +#[test] +fn the_checkboxes_read_the_reference_labels_left_to_right() { + let h = remove_bar(); + let mut boxes: Vec<(f32, String)> = + h.query_all_by_role(Role::CheckBox).map(|n| (n.rect().left(), n.accesskit_node().label().unwrap_or_default())).collect(); + boxes.sort_by(|a, b| a.0.total_cmp(&b.0)); + let labels: Vec<&str> = boxes.iter().map(|(_, l)| l.as_str()).collect(); + assert_eq!(labels, BOXES.map(|(label, _)| label)); +} + +#[test] +fn hovering_each_checkbox_shows_its_tooltip() { + for (label, tip) in BOXES { + let mut h = remove_bar(); + assert!(h.query_by_label(tip).is_none(), "{label}: no tooltip before the hover"); + let before = h.state().ui.tool_options.clone(); + hover(&mut h, Role::CheckBox, label, tip); + let o = &h.state().ui.tool_options; + assert_eq!( + (o.sample_all.remove, o.remove_after_each_stroke, o.remove_new_layer), + (before.sample_all.remove, before.remove_after_each_stroke, before.remove_new_layer) + ); + } +} + +#[test] +fn defaults_show_only_remove_after_each_stroke_on_and_reset_tool_restores_them() { + let mut h = remove_bar(); + let defaults = [false, true, false]; + assert_eq!(BOXES.map(|(label, _)| checked(&h, label)), defaults); + for (label, _) in BOXES { + control(&h, Role::CheckBox, label).click(); + h.run_steps(2); + } + assert_eq!(BOXES.map(|(label, _)| checked(&h, label)), defaults.map(|on| !on), "each click toggles its own box"); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "tool.reset", json!({})).unwrap(); + h.run_steps(2); + assert_eq!(BOXES.map(|(label, _)| checked(&h, label)), defaults); +} + +#[test] +fn create_new_layer_greys_when_a_mask_or_colour_subset_is_targeted() { + let mut h = remove_bar(); + assert!(!control(&h, Role::CheckBox, "Create new layer").accesskit_node().is_disabled()); + let app = h.state_mut(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.ui.mask_target = true; + h.run_steps(2); + assert!(control(&h, Role::CheckBox, "Create new layer").accesskit_node().is_disabled(), "a targeted mask greys it"); + let app = h.state_mut(); + app.ui.mask_target = false; + app.run("channel.target", json!({"colors": [0, 2]})).unwrap(); + h.run_steps(2); + assert!(control(&h, Role::CheckBox, "Create new layer").accesskit_node().is_disabled(), "a colour subset greys it"); + for (label, _) in &BOXES[..2] { + assert!(!control(&h, Role::CheckBox, label).accesskit_node().is_disabled(), "{label} stays enabled"); + } +} + +#[test] +fn the_boxes_ticked_on_the_bar_reach_the_removal_options() { + let mut h = remove_bar(); + for label in ["Sample all layers", "Create new layer"] { + control(&h, Role::CheckBox, label).click(); + h.run_steps(2); + } + let app = h.state_mut(); + let m = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: 30.0, y: 18.0, pressure: 1.0 }, m); + tool_event(app, ToolEvent::Up { x: 30.0, y: 42.0 }, m); + assert!(!app.ui.status_error, "{}", app.ui.status); + let (id, p) = app.session.journal.last().cloned().unwrap(); + assert_eq!((id.as_str(), p["sampleAllLayers"].as_bool(), p["newLayer"].as_bool()), ("paint.remove", Some(true), Some(true))); +} diff --git a/crates/ui-egui/src/tools/remove_type_layer_tests.rs b/crates/ui-egui/src/tools/remove_type_layer_tests.rs new file mode 100644 index 0000000000..540b434ebd --- /dev/null +++ b/crates/ui-egui/src/tools/remove_type_layer_tests.rs @@ -0,0 +1,58 @@ +//! #12553: a press and drag with the Remove tool on a type layer does nothing, as in the +//! reference: no rasterize prompt, no stroke overlay, no message and no history state; the layer +//! stays type. The other pixel tools, and the Remove tool on shape, Smart Object and fill +//! layers, still ask to rasterize first. + +use egui::Modifiers; + +use super::Kind; +use super::tests::{active_content, app_with, click, past, prompt}; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// Both Remove modes: filled at each release, and collected for ↩ (no stroke is collected). +#[test] +fn a_remove_drag_on_a_type_layer_does_nothing() { + for after_each in [true, false] { + let mut app = app_with(Kind::Type); + app.ui.tool = Tool::Remove; + app.ui.tool_options.remove_after_each_stroke = after_each; + let before = (past(&app), app.session.active().unwrap().doc.clone()); + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 40.0, pressure: 1.0 }, Modifiers::NONE); + for i in 1..20 { + tool_event(&mut app, ToolEvent::Move { x: 20.0 + f64::from(i) * 3.0, y: 40.0, pressure: 1.0 }, Modifiers::NONE); + assert!(app.drag.is_none() && app.trail.is_none() && app.live_stroke.is_none(), "{after_each}: no stroke overlay while dragging"); + } + tool_event(&mut app, ToolEvent::Up { x: 77.0, y: 40.0 }, Modifiers::NONE); + assert!(app.ui.dialogs.is_empty(), "{after_each}: no prompt: {:?}", app.ui.dialogs.iter().map(|d| &d.fields).collect::>()); + assert!(app.remove_pending.is_empty(), "{after_each}: no stroke collected"); + assert!(app.ui.status.is_empty(), "{after_each}: no message: {}", app.ui.status); + assert_eq!(past(&app), before.0, "{after_each}: no history state"); + assert_eq!(*app.session.active().unwrap().doc, *before.1, "{after_each}: nothing changes"); + assert_eq!(active_content(&app), "Type"); + } +} + +#[test] +fn brush_and_eraser_still_ask_on_a_type_layer() { + for tool in [Tool::Brush, Tool::Eraser] { + let mut app = app_with(Kind::Type); + app.ui.tool = tool; + click(&mut app, 30.0, 20.0); + let d = prompt(&app).unwrap_or_else(|| panic!("{tool:?}: no prompt")); + assert_eq!(d.fields["message"], serde_json::json!(Kind::Type.message())); + } +} + +#[test] +fn remove_still_asks_on_shape_smart_object_and_fill_layers() { + for kind in [Kind::Shape, Kind::SmartObject, Kind::Fill] { + let mut app = app_with(kind); + app.ui.tool = Tool::Remove; + let before = past(&app); + click(&mut app, 30.0, 20.0); + let d = prompt(&app).unwrap_or_else(|| panic!("{kind:?}: no prompt")); + assert_eq!(d.fields["message"], serde_json::json!(kind.message())); + assert_eq!(past(&app), before, "{kind:?}: nothing happens until the answer"); + } +} diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 175909908e..944c9a28b9 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -27,27 +27,34 @@ pub(crate) fn alt_flipped(tool: Tool, alt: bool) -> Tool { /// `points` and `target`): shared by the live preview and the commit. `None` when no source /// point is set yet. pub(crate) fn clone_params(app: &PhotocraftApp) -> Option { + // Refused there (`healing_refused`): no live preview either. + if healing_in_indexed(app, app.ui.tool) { + return None; + } let o = &app.ui.tool_options; // The options bar's Mode is the tool's own brush's. let mode = crate::blend_keys::brush_tool_mode(app.ui.tool, app.session.tools.brush.mode); // View › Pattern Preview: both tools carry a stroke on across the canvas edges (#8883). - let mut p = json!({"aligned": o.clone_aligned, "sampleLayer": o.clone_sample, "mode": mode.label(), "wrap": app.ui.view.pattern_preview}); + let sample = if clone_stamp_indexed(app) { "current" } else { o.clone_sample.as_str() }; + let mut p = json!({"aligned": o.clone_aligned, "sampleLayer": sample, "mode": mode.label(), "wrap": app.ui.view.pattern_preview}); if app.ui.tool == Tool::CloneStamp { p["opacity"] = json!(app.session.tools.brush.opacity * 100.0); p["flow"] = json!(app.session.tools.brush.flow * 100.0); } // The Clone Source panel's active slot (set by ⌥-click) drives the stroke: the engine keeps - // the aligned pairing and applies the slot's scale/rotation/flip. - let slot = app.session.presets.clone.active().source.is_some(); - match (app.ui.clone_offset.filter(|_| o.clone_aligned && !slot), app.ui.clone_source.filter(|_| !slot)) { - _ if slot => {} - (Some(off), _) => p["offset"] = json!(off), - (None, Some(src)) => p["source"] = json!(src), - (None, None) => return None, - } + // the aligned pairing and applies the slot's scale/rotation/flip. An empty slot refuses to + // paint, as with no source at all: `ui.clone_source` / `ui.clone_offset` carry no document, + // so falling back to them would read another document's coordinates from this one's pixels. + app.session.presets.clone.active().source?; Some(p) } +/// The Clone Stamp in an Indexed Color document, where the reference greys Sample at Current Layer +/// and names the Normal Mode "Threshold" (#12613). +pub(crate) fn clone_stamp_indexed(app: &PhotocraftApp) -> bool { + app.ui.tool == Tool::CloneStamp && app.session.active().is_some_and(|st| st.doc.mode == photocraft_doc::ColorMode::Indexed) +} + /// History Brush params for the live preview and the commit (without `points` and `target`): the /// options bar's Mode and the tool's own brush. For an Eraser with Erase to History they also /// carry `eraseToHistory` and the Eraser's Pencil or Block tip. @@ -173,6 +180,8 @@ pub(crate) fn pattern_stamp_params(app: &PhotocraftApp, points: &[[f64; 3]]) -> "seed": stroke_seed(points), // The options bar's Mode is the tool's own brush's; Behind is a mode of that list. "mode": if app.session.tools.brush.behind { "Behind" } else { app.session.tools.brush.mode.label() }, + "opacity": app.session.tools.brush.opacity * 100.0, + "flow": app.session.tools.brush.flow * 100.0, }); if o.pattern_stamp_aligned && let Some(ph) = app.ui.pattern_stamp_phase @@ -194,6 +203,21 @@ pub(crate) fn stroke_seed(points: &[[f64; 3]]) -> u64 { photocraft_engine::paint::rng::seed_from_bytes(first.as_bytes()) } +/// A Clone Stamp press with no source point yet: the reference application's alert, opened at +/// the press (#12609) and once while it is up. Returns whether it refused the stroke. +pub(crate) fn clone_stamp_without_source(app: &mut PhotocraftApp, tool: Tool) -> bool { + if tool != Tool::CloneStamp || clone_params(app).is_some() { + return false; + } + let message = if cfg!(target_os = "macos") { + tl!("Could not use the clone stamp tool because the area to clone has not been defined (Option-click to define a source point).") + } else { + tl!("Could not use the clone stamp tool because the area to clone has not been defined (Alt-click to define a source point).") + }; + open_alert_once(app, message); + true +} + /// Finish a stroke with a retouching tool. Returns false if `tool` isn't one. pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]], mods: egui::Modifiers, line: bool) -> bool { finish_stroke_with(app, tool, points, mods, line, None) @@ -216,7 +240,13 @@ pub(crate) fn finish_stroke_with(app: &mut PhotocraftApp, tool: Tool, points: &[ Tool::ColorReplacement => ("paint.colorReplacement", color_replacement_params(app)), Tool::PatternStamp => ("paint.patternStamp", pattern_stamp_params(app, points)), Tool::Healing | Tool::CloneStamp => { + if healing_refused(app, tool) { + return true; + } let Some(p) = clone_params(app) else { + if clone_stamp_without_source(app, tool) { + return true; + } // Option-click on the Mac, Alt-click on Windows. app.ui.status = if cfg!(target_os = "macos") { tl!("Option-click to define a source point to clone from") @@ -594,10 +624,10 @@ pub fn content_aware_move_params(app: &PhotocraftApp, offset: [i64; 2]) -> Value /// Object Selection: the dragged rectangle. A click (or a sub-2 px nudge) cannot be a /// rectangle: with Object Finder on it selects the object under the pointer, the one hovering -/// highlighted (#4087; ⇧ adds, ⌥ subtracts, ⇧⌥ intersects, otherwise replaces). With it off it -/// falls back to a Quick Selection dab at -/// the brush size instead of looking dead (⌥ subtracts, otherwise it adds). Larger drags -/// run the rectangle GrabCut (⌥ subtracts, ⇧ adds, otherwise replaces). +/// highlighted (#4087). With it off it falls back to a Quick Selection dab at the brush size +/// instead of looking dead (⌥ or Subtract mode subtracts, otherwise it adds). Larger drags +/// run the rectangle GrabCut. Both combine as the options bar's New / Add / Subtract / +/// Intersect buttons say, with ⇧ adding, ⌥ subtracting and ⇧⌥ intersecting (#12853). pub fn finish_object_selection(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) { // Indexed Color and Bitmap: the reference application's alert with OK (#12867), and nothing runs. if let Some(why) = app.session.active().and_then(|st| photocraft_engine::smartselect_cmds::object_mode_refusal(st.doc.mode)) { @@ -608,14 +638,9 @@ pub fn finish_object_selection(app: &mut PhotocraftApp, start: [f64; 2], end: [f let (x, y) = (start[0].min(end[0]), start[1].min(end[1])); let (w, h) = ((end[0] - start[0]).abs(), (end[1] - start[1]).abs()); let sample_all = app.ui.tool_options.sample_all.object_selection; + let mode = crate::tool_feedback::selection_mode(Tool::ObjectSelection, app.ui.selection_mode, mods); if (w < 2.0 || h < 2.0) && app.ui.tool_options.object_finder { // Object Finder (#4087): the object under the click, as hovering highlighted it. - let mode = match (mods.shift, mods.alt) { - (true, true) => "intersect", - (true, false) => "add", - (false, true) => "subtract", - (false, false) => "replace", - }; let r = app.run("select.object", json!({"point": [end[0], end[1]], "mode": mode, "sampleAllLayers": sample_all})); crate::object_finder::clear(app); report_smart_result(app, r, tl!("No object found there — drag a rectangle around it")); @@ -623,18 +648,11 @@ pub fn finish_object_selection(app: &mut PhotocraftApp, start: [f64; 2], end: [f } if w < 2.0 || h < 2.0 { let size = app.session.tools.brush.size; - let mode = if mods.alt { "subtract" } else { "add" }; + let mode = if mods.alt || mode == "subtract" { "subtract" } else { "add" }; let r = app.run("select.quick", json!({"points": [[end[0], end[1]]], "size": size, "mode": mode, "sampleAllLayers": sample_all})); report_smart_result(app, r, tl!("Quick Selection found nothing there")); return; } - let mode = if mods.alt { - "subtract" - } else if mods.shift { - "add" - } else { - "replace" - }; let r = app.run("select.object", json!({"rect": [x.round(), y.round(), w.round(), h.round()], "mode": mode, "sampleAllLayers": sample_all})); report_smart_result(app, r, tl!("Object Selection found nothing there — try a tighter rectangle")); } @@ -650,8 +668,28 @@ pub fn report_smart_result(app: &mut PhotocraftApp, res: Result, } } +/// The Healing Brush in an Indexed Color document: the reference's alert with OK at the ⌥-click +/// and at a stroke, and nothing changes (#12112). The engine refuses the stroke with the same words. +fn healing_refused(app: &mut PhotocraftApp, tool: Tool) -> bool { + if !healing_in_indexed(app, tool) { + return false; + } + crate::brush_refusal::prompt( + app, + tl!("Could not set the clone source because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."), + ); + true +} + +fn healing_in_indexed(app: &PhotocraftApp, tool: Tool) -> bool { + tool == Tool::Healing && app.session.active().is_some_and(|st| st.doc.mode == photocraft_doc::ColorMode::Indexed) +} + /// ⌥-click with Clone Stamp / Healing Brush sets the source. pub fn set_source(app: &mut PhotocraftApp, x: f64, y: f64) { + if healing_refused(app, app.active_tool()) { + return; + } app.ui.clone_source = Some([x.round(), y.round()]); app.ui.clone_offset = None; let _ = app.run("cloneSource.set", json!({"source": [x.round(), y.round()]})); @@ -662,16 +700,17 @@ pub fn set_source(app: &mut PhotocraftApp, x: f64, y: f64) { /// Where the clone source is sampled from, shown only while a Clone Stamp or Healing Brush stroke /// is painted, as in Photoshop: setting the source (⌥-click) leaves nothing on the canvas (#668). +/// A source in another open document has no point on this canvas. pub fn source_marker_point(app: &PhotocraftApp) -> Option<[f64; 2]> { if !matches!(app.active_tool(), Tool::CloneStamp | Tool::Healing) { return None; } - let at = app.drag.as_ref().filter(|d| matches!(d.tool, Tool::CloneStamp | Tool::Healing)).and_then(|d| d.points.last().map(|p| [p[0], p[1]]))?; - match (crate::preset_panels::clone_sample_point(app, Some(at)), app.ui.clone_offset, app.ui.clone_source) { - (Some(p), ..) => Some(p), - (None, Some(off), _) => Some([at[0] + off[0], at[1] + off[1]]), - (None, None, s) => s, + let slot = app.session.presets.clone.active(); + if slot.document_closed || slot.document.is_some_and(|id| app.session.active().is_none_or(|st| st.doc.id != id)) { + return None; } + let at = app.drag.as_ref().filter(|d| matches!(d.tool, Tool::CloneStamp | Tool::Healing)).and_then(|d| d.points.last().map(|p| [p[0], p[1]]))?; + crate::preset_panels::clone_sample_point(app, Some(at)) } /// Crosshair at [`source_marker_point`]. @@ -756,7 +795,8 @@ fn cam_amount_slider(ui: &mut egui::Ui, name: &str, value: &mut f32, lo: f32, hi }); } -fn open_cam_range_alert(app: &mut PhotocraftApp, message: &str) { +/// Opens the alert with `message` (English, translated here) unless it is already up. +fn open_alert_once(app: &mut PhotocraftApp, message: &str) { let message = tl!(message).to_owned(); let shown = app.ui.dialogs.iter().any(|d| d.kind == crate::state::DialogKind::Error && d.fields.get("message").and_then(|m| m.as_str()) == Some(message.as_str())); @@ -780,11 +820,11 @@ fn content_aware_move_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } opt(ui, tl!("Structure:")); if cam_integer_popup(ui, "cam-structure", "Structure", &mut app.ui.tool_options.cam_structure, 1.0, 7.0, STRUCTURE_TIP) { - open_cam_range_alert(app, STRUCTURE_RANGE_ALERT); + open_alert_once(app, STRUCTURE_RANGE_ALERT); } opt(ui, tl!("Color:")); if cam_integer_popup(ui, "cam-color", "Color", &mut app.ui.tool_options.cam_color, 0.0, 10.0, COLOR_TIP) { - open_cam_range_alert(app, COLOR_RANGE_ALERT); + open_alert_once(app, COLOR_RANGE_ALERT); } crate::widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.content_aware_move, tl!("Sample All Layers")) .on_hover_text(tl!("Enable to remix all layers")); @@ -842,6 +882,17 @@ fn protect_tones_checkbox(ui: &mut egui::Ui, on: &mut bool) -> (egui::Response, (resp, label_resp.id) } +/// The Clone Stamp's and Healing Brush's Sample. `indexed` ([`clone_stamp_indexed`]) greys it at +/// Current Layer and leaves the stored choice for other documents. +fn clone_sample_dropdown(ui: &mut egui::Ui, stored: &mut String, indexed: bool) { + let opts = [("current", tl!("Current Layer")), ("currentAndBelow", tl!("Current & Below")), ("all", tl!("All Layers"))]; + let mut sample = if indexed { "current" } else { stored.as_str() }; + let changed = ui.add_enabled_ui(!indexed, |ui| crate::widgets::dropdown(ui, "clone-sample", tl!("Source"), &mut sample, &opts, 130.0)).inner; + if changed && !indexed { + *stored = sample.to_owned(); + } +} + /// Options bar for the retouching and smart-selection tools. Returns false for other tools. pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool { if !tool.is_brushlike() && !matches!(tool, Tool::QuickSelection | Tool::ObjectSelection | Tool::Patch | Tool::ContentAwareMove | Tool::RedEye) @@ -854,6 +905,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo return true; } let composite = crate::canvas::paint_target(app).as_str() == Some("pixels"); + let indexed = clone_stamp_indexed(app); let o = &mut app.ui.tool_options; match tool { Tool::SpotHealing => { @@ -868,11 +920,14 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo crate::widgets::checkbox(ui, &mut o.sample_all.spot_healing, tl!("Sample All Layers")); } Tool::Remove => { - // Photoshop's options bar: Sample All Layers, Create a new layer, Remove after each - // stroke; with strokes waiting, ✓ applies them and ⊘ drops them. - crate::widgets::checkbox(ui, &mut o.sample_all.remove, tl!("Sample All Layers")); - ui.add_enabled_ui(composite, |ui| crate::widgets::checkbox(ui, &mut o.remove_new_layer, tl!("Create a new layer"))); - crate::widgets::checkbox(ui, &mut o.remove_after_each_stroke, tl!("Remove after each stroke")); + // Photoshop's options bar (#12546): Sample all layers, Remove after each stroke, Create + // new layer; with strokes waiting, ✓ applies them and ⊘ drops them. + crate::widgets::checkbox(ui, &mut o.sample_all.remove, tl!("Sample all layers")).on_hover_text(tl!("Sample content from all visible layers")); + crate::widgets::checkbox(ui, &mut o.remove_after_each_stroke, tl!("Remove after each stroke")) + .on_hover_text(tl!("Remove area after a single stroke")); + ui.add_enabled_ui(composite, |ui| { + crate::widgets::checkbox(ui, &mut o.remove_new_layer, tl!("Create new layer")).on_hover_text(tl!("Create new layer with results")); + }); if !app.remove_pending.is_empty() { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if crate::widgets::primary_button(ui, "✓", 32.0) @@ -919,13 +974,8 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo Tool::Healing | Tool::CloneStamp => { crate::widgets::checkbox(ui, &mut o.clone_aligned, tl!("Aligned")); opt(ui, tl!("Sample:")); - let opts = [ - ("current".to_string(), tl!("Current Layer")), - ("currentAndBelow".to_string(), tl!("Current & Below")), - ("all".to_string(), tl!("All Layers")), - ]; - crate::widgets::dropdown(ui, "clone-sample", tl!("Source"), &mut o.clone_sample, &opts, 130.0); - if app.ui.clone_source.is_none() { + clone_sample_dropdown(ui, &mut o.clone_sample, indexed); + if app.session.presets.clone.active().source.is_none() { crate::widgets::vline(ui, 22.0); opt(ui, &crate::i18n::fmt(tl!("{key}-click to set the source"), &[("key", &crate::shortcuts::pretty("Alt"))])); } @@ -1108,6 +1158,8 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo } } Tool::ObjectSelection => { + crate::panels::selection_mode_buttons(&mut app.ui.selection_mode, ui); + crate::widgets::vline(ui, 22.0); crate::widgets::checkbox(ui, &mut o.object_finder, tl!("Object Finder")); crate::widgets::checkbox(ui, &mut o.sample_all.object_selection, tl!("Sample All Layers")); opt(ui, tl!("Drag a rectangle around the object")); @@ -1176,3 +1228,15 @@ mod smudge_mode_bar_tests; #[cfg(test)] #[path = "../sponge_flow_field_tests.rs"] mod sponge_flow_field_tests; + +#[cfg(test)] +#[path = "../healing_indexed_alert_tests.rs"] +mod healing_indexed_alert_tests; + +#[cfg(test)] +#[path = "../clone_stamp_no_source_alert_tests.rs"] +mod clone_stamp_no_source_alert_tests; + +#[cfg(test)] +#[path = "remove_options_bar_labels_tests.rs"] +mod remove_options_bar_labels_tests; diff --git a/crates/ui-egui/src/tools/retouch_ui/tests.rs b/crates/ui-egui/src/tools/retouch_ui/tests.rs index cae060ba6e..e620f56a93 100644 --- a/crates/ui-egui/src/tools/retouch_ui/tests.rs +++ b/crates/ui-egui/src/tools/retouch_ui/tests.rs @@ -1,7 +1,7 @@ use super::*; use crate::canvas::{ToolEvent, tool_event}; -fn app() -> PhotocraftApp { +pub(super) fn app() -> PhotocraftApp { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 100, "height": 60})).unwrap(); app.run("tools.setBrush", json!({"brush": {"size": 16, "hardness": 1.0}})).unwrap(); @@ -22,7 +22,7 @@ fn active(app: &PhotocraftApp) -> &photocraft_doc::Layer { st.active_layer.and_then(|id| st.doc.layer(id)).unwrap() } -fn stripes(app: &mut PhotocraftApp, step: usize, target: &str) { +pub(super) fn stripes(app: &mut PhotocraftApp, step: usize, target: &str) { for x in (0..100).step_by(step) { app.run("paint.pencil", json!({"points": [[x, 0], [x, 60]], "size": 2, "color": "#606060", "target": target})).unwrap(); } @@ -53,7 +53,7 @@ fn only_clone_stamp_and_healing_brush_wrap_in_pattern_preview() { let mut app = app(); stripes(&mut app, 8, "pixels"); app.ui.view.pattern_preview = pattern_preview; - app.ui.clone_source = Some([20.0, 30.0]); + set_source(&mut app, 20.0, 30.0); app.ui.tool = tool; let m = egui::Modifiers::NONE; tool_event(&mut app, ToolEvent::Down { x: 86.0, y: 30.0, pressure: 1.0 }, m); @@ -75,7 +75,7 @@ fn clone_stamp_in_pattern_preview_wraps_a_dab_across_the_right_edge() { crate::paint_mouse::sync_tool_brush(&mut app); // A hard tip, so the wrapped part of the dab is fully painted. app.run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 1}})).unwrap(); - app.ui.clone_source = Some([10.0, 10.0]); + set_source(&mut app, 10.0, 10.0); app.ui.view.pattern_preview = pattern_preview; let modifiers = egui::Modifiers::NONE; tool_event(&mut app, ToolEvent::Down { x: 98.0, y: 30.0, pressure: 1.0 }, modifiers); @@ -104,7 +104,7 @@ fn clone_stamp_paints_with_the_brush_hardness() { app.run("tools.setBrush", json!({"brush": {"size": 24, "hardness": hardness}})).unwrap(); app.run("paint.pencil", json!({"points": [[15, 30]], "size": 40, "color": "#ff0000"})).unwrap(); app.ui.tool = Tool::CloneStamp; - app.ui.clone_source = Some([15.0, 30.0]); + set_source(&mut app, 15.0, 30.0); let m = egui::Modifiers::NONE; tool_event(&mut app, ToolEvent::Down { x: 70.0, y: 30.0, pressure: 1.0 }, m); tool_event(&mut app, ToolEvent::Up { x: 70.0, y: 30.0 }, m); @@ -149,7 +149,7 @@ fn clone_stamp_brush_opacity_and_flow_reach_the_painted_pixels() { app.run("paint.pencil", json!({"points": [[10, 10]], "size": 16, "color": "#ff0000"})).unwrap(); app.run("layer.new.layer", json!({})).unwrap(); app.ui.tool = Tool::CloneStamp; - app.ui.clone_source = Some([10.0, 10.0]); + set_source(&mut app, 10.0, 10.0); app.ui.tool_options.clone_sample = "all".into(); app.run("tools.setBrush", json!({"brush": {"opacity": 0.5, "flow": 0.5}})).unwrap(); assert!(finish_stroke(&mut app, Tool::CloneStamp, &[[50.0, 30.0, 1.0]], egui::Modifiers::NONE, false)); @@ -171,7 +171,7 @@ fn healing_brush_heals_in_normal_with_a_mode_outside_its_menu() { app.ui.tool = tool; crate::paint_mouse::sync_tool_brush(&mut app); app.session.tools.brush.mode = photocraft_color::BlendMode::Overlay; - app.ui.clone_source = Some([10.0, 10.0]); + set_source(&mut app, 10.0, 10.0); drag(&mut app, tool); let (_, params) = app.session.journal.last().unwrap(); assert_eq!(params["mode"], want, "{tool:?}"); @@ -192,7 +192,7 @@ fn retouch_mode_reaches_the_command() { app.ui.tool = tool; crate::paint_mouse::sync_tool_brush(&mut app); app.run("tools.setBrush", json!({"brush": {"mode": mode}})).unwrap(); - app.ui.clone_source = Some([10.0, 10.0]); + set_source(&mut app, 10.0, 10.0); drag(&mut app, tool); let (id, params) = app.session.journal.last().unwrap(); assert_eq!((id.as_str(), params["mode"].as_str()), (cmd, Some(mode)), "{tool:?}"); @@ -225,15 +225,15 @@ fn paint_bucket_mode_reaches_the_fill() { #[test] fn clone_without_a_source_names_the_platform_modifier() { - // Option-click on the Mac, Alt-click elsewhere (#251). - for tool in [Tool::CloneStamp, Tool::Healing] { - let mut app = app(); - app.ui.tool = tool; - assert!(finish_stroke(&mut app, tool, &[[10.0, 30.0, 1.0], [50.0, 30.0, 1.0]], egui::Modifiers::NONE, false)); - assert!(app.ui.status_error, "{tool:?}"); - let want = if cfg!(target_os = "macos") { "Option-click" } else { "Alt-click" }; - assert!(app.ui.status.starts_with(want), "{tool:?}: {}", app.ui.status); - } + // Option-click on the Mac, Alt-click elsewhere (#251). The Clone Stamp says it in an alert + // (#12609, clone_stamp_no_source_alert_tests.rs). + let tool = Tool::Healing; + let mut app = app(); + app.ui.tool = tool; + assert!(finish_stroke(&mut app, tool, &[[10.0, 30.0, 1.0], [50.0, 30.0, 1.0]], egui::Modifiers::NONE, false)); + assert!(app.ui.status_error); + let want = if cfg!(target_os = "macos") { "Option-click" } else { "Alt-click" }; + assert!(app.ui.status.starts_with(want), "{}", app.ui.status); } #[test] @@ -824,6 +824,7 @@ fn waiting_remove_strokes_keep_their_own_brush() { let mut app = app(); app.run("paint.pencil", json!({"points": [[0, 30], [100, 30]], "size": 200, "color": "#808080"})).unwrap(); app.ui.tool = Tool::Remove; + crate::paint_mouse::sync_tool_brush(&mut app); app.ui.tool_options.remove_after_each_stroke = false; let m = egui::Modifiers::NONE; let stroke = |app: &mut PhotocraftApp, x: f64| { @@ -1211,3 +1212,16 @@ fn history_brush_options_bar_shows_source_name() { h.run_steps(4); h.get_by_label("The History Brush source was deleted: set a new source in the History panel"); } + +/// An empty Clone Source slot refuses to paint, as with no source at all: the ⌥-click point left +/// in `ui.clone_source` carries no document, so it must not be read from another document. +#[test] +fn an_empty_clone_source_slot_refuses_to_paint() { + let mut app = app(); + app.ui.tool = Tool::CloneStamp; + crate::retouch_ui::set_source(&mut app, 10.0, 10.0); + assert!(crate::retouch_ui::clone_params(&app).is_some()); + app.run("cloneSource.select", json!({"index": 1})).unwrap(); + assert!(app.ui.clone_source.is_some(), "the old ⌥-click point is still remembered"); + assert!(crate::retouch_ui::clone_params(&app).is_none()); +} diff --git a/crates/ui-egui/src/tools/shape_bounds_box.rs b/crates/ui-egui/src/tools/shape_bounds_box.rs index d56508bf96..ad5a459d95 100644 --- a/crates/ui-egui/src/tools/shape_bounds_box.rs +++ b/crates/ui-egui/src/tools/shape_bounds_box.rs @@ -7,9 +7,11 @@ //! scales both ways, the pointer projected onto the box diagonal as Free Transform's corner does //! (#11096); an edge scales one way, grabbed at its middle handle or anywhere along its line //! (#11473). The corner radius widgets (`corner_radius`) keep priority on a press. +//! With the Line tool, a live line shows its own end and midpoint controls instead; its ends still +//! scale it as the box's handles there do. use egui::{Color32, CursorIcon, Modifiers, Pos2, Stroke, vec2}; -use photocraft_doc::LayerContent; +use photocraft_doc::{LayerContent, LiveShape}; use photocraft_geom::Affine; use serde_json::json; @@ -63,6 +65,99 @@ fn shows(app: &PhotocraftApp) -> bool { app.ui.transform.is_none() && app.ui.view.shows(app.ui.view.show.target_path) && matches!(app.ui.tool, Tool::PathSelection | Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Star | Tool::Line) + // A live line shows its own controls instead (#13263); a drag from one of its ends keeps + // the box until the release. + && (app.ui.shape_box.is_some() || live_line(app).is_none()) +} + +/// A live line's ends and, with an arrowhead, the corners of its box aligned with the segment. +struct LiveLine { + from: [f64; 2], + to: [f64; 2], + rotated: Option<[[f64; 2]; 4]>, +} + +/// With the Line tool, the active layer's live line when it is the whole selection. +fn live_line(app: &PhotocraftApp) -> Option { + if app.ui.tool != Tool::Line { + return None; + } + let st = app.session.active()?; + let id = st.active_layer?; + if st.selected_layers() != [id] { + return None; + } + let LayerContent::Shape(sh) = &st.doc.layer(id)?.content else { return None }; + let (from, to, arrow) = match sh.live.as_ref()? { + LiveShape::Line { from, to, .. } => (*from, *to, false), + LiveShape::ArrowLine { from, to, start, end, .. } => (*from, *to, *start || *end), + _ => return None, + }; + let len = (to[0] - from[0]).hypot(to[1] - from[1]); + if !(from.iter().chain(&to).all(|v| v.is_finite()) && len > 0.0) { + return None; + } + let rotated = arrow.then(|| { + // The path's control points in the segment's frame: `u` along it, `n` across it. + let (u, n) = ([(to[0] - from[0]) / len, (to[1] - from[1]) / len], [(from[1] - to[1]) / len, (to[0] - from[0]) / len]); + let at = |a: f64, b: f64| [from[0] + u[0] * a + n[0] * b, from[1] + u[1] * a + n[1] * b]; + let mut r = [0.0, 0.0, len, 0.0]; + for p in sh.path.subpaths.iter().flat_map(|s| &s.knots).flat_map(|k| [k.anchor, k.in_ctrl, k.out_ctrl]) { + let (dx, dy) = (p.x - from[0], p.y - from[1]); + let (a, b) = (dx * u[0] + dy * u[1], dx * n[0] + dy * n[1]); + r = [r[0].min(a), r[1].min(b), r[2].max(a), r[3].max(b)]; + } + [at(r[0], r[1]), at(r[2], r[1]), at(r[2], r[3]), at(r[0], r[3])] + }); + Some(LiveLine { from, to, rotated }) +} + +/// The live line whose controls show, under the box's own view conditions. +fn line_controls(app: &PhotocraftApp) -> Option { + (app.ui.transform.is_none() && app.ui.view.shows(app.ui.view.show.target_path)).then(|| live_line(app)).flatten() +} + +/// The box handle an end of the live line within `tol` of document point `p` stands for: the +/// corner (on a level or upright line the side) the end points to, away from the other end. Its +/// drag scales the line as that handle's does; the other handles and the sides are hidden, so they +/// take no press. +fn line_end_hit(l: &LiveLine, p: [f64; 2], tol: f64) -> Option<[i8; 2]> { + let sign = |d: f64| i8::from(d > 0.0) - i8::from(d < 0.0); + [(l.to, l.from), (l.from, l.to)] + .into_iter() + .map(|(end, other)| ([sign(end[0] - other[0]), sign(end[1] - other[1])], (end[0] - p[0]).hypot(end[1] - p[1]))) + .filter(|(_, d)| *d <= tol) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(h, _)| h) +} + +/// The Line tool's controls on its live line (#13263), drawn instead of the box: a handle at each +/// end and a round widget at the midpoint; with an arrowhead also the box aligned with the segment +/// and its side handles. Only the end handles take a press (`line_end_hit`). +pub fn draw_line_controls(app: &PhotocraftApp, painter: &egui::Painter, to_scr: &dyn Fn([f64; 2]) -> Pos2, accent: Color32) { + // While an end is dragged the box draws the scaled preview instead. + if app.ui.shape_box.is_some() { + return; + } + let Some(LiveLine { from, to, rotated }) = line_controls(app) else { return }; + let square = |at: [f64; 2]| { + let h = egui::Rect::from_center_size(to_scr(at), vec2(7.0, 7.0)); + painter.rect_filled(h, 0.0, Color32::WHITE); + painter.rect_stroke(h, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Inside); + }; + if let Some(c) = rotated { + painter.add(egui::Shape::closed_line(c.map(to_scr).to_vec(), Stroke::new(1.0, accent))); + for i in 0..4 { + let (a, b) = (c[i], c[(i + 1) % 4]); + square([(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]); + } + } + square(from); + square(to); + // As the corner radius widgets look (`corner_radius::draw`). + let mid = to_scr([(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0]); + painter.circle(mid, 5.0, Color32::WHITE, Stroke::new(1.5, accent)); + painter.circle_filled(mid, 2.5, accent); } /// The selected shape layers and the box round their paths. `None` unless at least one layer is @@ -146,6 +241,9 @@ fn zoom(app: &PhotocraftApp) -> f64 { /// line it is on or just outside, as that side's middle handle, unless an unselected shape is /// there. The handles come first, so a corner keeps its press where the sides' bands meet it. fn hit(app: &PhotocraftApp, p: [f64; 2]) -> Option<[i8; 2]> { + if let Some(l) = line_controls(app) { + return line_end_hit(&l, p, GRAB_PX / zoom(app)); + } if !shows(app) { return None; } @@ -279,7 +377,8 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool } } -/// The box and its handles, and while a handle is dragged the scaled outlines. +/// The box and its handles (with the Ellipse tool, its centre mark too), and while a handle is +/// dragged the scaled outlines. pub fn draw(app: &PhotocraftApp, painter: &egui::Painter, to_scr: &dyn Fn([f64; 2]) -> Pos2, accent: Color32) { if !shows(app) { return; @@ -302,9 +401,23 @@ pub fn draw(app: &PhotocraftApp, painter: &egui::Painter, to_scr: &dyn Fn([f64; let [x0, y0, x1, y1] = shown; let corners = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]].map(to_scr); painter.add(egui::Shape::closed_line(corners.to_vec(), Stroke::new(1.0, accent))); + // Under the handles: on a small box the middle ones keep their white squares on top. + if app.ui.tool == Tool::EllipseShape { + draw_center_mark(painter, to_scr([(x0 + x1) / 2.0, (y0 + y1) / 2.0]), accent); + } for (_, at) in handles(shown) { let h = egui::Rect::from_center_size(to_scr(at), vec2(7.0, 7.0)); painter.rect_filled(h, 0.0, Color32::WHITE); painter.rect_stroke(h, 0.0, Stroke::new(1.0, accent), egui::StrokeKind::Inside); } } + +/// The Ellipse tool's centre mark (#13239): a crosshair in a small circle at the box centre, a +/// fixed size on screen as the handles are. It takes no press. +fn draw_center_mark(painter: &egui::Painter, c: Pos2, accent: Color32) { + const R: f32 = 4.0; + let stroke = Stroke::new(1.0, accent); + painter.circle_stroke(c, R, stroke); + painter.line_segment([c - vec2(R, 0.0), c + vec2(R, 0.0)], stroke); + painter.line_segment([c - vec2(0.0, R), c + vec2(0.0, R)], stroke); +} diff --git a/crates/ui-egui/src/tools/shape_options.rs b/crates/ui-egui/src/tools/shape_options.rs index 8aabe45922..761cea5471 100644 --- a/crates/ui-egui/src/tools/shape_options.rs +++ b/crates/ui-egui/src/tools/shape_options.rs @@ -101,27 +101,30 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool o.stroke_width = enabled_stroke_width(o.stroke_width); } } + let (mut radius_alert, mut sides_alert) = (false, false); match tool { Tool::Rectangle => { crate::widgets::vline(ui, 22.0); - lbl(ui, tl!("Radius:")); - let mut r = match target.as_ref().and_then(|s| s.live.as_ref()) { - Some(photocraft_doc::LiveShape::Rect { radii, .. }) => radii[0] as f32, - _ => o.corner_radius, - }; - if crate::widgets::value_field(ui, &mut r, 0.0..=10000.0, "px", 62.0).changed() { + let label = tl!("Radius:"); + lbl(ui, label); + // The tool's own radius for the next rectangle (#13338); the active shape is not touched. + let mut r = o.corner_radius; + let (resp, out_of_range) = crate::widgets::value_field_alerting(ui, label, &mut r, RADIUS_RANGE, "px", 62.0); + radius_alert = out_of_range; + if resp.changed() { o.corner_radius = r; - let rf = r as f64; - edit = Some(json!({"radii": [rf, rf, rf, rf], "coalesce": key("radius")})); } } Tool::Polygon => { crate::widgets::vline(ui, 22.0); - lbl(ui, tl!("Sides:")); - let mut s = o.polygon_sides as f32; - if crate::widgets::value_field(ui, &mut s, 3.0..=100.0, "", 48.0).changed() { - o.polygon_sides = s.round().clamp(3.0, 100.0) as u32; - } + let label = tl!("Sides:"); + lbl(ui, label); + sides_alert = sides_field(ui, label, &mut o.polygon_sides); + } + Tool::Triangle => { + crate::widgets::vline(ui, 22.0); + // Only a shape layer has pixel edges to align: greyed in Path mode (and in a pixels mode). + ui.add_enabled_ui(o.shape_mode == "shape", |ui| crate::widgets::checkbox(ui, &mut o.align_edges, tl!("Align Edges"))); } Tool::Line => { crate::widgets::vline(ui, 22.0); @@ -196,8 +199,55 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool if let Some(rgb) = recent { crate::paint_picker::remember(app, rgb); } + range_alert(app, radius_alert, RADIUS_RANGE_ALERT); + range_alert(app, sides_alert, SIDES_RANGE_ALERT); } +/// The Rectangle tool's corner radius in px, as the reference takes it (#13336). +pub(crate) const RADIUS_RANGE: std::ops::RangeInclusive = 0.0..=150_000.0; + +/// The reference's alert for a Rectangle tool Radius typed past [`RADIUS_RANGE`] (#13336). +pub(crate) const RADIUS_RANGE_ALERT: &str = "A value between 0.000 pixel and 150000.000 Pixels is required. Closest value inserted."; + +/// The Polygon tool's Sides: whole numbers 3..100. Returns true once the field is left with a +/// value typed past them, so the caller shows [`SIDES_RANGE_ALERT`] (#13304). +fn sides_field(ui: &mut egui::Ui, label: &str, sides: &mut u32) -> bool { + let mut s = *sides as f32; + let (r, out_of_range) = crate::widgets::value_field_whole_alerting(ui, label, &mut s, 3.0..=100.0, "", 48.0); + if r.changed() { + *sides = s.round().clamp(3.0, 100.0) as u32; + } + out_of_range +} + +/// The reference's alert for a Polygon Sides value typed past 3..100 (#13304). +pub(crate) const SIDES_RANGE_ALERT: &str = "An integer between 3 and 100 is required. Closest value inserted."; + +/// Shows `alert` ([`RADIUS_RANGE_ALERT`], [`SIDES_RANGE_ALERT`]) as a modal with OK when `owed`, +/// once even if more than one pass asks. +fn range_alert(app: &mut PhotocraftApp, owed: bool, alert: &str) { + if !owed { + return; + } + let message = tl!(alert).to_owned(); + let shown = app.ui.dialogs.iter().any(|d| d.kind == crate::state::DialogKind::Error && d.fields.get("message").and_then(|m| m.as_str()) == Some(&message)); + if !shown { + app.ui.open_dialog(crate::state::DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default()); + } +} + +#[cfg(test)] +#[path = "rectangle_radius_range_tests.rs"] +mod rectangle_radius_range_tests; + +#[cfg(test)] +#[path = "rectangle_radius_target_tests.rs"] +mod rectangle_radius_target_tests; + +#[cfg(test)] +#[path = "polygon_sides_alert_tests.rs"] +mod polygon_sides_alert_tests; + /// Tool-bar paint changes affect the next shape; Properties edits the selected shape instead. pub(crate) fn set_tool_paint(app: &mut PhotocraftApp, stroke: bool, change: PaintChange) -> Result<(), String> { // A colour takes the place of a gradient; No Color keeps it for when the paint comes back. diff --git a/crates/ui-egui/src/tools/stroke_constraint.rs b/crates/ui-egui/src/tools/stroke_constraint.rs index 02f636d849..b02cfcf81a 100644 --- a/crates/ui-egui/src/tools/stroke_constraint.rs +++ b/crates/ui-egui/src/tools/stroke_constraint.rs @@ -105,6 +105,20 @@ pub fn snap45(origin: [f64; 2], p: [f64; 2]) -> [f64; 2] { } } +/// `snap45` for a Direct Selection anchor drag (#13207). The reference application keeps a +/// (+60, -25) drag on the horizontal, just past `snap45`'s 22.5° split, so drags up to that slope +/// (5:12) from an axis stay on it. Where its switch really lies isn't measured; steeper drags +/// keep `snap45`. +pub fn snap45_anchor(origin: [f64; 2], p: [f64; 2]) -> [f64; 2] { + let (dx, dy) = ((p[0] - origin[0]).abs(), (p[1] - origin[1]).abs()); + // The measured drag sits exactly on the 5:12 bound, and the f32 screen-to-document mapping + // puts ~1e-4 px of noise on it, so the bound gets a small slack. + if dx.is_finite() && dy.is_finite() && dx.max(dy) > 0.0 && dx.min(dy) * 12.0 <= dx.max(dy) * 5.0 + 1e-3 { + return if dx >= dy { [p[0], origin[1]] } else { [origin[0], p[1]] }; + } + snap45(origin, p) +} + /// Constrain the pointer at `p` for a drag of `tool` that started at `start` and has reached /// `last`. `axis` carries the stroke's lock between events; `zoom` converts the lock distance /// to document pixels. The lock follows the tool's [`snap_mode`]: horizontal/vertical for the diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index b40ecb59af..ba62a52b9d 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -1,5 +1,6 @@ //! Reset Tool and Reset All Tools (#2825), as in Photoshop: right-click the tool icon at the far -//! left of the options bar. Reset Tool puts the current tool's options back to their defaults; +//! left of the options bar. Reset Tool puts the current tool's options back to their defaults +//! (all but the few it keeps, [`kept_by_reset_tool`]); //! Reset All Tools asks first ("Reset all tools to their default settings?"), then resets every //! tool's options. //! @@ -132,16 +133,30 @@ fn is_selection_tool(tool: Tool) -> bool { ) } -/// Put `tool`'s fields of `o` back to their defaults. +/// The fields of [`option_keys`] that Reset Tool leaves as they are, as the reference app does +/// (Zoom Out, #12066; Patch Structure and Color, #12127; Content-Aware Move Mode, #12183). +/// They stay in [`option_keys`], so a tool preset still stores them, and Reset All Tools still +/// resets them (it starts from the defaults). +fn kept_by_reset_tool(tool: Tool) -> &'static [&'static str] { + match tool { + Tool::Zoom => &["zoom_in"], + Tool::Patch => &["patch_structure", "patch_color"], + Tool::ContentAwareMove => &["cam_mode"], + _ => &[], + } +} + +/// Put `tool`'s fields of `o` back to their defaults, except those Reset Tool keeps. pub fn reset_options(o: &mut ToolOptions, tool: Tool) { let keys = option_keys(tool); + let kept = kept_by_reset_tool(tool); if keys.is_empty() { return; } let (Ok(Value::Object(mut cur)), Ok(Value::Object(d))) = (serde_json::to_value(&*o), serde_json::to_value(ToolOptions::default())) else { return; }; - for k in keys { + for k in keys.iter().filter(|k| !kept.contains(k)) { if let Some(v) = d.get(*k) { cur.insert((*k).to_string(), v.clone()); } @@ -167,8 +182,8 @@ pub fn sample_all_key(tool: Tool) -> Option { m.into_iter().find(|(k, v)| b.get(k) != Some(v)).map(|(k, _)| k) } -/// The [`ToolOptions`] fields `tool` shows, by their serialized names: what Reset Tool resets and -/// what a tool preset made with + stores (#7356). +/// The [`ToolOptions`] fields `tool` shows, by their serialized names: what Reset Tool resets +/// (less [`kept_by_reset_tool`]) and what a tool preset made with + stores (#7356). pub fn option_keys(tool: Tool) -> &'static [&'static str] { // `reset!` names each field once; one that is misspelt or gone fails to compile. macro_rules! reset { @@ -226,7 +241,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => { reset!(type_font, type_style, type_size, type_aa, type_align, type_direction, type_style_defaults) } - Tool::Zoom => reset!(zoom_scrubby), + Tool::Zoom => reset!(zoom_scrubby, zoom_in), Tool::Hand => reset!(hand_scroll_all), Tool::SpotHealing => reset!(spot_type), Tool::Healing => reset!(clone_aligned, clone_sample), @@ -246,6 +261,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { Tool::FreeformPen => reset!(vector_mode, pen_path_op, curve_fit), Tool::Line => reset!( shape_mode, + shape_path_op, shape_fill, stroke_width, shape_stroke, @@ -261,7 +277,19 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { arrow_concavity, ), Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Star | Tool::CustomShape => { - reset!(shape_mode, shape_fill, stroke_width, shape_stroke, shape_fill_gradient, shape_stroke_gradient, corner_radius, polygon_sides, line_weight) + reset!( + shape_mode, + shape_path_op, + shape_fill, + stroke_width, + shape_stroke, + shape_fill_gradient, + shape_stroke_gradient, + corner_radius, + align_edges, + polygon_sides, + line_weight + ) } Tool::MixerBrush => reset!(mixer_combination), Tool::ColorSampler @@ -307,6 +335,17 @@ mod tests { } } + /// What Reset Tool keeps is the tool's own option, by a name that exists: a renamed or + /// misspelt field would otherwise silently be reset again (#12127, #12183). + #[test] + fn kept_options_are_the_tools_own() { + for t in Tool::ALL { + for k in kept_by_reset_tool(t) { + assert!(option_keys(t).contains(k), "{k} is not an option of {t:?}"); + } + } + } + /// Reset Tool resets only the current tool's options; Reset All Tools asks, then resets all. #[test] fn reset_tool_and_reset_all_tools() { diff --git a/crates/ui-egui/src/tools/transform_tex.rs b/crates/ui-egui/src/tools/transform_tex.rs index ae67b2e2c5..77dbfbd79a 100644 --- a/crates/ui-egui/src/tools/transform_tex.rs +++ b/crates/ui-egui/src/tools/transform_tex.rs @@ -11,8 +11,12 @@ //! enlarged by the transform: the full-resolution level with nearest filtering, so pixels stay //! crisp like the canvas around them. //! -//! Levels and filter variants are uploaded on first use and cached for the session. +//! Levels and filter variants are uploaded on first use and cached for the session. A mip level +//! first needed mid-drag (the scale crossing ½, ¼…) is built, colour-converted and uploaded on a +//! helper thread, and the closest finer level already uploaded is shown until it is ready +//! (#11103): halving a 24 MP layer took a whole frame or more on the UI thread. +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; use egui::{Color32, ColorImage, TextureHandle, TextureId, TextureOptions}; @@ -30,12 +34,36 @@ struct Level { pub struct PreviewTextures { name: String, /// CPU copies of the levels built so far (level 0 = full resolution), premultiplied. - images: Mutex>>, + images: Arc>>>, /// uv extent of level 0 that covers the source exactly (< 1 when level 0 was padded). base_uv: [f32; 2], - uploaded: Mutex>, + uploaded: Arc>>, + /// Mip levels being built off the UI thread, as `(level, display key)`. + building: Arc>>, + /// Whether a mip level that has a finer level to stand in for it is built off the UI thread. + background: bool, + /// Cleared when the preview closes (under the `uploaded` lock): a level finishing after that is + /// neither converted nor uploaded. Workers only read it, so they never keep the preview alive. + alive: Arc, + /// Held by a test to pause the workers just before they check `alive`. + #[cfg(test)] + gate: Arc>, + /// How many levels the workers have uploaded, for tests. + #[cfg(test)] + uploads: Arc, } +impl Drop for PreviewTextures { + fn drop(&mut self) { + let _uploads = self.uploaded.lock().unwrap_or_else(PoisonError::into_inner); + self.alive.store(false, Ordering::Release); + } +} + +/// Off the UI thread on native builds; the web build has no threads to spare. Unit tests build +/// synchronously unless they ask (`set_background_builds`), so frames stay deterministic. +const BUILD_IN_BACKGROUND: bool = cfg!(not(any(test, target_arch = "wasm32"))); + /// A source pixel shown at this many screen pixels or more counts as "zoomed in" (nearest). const CRISP_ZOOM: f32 = 2.0; @@ -47,12 +75,40 @@ impl PreviewTextures { let base_uv = [base_uv[0].clamp(0.0, 1.0), base_uv[1].clamp(0.0, 1.0)]; Self { name, - images: Mutex::new(vec![image]), + images: Arc::new(Mutex::new(vec![image])), base_uv, - uploaded: Mutex::new(vec![Level { level: 0, display_key: 0, nearest: false, tex, uv: base_uv }]), + uploaded: Arc::new(Mutex::new(vec![Level { level: 0, display_key: 0, nearest: false, tex, uv: base_uv }])), + building: Arc::new(Mutex::new(Vec::new())), + background: BUILD_IN_BACKGROUND, + alive: Arc::new(AtomicBool::new(true)), + #[cfg(test)] + gate: Arc::new(Mutex::new(())), + #[cfg(test)] + uploads: Arc::new(std::sync::atomic::AtomicUsize::new(0)), } } + /// Build mip levels off the UI thread (`true`) or in the frame that first needs them. + #[cfg(test)] + pub(crate) fn set_background_builds(&mut self, on: bool) { + self.background = on; + } + + /// Whether a mip level is still being built off the UI thread. + #[cfg(test)] + pub(crate) fn is_building(&self) -> bool { + !self.building.lock().unwrap_or_else(PoisonError::into_inner).is_empty() + } + + /// What a test locks to pause the workers just before they check that the preview is open, + /// what tells it they are all done, and how many levels they uploaded; the last two still work + /// once the preview is gone. + #[cfg(test)] + pub(crate) fn worker_hooks(&self) -> (Arc>, impl Fn() -> bool + use<>, Arc) { + let building = Arc::clone(&self.building); + (Arc::clone(&self.gate), move || building.lock().unwrap_or_else(PoisonError::into_inner).is_empty(), Arc::clone(&self.uploads)) + } + /// Size of the full-resolution level in texels. pub fn size(&self) -> [usize; 2] { self.images.lock().unwrap_or_else(PoisonError::into_inner).first().map_or([0, 0], |i| i.size) @@ -100,6 +156,19 @@ impl PreviewTextures { if let Some(l) = up.iter().find(|l| l.level == level && l.nearest == nearest && l.display_key == display_key) { return (l.tex.id(), l.uv); } + // A level first needed mid-drag: show the closest finer level already uploaded for this + // display while a helper thread builds it (#11103). + if self.background + && level > 0 + && let Some(finer) = up.iter().filter(|l| l.display_key == display_key && l.level < level).max_by_key(|l| (l.level, !l.nearest)) + { + let shown = (finer.tex.id(), finer.uv); + drop(up); + if self.build_in_background(ctx, level, display, display_key) { + return shown; + } + up = self.uploaded.lock().unwrap_or_else(PoisonError::into_inner); + } let Some((img, uv)) = self.level_image(level) else { // Can't build it (shouldn't happen): fall back to the first upload. return up.first().map_or((TextureId::default(), [1.0, 1.0]), |l| (l.tex.id(), l.uv)); @@ -114,24 +183,93 @@ impl PreviewTextures { (id, uv) } + /// Builds level `level` on a helper thread, uploads it and asks for a frame. False when no + /// thread could be started (the caller builds it in this frame instead). + fn build_in_background(&self, ctx: &egui::Context, level: u32, display: Option<&CanvasDisplay>, display_key: u64) -> bool { + { + let mut building = self.building.lock().unwrap_or_else(PoisonError::into_inner); + if building.contains(&(level, display_key)) { + return true; + } + building.push((level, display_key)); + } + let (images, uploaded, building, alive) = (Arc::clone(&self.images), Arc::clone(&self.uploaded), Arc::clone(&self.building), Arc::clone(&self.alive)); + let (ctx, base_uv, name) = (ctx.clone(), self.base_uv, format!("{}-{level}-linear", self.name)); + let display = display.map(share_display); + #[cfg(test)] + let (gate, uploads) = (Arc::clone(&self.gate), Arc::clone(&self.uploads)); + let job = move || { + let built = level_of(&images, base_uv, level); + #[cfg(test)] + drop(gate.lock().unwrap_or_else(PoisonError::into_inner)); + // The box closed meanwhile: neither convert nor upload. + if let Some((img, uv)) = built.filter(|_| alive.load(Ordering::Acquire)) { + let img = display.as_ref().map_or_else(|| Arc::clone(&img), |d| Arc::new(display_image(&img, d))); + let mut up = uploaded.lock().unwrap_or_else(PoisonError::into_inner); + // Checked again under the lock the preview takes as it closes. A monitor profile + // change meanwhile released this display's uploads: drop it then too. + if alive.load(Ordering::Acquire) && up.iter().all(|l| l.display_key == display_key) && !up.iter().any(|l| l.level == level && !l.nearest) { + let tex = ctx.load_texture(name, img, TextureOptions::LINEAR); + #[cfg(test)] + uploads.fetch_add(1, Ordering::Relaxed); + up.push(Level { level, display_key, nearest: false, tex, uv }); + } + } + building.lock().unwrap_or_else(PoisonError::into_inner).retain(|b| *b != (level, display_key)); + ctx.request_repaint(); + }; + let started = std::thread::Builder::new().name("transform-mip".into()).spawn(job).is_ok(); + if !started { + self.building.lock().unwrap_or_else(PoisonError::into_inner).retain(|b| *b != (level, display_key)); + } + started + } + /// Level `n` of the mip chain (built on demand by 2×2 box filtering) and its uv extent. pub(crate) fn level_image(&self, n: u32) -> Option<(Arc, [f32; 2])> { - let mut imgs = self.images.lock().unwrap_or_else(PoisonError::into_inner); - while imgs.len() <= n as usize { + level_of(&self.images, self.base_uv, n) + } +} + +/// Level `n` of `images` (built on demand by 2×2 box filtering) and its uv extent. Each level is +/// filtered with the lock released, so a helper thread building one doesn't stall the frame +/// reading another (the layer-style preview reads them too). +fn level_of(images: &Mutex>>, base_uv: [f32; 2], n: u32) -> Option<(Arc, [f32; 2])> { + loop { + let (prev, len) = { + let imgs = images.lock().unwrap_or_else(PoisonError::into_inner); let prev = imgs.last()?; - if prev.size[0] <= 1 && prev.size[1] <= 1 { + if imgs.len() > n as usize || (prev.size[0] <= 1 && prev.size[1] <= 1) { break; } - let next = Arc::new(halve(prev)); + (Arc::clone(prev), imgs.len()) + }; + let next = Arc::new(halve(&prev)); + let mut imgs = images.lock().unwrap_or_else(PoisonError::into_inner); + // Another thread may have added this level meanwhile: keep the first. + if imgs.len() == len { imgs.push(next); } - let k = (imgs.len() - 1).min(n as usize); - let img = imgs.get(k)?.clone(); - let base = imgs.first()?.size; - // Level k covers size·2^k base texels (the last row/column may be padding). - let f = (1u64 << k) as f32; - let uv = [self.base_uv[0] * base[0] as f32 / (img.size[0] as f32 * f).max(1.0), self.base_uv[1] * base[1] as f32 / (img.size[1] as f32 * f).max(1.0)]; - Some((img, [uv[0].min(1.0), uv[1].min(1.0)])) + } + let imgs = images.lock().unwrap_or_else(PoisonError::into_inner); + let k = (imgs.len() - 1).min(n as usize); + let img = imgs.get(k)?.clone(); + let base = imgs.first()?.size; + // Level k covers size·2^k base texels (the last row/column may be padding). + let f = (1u64 << k) as f32; + let uv = [base_uv[0] * base[0] as f32 / (img.size[0] as f32 * f).max(1.0), base_uv[1] * base[1] as f32 / (img.size[1] as f32 * f).max(1.0)]; + Some((img, [uv[0].min(1.0), uv[1].min(1.0)])) +} + +/// A copy of `d` for a helper thread (its profiles and transform are shared, not copied). +fn share_display(d: &CanvasDisplay) -> CanvasDisplay { + CanvasDisplay { + encode_srgb: d.encode_srgb, + source: Arc::clone(&d.source), + monitor: Arc::clone(&d.monitor), + transform: d.transform.clone(), + key: d.key, + texture_key: d.texture_key, } } @@ -163,12 +301,21 @@ fn halve(img: &ColorImage) -> ColorImage { let (nw, nh) = (w.div_ceil(2).max(1), h.div_ceil(2).max(1)); let mut out = vec![Color32::TRANSPARENT; nw * nh]; let px = |x: usize, y: usize| img.pixels.get(y.min(h.saturating_sub(1)) * w + x.min(w.saturating_sub(1))).copied().unwrap_or_default(); - for (y, row) in out.chunks_mut(nw).enumerate() { + let row = |y: usize, row: &mut [Color32]| { for (x, o) in row.iter_mut().enumerate() { let q = [px(2 * x, 2 * y), px(2 * x + 1, 2 * y), px(2 * x, 2 * y + 1), px(2 * x + 1, 2 * y + 1)]; let avg = |c: fn(&Color32) -> u8| ((q.iter().map(|p| u32::from(c(p))).sum::() + 2) / 4) as u8; *o = Color32::from_rgba_premultiplied(avg(Color32::r), avg(Color32::g), avg(Color32::b), avg(Color32::a)); } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + out.par_chunks_mut(nw).enumerate().for_each(|(y, r)| row(y, r)); + } + #[cfg(target_arch = "wasm32")] + for (y, r) in out.chunks_mut(nw).enumerate() { + row(y, r); } ColorImage::new([nw, nh], out) } diff --git a/crates/ui-egui/src/tools/transform_tool/options_bar.rs b/crates/ui-egui/src/tools/transform_tool/options_bar.rs index d8350ebb4a..f79cae7c3a 100644 --- a/crates/ui-egui/src/tools/transform_tool/options_bar.rs +++ b/crates/ui-egui/src/tools/transform_tool/options_bar.rs @@ -267,7 +267,7 @@ fn reference_point_toggle(ui: &mut egui::Ui, on: &mut bool) -> bool { // The catalogue's "Toggle reference point" (sentence case, like the grid's tooltip). let label = tl!("Toggle reference point"); resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, *on, label)); - resp.on_hover_text(label); + resp.on_hover_text(label).on_disabled_hover_text(label); *on } @@ -374,7 +374,7 @@ fn anchor_grid_widget(ui: &mut egui::Ui, current_anchor: Option, enabled: painter.rect_filled(pt_rect, 0.5, if enabled { color } else { color.gamma_multiply(0.4) }); } } - resp.on_hover_text(tl!("Reference point location")); + resp.on_hover_text(tl!("Reference point location")).on_disabled_hover_text(tl!("Reference point location")); clicked } @@ -467,6 +467,14 @@ fn warp_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, w: &Warp) { let on_type = warps_type(app); // A cylinder has no splits or grid either (#4112): its handles are its own. let cylinder = w.style == WarpStyle::Cylinder; + // Free Transform's reference point check box and grid keep their slots, greyed and inert, as + // in the reference (#12503): on, at the centre. The disabled `Ui` greys the grid once; its own + // greying (for Toggle Reference Point off) would dim it again. + ui.add_enabled_ui(false, |ui| { + reference_point_toggle(ui, &mut true); + anchor_grid_widget(ui, Some(4), true); + }); + crate::widgets::vline(ui, 22.0); // Split, Grid, then the warp style with its bend fields. ui.add_enabled_ui(!on_type && !cylinder, |ui| warp_mesh_fields(app, ui, w)); crate::widgets::vline(ui, 22.0); @@ -501,13 +509,30 @@ fn warp_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, w: &Warp) { for (k, (name, v)) in fields.iter().enumerate() { lbl(ui, name); let mut f = *v as f32; - if crate::widgets::value_field(ui, &mut f, -100.0..=100.0, "%", 58.0).accessible_name(*name).changed() + let shown = ((f64::from(f) * 10.0).round() / 10.0) as f32; + let r = crate::widgets::value_field_fixed(ui, &mut f, -100.0..=100.0, "%", 62.0, 1).accessible_name(*name); + // The fields take one decimal: a typed 12.345 is stored as the 12.3 they show once the + // field is left (rounding each keystroke would rewrite the text being typed). Only an + // edit rounds: tabbing through keeps a value from a file (33.333) as it is, though the + // field applies its shown text (33.3) as it loses the focus. Arithmetic (`10+2`) only + // applies then, so a value other than the shown one is an edit too. + let edited_id = r.id.with("warp-edited"); + let edited = ui.data(|d| d.get_temp::(edited_id)).unwrap_or(false); + let left = !r.has_focus(); + if left { + ui.data_mut(|d| d.remove_temp::(edited_id)); + } else if r.changed() { + ui.data_mut(|d| d.insert_temp(edited_id, true)); + } + let edited = edited || (r.changed() && f != shown); + if ((r.changed() && !r.lost_focus()) || (r.lost_focus() && edited)) && let Some(Some(cur)) = app.ui.transform.as_mut().map(|t| t.warp.as_mut()) { + let f = if left { (f64::from(f) * 10.0).round() / 10.0 } else { f64::from(f) }; match k { - 0 => cur.bend = f64::from(f), - 1 => cur.h_distort = f64::from(f), - _ => cur.v_distort = f64::from(f), + 0 => cur.bend = f, + 1 => cur.h_distort = f, + _ => cur.v_distort = f, } } } @@ -645,26 +670,22 @@ fn split_icon(ui: &mut egui::Ui, kind: &str, tip: &str, on: bool) -> egui::Respo /// `mode_switch`: the Free Transform / Warp switch (not for Content-Aware Scale, which only scales). fn transform_actions(app: &mut PhotocraftApp, ui: &mut egui::Ui, warping: bool, mode_switch: bool) { ui.add_space(8.0); - let commit_tip = if warping { - crate::i18n::fmt(tl!("Commit warp ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]) - } else { - crate::i18n::fmt(tl!("Commit transform ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]) - }; + // Warp and Free Transform share these tooltips, as in the reference (#12503). + let commit_tip = crate::i18n::fmt(tl!("Commit transform ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]); let commit_btn = crate::icons::button(ui, "check", 26.0, false, &commit_tip); let label = "Commit transform"; commit_btn.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(label))); if commit_btn.clicked() { commit(app); } - let cancel_tip = if warping { tl!("Cancel warp (Esc)") } else { tl!("Cancel transform (Esc)") }; - let cancel_btn = crate::icons::button(ui, "ban", 26.0, false, cancel_tip); + let cancel_btn = crate::icons::button(ui, "ban", 26.0, false, tl!("Cancel transform (Esc)")); let label = "Cancel transform"; cancel_btn.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(label))); if cancel_btn.clicked() { cancel(app); } if warping { - let reset = crate::icons::button(ui, "undo-2", 26.0, false, tl!("Reset")); + let reset = crate::icons::button(ui, "undo-2", 26.0, false, tl!("Reset the warp")); reset.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Reset warp")); if reset.clicked() { reset_warp(app); @@ -707,3 +728,7 @@ pub(super) fn rotate_about_pivot(app: &mut PhotocraftApp, da: f64) { [c[0] + x * cs - y * sn, c[1] + x * sn + y * cs] }); } + +#[cfg(test)] +#[path = "warp_options_bar_tests.rs"] +mod warp_options_bar_tests; diff --git a/crates/ui-egui/src/tools/transform_tool/tests.rs b/crates/ui-egui/src/tools/transform_tool/tests.rs index 544d00ee37..113c788bb0 100644 --- a/crates/ui-egui/src/tools/transform_tool/tests.rs +++ b/crates/ui-egui/src/tools/transform_tool/tests.rs @@ -1,6 +1,6 @@ use super::*; -fn session() -> TransformSession { +pub(super) fn session() -> TransformSession { TransformSession { session: 1, layer: 1, @@ -221,7 +221,7 @@ fn warp_bar_buttons_follow_the_fields_on_a_wide_bar() { h.run_steps(4); assert!(h.state().ui.transform.as_ref().unwrap().warp.is_some()); let commit = h.get_by_label("Commit transform").rect(); - assert!(commit.right() < width / 2.0, "commit sits next to the fields, not at the far right: {commit:?}"); + assert!(commit.right() < width * 0.6, "commit sits next to the fields, not at the far right: {commit:?}"); let reset = h.get_by_label("Reset warp").rect(); assert!(reset.right() < commit.left() + 1.0, "reset is left of commit"); h.get_by_label("Reset warp").click(); @@ -325,7 +325,7 @@ fn type_into_bar_field(n: usize, text: &str) -> TransformSession { /// The transform bar over the test box, after `setup` (e.g. picking the W/H unit). Tall enough /// for the fields' unit menu to open below the bar unscrolled. -fn bar_harness(setup: impl FnOnce(&mut PhotocraftApp)) -> egui_kittest::Harness<'static, PhotocraftApp> { +pub(super) fn bar_harness(setup: impl FnOnce(&mut PhotocraftApp)) -> egui_kittest::Harness<'static, PhotocraftApp> { use egui_kittest::Harness; let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.ui.transform = Some(session()); @@ -345,7 +345,7 @@ fn bar_harness(setup: impl FnOnce(&mut PhotocraftApp)) -> egui_kittest::Harness< } /// [`type_into_bar_field`] after `setup`. -fn type_into_bar_field_with(setup: impl FnOnce(&mut PhotocraftApp), n: usize, text: &str) -> TransformSession { +pub(super) fn type_into_bar_field_with(setup: impl FnOnce(&mut PhotocraftApp), n: usize, text: &str) -> TransformSession { use egui_kittest::kittest::Queryable; let mut h = bar_harness(setup); h.get_all_by_role(egui::accesskit::Role::SpinButton).nth(n).unwrap().click(); diff --git a/crates/ui-egui/src/tools/transform_tool/warp_options_bar_tests.rs b/crates/ui-egui/src/tools/transform_tool/warp_options_bar_tests.rs new file mode 100644 index 0000000000..b7de5cacbf --- /dev/null +++ b/crates/ui-egui/src/tools/transform_tool/warp_options_bar_tests.rs @@ -0,0 +1,185 @@ +//! #12503: the Warp options bar keeps Bend, H and V to one decimal, shares Free Transform's +//! Commit and Cancel tooltips (Reset reads "Reset the warp"), and starts with Free Transform's +//! reference point check box and grid, greyed and inert; the tool preset picker is greyed too. + +use super::super::tests::{bar_harness, session, type_into_bar_field_with}; +use super::*; +use egui_kittest::kittest::{NodeT, Queryable}; + +type Harness = egui_kittest::Harness<'static, PhotocraftApp>; + +/// An Arc warp over the test box, so Bend, H and V are live. +fn arc(app: &mut PhotocraftApp) { + let t = app.ui.transform.as_mut().unwrap(); + t.warp = Some(Warp { style: WarpStyle::Arc, bend: 50.0, ..Warp::none(t.rect) }); +} + +fn warp(t: &TransformSession) -> [f64; 3] { + let w = t.warp.as_ref().unwrap(); + [w.bend, w.h_distort, w.v_distort] +} + +/// Hovers `label`'s control long enough for its tooltip, and says whether `tip` is shown. +fn shows_tip(h: &mut Harness, label: &str, tip: &str) -> bool { + h.get_by_label(label).hover(); + h.run_steps(60); + h.query_all_by_label(tip).any(|n| n.accesskit_node().role() == egui::accesskit::Role::Label) +} + +#[test] +fn bend_h_and_v_store_the_one_decimal_they_show() { + for n in 0..3 { + let mut want = [50.0, 0.0, 0.0]; + want[n] = 12.3; + assert_eq!(warp(&type_into_bar_field_with(arc, n, "12.345")), want, "field {n}"); + } + // Past the range, the value is clamped as before. + assert_eq!(warp(&type_into_bar_field_with(arc, 1, "-150")), [50.0, -100.0, 0.0]); + let h = bar_harness(|app| { + arc(app); + app.ui.transform.as_mut().unwrap().warp.as_mut().unwrap().h_distort = 12.3; + }); + assert_eq!(shown(&h), ["50.0", "12.3", "0.0"]); + // Entering Warp from Free Transform: no bend yet. + let mut h = bar_harness(|_| {}); + // Free Transform's X, Y, W and H keep dropping trailing zeros. + assert_eq!(shown(&h)[..4], ["50", "25", "100", "100"]); + h.get_by_label("Switch between free transform and warp modes").click(); + h.run_steps(4); + assert_eq!(shown(&h), ["0.0", "0.0", "0.0"]); +} + +#[test] +fn tabbing_through_keeps_a_value_it_did_not_edit() { + let mut h = bar_harness(|app| { + arc(app); + app.ui.transform.as_mut().unwrap().warp.as_mut().unwrap().bend = 33.333; + }); + h.get_all_by_role(egui::accesskit::Role::SpinButton).next().unwrap().click(); + h.run(); + h.key_press(egui::Key::Tab); + h.run_steps(3); + assert_eq!(warp(h.state().ui.transform.as_ref().unwrap()), [33.333, 0.0, 0.0]); +} + +#[test] +fn an_arithmetic_entry_is_stored_as_the_field_is_left() { + assert_eq!(warp(&type_into_bar_field_with(arc, 1, "10+2")), [50.0, 12.0, 0.0]); + // Appended to the shown 10.0, no keystroke changes the value before the field is left. + for leave in [egui::Key::Enter, egui::Key::Tab] { + let mut h = bar_harness(|app| { + arc(app); + app.ui.transform.as_mut().unwrap().warp.as_mut().unwrap().h_distort = 10.0; + }); + h.get_all_by_role(egui::accesskit::Role::SpinButton).nth(1).unwrap().click(); + h.run(); + h.key_press(egui::Key::End); + h.run(); + for c in "+2.25".chars() { + h.event(egui::Event::Text(c.to_string())); + h.run(); + } + h.key_press(leave); + h.run_steps(3); + assert_eq!(warp(h.state().ui.transform.as_ref().unwrap()), [50.0, 12.3, 0.0], "{leave:?}"); + } +} + +/// The text of every number field in the bar, in order. +fn shown(h: &Harness) -> Vec { + h.get_all_by_role(egui::accesskit::Role::SpinButton).map(|n| n.accesskit_node().value().unwrap_or_default().to_string()).collect() +} + +#[test] +fn warp_actions_have_the_free_transform_tooltips() { + let commit = crate::i18n::fmt("Commit transform ({key})", &[("key", &crate::shortcuts::pretty("Enter"))]); + let mut h = bar_harness(arc); + assert!(shows_tip(&mut h, "Commit transform", &commit)); + assert!(shows_tip(&mut h, "Cancel transform", "Cancel transform (Esc)")); + assert!(shows_tip(&mut h, "Reset warp", "Reset the warp")); + // Free Transform keeps its own, and has no Reset. + let mut h = bar_harness(|_| {}); + assert!(shows_tip(&mut h, "Commit transform", &commit)); + assert!(shows_tip(&mut h, "Cancel transform", "Cancel transform (Esc)")); + assert!(h.query_by_label("Reset warp").is_none()); +} + +#[test] +fn warp_bar_starts_with_the_greyed_reference_point_controls() { + let mut h = bar_harness(arc); + let toggle = h.get_by_label("Toggle reference point"); + let node = toggle.accesskit_node(); + assert!(node.is_disabled() && node.toggled() == Some(egui::accesskit::Toggled::True), "greyed and on"); + let rect = toggle.rect(); + assert!(rect.right() < h.get_by_label("Split Warp Crosswise").rect().left(), "before Split"); + // In the slot Free Transform has it in. + assert_eq!(rect.left(), bar_harness(|_| {}).get_by_label("Toggle reference point").rect().left()); + assert!(shows_tip(&mut h, "Toggle reference point", "Toggle reference point")); + + // The grid follows the check box; its top-left dot would move the reference point. + let gap = h.ctx.global_style().spacing.item_spacing.x; + let grid_top_left = egui::pos2(rect.right() + gap + 16.0 / 6.0, rect.center().y - 16.0 / 3.0); + h.event(egui::Event::PointerMoved(grid_top_left)); + h.run_steps(60); + assert!(h.query_all_by_label("Reference point location").any(|n| n.accesskit_node().role() == egui::accesskit::Role::Label), "grid tooltip"); + + let state = |h: &Harness| (h.state().ui.tool_options.transform_reference_point, h.state().ui.transform.as_ref().unwrap().pivot); + let before = state(&h); + h.get_by_label("Toggle reference point").click(); + h.run_steps(2); + click(&mut h, grid_top_left); + assert_eq!(state(&h), before, "greyed controls do nothing"); + + // The same click in Free Transform, with the reference point shown, moves it to the corner. + let mut h = bar_harness(|app| app.ui.tool_options.transform_reference_point = true); + click(&mut h, grid_top_left); + assert_eq!(state(&h), (true, [0.0, 0.0])); +} + +fn click(h: &mut Harness, pos: egui::Pos2) { + click_with(h, pos, egui::PointerButton::Primary); +} + +fn click_with(h: &mut Harness, pos: egui::Pos2, button: egui::PointerButton) { + h.event(egui::Event::PointerMoved(pos)); + h.run(); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos, button, pressed, modifiers: Default::default() }); + h.run(); + } + h.run_steps(2); +} + +/// The whole options bar (tool preset picker included) over the test box, warping or not. +fn full_bar(warping: bool) -> Harness { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.transform = Some(session()); + if warping { + arc(&mut app); + } + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 300.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + crate::panels::options_bar(app, ui); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(6); + h +} + +#[test] +fn the_tool_preset_picker_is_greyed_only_while_warping() { + for warping in [false, true] { + let mut h = full_bar(warping); + let tool = h.state().ui.tool.label(); + let picker = h.get_by_label(tool); + assert_eq!(picker.accesskit_node().is_disabled(), warping, "warping: {warping}"); + // Its right-click menu (Reset Tool) opens only when it is live. + let at = picker.rect().center(); + click_with(&mut h, at, egui::PointerButton::Secondary); + assert_eq!(h.query_by_label("Reset Tool").is_none(), warping, "warping: {warping}"); + } +} diff --git a/crates/ui-egui/src/tools/type_tool.rs b/crates/ui-egui/src/tools/type_tool.rs index 60dbb231ed..636c0f3e75 100644 --- a/crates/ui-egui/src/tools/type_tool.rs +++ b/crates/ui-egui/src/tools/type_tool.rs @@ -144,6 +144,8 @@ mod font_commit_tests; mod font_picker_tests; #[cfg(test)] mod options_tooltips_tests; +#[cfg(test)] +mod panels_toggle_tests; #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/tools/type_tool/mask_click_text_layer_tests.rs b/crates/ui-egui/src/tools/type_tool/mask_click_text_layer_tests.rs new file mode 100644 index 0000000000..56704f3da1 --- /dev/null +++ b/crates/ui-egui/src/tools/type_tool/mask_click_text_layer_tests.rs @@ -0,0 +1,188 @@ +//! #12075: a Horizontal or Vertical Type Mask click on a text layer's glyphs edits that layer as +//! the Type tool does: it becomes active, no mask session starts, and the commit adds the Type +//! tool's own history state (renamed by #12048) and no selection, and gives the mask tool back. +//! A fully locked text layer shows the Type tool's alert. A click on empty canvas, on a partly +//! locked text layer or with ⇧ still starts a mask (the last two are not measured). Clicks go +//! through the canvas's tool events. + +use egui::Modifiers; +use egui_kittest::Harness; +use photocraft_doc::LayerId; +use serde_json::json; + +use super::super::mask_replace_selection_tests::{click, new_app, selection}; +use super::super::{commit, current_text, insert}; +use super::{hit_layer, hit_offset}; +use crate::PhotocraftApp; +use crate::state::{DialogKind, Tool}; + +const MASKS: [Tool; 2] = [Tool::HorizontalTypeMask, Tool::VerticalTypeMask]; +/// The canvas well away from the text. +const OFF_TEXT: (f64, f64) = (500.0, 100.0); + +/// A committed type layer "TXT" made with `type_tool` and, active above it, an empty layer, with +/// no selection and `tool` in hand. +fn typed(type_tool: Tool, tool: Tool) -> (PhotocraftApp, LayerId) { + let mut app = new_app(); + app.run("select.deselect", json!({})).unwrap(); + app.ui.tool = type_tool; + click(&mut app, 100.0, 200.0, Modifiers::NONE); + insert(&mut app, "TXT"); + commit(&mut app); + let id = active_layer(&app).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = tool; + (app, id) +} + +/// [`typed`] horizontal text, and the point on its glyphs between "T" and "X". +fn txt(tool: Tool) -> (PhotocraftApp, LayerId, (f64, f64)) { + let (mut app, id) = typed(Tool::Type, tool); + let y = 185.0; + let x = (100..200) + .map(f64::from) + .find(|&x| hit_layer(&mut app, x, y) == Some(id) && hit_offset(&mut app, id, x, y) == 1) + .expect("a point after the first letter"); + (app, id, (x, y)) +} + +/// Frames of the app's own logic, each frame as the app runs it: the commit when the tool in hand +/// no longer matches the edit, then the shortcuts and typing; one of `events` per frame. +fn frames(app: PhotocraftApp, events: Vec) -> PhotocraftApp { + let mut h = Harness::builder().build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + app.logic_frame(&ctx, &mut eframe::Frame::_new_kittest()); + // As `canvas_tests`' harness: the shortcuts wait for the app's fonts. + if ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + crate::shortcuts::handle(app, &ctx); + } + }, + app, + ); + h.run_steps(4); + for event in events { + h.event(event); + h.run_steps(1); + } + h.into_state() +} + +fn active_layer(app: &PhotocraftApp) -> Option { + app.session.active().and_then(|st| st.active_layer) +} + +fn history(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().history.entries() +} + +fn layers(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.layers.len() +} + +fn alerts(app: &PhotocraftApp) -> Vec<&str> { + app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str()).collect() +} + +#[test] +fn a_type_mask_click_on_text_edits_that_layer_as_the_type_tool_does() { + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + let mut states = Vec::new(); + for tool in [Tool::Type, Tool::HorizontalTypeMask, Tool::VerticalTypeMask] { + let (mut app, id, at) = txt(tool); + let (before, count) = (history(&app), layers(&app)); + click(&mut app, at.0, at.1, Modifiers::NONE); + let app = frames(app, Vec::new()); + let ed = app.ui.text_edit.clone().unwrap_or_else(|| panic!("{tool:?}: the edit outlives the frame")); + assert_eq!((ed.layer, ed.created, ed.mask), (id.0, false, false), "{tool:?}: the text layer itself, no mask"); + assert_eq!((ed.anchor, ed.caret), (1, 1), "{tool:?}: the caret where clicked"); + assert_eq!(active_layer(&app), Some(id), "{tool:?}: the layer becomes active"); + assert_eq!(app.ui.tool, Tool::Type, "{tool:?}: the edit is the Type tool's"); + // "Use Escape to Commit" is on by default. + let app = frames(app, vec![egui::Event::Text("Y".into()), escape.clone()]); + assert!(app.ui.text_edit.is_none(), "{tool:?}"); + assert_eq!(app.ui.tool, tool, "{tool:?}: the tool in hand is back"); + assert_eq!(current_text(&app, id).as_deref(), Some("TYXT"), "{tool:?}"); + let after = history(&app); + assert_eq!(after.len(), before.len() + 1, "{tool:?}: one history state: {after:?}"); + assert_eq!(layers(&app), count, "{tool:?}: no layer is added"); + assert!(selection(&app).is_none(), "{tool:?}: no selection"); + states.push(after.last().cloned()); + } + assert!(states[0].is_some()); + assert_eq!(states[1..], [states[0].clone(), states[0].clone()], "the masks add the Type tool's state"); +} + +#[test] +fn a_type_mask_click_on_vertical_text_edits_it_with_the_vertical_type_tool() { + for tool in MASKS { + let (mut app, id) = typed(Tool::VerticalType, tool); + let at = (60..140) + .flat_map(|x| (100..300).map(move |y| (f64::from(x), f64::from(y)))) + .find(|&(x, y)| hit_layer(&mut app, x, y) == Some(id)) + .expect("a point on the vertical glyphs"); + click(&mut app, at.0, at.1, Modifiers::NONE); + assert_eq!(app.ui.text_edit.as_ref().map(|ed| (ed.layer, ed.mask)), Some((id.0, false)), "{tool:?}"); + assert_eq!(app.ui.tool, Tool::VerticalType, "{tool:?}"); + commit(&mut app); + assert_eq!(app.ui.tool, tool, "{tool:?}: the mask tool is back"); + } +} + +#[test] +fn a_type_mask_click_on_fully_locked_text_alerts_and_changes_nothing() { + for tool in MASKS { + let (mut app, id, at) = txt(tool); + app.run("layer.select", json!({"layer": id.0, "mode": "replace"})).unwrap(); + app.run("layer.lockLayers", json!({"all": true})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let (before, count) = (history(&app), layers(&app)); + click(&mut app, at.0, at.1, Modifiers::NONE); + assert_eq!(alerts(&app), ["Could not use the type tool because the layer is locked."], "{tool:?}"); + assert!(app.ui.text_edit.is_none(), "{tool:?}: no edit and no mask"); + assert_eq!(active_layer(&app), Some(id), "{tool:?}: the layer becomes active, as with the Type tool"); + assert_eq!(history(&app), before, "{tool:?}: no history state"); + assert_eq!(layers(&app), count, "{tool:?}"); + assert_eq!(current_text(&app, id).as_deref(), Some("TXT"), "{tool:?}"); + assert!(selection(&app).is_none(), "{tool:?}"); + } +} + +#[test] +fn a_type_mask_click_on_partly_locked_text_still_starts_a_mask() { + for lock in [json!({"position": true}), json!({"pixels": true})] { + for tool in MASKS { + let (mut app, id, at) = txt(tool); + app.run("layer.select", json!({"layer": id.0, "mode": "replace"})).unwrap(); + app.run("layer.lockLayers", lock.clone()).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + click(&mut app, at.0, at.1, Modifiers::NONE); + let what = format!("{tool:?}, {lock}"); + assert!(app.ui.text_edit.as_ref().is_some_and(|ed| ed.mask && ed.created && ed.layer != id.0), "{what}: a new mask"); + assert!(alerts(&app).is_empty(), "{what}"); + assert_eq!(app.ui.tool, tool, "{what}"); + assert_eq!(current_text(&app, id).as_deref(), Some("TXT"), "{what}"); + } + } +} + +#[test] +fn a_type_mask_click_off_the_text_still_starts_a_mask() { + for tool in MASKS { + let (mut app, _, _) = txt(tool); + click(&mut app, OFF_TEXT.0, OFF_TEXT.1, Modifiers::NONE); + assert!(app.ui.text_edit.as_ref().is_some_and(|ed| ed.mask && ed.created), "{tool:?}: a new mask"); + assert_eq!(app.ui.tool, tool, "{tool:?}"); + } +} + +#[test] +fn a_shift_click_on_text_still_starts_new_text_over_it() { + for tool in [Tool::Type, Tool::HorizontalTypeMask, Tool::VerticalTypeMask] { + let (mut app, id, at) = txt(tool); + click(&mut app, at.0, at.1, Modifiers::SHIFT); + let ed = app.ui.text_edit.as_ref().unwrap_or_else(|| panic!("{tool:?}: new text starts")); + assert!(ed.created && ed.layer != id.0, "{tool:?}: new text, not an edit of the old"); + assert_eq!(ed.mask, tool.is_type_mask(), "{tool:?}"); + } +} diff --git a/crates/ui-egui/src/tools/type_tool/options_bar.rs b/crates/ui-egui/src/tools/type_tool/options_bar.rs index fc3fe358a8..56b54b5c27 100644 --- a/crates/ui-egui/src/tools/type_tool/options_bar.rs +++ b/crates/ui-egui/src/tools/type_tool/options_bar.rs @@ -107,12 +107,12 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { None => o.type_align.as_str(), }; // Vertical text shows Top / Center / Bottom for the same left / center / right values, after the - // targeted layer's orientation, or with no text targeted the Vertical Type tool's (#12059). The - // Type Mask tools keep the horizontal buttons (not measured). - let vertical = !app.ui.tool.is_type_mask() + // targeted layer's orientation, or with no text targeted the vertical tools' (#12059, #12088). + // The Horizontal Type Mask tool keeps the horizontal buttons (not measured). + let vertical = app.ui.tool != crate::state::Tool::HorizontalTypeMask && match super::defaults::target_text(app) { Some(t) => t.orientation == photocraft_doc::text::Orientation::Vertical, - None => app.ui.tool == crate::state::Tool::VerticalType, + None => app.ui.tool.is_vertical_type(), }; let buttons = if vertical { [ @@ -167,6 +167,14 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { app.ui.status = e; app.ui.status_error = true; } + // The bar's last button, as in Photoshop (#12054): Window › Character, which shows the + // Character | Paragraph group with Character in front, and hides it when clicked again. + if crate::icons::button(ui, "panels-top-left", 24.0, false, tl!("Toggle Character and Paragraph panels")).clicked() + && let Err(e) = crate::menus::invoke(app, &ui.ctx().clone(), "window.panel.character", json!({})) + { + app.ui.status = e; + app.ui.status_error = true; + } if app.ui.text_edit.is_some() { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.add_space(8.0); @@ -495,3 +503,7 @@ fn size_field(ui: &mut egui::Ui, display: &mut f32, unit: f32, label: &str) -> O #[cfg(test)] #[path = "size_presets_tests.rs"] mod size_presets_tests; + +#[cfg(test)] +#[path = "vertical_mask_align_buttons_tests.rs"] +mod vertical_mask_align_buttons_tests; diff --git a/crates/ui-egui/src/tools/type_tool/panels_toggle_tests.rs b/crates/ui-egui/src/tools/type_tool/panels_toggle_tests.rs new file mode 100644 index 0000000000..893a5a90ba --- /dev/null +++ b/crates/ui-egui/src/tools/type_tool/panels_toggle_tests.rs @@ -0,0 +1,149 @@ +//! #12054: the Type options bar ends with the reference application's button that shows and +//! hides the Character and Paragraph panels. It runs Window › Character, so the cases the issue +//! leaves unmeasured keep that command's behaviour. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::LayerId; +use serde_json::json; + +use crate::PhotocraftApp; + +const TOGGLE: &str = "Toggle Character and Paragraph panels"; + +fn bare_app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.tool = crate::state::Tool::Type; + app +} + +/// An app with one selected type layer, and the layer's id. +fn app_with_layer() -> (PhotocraftApp, LayerId) { + let mut app = bare_app(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let made = app.run("type.create", json!({"text": "Sample", "font": "Inter", "size": 18})).unwrap(); + let id = LayerId(made["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": id.0, "mode": "replace"})).unwrap(); + (app, id) +} + +fn editing(mut app: PhotocraftApp, id: LayerId) -> PhotocraftApp { + app.ui.text_edit = Some(crate::state::TextEdit { + layer: id.0, + document: None, + caret: 2, + anchor: 2, + session: "panels-toggle".into(), + created: false, + mask: false, + dragging: false, + resize: None, + preedit: None, + }); + app +} + +/// The options bar in a row, once the app's fonts are set up (the first pass has none). +fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1400.0, 200.0)).with_max_steps(16).build_ui_state( + |ui, app| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + ui.horizontal(|ui| super::options_bar::options_bar(app, ui)); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +fn click(h: &mut Harness<'static, PhotocraftApp>) { + h.get_by_role_and_label(Role::Button, TOGGLE).click(); + h.run(); +} + +/// Whether the Character | Paragraph group is shown, and its front tab (0 Character, 1 Paragraph). +fn group(h: &Harness<'static, PhotocraftApp>) -> (bool, usize) { + (h.state().ui.panels.character, h.state().ui.dock_tabs.character) +} + +/// Clicks the button twice: the group opens with Character in front, then closes. +fn opens_then_closes(app: PhotocraftApp) { + let mut h = harness(app); + assert!(!group(&h).0, "the group starts hidden"); + click(&mut h); + assert_eq!(group(&h), (true, 0)); + click(&mut h); + assert!(!group(&h).0, "the second click hides the group"); +} + +#[test] +fn the_button_follows_create_warped_text_with_the_reference_tooltip() { + let (app, _) = app_with_layer(); + let h = harness(app); + let warp = h.get_by_role_and_label(Role::Button, "Create warped text").rect(); + let toggle = h.get_by_role_and_label(Role::Button, TOGGLE); + let rect = toggle.rect(); + assert!(rect.left() >= warp.right(), "{rect:?} is not after {warp:?}"); + assert!((rect.center().y - warp.center().y).abs() < 1.0, "{rect:?} is not in the row of {warp:?}"); + // Nothing sits between the two. + let between = h.query_all_by_role(Role::Button).filter(|b| b.rect().left() >= warp.right() && b.rect().right() <= rect.left()).count(); + assert_eq!(between, 0); + assert_eq!(toggle.accesskit_node().description().map(|d| d.to_string()), Some(TOGGLE.to_owned())); +} + +#[test] +fn with_a_type_layer_it_opens_the_group_with_character_in_front_then_closes_it() { + opens_then_closes(app_with_layer().0); +} + +#[test] +fn without_a_document_it_opens_and_closes_the_group() { + opens_then_closes(bare_app()); +} + +#[test] +fn while_editing_text_it_opens_and_closes_the_group() { + let (app, id) = app_with_layer(); + opens_then_closes(editing(app, id)); +} + +/// While editing, Cancel and Commit stay at the bar's right end, after the toggle. +#[test] +fn while_editing_cancel_and_commit_follow_the_toggle() { + let (app, id) = app_with_layer(); + let h = harness(editing(app, id)); + let toggle = h.get_by_role_and_label(Role::Button, TOGGLE).rect(); + for label in ["Cancel any current edits (Esc)", "Commit any current edits (⌘↩)"] { + let r = h.query_all_by_role(Role::Button).find(|b| b.accesskit_node().label().is_some_and(|l| l.starts_with(&label[..12]))); + let r = r.unwrap_or_else(|| panic!("no {label}")).rect(); + assert!(r.left() >= toggle.right(), "{label} {r:?} is before the toggle {toggle:?}"); + } +} + +/// Not measured: with Paragraph in front, the button does what Window › Character does and +/// brings Character to the front of the open group. +#[test] +fn with_paragraph_in_front_it_brings_character_forward_like_window_character() { + let (mut app, _) = app_with_layer(); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "window.panel.paragraph", json!({})).unwrap(); + let mut h = harness(app); + assert_eq!(group(&h), (true, 1)); + click(&mut h); + assert_eq!(group(&h), (true, 0)); +} + +#[test] +fn the_toggle_leaves_the_document_alone() { + let (app, _) = app_with_layer(); + let steps = app.session.active().unwrap().history.entries().len(); + let mut h = harness(app); + click(&mut h); + click(&mut h); + assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps); + assert!(!h.state().ui.status_error, "{}", h.state().ui.status); +} diff --git a/crates/ui-egui/src/tools/type_tool/pointer.rs b/crates/ui-egui/src/tools/type_tool/pointer.rs index 4e092190a8..4c5b71cba5 100644 --- a/crates/ui-egui/src/tools/type_tool/pointer.rs +++ b/crates/ui-egui/src/tools/type_tool/pointer.rs @@ -152,12 +152,15 @@ pub fn pointer_down(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifie return true; // Photoshop: a click outside commits without starting new text } app.ui.type_insertion_style = None; - // The Type Mask tools always start new text: existing type layers are just pixels to them; - // so does a ⇧-click with the Type tool, as in Photoshop, to start new text over old. - if app.ui.tool.is_type_mask() || mods.shift { + // A ⇧-click starts new text over old, as in Photoshop. A Type Mask click on a text layer's + // glyphs edits it as the Type tool does (#12075), unless ⇧ is held or the layer is only partly + // locked: neither is measured, so those keep starting a new mask. + let hit = hit_layer(app, x, y); + let partly_locked = |id| app.session.active().map(|st| st.doc.effective_locks(id)).is_some_and(|l| l.any() && !l.all); + if mods.shift || (app.ui.tool.is_type_mask() && hit.is_some_and(partly_locked)) { return false; } - if let Some(id) = hit_layer(app, x, y) { + if let Some(id) = hit { let _ = app.session.select_layer(id); // Lock All (the layer's own or a group's) refuses the edit before it starts, as the engine // would refuse the first keystroke; the reference application says so in an alert (#12040). @@ -183,7 +186,14 @@ pub fn pointer_down(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifie resize: None, preedit: None, }); - app.ui.text_edit_return_tool = None; + // The frame commits an edit that is no mask while a Type Mask tool is in hand: edit with + // the Type tool, as Move's double-click does, and give the mask tool back at the end. + app.ui.text_edit_return_tool = app.ui.tool.is_type_mask().then_some(app.ui.tool); + if app.ui.text_edit_return_tool.is_some() { + let vertical = + app.session.active().and_then(|st| text_layer(&st.doc, id)).is_some_and(|t| t.orientation == photocraft_doc::text::Orientation::Vertical); + app.ui.tool = if vertical { crate::state::Tool::VerticalType } else { crate::state::Tool::Type }; + } return true; } false @@ -481,3 +491,7 @@ pub fn multi_click(app: &mut PhotocraftApp, egui_count: u32, x: f64, y: f64) { #[cfg(test)] #[path = "mask_placeholder_tests.rs"] mod mask_placeholder_tests; + +#[cfg(test)] +#[path = "mask_click_text_layer_tests.rs"] +mod mask_click_text_layer_tests; diff --git a/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs b/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs index 9d3145e9ef..25b9993943 100644 --- a/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/vertical_align_buttons_tests.rs @@ -1,7 +1,8 @@ //! #12059: for vertical text the options bar's alignment buttons are Top / Center / Bottom, after //! the targeted text layer's orientation, or with no text targeted the Vertical Type tool's. They -//! still set left / center / right, and the lit one follows the targeted paragraph. The Type Mask -//! tools keep the horizontal buttons (not measured). +//! still set left / center / right, and the lit one follows the targeted paragraph. The Horizontal +//! Type Mask tool keeps the horizontal buttons (not measured); the Vertical Type Mask tool's are in +//! `vertical_mask_align_buttons_tests` (#12088). use egui::accesskit::{Role, Toggled}; use egui_kittest::Harness; @@ -12,10 +13,10 @@ use serde_json::json; use crate::PhotocraftApp; use crate::state::Tool; -const HORIZONTAL: [&str; 3] = ["Left align text", "Center text", "Right align text"]; -const VERTICAL: [&str; 3] = ["Top align text", "Center text", "Bottom align text"]; +pub(super) const HORIZONTAL: [&str; 3] = ["Left align text", "Center text", "Right align text"]; +pub(super) const VERTICAL: [&str; 3] = ["Top align text", "Center text", "Bottom align text"]; -fn new_app(tool: Tool) -> PhotocraftApp { +pub(super) fn new_app(tool: Tool) -> PhotocraftApp { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 800, "height": 400})).unwrap(); app.sync_views(); @@ -29,7 +30,7 @@ fn text_layer(app: &mut PhotocraftApp, orientation: &str) -> LayerId { LayerId(made["layer"].as_u64().unwrap()) } -fn bar(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { +pub(super) fn bar(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { let mut h = Harness::builder().with_size(egui::vec2(1200.0, 60.0)).build_ui_state( |ui, app: &mut PhotocraftApp| { ui.horizontal(|ui| super::options_bar(app, ui)); @@ -42,7 +43,7 @@ fn bar(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { } /// Which of the two button sets the bar shows; panics on a mix or neither. -fn shown(h: &Harness<'static, PhotocraftApp>) -> [&'static str; 3] { +pub(super) fn shown(h: &Harness<'static, PhotocraftApp>) -> [&'static str; 3] { let has = |label: &str| h.query_by_role_and_label(Role::Button, label).is_some(); match (has("Top align text") && has("Bottom align text"), has("Left align text") && has("Right align text")) { (true, false) => VERTICAL, @@ -52,11 +53,11 @@ fn shown(h: &Harness<'static, PhotocraftApp>) -> [&'static str; 3] { } } -fn lit(h: &Harness<'static, PhotocraftApp>, label: &str) -> bool { +pub(super) fn lit(h: &Harness<'static, PhotocraftApp>, label: &str) -> bool { h.get_by_role_and_label(Role::Button, label).accesskit_node().toggled() == Some(Toggled::True) } -fn align_of(app: &PhotocraftApp, id: LayerId) -> TextAlign { +pub(super) fn align_of(app: &PhotocraftApp, id: LayerId) -> TextAlign { match &app.session.active().unwrap().doc.layer(id).unwrap().content { LayerContent::Text(t) => t.paragraphs[0].style.align, other => panic!("{}", other.kind_name()), @@ -113,14 +114,12 @@ fn the_vertical_buttons_set_left_center_and_right_and_follow_the_paragraph() { } #[test] -fn the_type_mask_tools_keep_the_horizontal_buttons() { - for tool in [Tool::VerticalTypeMask, Tool::HorizontalTypeMask] { - assert_eq!(shown(&bar(new_app(tool))), HORIZONTAL, "{tool:?}, idle"); - let mut app = new_app(tool); - super::pointer_up(&mut app, [400.0, 100.0], [400.0, 100.0]); - assert!(app.ui.text_edit.as_ref().is_some_and(|ed| ed.mask), "{tool:?}: typing a mask"); - assert_eq!(shown(&bar(app)), HORIZONTAL, "{tool:?}, editing"); - } +fn the_horizontal_type_mask_tool_keeps_the_horizontal_buttons() { + assert_eq!(shown(&bar(new_app(Tool::HorizontalTypeMask))), HORIZONTAL, "idle"); + let mut app = new_app(Tool::HorizontalTypeMask); + super::pointer_up(&mut app, [400.0, 100.0], [400.0, 100.0]); + assert!(app.ui.text_edit.as_ref().is_some_and(|ed| ed.mask), "typing a mask"); + assert_eq!(shown(&bar(app)), HORIZONTAL, "editing"); } /// Clicking Toggle text orientation switches the buttons in the same frame (the toggle is drawn diff --git a/crates/ui-egui/src/tools/type_tool/vertical_mask_align_buttons_tests.rs b/crates/ui-egui/src/tools/type_tool/vertical_mask_align_buttons_tests.rs new file mode 100644 index 0000000000..d92161045b --- /dev/null +++ b/crates/ui-egui/src/tools/type_tool/vertical_mask_align_buttons_tests.rs @@ -0,0 +1,73 @@ +//! #12088: with the Vertical Type Mask tool the options bar's alignment buttons are Top / Center / +//! Bottom, idle and while editing vertical mask text, and Left / Center / Right once the mask text +//! is toggled horizontal. They still set left / center / right. + +use egui::accesskit::Role; +use egui_kittest::kittest::Queryable; +use photocraft_doc::{LayerId, text::TextAlign}; + +use super::super::pointer_up; +use super::super::vertical_align_buttons_tests::{HORIZONTAL, VERTICAL, align_of, bar, lit, new_app, shown}; +use crate::PhotocraftApp; +use crate::state::Tool; + +/// The Vertical Type Mask tool typing a new mask; returns its hidden working layer. +fn typing_a_mask(app: &mut PhotocraftApp) -> LayerId { + pointer_up(app, [400.0, 100.0], [400.0, 100.0]); + let ed = app.ui.text_edit.as_ref().filter(|ed| ed.mask).expect("typing a mask"); + LayerId(ed.layer) +} + +#[test] +fn idle_the_bar_shows_the_vertical_buttons_with_top_lit() { + let h = bar(new_app(Tool::VerticalTypeMask)); + assert_eq!(shown(&h), VERTICAL); + assert!(lit(&h, "Top align text"), "the default, left, lights Top"); +} + +#[test] +fn editing_vertical_mask_text_shows_the_vertical_buttons() { + let mut app = new_app(Tool::VerticalTypeMask); + typing_a_mask(&mut app); + assert_eq!(shown(&bar(app)), VERTICAL); +} + +#[test] +fn toggling_the_mask_text_horizontal_shows_left_center_and_right() { + let mut app = new_app(Tool::VerticalTypeMask); + typing_a_mask(&mut app); + let mut h = bar(app); + assert_eq!(shown(&h), VERTICAL, "before the toggle"); + h.get_by_role_and_label(Role::Button, "Toggle text orientation").click(); + h.run_steps(2); + assert!(h.state().ui.text_edit.is_some(), "still editing"); + assert_eq!(shown(&h), HORIZONTAL); +} + +#[test] +fn the_vertical_buttons_set_left_center_and_right_on_the_mask_text_and_the_tool() { + for (label, align, value) in + [("Bottom align text", TextAlign::Right, "right"), ("Center text", TextAlign::Center, "center"), ("Top align text", TextAlign::Left, "left")] + { + let mut app = new_app(Tool::VerticalTypeMask); + app.ui.tool_options.type_align = "center".into(); + let id = typing_a_mask(&mut app); + let mut h = bar(app); + h.get_by_role_and_label(Role::Button, label).click(); + h.run_steps(2); + assert_eq!(align_of(h.state(), id), align, "{label}: the mask text"); + assert_eq!(h.state().ui.tool_options.type_align, value, "{label}: the tool default"); + for other in VERTICAL { + assert_eq!(lit(&h, other), other == label, "{label} clicked: {other}"); + } + } +} + +#[test] +fn idle_the_vertical_buttons_set_the_tool_default() { + let mut h = bar(new_app(Tool::VerticalTypeMask)); + h.get_by_role_and_label(Role::Button, "Bottom align text").click(); + h.run_steps(2); + assert_eq!(h.state().ui.tool_options.type_align, "right"); + assert!(lit(&h, "Bottom align text")); +} diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index 54fe6527ce..6dbfb9fa81 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -24,6 +24,7 @@ mod overlay; mod path_ops; mod paths_panel; mod pen; +mod pen_resume; mod shapes; pub(crate) use curvature::curvature_anchor_at; @@ -56,7 +57,7 @@ pub use paths_panel::{PathEntry, PathRow, path_rows, paths_footer, paths_panel}; pub(crate) use pen::over_first_anchor; #[cfg(test)] use pen::pen_to_json; -pub(crate) use pen::{PATH_OPS, pen_path, pen_replace}; +pub(crate) use pen::{PATH_OPS, path_op_field, pen_path, pen_replace}; pub use pen::{ cancel_stale, closes_path_at, continues_path_at, freeform_finish, pen_break_handle, pen_commit, pen_down, pen_end, pen_enter, pen_grab_handle, pen_move, pen_undo_last_point, pen_up, @@ -113,7 +114,7 @@ fn copy_arrow_to_tool_defaults(app: &mut PhotocraftApp, id: photocraft_doc::Laye *end, bounded(*width, 1.0, 4096.0), bounded(*length, 1.0, 4096.0), - bounded(*concavity, 0.0, 100.0), + bounded(*concavity, -50.0, 50.0), bounded(*weight, 1.0, 10000.0), )) } @@ -222,6 +223,14 @@ mod pen_rubber_band_tests; #[cfg(test)] mod paint_tests; +#[cfg(test)] +mod triangle_box_geometry_tests; +#[cfg(test)] +mod triangle_properties_fields_tests; + +#[cfg(test)] +mod pen_resume_tests; + #[cfg(test)] mod add_anchor_options_bar_tests; @@ -231,7 +240,28 @@ mod delete_anchor_options_bar_tests; #[cfg(test)] mod pen_enter_deselects_tests; +#[cfg(test)] +mod line_shift_snap_tests; + +#[cfg(test)] +mod ellipse_shift_circle_tests; + +#[cfg(test)] +mod pen_mode_menu_tests; + +#[cfg(test)] +mod ellipse_path_menus_tests; + +#[cfg(test)] +mod triangle_align_edges_tests; + +#[cfg(test)] +mod triangle_shift_equilateral_tests; + pub(crate) use pen::freeform_locked_shape; +#[cfg(test)] +use pen_resume::pen_finish_on_redo; +pub(crate) use pen_resume::{FinishedPen, box_steps, pen_history_enabled, pen_history_step}; /// Where a Pen draft goes, captured at its first anchor. #[derive(Clone, Debug)] diff --git a/crates/ui-egui/src/tools/vector_ui/ellipse_path_menus_tests.rs b/crates/ui-egui/src/tools/vector_ui/ellipse_path_menus_tests.rs new file mode 100644 index 0000000000..11b3d5c49a --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/ellipse_path_menus_tests.rs @@ -0,0 +1,198 @@ +//! #13235: the shape tools' options bar has Path operations, Path alignment and Path arrangement. +//! The operation is the shape tools' own setting: with one other than New Layer a drag becomes a +//! component of the active shape layer; Reset Tool puts it back to New Layer. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::vector::PathOp; +use photocraft_doc::{LayerContent, ShapeLayer}; +use serde_json::json; + +use super::pen::{PATH_ALIGN_ENTRIES, PATH_ARRANGE_ENTRIES, PATH_DISTRIBUTE_ENTRIES, PATH_SPACING_ENTRIES, shape_path_op}; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::{Tool, ToolOptions}; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::EllipseShape; + app +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + let mods = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods); +} + +fn layer_count(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.layer_count() +} + +fn active_shape(app: &PhotocraftApp) -> ShapeLayer { + let st = app.session.active().unwrap(); + match &st.doc.layer(st.active_layer.unwrap()).unwrap().content { + LayerContent::Shape(s) => s.clone(), + _ => panic!("the active layer is not a shape layer"), + } +} + +#[test] +fn defaults_are_new_layer_in_shape_mode_and_exclude_in_path_mode() { + let mut o = ToolOptions::default(); + assert_eq!(o.shape_path_op, "newLayer"); + assert_eq!(shape_path_op(&o), None); + o.shape_mode = "path".into(); + assert_eq!(shape_path_op(&o), Some("exclude")); +} + +#[test] +fn an_operation_adds_the_next_drag_to_the_active_shape_layer() { + for (op, want) in [("combine", PathOp::Combine), ("subtract", PathOp::Subtract), ("intersect", PathOp::Intersect), ("exclude", PathOp::Exclude)] { + let mut app = app(); + drag(&mut app, [50.0, 50.0], [200.0, 200.0]); + let layers = layer_count(&app); + app.ui.tool_options.shape_path_op = op.into(); + drag(&mut app, [100.0, 100.0], [250.0, 250.0]); + assert_eq!(layer_count(&app), layers, "{op}: no new layer"); + let shape = active_shape(&app); + assert_eq!(shape.path.subpaths.len(), 2, "{op}: a second component"); + assert_eq!(shape.path.subpaths[1].op, want, "{op}"); + } +} + +#[test] +fn new_layer_makes_a_new_shape_layer() { + let mut app = app(); + drag(&mut app, [50.0, 50.0], [200.0, 200.0]); + let layers = layer_count(&app); + drag(&mut app, [100.0, 100.0], [250.0, 250.0]); + assert_eq!(layer_count(&app), layers + 1); +} + +#[test] +fn an_operation_with_a_pixel_layer_active_still_makes_a_shape_layer() { + let mut app = app(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool_options.shape_path_op = "combine".into(); + let layers = layer_count(&app); + drag(&mut app, [50.0, 50.0], [200.0, 200.0]); + assert_eq!(layer_count(&app), layers + 1); + assert!(matches!(app.session.active().unwrap().doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap().content, LayerContent::Shape(_))); +} + +#[test] +fn set_op_writes_the_active_tools_own_setting() { + let mut app = app(); + crate::path_components::set_op(&mut app, "subtract").unwrap(); + assert_eq!(app.ui.tool_options.shape_path_op, "subtract"); + assert_eq!(app.ui.tool_options.pen_path_op, "newLayer"); + app.ui.tool = Tool::Pen; + crate::path_components::set_op(&mut app, "intersect").unwrap(); + assert_eq!(app.ui.tool_options.pen_path_op, "intersect"); + assert_eq!(app.ui.tool_options.shape_path_op, "subtract"); +} + +#[test] +fn reset_tool_restores_new_layer() { + let mut app = app(); + app.ui.tool_options.shape_path_op = "exclude".into(); + crate::menus::invoke(&mut app, &egui::Context::default(), crate::tool_reset::RESET, json!({})).unwrap(); + assert_eq!(app.ui.tool_options.shape_path_op, "newLayer"); +} + +fn labels(e: &[(&'static str, &'static str)]) -> Vec<&'static str> { + e.iter().map(|(l, _)| *l).collect() +} + +#[test] +fn entries_follow_the_reference_order() { + assert_eq!( + labels(&PATH_ALIGN_ENTRIES), + ["Align Left Edges", "Align Horizontal Centers", "Align Right Edges", "Align Top Edges", "Align Vertical Centers", "Align Bottom Edges"] + ); + assert_eq!( + labels(&PATH_DISTRIBUTE_ENTRIES), + [ + "Distribute Left Edges", + "Distribute Horizontal Centers", + "Distribute Right Edges", + "Distribute Top Edges", + "Distribute Vertical Centers", + "Distribute Bottom Edges" + ] + ); + assert_eq!(labels(&PATH_SPACING_ENTRIES), ["Distribute Horizontally", "Distribute Vertically"]); + assert_eq!(PATH_ARRANGE_ENTRIES, ["Bring Shape To Front", "Bring Shape Forward", "Send Shape Backward", "Send Shape To Back"]); +} + +#[test] +fn options_bar_shows_the_three_buttons_and_greys_the_entries_without_a_shape() { + let mut h = Harness::builder().with_size(vec2(1600.0, 500.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + ui.horizontal(|ui| super::options_bar(app, ui, Tool::EllipseShape)); + } + }, + app(), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(4); + let x = |h: &Harness<'_, PhotocraftApp>, l: &str| h.get_by_label(l).rect().min.x; + let order = [x(&h, "Path operations"), x(&h, "Path alignment"), x(&h, "Path arrangement")]; + assert!(order.is_sorted_by(|a, b| a < b), "left to right: {order:?}"); + h.get_by_label("Path operations").click(); + h.run_steps(3); + assert!(h.get_by_label("Merge Shape Components").accesskit_node().is_disabled()); + h.key_press(egui::Key::Escape); + h.run_steps(2); + h.get_by_label("Path alignment").click(); + h.run_steps(3); + for (label, _) in PATH_ALIGN_ENTRIES { + assert!(h.get_by_label(label).accesskit_node().is_disabled(), "{label}"); + } +} + +/// #13442 review: the Custom Shape tool also adds to the active shape layer, as one component +/// whose hole stays joined to it. +#[test] +fn a_custom_shape_with_an_operation_joins_the_active_shape_layer() { + let mut app = app(); + drag(&mut app, [50.0, 50.0], [200.0, 200.0]); + let layers = layer_count(&app); + app.ui.tool = Tool::CustomShape; + app.ui.presets_ui.custom_shape = "Ring".into(); + app.ui.tool_options.shape_path_op = "subtract".into(); + drag(&mut app, [100.0, 100.0], [250.0, 250.0]); + assert_eq!(layer_count(&app), layers, "no new layer"); + let ops: Vec = active_shape(&app).path.subpaths.iter().map(|s| s.op).collect(); + assert_eq!(ops, [PathOp::Combine, PathOp::Subtract, PathOp::Join], "the ellipse, the ring and its hole"); +} + +/// #13442 review: a custom shape that can't be made one component (its parts exclude each other) +/// is not added with an operation, which would change its parts' operations: the layer stays as +/// it was and the status says why. +#[test] +fn a_custom_shape_that_is_not_one_component_is_refused() { + use photocraft_doc::vector::{Path, Subpath}; + let mut app = app(); + drag(&mut app, [50.0, 50.0], [200.0, 200.0]); + let before = active_shape(&app).path; + let xor = Path::new(vec![ + Subpath::polygon(&[(0.0, 0.0), (60.0, 0.0), (60.0, 60.0), (0.0, 60.0)]), + Subpath::polygon(&[(40.0, 40.0), (100.0, 40.0), (100.0, 100.0), (40.0, 100.0)]).with_op(PathOp::Exclude), + ]); + let r = app.run("shape.presets.new", json!({"name": "Xor", "path": photocraft_engine::vector_cmds::path_json(&xor)})).unwrap(); + app.ui.tool = Tool::CustomShape; + app.ui.presets_ui.custom_shape = r["name"].as_str().unwrap().into(); + app.ui.tool_options.shape_path_op = "combine".into(); + let layers = layer_count(&app); + drag(&mut app, [100.0, 100.0], [250.0, 250.0]); + assert_eq!(layer_count(&app), layers); + assert_eq!(active_shape(&app).path, before, "the layer is unchanged"); + assert!(app.ui.status_error, "{}", app.ui.status); +} diff --git a/crates/ui-egui/src/tools/vector_ui/ellipse_shift_circle_tests.rs b/crates/ui-egui/src/tools/vector_ui/ellipse_shift_circle_tests.rs new file mode 100644 index 0000000000..0d134ece1a --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/ellipse_shift_circle_tests.rs @@ -0,0 +1,76 @@ +//! #13222: ⇧ while dragging with the Ellipse tool makes a circle from the shorter side of the +//! drag, as in the reference application, not the longer one; ⇧⌥ centres that circle on the +//! press. The drag preview (`shape_bounds`) shows the same box as the layer the drag makes. + +use egui::Modifiers; +use photocraft_doc::{LayerContent, LiveShape}; +use serde_json::json; + +use super::shape_bounds; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::EllipseShape; + app +} + +/// A drag pressed without modifiers, with `mods` pressed after the start (so the press picks no +/// path operation or eyedropper). +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: (from[0] + to[0]) / 2.0, y: (from[1] + to[1]) / 2.0, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods); +} + +/// The active layer's live ellipse `[x, y, w, h]`. +fn ellipse_rect(app: &PhotocraftApp) -> [f64; 4] { + let st = app.session.active().unwrap(); + match &st.doc.layer(st.active_layer.unwrap()).unwrap().content { + LayerContent::Shape(s) => match &s.live { + Some(LiveShape::Ellipse { rect }) => *rect, + other => panic!("a live ellipse, got {other:?}"), + }, + _ => panic!("a shape layer"), + } +} + +fn preview(app: &PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) -> [f64; 4] { + shape_bounds(&app.ui.tool_options, Tool::EllipseShape, from, to, mods).expect("a box") +} + +#[test] +fn shift_makes_a_circle_from_the_shorter_side() { + let mut app = app(); + drag(&mut app, [400.0, 300.0], [600.0, 400.0], Modifiers::SHIFT); + assert_eq!(ellipse_rect(&app), [400.0, 300.0, 100.0, 100.0]); + assert_eq!(preview(&app, [400.0, 300.0], [600.0, 400.0], Modifiers::SHIFT), [400.0, 300.0, 500.0, 400.0]); +} + +#[test] +fn shift_uses_the_shorter_side_when_the_drag_is_taller_than_wide() { + let mut app = app(); + drag(&mut app, [400.0, 300.0], [450.0, 500.0], Modifiers::SHIFT); + assert_eq!(ellipse_rect(&app), [400.0, 300.0, 50.0, 50.0]); + assert_eq!(preview(&app, [400.0, 300.0], [450.0, 500.0], Modifiers::SHIFT), [400.0, 300.0, 450.0, 350.0]); +} + +#[test] +fn shift_alt_centres_the_shorter_side_circle_on_the_press() { + let mut app = app(); + let mods = Modifiers::SHIFT | Modifiers::ALT; + drag(&mut app, [400.0, 300.0], [600.0, 400.0], mods); + assert_eq!(ellipse_rect(&app), [300.0, 200.0, 200.0, 200.0]); + assert_eq!(preview(&app, [400.0, 300.0], [600.0, 400.0], mods), [300.0, 200.0, 500.0, 400.0]); +} + +#[test] +fn shift_keeps_the_drag_direction_up_and_left() { + let app = app(); + assert_eq!(preview(&app, [400.0, 300.0], [200.0, 200.0], Modifiers::SHIFT), [300.0, 200.0, 400.0, 300.0]); +} diff --git a/crates/ui-egui/src/tools/vector_ui/freeform_close_tolerance_tests.rs b/crates/ui-egui/src/tools/vector_ui/freeform_close_tolerance_tests.rs new file mode 100644 index 0000000000..dd47cb0fac --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/freeform_close_tolerance_tests.rs @@ -0,0 +1,95 @@ +//! #12830: a Freeform Pen stroke closes only when it is released within 3 screen px of its start +//! on each axis, as in Photoshop. Other zoom levels keep the screen-based scaling. + +use egui::Modifiers; +use photocraft_doc::vector::Subpath; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// The measured document: 800 × 600 px with the Freeform Pen in Path mode at `zoom`. +fn app(zoom: f32) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = zoom; + app.ui.tool = Tool::FreeformPen; + app.ui.tool_options.vector_mode = "path".into(); + app +} + +/// The measured stroke: a circle around (600, 300) of radius 100 from (700, 300) in 60 moves, +/// released `off` document px from its start. Returns the stroke's subpath. +fn circle(app: &mut PhotocraftApp, off: [f64; 2]) -> Subpath { + let mods = Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: 700.0, y: 300.0, pressure: 1.0 }, mods); + for i in 1..60 { + let a = std::f64::consts::TAU * f64::from(i) / 60.0; + tool_event(app, ToolEvent::Move { x: 600.0 + 100.0 * a.cos(), y: 300.0 + 100.0 * a.sin(), pressure: 1.0 }, mods); + } + let [x, y] = [700.0 + off[0], 300.0 + off[1]]; + tool_event(app, ToolEvent::Move { x, y, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x, y }, mods); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo_label(), Some("Freeform Pen"), "one History step"); + st.doc.work_path.as_ref().unwrap().subpaths.last().unwrap().clone() +} + +/// The measured cases at 100 %: within ±3 px on each axis (a square) closes, 4 px off does not. +#[test] +fn at_100_percent_a_release_within_3_px_on_each_axis_closes_the_circle() { + for off in [[0.0, 0.0], [3.0, 0.0], [0.0, -3.0], [3.0, 3.0], [-3.0, 3.0]] { + let mut app = app(1.0); + let n = app.session.active().unwrap().history.past_len(); + assert!(circle(&mut app, off).closed, "released {off:?} off the start closes"); + assert_eq!(app.session.active().unwrap().history.past_len(), n + 1); + } + for off in [[4.0, 0.0], [0.0, 4.0], [5.0, 0.0], [4.0, 4.0], [5.0, 3.0], [-4.0, 0.0]] { + assert!(!circle(&mut app(1.0), off).closed, "released {off:?} off the start stays open"); + } +} + +/// Not measured, kept as today: the box scales with zoom like the old reach, 3 screen px. +#[test] +fn at_other_zooms_the_3_px_box_is_in_screen_pixels() { + for (zoom, inside, outside) in [(2.0, [1.5, 1.5], [2.0, 0.0]), (0.5, [6.0, 6.0], [0.0, 8.0])] { + assert!(circle(&mut app(zoom), inside).closed, "{inside:?} off at {zoom}× closes"); + assert!(!circle(&mut app(zoom), outside).closed, "{outside:?} off at {zoom}× stays open"); + } +} + +/// Not measured: a trace with ⌥-clicked straight segments closes like a freehand one. It ends in +/// a freehand run released near the start: an ⌥-click there would be the outline's own grab. +#[test] +fn a_trace_with_straight_segments_closes_within_the_same_box() { + for (off, closed) in [([3.0, 3.0], true), ([4.0, 0.0], false)] { + let mut app = app(1.0); + for [x, y] in [[100.0, 100.0], [300.0, 100.0], [300.0, 300.0]] { + tool_event(&mut app, ToolEvent::Down { x, y, pressure: 1.0 }, Modifiers::ALT); + tool_event(&mut app, ToolEvent::Up { x, y }, Modifiers::ALT); + } + tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 300.0, pressure: 1.0 }, Modifiers::ALT); + let end = [100.0 + off[0], 100.0 + off[1]]; + for i in 1..=10 { + let y = 300.0 + (end[1] - 300.0) * f64::from(i) / 10.0; + tool_event(&mut app, ToolEvent::Move { x: 100.0 + off[0] * f64::from(i) / 10.0, y, pressure: 1.0 }, Modifiers::ALT); + } + tool_event(&mut app, ToolEvent::Up { x: end[0], y: end[1] }, Modifiers::NONE); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo_label(), Some("Freeform Pen"), "one History step"); + let sub = &st.doc.work_path.as_ref().unwrap().subpaths[0]; + assert_eq!(sub.knots[0].out_ctrl, sub.knots[0].anchor, "the first segment is straight"); + assert_eq!(sub.closed, closed, "released {off:?} off the start"); + } +} + +/// The release decides: a short last run that fitting shortens past the box still closes. +#[test] +fn a_release_in_the_box_closes_even_when_fitting_moves_the_last_anchor() { + let trace = [[100.0, 100.0], [200.0, 100.0], [200.0, 200.0], [103.01, 100.0], [103.0, 100.0]]; + let (pen, closed) = super::fit_with_straight_segments(&trace, &[1, 2, 3], 2.0, true); + assert!(closed); + assert_eq!(pen.knots.len(), 3, "the last anchor became the first one"); +} diff --git a/crates/ui-egui/src/tools/vector_ui/line_arrow_concavity_field_tests.rs b/crates/ui-egui/src/tools/vector_ui/line_arrow_concavity_field_tests.rs new file mode 100644 index 0000000000..716ec56173 --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/line_arrow_concavity_field_tests.rs @@ -0,0 +1,121 @@ +//! #13258: arrowhead Concavity takes whole numbers from -50 % to 50 % in the Properties panel and +//! the Line tool's gear menu; a value typed past the range becomes the closest end and, once the +//! field is left, the reference's "Closest value inserted" alert with OK says so. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::{LayerContent, LayerId, LiveShape}; +use serde_json::json; + +use super::{CONCAVITY_RANGE_ALERT, shape_properties}; +use crate::PhotocraftApp; +use crate::state::{DialogKind, Tool}; + +/// An 800 x 600 document with a weight 4 End arrow (5 x 10 px head) from 400,300 to 600,300. +fn app_with_arrow() -> (PhotocraftApp, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + let made = app + .run("shape.create", json!({"kind": "line", "from": [400, 300], "to": [600, 300], "weight": 4, "arrowEnd": true, "arrowWidth": 5, "arrowLength": 10})) + .unwrap(); + let id = LayerId(made["layer"].as_u64().unwrap()); + (app, id) +} + +/// True once `setup_context` installed the app's fonts (the first frame runs before it). +fn fonts_ready(ui: &egui::Ui) -> bool { + ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) +} + +fn properties() -> (Harness<'static, PhotocraftApp>, LayerId) { + let (app, id) = app_with_arrow(); + let mut h = Harness::builder().with_size(vec2(400.0, 900.0)).build_ui_state( + move |ui, app| { + if fonts_ready(ui) { + shape_properties(app, ui, id); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + (h, id) +} + +/// The options bar with the Line tool active, its arrowhead gear menu open. +fn gear() -> Harness<'static, PhotocraftApp> { + let (mut app, _) = app_with_arrow(); + app.ui.tool = Tool::Line; + let mut h = Harness::builder().with_size(vec2(1800.0, 400.0)).build_ui_state( + |ui, app| { + if fonts_ready(ui) { + crate::panels::options_bar(app, ui); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h.query_by_label("Arrowhead options").expect("the arrowhead gear").click(); + h.run_steps(3); + h +} + +/// Types `text` into the Concavity field, then Tabs out of it. +fn type_concavity(h: &mut Harness<'static, PhotocraftApp>, text: &str) { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Concavity")).expect("the Concavity field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn alerts(h: &Harness<'static, PhotocraftApp>) -> Vec { + h.state().ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(str::to_owned)).collect() +} + +fn concavity(h: &Harness<'static, PhotocraftApp>, id: LayerId) -> f64 { + match h.state().session.active().and_then(|st| st.doc.layer(id)).map(|l| &l.content) { + Some(LayerContent::Shape(sh)) => match sh.live { + Some(LiveShape::ArrowLine { concavity, .. }) => concavity, + _ => panic!("expected a live arrow"), + }, + _ => panic!("expected a shape layer"), + } +} + +#[test] +fn properties_concavity_in_range_is_applied_without_an_alert() { + for (typed, want) in [("-50", -50.0), ("-12", -12.0), ("25", 25.0), ("50", 50.0)] { + let (mut h, id) = properties(); + type_concavity(&mut h, typed); + assert_eq!(concavity(&h, id), want, "{typed}"); + assert!(alerts(&h).is_empty(), "{typed} is in range"); + } +} + +#[test] +fn properties_concavity_past_the_range_takes_the_closest_value_and_alerts() { + for (typed, want) in [("-60", -50.0), ("60", 50.0)] { + let (mut h, id) = properties(); + type_concavity(&mut h, typed); + assert_eq!(concavity(&h, id), want, "{typed}"); + assert_eq!(alerts(&h), vec![CONCAVITY_RANGE_ALERT.to_string()], "{typed}: one alert"); + } +} + +#[test] +fn gear_concavity_past_the_range_takes_the_closest_value_and_alerts() { + for (typed, want) in [("-60", -50.0), ("60", 50.0), ("-20", -20.0)] { + let mut h = gear(); + assert!(h.query_all_by_role(Role::SpinButton).any(|n| n.accesskit_node().label().as_deref() == Some("Concavity")), "the gear menu is open"); + type_concavity(&mut h, typed); + assert_eq!(h.state().ui.tool_options.arrow_concavity, want, "{typed}"); + let expected: Vec = if typed == "-20" { vec![] } else { vec![CONCAVITY_RANGE_ALERT.to_string()] }; + assert_eq!(alerts(&h), expected, "{typed}"); + } +} diff --git a/crates/ui-egui/src/tools/vector_ui/line_shift_snap_tests.rs b/crates/ui-egui/src/tools/vector_ui/line_shift_snap_tests.rs new file mode 100644 index 0000000000..867df50cef --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/line_shift_snap_tests.rs @@ -0,0 +1,131 @@ +//! #13243: ⇧ while dragging with the Line tool snaps to multiples of 45° as Photoshop does: a +//! diagonal line ends at the shorter of the drag's two distances on both axes, a horizontal or +//! vertical one keeps the full distance along its axis (and its 0.5 px centring on the pixel). +//! The drag preview shows the same line as the layer, and ⇧ pressed after the start gives the +//! same line as ⇧ held from the press. + +use egui::Modifiers; +use photocraft_doc::{LayerContent, LiveShape}; +use serde_json::json; + +use super::shape_preview; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// The five measured drags from 400,300 and the line Photoshop draws for each: a flat line's +/// ends move 0.5 px across it, onto the middle of the pixel. +const CASES: [([f64; 2], [[f64; 2]; 2]); 5] = [ + ([600.0, 400.0], [[400.0, 299.5], [600.0, 299.5]]), + ([600.0, 480.0], [[400.0, 300.0], [580.0, 480.0]]), + ([600.0, 520.0], [[400.0, 300.0], [600.0, 500.0]]), + ([300.0, 420.0], [[400.0, 300.0], [300.0, 400.0]]), + ([450.0, 500.0], [[399.5, 300.0], [399.5, 500.0]]), +]; + +const START: [f64; 2] = [400.0, 300.0]; + +/// A new 800 × 600 document with the Line tool picked. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Line; + app +} + +/// A drag from `from` to `to`, with `at_press` held at the press and `later` from the first move. +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], at_press: Modifiers, later: Modifiers) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, at_press); + tool_event(app, ToolEvent::Move { x: (from[0] + to[0]) / 2.0, y: (from[1] + to[1]) / 2.0, pressure: 1.0 }, later); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, later); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, later); +} + +/// The active layer's shape: its live line's ends, and its outline. +fn line(app: &PhotocraftApp) -> ([f64; 2], [f64; 2], photocraft_doc::vector::Path) { + let st = app.session.active().unwrap(); + match &st.doc.layer(st.active_layer.unwrap()).unwrap().content { + LayerContent::Shape(s) => match &s.live { + Some(LiveShape::Line { from, to, .. } | LiveShape::ArrowLine { from, to, .. }) => (*from, *to, s.path.clone()), + other => panic!("a live line, got {other:?}"), + }, + _ => panic!("a shape layer"), + } +} + +/// The measured ⇧-drags end where Photoshop ends them. +#[test] +fn shift_drags_end_where_photoshop_ends_them() { + for (to, want) in CASES { + let mut app = app(); + drag(&mut app, START, to, Modifiers::SHIFT, Modifiers::SHIFT); + let (from, end, _) = line(&app); + assert_eq!([from, end], want, "⇧-drag 400,300 → {to:?}"); + } +} + +/// ⇧ pressed after the drag started constrains the line as ⇧ held from the press does. +#[test] +fn shift_pressed_after_the_start_gives_the_same_line() { + for (to, _) in CASES { + let mut held = app(); + drag(&mut held, START, to, Modifiers::SHIFT, Modifiers::SHIFT); + let mut later = app(); + drag(&mut later, START, to, Modifiers::NONE, Modifiers::SHIFT); + assert_eq!(line(&held), line(&later), "⇧ at the press or after it, → {to:?}"); + } +} + +/// The drag preview's outline is the outline of the layer the drag makes. +#[test] +fn the_preview_shows_the_line_the_drag_makes() { + for (to, _) in CASES { + let mut app = app(); + let preview = shape_preview(&app, Tool::Line, START, to, Modifiers::SHIFT).expect("a preview"); + drag(&mut app, START, to, Modifiers::NONE, Modifiers::SHIFT); + assert_eq!(preview.path, line(&app).2, "preview of → {to:?}"); + } +} + +/// Up-left, up-right and down-left drags snap the same way, mirrored. +#[test] +fn shift_snaps_every_direction() { + let o = app().ui.tool_options.clone(); + for (to, want) in [([200.0, 180.0], [280.0, 180.0]), ([520.0, 100.0], [520.0, 180.0]), ([380.0, 100.0], [399.5, 100.0]), ([200.0, 310.0], [200.0, 299.5])] { + let g = super::shape_geometry(&o, Tool::Line, START, to, Modifiers::SHIFT).expect("a line"); + assert_eq!(g["to"], json!(want), "⇧-drag 400,300 → {to:?}: {g}"); + } +} + +/// CodeRabbit on #13283: a short fractional ⇧-drag still draws a one-pixel diagonal. Snapped to +/// 0.65 × 0.65 it is shorter than a pixel, but the drag itself is not, and its ends round to a +/// whole-pixel 45° step. +#[test] +fn a_short_fractional_shift_drag_still_draws_a_diagonal() { + let o = app().ui.tool_options.clone(); + let g = super::shape_geometry(&o, Tool::Line, [10.0, 10.0], [11.1, 10.65], Modifiers::SHIFT).expect("a line"); + assert_eq!((g["from"].clone(), g["to"].clone()), (json!([10.0, 10.0]), json!([11.0, 11.0])), "{g}"); +} + +/// CodeRabbit on #13283: a short ⇧-drag near an axis still draws a one-pixel line. With +/// Preferences › Tools › Snap Vector Tools and Transforms to Pixel Grid off, 0.96 × 0.30 snaps +/// flat, and its 0.96 px along the axis would round both ends to x 201; the preview and the layer +/// both show a line one pixel long. +#[test] +fn a_short_shift_drag_near_an_axis_still_draws_a_line() { + for (from, to, want) in [ + ([200.51, 100.0], [201.47, 100.30], [[201.0, 99.5], [202.0, 99.5]]), + ([200.0, 100.51], [200.30, 101.47], [[199.5, 101.0], [199.5, 102.0]]), + ([201.47, 100.0], [200.51, 100.30], [[201.0, 99.5], [200.0, 99.5]]), + ] { + let mut app = app(); + app.run("prefs.set", json!({"path": "tools.snapVectorToolsAndTransformsToPixelGrid", "value": false})).unwrap(); + app.ui.views[0].zoom = 16.0; + let preview = shape_preview(&app, Tool::Line, from, to, Modifiers::SHIFT).expect("a preview"); + drag(&mut app, from, to, Modifiers::SHIFT, Modifiers::SHIFT); + let (a, b, path) = line(&app); + assert_eq!([a, b], want, "⇧-drag {from:?} → {to:?}"); + assert_eq!(preview.path, path, "preview of {from:?} → {to:?}"); + } +} diff --git a/crates/ui-egui/src/tools/vector_ui/options.rs b/crates/ui-egui/src/tools/vector_ui/options.rs index cd0d4fbfe2..d97da4c1e0 100644 --- a/crates/ui-egui/src/tools/vector_ui/options.rs +++ b/crates/ui-egui/src/tools/vector_ui/options.rs @@ -67,8 +67,13 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo return true; } if matches!(tool, Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen) { - let opts = [("path".to_string(), tl!("Path")), ("shape".to_string(), tl!("Shape"))]; - crate::widgets::dropdown(ui, "pen-mode", tl!("Mode"), &mut o.vector_mode, &opts, 80.0); + // Photoshop's Pen lists Shape, Path and a greyed Pixels (#12906); the other pens keep theirs. + let opts = if tool == Tool::Pen { + vec![("shape".to_string(), tl!("Shape")), ("path".to_string(), tl!("Path")), ("pixels".to_string(), tl!("Pixels"))] + } else { + vec![("path".to_string(), tl!("Path")), ("shape".to_string(), tl!("Shape"))] + }; + crate::widgets::dropdown_enabled(ui, "pen-mode", tl!("Mode"), &mut o.vector_mode, &opts, 80.0, |m| m != "pixels"); crate::widgets::vline(ui, 22.0); if o.vector_mode == "shape" { crate::widgets::value_field(ui, &mut o.stroke_width, 0.0..=288.0, "px", 58.0).accessible_name(tl!("Stroke:")); @@ -132,10 +137,23 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo // geometry, the Line's arrowheads included, stays. let paint = !(is_shape_tool(tool) && draws_path(&app.ui.tool_options)); crate::shape_options::options_bar(app, ui, tool, paint); + if is_shape_tool(tool) { + // Path operations, alignment and arrangement, in Shape and Path mode (#13235). + crate::widgets::vline(ui, 22.0); + super::pen::path_operations_menu(app, ui); + super::pen::path_alignment_menu(app, ui); + super::pen::path_arrangement_menu(app, ui); + } // 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 mut concavity_alert = false; + // Stays open on clicks inside, like the Pen's gear: a click into a field to type a value + // would otherwise close the menu before the value was entered (#13258). + let config = egui::containers::menu::MenuConfig::new().close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); + let gear = egui::Button::image(crate::icons::image("settings", 18.0, t.icon)); + let menu = egui::containers::menu::MenuButton::from_button(gear).config(config); + let (gear, _) = menu.ui(ui, |ui| { let o = &mut app.ui.tool_options; ui.set_min_width(170.0); ui.label(tl!("Arrowheads")); @@ -153,16 +171,25 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo 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(" %")); + let label = tl!("Concavity"); + ui.label(label); + concavity_alert = crate::widgets::value_field_whole_alerting(ui, label, &mut o.arrow_concavity, CONCAVITY_RANGE, "%", 52.0).1; }); - }) - .response - .on_hover_text(tl!("Arrowhead options")); + }); + gear.on_hover_text(tl!("Arrowhead options")); + if concavity_alert { + crate::panels::options_bar::range_alert(&mut app.ui, CONCAVITY_RANGE_ALERT); + } } true } +/// Arrowhead Concavity in percent of the head's length, as the reference takes it (#13258). +pub(crate) const CONCAVITY_RANGE: std::ops::RangeInclusive = -50.0..=50.0; + +/// The reference's alert for a Concavity typed past [`CONCAVITY_RANGE`] (#13258). +pub(crate) const CONCAVITY_RANGE_ALERT: &str = "An integer between -50% and 50% is required. Closest value inserted."; + /// Path mode's "Make:" row, as in Photoshop's options bar: Selection… (#5703), Mask (#12904) and /// Shape (#10934), from the path being drawn or the active path; all greyed without one. fn make_buttons(app: &mut PhotocraftApp, ui: &mut egui::Ui) { @@ -269,6 +296,7 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra }; let t = Tokens::get(ui.ctx()); let mut edit: Option = None; + let mut concavity_alert = false; // A swatch picked in a Fill/Stroke popover joins the Recently Used Colors once the edit took it. let mut recent: Option<[f32; 3]> = None; let doc_id = app.session.active().map(|st| st.doc.id); @@ -362,7 +390,8 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra match live { photocraft_doc::vector::LiveShape::Rect { rect, .. } | photocraft_doc::vector::LiveShape::Ellipse { rect } - | photocraft_doc::vector::LiveShape::Polygon { rect, .. } => { + | photocraft_doc::vector::LiveShape::Polygon { rect, .. } + | photocraft_doc::vector::LiveShape::Triangle { rect, .. } => { ui.horizontal(|ui| { let (mut w, mut h) = (rect[2] as f32, rect[3] as f32); let cw = num(ui, "W", &mut w, 1.0..=300000.0, "px"); @@ -397,7 +426,7 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra } } photocraft_doc::vector::LiveShape::Polygon { sides, star_ratio, corner_radius, .. } => { - // One radius rounds every vertex of a triangle, polygon or star, as in Photoshop. + // One radius rounds every vertex of a triangle or polygon, or a star's outer points, as in Photoshop. ui.horizontal(|ui| { let mut r = *corner_radius as f32; if num(ui, tl!("Corner radius"), &mut r, 0.0..=100000.0, "px") { @@ -416,6 +445,16 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra }) .inner } + photocraft_doc::vector::LiveShape::Triangle { corner_radius, .. } => { + // One radius rounds all three corners of a triangle; it has no sides or star ratio. + ui.horizontal(|ui| { + let mut r = *corner_radius as f32; + if num(ui, tl!("Corner radius"), &mut r, 0.0..=100000.0, "px") { + edit = Some(json!({"cornerRadius": r, "coalesce": key("corner-radius")})); + } + }) + .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| { @@ -447,8 +486,12 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra } }); ui.horizontal(|ui| { + let label = tl!("Concavity"); + ui.label(egui::RichText::new(label).color(t.text_dim).size(12.0)); let mut v = *concavity as f32; - if num(ui, "Concavity", &mut v, 0.0..=100.0, "%") { + let (r, out_of_range) = crate::widgets::value_field_whole_alerting(ui, label, &mut v, CONCAVITY_RANGE, "%", 64.0); + concavity_alert |= out_of_range; + if r.changed() { edit = Some(json!({"arrowConcavity": v, "coalesce": key("arrow-concavity")})); } }); @@ -515,8 +558,15 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra }); } } + if concavity_alert { + crate::panels::options_bar::range_alert(&mut app.ui, CONCAVITY_RANGE_ALERT); + } } +#[cfg(test)] +#[path = "line_arrow_concavity_field_tests.rs"] +mod line_arrow_concavity_field_tests; + #[cfg(test)] #[path = "pen_make_mask_tests.rs"] mod pen_make_mask_tests; diff --git a/crates/ui-egui/src/tools/vector_ui/overlay.rs b/crates/ui-egui/src/tools/vector_ui/overlay.rs index 47959fa8b7..ea3825b3f4 100644 --- a/crates/ui-egui/src/tools/vector_ui/overlay.rs +++ b/crates/ui-egui/src/tools/vector_ui/overlay.rs @@ -215,6 +215,7 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform // Only over the active document, whose selected layers the box frames. if st.is_some_and(|s| s.doc.id == doc.id) { crate::shape_bounds_box::draw(app, painter, &to_scr, accent); + crate::shape_bounds_box::draw_line_controls(app, painter, &to_scr, accent); } crate::corner_radius::draw(app, painter, &to_scr, accent); } diff --git a/crates/ui-egui/src/tools/vector_ui/path_ops.rs b/crates/ui-egui/src/tools/vector_ui/path_ops.rs index f8fc316fcd..6c86c1d287 100644 --- a/crates/ui-egui/src/tools/vector_ui/path_ops.rs +++ b/crates/ui-egui/src/tools/vector_ui/path_ops.rs @@ -216,14 +216,14 @@ pub(crate) fn delete_key_deletes_work_path(app: &PhotocraftApp) -> bool { && matches!(target_path(app), Some((PathTarget::Work, _))) } -/// The anchor ⌫ / Delete removes, with its two segments: with the Add Anchor Point tool, the one +/// The anchor ⌫ / Delete removes, with its two segments: with the Add or Delete Anchor Point tool, the one /// anchor selected on it (⌘/Ctrl+click) while that selection still holds and its path is shown, /// as in Photoshop (#12703). The key reached Edit › Clear and deleted the active layer. Several /// selected anchors weren't measured and keep the key's other routes. pub(crate) fn delete_key_deletes_anchor(app: &PhotocraftApp) -> Option<(crate::direct_select::PathRef, [usize; 2])> { let ds = &app.ui.direct_selection; let ([[s, k]], Some(target)) = (ds.anchors.as_slice(), ds.target) else { return None }; - let usable = app.ui.tool == Tool::AddAnchorPoint + let usable = matches!(app.ui.tool, Tool::AddAnchorPoint | Tool::DeleteAnchorPoint) && app.ui.pen.is_none() && ds.drag.is_none() && app.ui.view.shows(app.ui.view.show.target_path) diff --git a/crates/ui-egui/src/tools/vector_ui/pen.rs b/crates/ui-egui/src/tools/vector_ui/pen.rs index c4640a8cfd..cac8010dc1 100644 --- a/crates/ui-egui/src/tools/vector_ui/pen.rs +++ b/crates/ui-egui/src/tools/vector_ui/pen.rs @@ -374,9 +374,11 @@ pub(super) fn try_pen_commit(app: &mut PhotocraftApp, closed: bool) -> Result<() let mut original = pen.clone(); original.dragging = false; original.adjusting_last = false; + let draft = super::pen_resume::draft_before_finish(&pen); if pen.curvature { curvature_refresh(&mut pen, closed); } + let before = super::pen_resume::current_doc(app); if let Err(e) = commit_path(app, &pen, closed) { app.ui.pen = Some(PenPath { commit_failed: true, ..original }); app.ui.status = e.clone(); @@ -384,6 +386,8 @@ pub(super) fn try_pen_commit(app: &mut PhotocraftApp, closed: bool) -> Result<() return Err(e); } app.ui.pen_doc = None; + // Undo back to this finish gives the path back to the Pen (`pen_resume_on_undo`). + super::pen_resume::remember_finish(app, draft, &before); Ok(()) } @@ -419,13 +423,17 @@ pub fn pen_end(app: &mut PhotocraftApp) { if app.ui.direct_selection.target == Some(crate::direct_select::PathRef::Pen) { app.ui.direct_selection = Default::default(); } + let draft = super::pen_resume::draft_before_finish(&pen); if pen.curvature { curvature_refresh(&mut pen, false); } let refused = std::mem::take(&mut app.ui.status); + let before = super::pen_resume::current_doc(app); let kept = app.run("path.set", json!({"name": "work", "op": "combine", "path": pen_to_json(&pen, false)})).is_ok(); if kept { app.ui.selected_path = Some("work".into()); + // Undo gives the path back to the Pen here too (`pen_resume_on_undo`). + super::pen_resume::remember_finish(app, draft, &before); } let outcome = if kept { tl!("The path was kept as the Work Path") } else { tl!("The path was discarded") }; app.ui.status = format!("{refused} ({outcome})"); @@ -701,6 +709,41 @@ pub(crate) fn pen_path_op(o: &ToolOptions) -> Option<&'static str> { } } +/// The operation (`shape.create` `op`) a Shape-tool drag is added with (#13235); None for a new +/// shape layer (New Layer, in Shape mode). Path mode has no New Layer: there it is Exclude +/// Overlapping Shapes, as the reference application's default. +pub(crate) fn shape_path_op(o: &ToolOptions) -> Option<&'static str> { + let op = PATH_OPS.iter().map(|(v, ..)| *v).find(|v| *v == o.shape_path_op).unwrap_or("newLayer"); + match op { + "newLayer" if o.shape_mode == "shape" => None, + "newLayer" => Some("exclude"), + op => Some(op), + } +} + +/// Whether the active tool draws shape layers (so New Layer applies): the Shape tools in Shape +/// mode, the Pens in Shape mode; Path Selection has no shape layer to make. +fn tool_in_shape_mode(app: &PhotocraftApp) -> bool { + let (tool, o) = (app.ui.tool, &app.ui.tool_options); + if tool == Tool::PathSelection { + false + } else if super::shapes::is_shape_tool(tool) { + o.shape_mode == "shape" + } else { + o.vector_mode == "shape" + } +} + +/// The active tool's resolved operation (see `pen_path_op` and `shape_path_op`). +fn tool_path_op(app: &PhotocraftApp) -> Option<&'static str> { + if super::shapes::is_shape_tool(app.ui.tool) { shape_path_op(&app.ui.tool_options) } else { pen_path_op(&app.ui.tool_options) } +} + +/// The Path Operations setting the active tool keeps: the Shape tools' own, else the Pens'. +pub(crate) fn path_op_field(app: &mut PhotocraftApp) -> &mut String { + if super::shapes::is_shape_tool(app.ui.tool) { &mut app.ui.tool_options.shape_path_op } else { &mut app.ui.tool_options.pen_path_op } +} + /// What the Path Operations menu's Merge Shape Components merges, as a command, its params and /// the number of shape components there: with Path Selection the path it selects in; in Shape /// mode the selected shape layer; in Path mode the path the Pen draws into (a targeted vector @@ -711,7 +754,7 @@ fn merge_target(app: &PhotocraftApp) -> Option<(&'static str, Value, usize)> { return Some(("path.mergeShapeComponents", r.params(app), p.components().len())); } let st = app.session.active()?; - if app.ui.tool_options.vector_mode == "shape" { + if tool_in_shape_mode(app) { let id = st.active_layer?; let LayerContent::Shape(sh) = &st.doc.layer(id)?.content else { return None }; return Some(("layer.combineShapes.mergeShapeComponents", json!({"layer": id.0}), sh.path.components().len())); @@ -730,10 +773,9 @@ fn merge_target(app: &PhotocraftApp) -> Option<(&'static str, Value, usize)> { /// shows the selected components' operation, else the tool's. pub(super) fn path_operations_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // New Layer makes a shape layer: Path mode and Path Selection have none. - let shape = app.ui.tool_options.vector_mode == "shape" && app.ui.tool != Tool::PathSelection; - let current = crate::path_components::selected_op(app) - .or_else(|| pen_path_op(&app.ui.tool_options)) - .map_or("newLayer", |op| if op == "newLayer" && !shape { "combine" } else { op }); + let shape = tool_in_shape_mode(app); + let current = + crate::path_components::selected_op(app).or_else(|| tool_path_op(app)).map_or("newLayer", |op| if op == "newLayer" && !shape { "combine" } else { op }); let icon = PATH_OPS.iter().find(|(v, ..)| *v == current).map_or("path-op-combine", |(.., i)| *i); let resp = crate::icons::button_with_icon_size(ui, icon, 24.0, 16.0, false, tl!("Path operations")); let resp = crate::brush_picker::named(resp, "Path operations"); @@ -768,6 +810,83 @@ pub(super) fn path_operations_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } } +/// Path alignment's Align entries: label and icon (#13235). +pub(crate) const PATH_ALIGN_ENTRIES: [(&str, &str); 6] = [ + ("Align Left Edges", "align-edge-left"), + ("Align Horizontal Centers", "align-edge-hcenter"), + ("Align Right Edges", "align-edge-right"), + ("Align Top Edges", "align-edge-top"), + ("Align Vertical Centers", "align-edge-vcenter"), + ("Align Bottom Edges", "align-edge-bottom"), +]; + +/// Path alignment's Distribute entries. +pub(crate) const PATH_DISTRIBUTE_ENTRIES: [(&str, &str); 6] = [ + ("Distribute Left Edges", "distribute-left"), + ("Distribute Horizontal Centers", "distribute-hcenter"), + ("Distribute Right Edges", "distribute-right"), + ("Distribute Top Edges", "distribute-top"), + ("Distribute Vertical Centers", "distribute-vcenter"), + ("Distribute Bottom Edges", "distribute-bottom"), +]; + +/// Path alignment's Distribute Spacing entries. +pub(crate) const PATH_SPACING_ENTRIES: [(&str, &str); 2] = + [("Distribute Horizontally", "distribute-horizontal"), ("Distribute Vertically", "distribute-vertical")]; + +/// Path arrangement's entries, front to back. +pub(crate) const PATH_ARRANGE_ENTRIES: [&str; 4] = ["Bring Shape To Front", "Bring Shape Forward", "Send Shape Backward", "Send Shape To Back"]; + +/// The Path alignment button of the Shape tools (#13235). Every entry is greyed: the engine has no +/// command that aligns or distributes the components of a path yet. +pub(super) fn path_alignment_menu(_app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let resp = crate::icons::button_with_icon_size(ui, "align-edge-left", 24.0, 16.0, false, tl!("Path alignment")); + let resp = crate::brush_picker::named(resp, "Path alignment"); + // Stays open while the Align To dropdown is used. + egui::Popup::menu(&resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + ui.set_min_width(240.0); + ui.label(tl!("Align:")); + for (label, glyph) in PATH_ALIGN_ENTRIES { + ui.add_enabled_ui(false, |ui| path_op_button(ui, glyph, tl!(label), false)); + } + ui.separator(); + ui.label(tl!("Distribute:")); + for (label, glyph) in PATH_DISTRIBUTE_ENTRIES { + ui.add_enabled_ui(false, |ui| path_op_button(ui, glyph, tl!(label), false)); + } + ui.separator(); + ui.label(tl!("Distribute Spacing:")); + for (label, glyph) in PATH_SPACING_ENTRIES { + ui.add_enabled_ui(false, |ui| path_op_button(ui, glyph, tl!(label), false)); + } + ui.separator(); + let key = egui::Id::unique("path-align-to"); + let mut canvas = ui.data(|d| d.get_temp::(key)).unwrap_or(false); + ui.horizontal(|ui| { + ui.label(tl!("Align To:")); + let text = if canvas { tl!("Canvas") } else { tl!("Selection") }; + craft_ui::ComboBox::from_id_salt("path-align-to-box").selected_text(text).show_ui(ui, |ui| { + ui.selectable_value(&mut canvas, false, tl!("Selection")); + ui.selectable_value(&mut canvas, true, tl!("Canvas")); + }); + }); + ui.data_mut(|d| d.insert_temp(key, canvas)); + }); +} + +/// The Path arrangement button of the Shape tools (#13235). Its entries are greyed: the engine +/// has no command that reorders the components of a path yet. +pub(super) fn path_arrangement_menu(_app: &mut PhotocraftApp, ui: &mut egui::Ui) { + let resp = crate::icons::button_with_icon_size(ui, "layers", 24.0, 16.0, false, tl!("Path arrangement")); + let resp = crate::brush_picker::named(resp, "Path arrangement"); + egui::Popup::menu(&resp).show(|ui| { + ui.set_min_width(200.0); + for label in PATH_ARRANGE_ENTRIES { + ui.add_enabled(false, egui::Button::new(tl!(label))); + } + }); +} + /// A Path Operations menu row: its icon and label, highlighted when it is the current operation. fn path_op_button(ui: &mut egui::Ui, glyph: &str, label: &str, checked: bool) -> egui::Response { let icon = egui::IdSalt::new((glyph, "icon")); @@ -810,9 +929,13 @@ pub(crate) fn freeform_finish_owned(app: &mut PhotocraftApp, points: &[[f64; 3]] } let trace: Vec<[f64; 2]> = points.iter().map(|p| [p[0], p[1]]).collect(); let (Some(first), Some(last)) = (trace.first(), trace.last()) else { return }; - let tol = 6.0 / app.point_zoom().max(0.01) as f64; + let zoom = app.point_zoom().max(0.01) as f64; + // Photoshop closes a release within 3 screen px of the start on each axis, a square (#12830). + let reach = 3.0 / zoom; + // The trace must still be longer than the former 4 × 6 screen px to close: unchanged. + let min_length = 24.0 / zoom; let length: f64 = trace.windows(2).map(|w| (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1])).sum(); - let closed = (first[0] - last[0]).hypot(first[1] - last[1]) < tol && length > 4.0 * tol; + let closed = near_start(first, last, reach) && length > min_length; let fit = f64::from(app.ui.tool_options.curve_fit); let pen = if straight.is_empty() { let Some(sub) = photocraft_vector::trace::fit_trace(&trace, fit, closed) else { return }; @@ -820,7 +943,7 @@ pub(crate) fn freeform_finish_owned(app: &mut PhotocraftApp, points: &[[f64; 3]] let unlinked = sub.knots.iter().enumerate().filter(|(_, k)| !k.smooth).map(|(i, _)| i).collect(); (PenPath { knots, unlinked, ..Default::default() }, sub.closed) } else { - fit_with_straight_segments(&trace, straight, fit, closed.then_some(tol)) + fit_with_straight_segments(&trace, straight, fit, closed) }; let (mut pen, closed) = pen; pen.owner = Some(owner); @@ -831,14 +954,22 @@ pub(crate) fn freeform_finish_owned(app: &mut PhotocraftApp, points: &[[f64; 3]] } } +/// Is the Freeform Pen's `end` within `reach` of its `start` on both axes? +fn near_start(start: &[f64; 2], end: &[f64; 2], reach: f64) -> bool { + // The screen-to-document conversion runs in f32, so a release exactly `reach` off can land a hair past it. + let reach = reach + 1e-3; + (start[0] - end[0]).abs() <= reach && (start[1] - end[1]).abs() <= reach +} + fn knot_points(k: &photocraft_doc::Knot) -> [[f64; 2]; 3] { [[k.anchor.x, k.anchor.y], [k.in_ctrl.x, k.in_ctrl.y], [k.out_ctrl.x, k.out_ctrl.y]] } /// A Freeform Pen trace with ⌥-clicked straight segments (into the points at `straight`): each /// freehand run between them is fitted on its own, and the runs are joined by straight lines -/// between corner anchors. `close` (a reach) closes the path when it ends on its start point. -fn fit_with_straight_segments(trace: &[[f64; 2]], straight: &[usize], fit: f64, close: Option) -> (PenPath, bool) { +/// between corner anchors. `close`: the release was near the start, so the last anchor becomes +/// the first one. The fitted last anchor is not tested again: fitting can move it past the reach. +fn fit_with_straight_segments(trace: &[[f64; 2]], straight: &[usize], fit: f64, close: bool) -> (PenPath, bool) { let mut cuts: Vec = straight.iter().copied().filter(|&i| i > 0 && i < trace.len()).collect(); cuts.sort_unstable(); cuts.dedup(); @@ -869,12 +1000,7 @@ fn fit_with_straight_segments(trace: &[[f64; 2]], straight: &[usize], fit: f64, } start = end; } - // Ended on the start point: the last anchor is the first one. - let ends_on_start = |k: &[[[f64; 2]; 3]], reach: f64| match (k.first(), k.last()) { - (Some(a), Some(b)) => k.len() > 3 && (a[0][0] - b[0][0]).hypot(a[0][1] - b[0][1]) < reach, - _ => false, - }; - let closed = close.is_some_and(|reach| ends_on_start(&knots, reach)); + let closed = close && knots.len() > 3; if closed && let Some(last) = knots.pop() { if let Some(k) = knots.first_mut() { k[1] = [last[1][0] - last[0][0] + k[0][0], last[1][1] - last[0][1] + k[0][1]]; @@ -978,3 +1104,7 @@ mod freeform_history_name_tests; #[cfg(test)] #[path = "pen_alt_drag_segment_tests.rs"] mod pen_alt_drag_segment_tests; + +#[cfg(test)] +#[path = "freeform_close_tolerance_tests.rs"] +mod freeform_close_tolerance_tests; diff --git a/crates/ui-egui/src/tools/vector_ui/pen_mode_menu_tests.rs b/crates/ui-egui/src/tools/vector_ui/pen_mode_menu_tests.rs new file mode 100644 index 0000000000..f5eb008821 --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/pen_mode_menu_tests.rs @@ -0,0 +1,110 @@ +//! #12906: the Pen's Mode dropdown lists Shape, Path and Pixels, in that order, as in Photoshop. +//! Pixels is greyed and can't be picked, by the pointer or the keys; the default stays Path, and +//! Reset Tool sets Path again. The Freeform and Curvature Pens keep their Path, Shape list. + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use super::add_anchor_options_bar_tests::harness; +use crate::PhotocraftApp; +use crate::state::{Tool, ToolOptions}; + +/// The options bar's Mode dropdown (the topmost one named Mode). +fn combo<'a>(h: &'a Harness<'static, PhotocraftApp>) -> egui_kittest::Node<'a> { + let combos = h.query_all_by_role(Role::ComboBox).filter(|n| n.accesskit_node().label().as_deref() == Some("Mode")); + combos.min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).expect("the Mode dropdown") +} + +/// Opens the options bar's Mode dropdown. +fn open(h: &mut Harness<'static, PhotocraftApp>) { + combo(h).click(); + h.run_steps(3); + assert!(crate::widgets::dropdown_list_open(&h.ctx), "the list is open"); +} + +/// The open list's rows top to bottom (the mode buttons below the dropdown), each with whether +/// it is greyed. +fn rows(h: &Harness<'static, PhotocraftApp>) -> Vec<(String, bool)> { + let combo = combo(h).rect(); + let mut rows: Vec<_> = h + .query_all_by_role(Role::Button) + .filter(|n| n.rect().top() >= combo.bottom() && n.accesskit_node().label().is_some_and(|l| ["Shape", "Path", "Pixels"].contains(&l.as_str()))) + .map(|n| (n.rect().top(), n.accesskit_node().label().unwrap_or_default(), n.accesskit_node().is_disabled())) + .collect(); + rows.sort_by(|a, b| a.0.total_cmp(&b.0)); + rows.into_iter().map(|(_, label, greyed)| (label, greyed)).collect() +} + +/// Clicks the open list's row `label`. +fn pick(h: &mut Harness<'static, PhotocraftApp>, label: &str) { + let combo = combo(h).rect(); + let row = h.query_all_by_label(label).find(|n| n.rect().top() >= combo.bottom()).expect("the row"); + row.click(); + h.run_steps(3); +} + +fn mode(h: &Harness<'static, PhotocraftApp>) -> String { + h.state().ui.tool_options.vector_mode.clone() +} + +#[test] +fn the_pens_list_is_shape_path_and_a_greyed_pixels() { + let mut h = harness(Tool::Pen); + open(&mut h); + let expected = [("Shape".to_string(), false), ("Path".to_string(), false), ("Pixels".to_string(), true)]; + assert_eq!(rows(&h), expected); +} + +#[test] +fn the_default_mode_is_path_and_reset_tool_sets_it_again() { + assert_eq!(ToolOptions::default().vector_mode, "path"); + let mut h = harness(Tool::Pen); + assert_eq!(mode(&h), "path"); + assert_eq!(combo(&h).value().as_deref(), Some("Path"), "the button shows Path"); + + open(&mut h); + pick(&mut h, "Shape"); + assert_eq!(mode(&h), "shape", "Shape can be picked"); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "tool.reset", json!({})).unwrap(); + assert_eq!(mode(&h), "path", "Reset Tool from Shape mode"); +} + +#[test] +fn clicking_pixels_leaves_the_mode() { + let mut h = harness(Tool::Pen); + open(&mut h); + pick(&mut h, "Pixels"); + assert_eq!(mode(&h), "path"); +} + +#[test] +fn the_keys_never_land_on_pixels() { + let mut h = harness(Tool::Pen); + open(&mut h); + // ↓ from Path, the last enabled row, would be Pixels. + h.key_press(egui::Key::ArrowDown); + h.run_steps(2); + assert_eq!(mode(&h), "path", "↓"); + // The next row starting with P after Path is Pixels. + h.key_press(egui::Key::P); + h.event(egui::Event::Text("p".into())); + h.run_steps(2); + assert_eq!(mode(&h), "path", "type-ahead P"); + // The keys still step between the enabled rows. + h.key_press(egui::Key::ArrowUp); + h.run_steps(2); + assert_eq!(mode(&h), "shape", "↑"); +} + +#[test] +fn the_freeform_and_curvature_pens_keep_path_and_shape() { + for tool in [Tool::FreeformPen, Tool::CurvaturePen] { + let mut h = harness(tool); + open(&mut h); + let expected = [("Path".to_string(), false), ("Shape".to_string(), false)]; + assert_eq!(rows(&h), expected, "{tool:?}"); + } +} diff --git a/crates/ui-egui/src/tools/vector_ui/pen_resume.rs b/crates/ui-egui/src/tools/vector_ui/pen_resume.rs new file mode 100644 index 0000000000..a7465fd8a4 --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/pen_resume.rs @@ -0,0 +1,227 @@ +//! Undo back to where a Pen path was finished gives the path back to the Pen; Redo finishes it +//! again, as in Photoshop. + +use std::sync::{Arc, Weak}; + +use serde_json::json; + +use super::pen::closing; +use super::{DocId, Document, PenPath, PhotocraftApp, Tool}; + +/// A Pen or Curvature Pen path finished: closed on its first anchor, ended with ↩/Esc or by +/// another tool. It keeps the path being drawn as it was just before, and the document the finish +/// made. Undo back to that document takes back only the finish and the Pen carries on drawing the +/// path, as in Photoshop; Redo finishes it again. `PhotocraftApp::finished_pens` keeps one per +/// path, so this holds for every path drawn, not just the last. +#[derive(Clone, Debug)] +pub(crate) struct FinishedPen { + draft: PenPath, + /// The document the finish made, or once resumed the one Undo went back to. A `Weak` keeps + /// the allocation, so a later document can't reuse its address and match by mistake, and + /// dies once History lets go of that document. + doc: Weak, + /// The document the path was finished in: a new step there clears only its own Redo. + document: DocId, + /// The History state the finish made. Redo must bring back this state, not just a document + /// (`Session::redo` may hand back a copy of it). + state: Option, + /// Undo has given the Pen the path back: Redo can finish it again. + resumed: bool, +} + +/// Is `doc` still the active document's current state (no step since)? +fn is_current(app: &PhotocraftApp, doc: &Weak) -> bool { + app.session.active().is_some_and(|st| std::ptr::eq(Arc::as_ptr(&st.doc), doc.as_ptr())) +} + +/// The id of the active document's current History state (`History::row_id`); `next` for the +/// state Redo would bring back. +fn history_state(app: &PhotocraftApp, next: bool) -> Option { + let history = &app.session.active()?.history; + history.row_id(history.past_len().checked_add(usize::from(next))?) +} + +pub(super) fn current_doc(app: &PhotocraftApp) -> Weak { + app.session.active().map(|st| Arc::downgrade(&st.doc)).unwrap_or_default() +} + +/// The path being finished as it was being drawn: without the stand-in that took a close-drag +/// (`pen_down`), whose handles went to the closed path only. +pub(super) fn draft_before_finish(pen: &PenPath) -> PenPath { + let mut draft = pen.clone(); + if !draft.curvature && closing(&draft) { + draft.knots.pop(); + let n = draft.knots.len(); + draft.unlinked.retain(|&i| i < n); + } + draft.dragging = false; + draft.adjusting_last = false; + draft.adjusting_in = false; + draft.moving = None; + draft.commit_failed = false; + draft +} + +/// After a commit of `draft` that left the document `before`: when the commit made a History +/// step, remember the finish so Undo can give the path back. Forgets the finishes whose documents +/// History no longer holds and this document's resumed ones, whose Redo the new step has cleared +/// (another document's Redo is untouched). +pub(super) fn remember_finish(app: &mut PhotocraftApp, draft: PenPath, before: &Weak) { + if is_current(app, before) { + return; + } + let Some(document) = app.session.active().map(|st| st.doc.id) else { return }; + let (doc, state) = (current_doc(app), history_state(app, false)); + app.finished_pens.retain(|f| !(f.resumed && f.document == document) && f.doc.strong_count() > 0); + app.finished_pens.push(FinishedPen { draft, doc, document, state, resumed: false }); +} + +/// The draft given back belongs to the document state Undo went back to: its owner moves to that +/// state (same target, options and colours), or `cancel_stale_pen` would take it for another +/// document's and finish it on the next frame. +fn rebind_owner(app: &PhotocraftApp, draft: &mut PenPath) { + let Some(st) = app.session.active() else { return }; + match draft.owner.as_mut() { + Some(owner) if owner.document == st.doc.id => { + owner.revision = st.revision; + owner.source = Arc::downgrade(&st.doc); + } + _ => draft.owner = super::capture_pen_owner(app), + } +} + +/// Edit › Undo back to the moment a Pen path was finished: undo the finish and give the Pen back +/// the path being drawn, rather than deleting the whole path. Also when another tool finished it +/// (the Pen that drew it comes back) and after undoing what came next, such as the selection +/// Make Selection made from it, or later paths. A path carried on from an endpoint (#6593) comes +/// back still carrying it on: Undo then takes back the anchors added to it, then drops the draft +/// and leaves the path as it was before (`pen_undo_last_point`). False for a plain Undo. +pub(crate) fn pen_resume_on_undo(app: &mut PhotocraftApp) -> Result { + if app.ui.pen.is_some() || box_steps(app, "edit.undo") { + return Ok(false); + } + let Some(i) = app.finished_pens.iter().rposition(|f| !f.resumed && is_current(app, &f.doc)) else { return Ok(false) }; + let before = current_doc(app); + app.run("edit.undo", json!({}))?; + // The finish wasn't taken back: the path stays finished. + if is_current(app, &before) { + return Ok(true); + } + let doc = current_doc(app); + let Some(finished) = app.finished_pens.get_mut(i) else { return Ok(true) }; + finished.doc = doc; + finished.resumed = true; + let mut draft = finished.draft.clone(); + rebind_owner(app, &mut draft); + if !draft.drawn_with(app.ui.tool) { + // Otherwise the next frame finishes it again (`finish_pen_if_left`). + crate::tool_memory::select(app, if draft.curvature { Tool::CurvaturePen } else { Tool::Pen }); + } + app.ui.pen_doc = app.session.active().map(|st| st.doc.id); + app.ui.pen = Some(draft); + Ok(true) +} + +/// The finish [`pen_resume_on_undo`] took back, while Redo would bring back the finish's History +/// state (not a step made and undone since). +fn resumed_finish(app: &PhotocraftApp) -> Option { + let next = history_state(app, true)?; + app.finished_pens.iter().rposition(|f| f.resumed && is_current(app, &f.doc) && f.state == Some(next)) +} + +/// The draft as Undo gave it back, ignoring what only ties it to a document state. Its target +/// counts: the same anchors redrawn in Shape mode are a new draft, not the Work Path's. +fn same_draft(a: &PenPath, b: &PenPath) -> bool { + a.knots == b.knots + && a.unlinked == b.unlinked + && a.curvature == b.curvature + && a.resumes == b.resumes + && a.fixed == b.fixed + && a.owner.as_ref().map(|o| &o.target) == b.owner.as_ref().map(|o| &o.target) +} + +/// Edit › Redo would put back the finish of the path the Pen is drawing, edited since Undo gave +/// it back: the finished path would sit beside its own draft. Redo does nothing until the draft is +/// finished (a new step, clearing Redo) or undone back to what Undo gave back. +pub(crate) fn pen_blocks_redo(app: &PhotocraftApp) -> bool { + !box_steps(app, "edit.redo") + && resumed_finish(app).and_then(|i| app.finished_pens.get(i)).is_some_and(|f| app.ui.pen.as_ref().is_some_and(|pen| !same_draft(pen, &f.draft))) +} + +/// Edit › Redo after [`pen_resume_on_undo`], with the path untouched since: finish it again. +/// Edited since, Redo does nothing ([`pen_blocks_redo`]). With the draft gone (a path carried on +/// from an endpoint, undone past its added anchors), Redo brings the finish back as History does, +/// and Undo can give the path back to the Pen again. +pub(crate) fn pen_finish_on_redo(app: &mut PhotocraftApp) -> Result { + if box_steps(app, "edit.redo") { + return Ok(false); + } + if pen_blocks_redo(app) { + return Ok(true); + } + let Some(i) = resumed_finish(app) else { return Ok(false) }; + let state = app.finished_pens.get(i).and_then(|f| f.state); + let (pen, pen_doc) = (app.ui.pen.take(), app.ui.pen_doc); + let redone = app.run("edit.redo", json!({})); + // Redo didn't bring back the finish's state: the Pen keeps its path, and the finish stays taken back. + if redone.is_err() || history_state(app, false) != state { + app.ui.pen = pen; + app.ui.pen_doc = pen_doc; + return redone.map(|_| true); + } + if app.ui.direct_selection.target == Some(crate::direct_select::PathRef::Pen) { + app.ui.direct_selection = Default::default(); + } + app.ui.pen_doc = None; + let doc = current_doc(app); + if let Some(finished) = app.finished_pens.get_mut(i) { + finished.doc = doc; + finished.resumed = false; + } + Ok(true) +} + +/// Edit › Undo and Redo, and the History panel's Step Backward and Step Forward, which step the +/// same way: a path being drawn loses its last anchor, Undo back to a finish gives the path back +/// to the Pen, and Redo finishes it again. `None` leaves `id` to History. +pub(crate) fn pen_history_step(app: &mut PhotocraftApp, id: &str) -> Option> { + let undo = match id { + "edit.undo" | "history.stepBackward" => true, + "edit.redo" | "history.stepForward" => false, + _ => return None, + }; + if box_steps(app, id) { + return None; + } + if undo && super::pen_undo_last_point(app) { + return Some(Ok(())); + } + match if undo { pen_resume_on_undo(app) } else { pen_finish_on_redo(app) } { + Ok(false) => None, + r => Some(r.map(|_| ())), + } +} + +/// Whether [`pen_history_step`] decides if `id` is enabled: Undo and Step Backward take back the +/// anchors of a path being drawn even with no History step yet; Redo and Step Forward grey out +/// while they would put a finished path back beside its edited draft ([`pen_blocks_redo`]). +pub(crate) fn pen_history_enabled(app: &PhotocraftApp, id: &str) -> Option { + let undo = match id { + "edit.undo" | "history.stepBackward" => true, + "edit.redo" | "history.stepForward" => false, + _ => return None, + }; + if box_steps(app, id) { + return None; + } + if undo { app.ui.pen.as_ref().is_some_and(|pen| !pen.knots.is_empty()).then_some(true) } else { pen_blocks_redo(app).then_some(false) } +} + +/// Do Free Transform's or the Crop tool's own box steps take `id` (Undo/Redo) rather than History +/// (`transform_tool::intercept`, `crop_ui::intercept`)? An open Free Transform or a drawn crop +/// frame also holds the History panel's steps (`panels::history`, `crop_ui::holds_history`). +pub(crate) fn box_steps(app: &PhotocraftApp, id: &str) -> bool { + crate::transform_tool::is_enabled(app, id).is_some() + || crate::crop_ui::is_enabled(app, id).is_some() + || (id.starts_with("history.") && (app.ui.transform.is_some() || crate::crop_ui::holds_history(app, id))) +} diff --git a/crates/ui-egui/src/tools/vector_ui/pen_resume_tests.rs b/crates/ui-egui/src/tools/vector_ui/pen_resume_tests.rs new file mode 100644 index 0000000000..78a645dec5 --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/pen_resume_tests.rs @@ -0,0 +1,621 @@ +//! Undo back to where a Pen path was finished gives the path back to the Pen, and Redo finishes +//! it again (`pen_resume`). + +use super::*; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.sync_views(); + app +} + +/// Edit › Undo or Redo as the menu, the shortcut and the control channel run it. +fn menu(app: &mut PhotocraftApp, id: &str) { + crate::menus::invoke(app, &egui::Context::default(), id, json!({})).unwrap(); +} + +/// A triangle drawn with the Pen and closed by clicking its first anchor; the knots it had +/// before the close. +fn close_triangle(app: &mut PhotocraftApp) -> Vec<[[f64; 2]; 3]> { + app.ui.tool = Tool::Pen; + for (x, y) in [(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)] { + pen_down(app, x, y, false); + pen_up(app); + } + let knots = app.ui.pen.as_ref().unwrap().knots.clone(); + pen_down(app, 20.0, 20.0, false); + pen_up(app); + assert!(app.ui.pen.is_none(), "clicking the first anchor commits the path"); + knots +} + +/// [`close_triangle`] in Path mode: the closed triangle is the work path. +fn closed_triangle(app: &mut PhotocraftApp) -> Vec<[[f64; 2]; 3]> { + let knots = close_triangle(app); + assert!(app.session.active().unwrap().doc.work_path.as_ref().unwrap().subpaths[0].closed); + knots +} + +#[test] +fn pen_undo_after_closing_reopens_the_path_instead_of_deleting_it() { + let mut app = app(); + let before = app.session.active().unwrap().history.past_len(); + let knots = closed_triangle(&mut app); + + // Undo takes back only the closing segment: the path is open again, still being drawn. + menu(&mut app, "edit.undo"); + let pen = app.ui.pen.as_ref().expect("the open path is back on the Pen"); + assert_eq!(pen.knots, knots); + assert_eq!(app.session.active().unwrap().history.past_len(), before); + assert!(app.session.active().unwrap().doc.work_path.is_none(), "the closed path is no longer committed"); + + // The next Undo removes the last anchor, as for any path being drawn. + menu(&mut app, "edit.undo"); + assert_eq!(app.ui.pen.as_ref().unwrap().knots, knots[..2].to_vec()); +} + +#[test] +fn pen_command_z_after_closing_reopens_the_path() { + let mut app = app(); + let knots = closed_triangle(&mut app); + press(&mut app, egui::Key::Z, egui::Modifiers::COMMAND); + assert_eq!(app.ui.pen.as_ref().map(|p| p.knots.clone()), Some(knots)); + assert!(app.session.active().unwrap().doc.work_path.is_none()); +} + +/// A key press through the keyboard shortcuts, as the app handles it. +fn press(app: &mut PhotocraftApp, key: egui::Key, modifiers: egui::Modifiers) { + let ctx = egui::Context::default(); + ctx.begin_pass(egui::RawInput { + events: vec![egui::Event::ModifiersChanged(modifiers), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }], + ..Default::default() + }); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); +} + +#[test] +fn pen_undo_after_enter_or_esc_gives_the_open_path_back() { + for key in [egui::Key::Enter, egui::Key::Escape] { + let mut app = app(); + app.ui.tool = Tool::Pen; + for (x, y) in [(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)] { + pen_down(&mut app, x, y, false); + pen_up(&mut app); + } + let knots = app.ui.pen.as_ref().unwrap().knots.clone(); + press(&mut app, key, egui::Modifiers::NONE); + assert!(app.ui.pen.is_none(), "{key:?} ends the path"); + assert!(!app.session.active().unwrap().doc.work_path.as_ref().unwrap().subpaths[0].closed); + + // Undo takes back only the ending: the Pen carries on from the last anchor. + press(&mut app, egui::Key::Z, egui::Modifiers::COMMAND); + assert_eq!(app.ui.pen.as_ref().map(|p| p.knots.clone()), Some(knots.clone()), "{key:?}"); + assert!(app.session.active().unwrap().doc.work_path.is_none()); + assert_eq!(app.ui.pen_doc, Some(app.session.active().unwrap().doc.id), "the path given back belongs to its document"); + press(&mut app, egui::Key::Z, egui::Modifiers::COMMAND); + assert_eq!(app.ui.pen.as_ref().unwrap().knots, knots[..2].to_vec(), "then Undo removes the last anchor"); + + // Ending it again, then Undo and Redo, works as for a closed path. + press(&mut app, key, egui::Modifiers::NONE); + menu(&mut app, "edit.undo"); + menu(&mut app, "edit.redo"); + assert!(app.ui.pen.is_none() && app.ui.pen_doc.is_none()); + assert_eq!(app.session.active().unwrap().doc.work_path.as_ref().unwrap().subpaths[0].knots.len(), 2); + } +} + +#[test] +fn pen_undo_after_a_close_drag_gives_back_the_first_anchor_unchanged() { + let mut app = app(); + app.ui.tool = Tool::Pen; + for (x, y) in [(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)] { + pen_down(&mut app, x, y, false); + pen_up(&mut app); + } + let knots = app.ui.pen.as_ref().unwrap().knots.clone(); + // Dragging from the first anchor pulls out its handles in the closed path only. + pen_down(&mut app, 20.0, 20.0, false); + pen_move(&mut app, 20.0, 60.0, false); + pen_up(&mut app); + let first = &app.session.active().unwrap().doc.work_path.as_ref().unwrap().subpaths[0].knots[0]; + assert!(first.smooth && first.out_ctrl.y > 20.0, "the close-drag shaped the closed path"); + + menu(&mut app, "edit.undo"); + let pen = app.ui.pen.as_ref().unwrap(); + assert_eq!(pen.knots, knots, "no stand-in knot and no pulled handles"); + assert!(!pen.dragging && !pen.adjusting_last); +} + +#[test] +fn curvature_pen_undo_after_closing_reopens_the_path() { + let mut app = app(); + app.ui.tool = Tool::CurvaturePen; + for (x, y) in [(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)] { + curvature_down(&mut app, x, y); + curvature_up(&mut app); + } + let knots = app.ui.pen.as_ref().unwrap().knots.clone(); + curvature_down(&mut app, 20.0, 20.0); + curvature_up(&mut app); + assert!(app.ui.pen.is_none()); + assert!(app.session.active().unwrap().doc.work_path.as_ref().unwrap().subpaths[0].closed); + + menu(&mut app, "edit.undo"); + let pen = app.ui.pen.as_ref().unwrap(); + assert!(pen.curvature); + assert_eq!(pen.knots, knots); + assert!(app.session.active().unwrap().doc.work_path.is_none()); +} + +#[test] +fn redo_closes_a_reopened_pen_path_again() { + let mut app = app(); + let knots = closed_triangle(&mut app); + let closed = app.session.active().unwrap().doc.work_path.clone(); + for _ in 0..2 { + menu(&mut app, "edit.undo"); + assert_eq!(app.ui.pen.as_ref().unwrap().knots, knots); + menu(&mut app, "edit.redo"); + assert!(app.ui.pen.is_none(), "Redo takes the draft back into the closed path"); + assert_eq!(app.session.active().unwrap().doc.work_path, closed); + } +} + +#[test] +fn redo_after_editing_a_reopened_path_leaves_the_draft_alone() { + let mut app = app(); + closed_triangle(&mut app); + menu(&mut app, "edit.undo"); + pen_down(&mut app, 60.0, 160.0, false); + pen_up(&mut app); + let draft = app.ui.pen.clone(); + // The draft changed since the reopen, so the closed path is not the one Redo brings back. + menu(&mut app, "edit.redo"); + assert_eq!(app.ui.pen, draft); +} + +#[test] +fn undo_after_a_later_step_takes_that_step_back_first() { + let mut app = app(); + let knots = closed_triangle(&mut app); + app.run("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 40], "fill": "#ff0000"})).unwrap(); + let after_close = app.session.active().unwrap().history.past_len() - 1; + menu(&mut app, "edit.undo"); + assert!(app.ui.pen.is_none(), "Undo takes back the rectangle only"); + assert_eq!(app.session.active().unwrap().history.past_len(), after_close); + assert!(app.session.active().unwrap().doc.work_path.is_some()); + // Back at the close, the next Undo reopens the path. + menu(&mut app, "edit.undo"); + assert_eq!(app.ui.pen.as_ref().map(|p| p.knots.clone()), Some(knots)); + assert!(app.session.active().unwrap().doc.work_path.is_none()); +} + +#[test] +fn undo_gives_every_finished_path_back_to_the_pen_not_just_the_last() { + let mut app = app(); + app.ui.tool = Tool::Pen; + let mut drafts = Vec::new(); + // Three paths, finished by closing, by Esc and by choosing another tool (↩ would deselect the + // Work Path, and the next path would replace it, #12892). + for (n, dy) in [0.0, 50.0, 100.0].into_iter().enumerate() { + crate::tool_memory::select(&mut app, Tool::Pen); + for (x, y) in [(20.0, 20.0 + dy), (120.0, 20.0 + dy), (120.0, 60.0 + dy)] { + pen_down(&mut app, x, y, false); + pen_up(&mut app); + } + drafts.push(app.ui.pen.as_ref().unwrap().knots.clone()); + match n { + 0 => { + pen_down(&mut app, 20.0, 20.0 + dy, false); + pen_up(&mut app); + } + 1 => press(&mut app, egui::Key::Escape, egui::Modifiers::NONE), + _ => { + crate::tool_memory::select(&mut app, Tool::Move); + pen_commit(&mut app, false); + } + } + assert!(app.ui.pen.is_none()); + } + let subpaths = |app: &PhotocraftApp| app.session.active().unwrap().doc.work_path.as_ref().map_or(0, |p| p.subpaths.len()); + assert_eq!(subpaths(&app), 3, "the paths build up in the work path"); + + // Undo walks back through each path: given back to the Pen, then one anchor at a time. + for (n, knots) in drafts.iter().enumerate().rev() { + press(&mut app, egui::Key::Z, egui::Modifiers::COMMAND); + assert_eq!(app.ui.tool, Tool::Pen); + assert_eq!(app.ui.pen.as_ref().map(|p| p.knots.clone()), Some(knots.clone()), "path {n} is being drawn again"); + assert_eq!(subpaths(&app), n, "path {n} is no longer in the work path"); + for left in (0..knots.len()).rev() { + press(&mut app, egui::Key::Z, egui::Modifiers::COMMAND); + assert_eq!(app.ui.pen.as_ref().map_or(0, |p| p.knots.len()), left); + } + assert_eq!(subpaths(&app), n, "taking back the anchors leaves the earlier paths alone"); + } +} + +#[test] +fn undo_steps_back_from_make_selection_to_the_path_being_drawn() { + let mut app = app(); + app.ui.tool = Tool::Pen; + for (x, y) in [(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)] { + pen_down(&mut app, x, y, false); + pen_up(&mut app); + } + let knots = app.ui.pen.as_ref().unwrap().knots.clone(); + // The canvas menu's Make Selection ends the path, then makes the selection from it. + pen_commit(&mut app, false); + app.run("path.toSelection", json!({"name": "work"})).unwrap(); + let doc = |app: &PhotocraftApp| app.session.active().unwrap().doc.clone(); + assert!(doc(&app).selection.is_some()); + + menu(&mut app, "edit.undo"); + assert!(doc(&app).selection.is_none(), "Undo takes back the selection first"); + assert!(doc(&app).work_path.is_some() && app.ui.pen.is_none()); + menu(&mut app, "edit.undo"); + assert_eq!(app.ui.pen.as_ref().map(|p| p.knots.clone()), Some(knots.clone()), "then the path is being drawn again"); + assert!(doc(&app).work_path.is_none()); + + // Redo walks forward again, and Undo back still finds the path being drawn. + menu(&mut app, "edit.redo"); + menu(&mut app, "edit.redo"); + assert!(doc(&app).selection.is_some() && app.ui.pen.is_none()); + menu(&mut app, "edit.undo"); + menu(&mut app, "edit.undo"); + assert_eq!(app.ui.pen.as_ref().map(|p| p.knots.clone()), Some(knots)); +} + +#[test] +fn undo_after_switching_tools_gives_the_path_back_to_the_pen() { + for (pen_tool, curvature) in [(Tool::Pen, false), (Tool::CurvaturePen, true)] { + let mut app = app(); + app.ui.tool = pen_tool; + for (x, y) in [(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)] { + if curvature { + curvature_down(&mut app, x, y); + curvature_up(&mut app); + } else { + pen_down(&mut app, x, y, false); + pen_up(&mut app); + } + } + let knots = app.ui.pen.as_ref().unwrap().knots.clone(); + // Choosing another tool ends the path, as the frame loop does (`PhotocraftApp::logic`). + crate::tool_memory::select(&mut app, Tool::Move); + pen_commit(&mut app, false); + assert!(app.session.active().unwrap().doc.work_path.is_some()); + + press(&mut app, egui::Key::Z, egui::Modifiers::COMMAND); + assert_eq!(app.ui.tool, pen_tool, "the tool that drew the path comes back"); + assert_eq!(app.ui.pen.as_ref().map(|p| p.knots.clone()), Some(knots)); + assert!(app.session.active().unwrap().doc.work_path.is_none()); + } +} + +#[test] +fn a_free_transform_box_keeps_its_own_undo_and_redo_over_a_finished_pen_path() { + let ctx = egui::Context::default(); + let mut app = app(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 50, "y": 50, "width": 60, "height": 60})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + app.ui.tool = Tool::Pen; + for (x, y) in [(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)] { + pen_down(&mut app, x, y, false); + pen_up(&mut app); + } + let knots = app.ui.pen.as_ref().unwrap().knots.clone(); + crate::tool_memory::select(&mut app, Tool::Move); + pen_commit(&mut app, false); + + // Undo under the box steps the box: the path stays finished, and comes back once it closes. + crate::transform_tool::begin(&mut app, &ctx).unwrap(); + menu(&mut app, "edit.undo"); + assert!(app.ui.transform.is_some() && app.ui.pen.is_none(), "the box took the Undo"); + assert!(app.session.active().unwrap().doc.work_path.is_some()); + crate::transform_tool::cancel(&mut app); + menu(&mut app, "edit.undo"); + assert_eq!(app.ui.pen.as_ref().map(|p| p.knots.clone()), Some(knots)); + + // Redo under the box steps the box too, leaving the Pen its path. + crate::transform_tool::begin(&mut app, &ctx).unwrap(); + menu(&mut app, "edit.redo"); + assert!(app.ui.transform.is_some() && app.ui.pen.is_some(), "the box took the Redo"); + assert!(app.session.active().unwrap().doc.work_path.is_none()); + + // Nor do ⌘/Ctrl+Z or Edit › Undo take an anchor off the draft under the box. + let knots = app.ui.pen.as_ref().unwrap().knots.clone(); + press(&mut app, egui::Key::Z, egui::Modifiers::COMMAND); + menu(&mut app, "edit.undo"); + assert!(app.ui.transform.is_some()); + assert_eq!(app.ui.pen.as_ref().unwrap().knots, knots, "the box took the Undo"); + crate::transform_tool::cancel(&mut app); + press(&mut app, egui::Key::Z, egui::Modifiers::COMMAND); + assert_eq!(app.ui.pen.as_ref().unwrap().knots, knots[..knots.len() - 1].to_vec(), "then Undo takes the last anchor"); +} + +#[test] +fn redo_does_not_put_a_finished_path_beside_its_edited_draft() { + let ctx = egui::Context::default(); + let mut app = app(); + app.ui.tool = Tool::Pen; + for (x, y) in [(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)] { + pen_down(&mut app, x, y, false); + pen_up(&mut app); + } + press(&mut app, egui::Key::Enter, egui::Modifiers::NONE); + menu(&mut app, "edit.undo"); + pen_down(&mut app, 20.0, 120.0, false); + pen_up(&mut app); + let knots = app.ui.pen.as_ref().unwrap().knots.clone(); + assert!(!crate::menus::is_enabled(&app, "edit.redo"), "Redo greys out over the edited draft"); + crate::menus::invoke(&mut app, &ctx, "edit.redo", json!({})).unwrap(); + assert!(app.session.active().unwrap().doc.work_path.is_none(), "no finished path beside the draft"); + assert_eq!(app.ui.pen.as_ref().unwrap().knots, knots); + + // Back to what Undo gave back, Redo finishes it again. + press(&mut app, egui::Key::Z, egui::Modifiers::COMMAND); + assert!(crate::menus::is_enabled(&app, "edit.redo")); + menu(&mut app, "edit.redo"); + assert!(app.ui.pen.is_none()); + assert_eq!(app.session.active().unwrap().doc.work_path.as_ref().unwrap().subpaths[0].knots.len(), 3); +} + +#[test] +fn redo_of_a_step_made_and_undone_over_a_resumed_path_does_not_finish_it() { + let mut app = app(); + app.ui.tool = Tool::Pen; + for (x, y) in [(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)] { + pen_down(&mut app, x, y, false); + pen_up(&mut app); + } + press(&mut app, egui::Key::Enter, egui::Modifiers::NONE); + menu(&mut app, "edit.undo"); + // Another step over the resumed path, undone: it, not the finish, is next to redo. + app.run("select.all", json!({})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + assert!(crate::menus::is_enabled(&app, "edit.redo")); + menu(&mut app, "edit.redo"); + let st = app.session.active().unwrap(); + assert!(st.doc.selection.is_some(), "Redo made the selection again"); + assert!(st.doc.work_path.is_none(), "and didn't finish the path"); + // The steps since changed the document under the draft, which drops it (`PenOwner::valid`). + assert!(app.ui.pen.is_none()); +} + +#[test] +fn a_refused_pen_redo_keeps_the_path_claimed_by_its_document() { + let mut app = app(); + app.ui.tool = Tool::Pen; + for (x, y) in [(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)] { + pen_down(&mut app, x, y, false); + pen_up(&mut app); + } + press(&mut app, egui::Key::Enter, egui::Modifiers::NONE); + menu(&mut app, "edit.undo"); + let owner = app.ui.pen_doc; + assert!(app.ui.pen.is_some() && owner.is_some()); + app.automation_input = true; + app.services.automation_command = Some(Box::new(|id, _| if id == "edit.redo" { Err("denied".into()) } else { Ok(()) })); + assert!(pen_finish_on_redo(&mut app).is_err()); + assert!(app.ui.pen.is_some()); + assert_eq!(app.ui.pen_doc, owner, "the path given back still belongs to its document"); +} + +#[test] +fn pen_undo_after_closing_a_shape_reopens_the_path() { + let mut app = app(); + app.ui.tool_options.vector_mode = "shape".into(); + let layers = app.session.active().unwrap().doc.layers.len(); + let knots = close_triangle(&mut app); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1); + menu(&mut app, "edit.undo"); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers, "the shape layer is gone"); + assert_eq!(app.ui.pen.as_ref().unwrap().knots, knots); +} + +fn work_path(app: &PhotocraftApp) -> Option { + app.session.active().unwrap().doc.work_path.clone() +} + +type Knots = Vec<[[f64; 2]; 3]>; + +/// An open path of two anchors ended with Esc (which keeps it selected, #12892), then carried on from its last anchor (#6593) by one +/// more anchor and ended again. The open path and the carried-on draft's knots. +fn carry_on_a_path(app: &mut PhotocraftApp) -> (Option, Knots, Knots) { + app.ui.tool = Tool::Pen; + for (x, y) in [(20.0, 20.0), (120.0, 20.0)] { + pen_down(app, x, y, false); + pen_up(app); + } + let first = app.ui.pen.as_ref().unwrap().knots.clone(); + press(app, egui::Key::Escape, egui::Modifiers::NONE); + let open = work_path(app); + pen_down(app, 120.0, 20.0, false); + pen_up(app); + assert!(app.ui.pen.as_ref().unwrap().resumes.is_some(), "a click on the endpoint carries the path on"); + pen_down(app, 120.0, 120.0, false); + pen_up(app); + let carried = app.ui.pen.as_ref().unwrap().knots.clone(); + assert_eq!(carried.len(), 3); + press(app, egui::Key::Escape, egui::Modifiers::NONE); + let work = work_path(app).unwrap(); + assert_eq!((work.subpaths.len(), work.subpaths[0].knots.len()), (1, 3), "the path grew in place"); + (open, first, carried) +} + +/// #6413 review: a path carried on from its endpoint (#6593) comes back from Undo still carried +/// on. Undo then takes back the added anchor, then drops the draft and leaves the path as it was +/// (`pen_undo_last_point`); one more Undo gives back the path's own first finish. +#[test] +fn undo_after_finishing_a_carried_on_path_gives_it_back_still_carried_on() { + let mut app = app(); + let (open, first, carried) = carry_on_a_path(&mut app); + + menu(&mut app, "edit.undo"); + let pen = app.ui.pen.as_ref().expect("the carried-on path is back on the Pen"); + assert_eq!(pen.knots, carried); + assert!(pen.resumes.is_some(), "still carrying the path on"); + assert_eq!(work_path(&app), open, "the path is as it was before the second finish"); + + menu(&mut app, "edit.undo"); + assert_eq!(app.ui.pen.as_ref().map(|p| p.knots.len()), Some(2), "the added anchor goes"); + menu(&mut app, "edit.undo"); + assert!(app.ui.pen.is_none(), "past the added anchors the draft goes"); + assert_eq!(work_path(&app), open, "and the path stays as it was"); + + menu(&mut app, "edit.undo"); + let pen = app.ui.pen.as_ref().expect("the first finish is taken back too"); + assert_eq!(pen.knots, first); + assert!(pen.resumes.is_none()); + assert!(work_path(&app).is_none()); +} + +#[test] +fn redo_finishes_a_carried_on_path_again_in_place() { + let mut app = app(); + let (_, _, carried) = carry_on_a_path(&mut app); + let finished = work_path(&app); + menu(&mut app, "edit.undo"); + menu(&mut app, "edit.redo"); + assert!(app.ui.pen.is_none()); + assert_eq!(work_path(&app), finished, "one subpath again, not a second one beside it"); + + // With the draft dropped, Redo brings the finish back, and Undo gives the path back again. + menu(&mut app, "edit.undo"); + menu(&mut app, "edit.undo"); + menu(&mut app, "edit.undo"); + assert!(app.ui.pen.is_none()); + menu(&mut app, "edit.redo"); + assert_eq!(work_path(&app), finished); + menu(&mut app, "edit.undo"); + assert_eq!(app.ui.pen.as_ref().map(|p| p.knots.clone()), Some(carried)); +} + +/// The draft Undo gives back belongs to the document state Undo went back to: the next frame +/// doesn't take it for a stale draft and finish it, and ↩ commits it. +#[test] +fn a_path_given_back_by_undo_is_owned_by_the_current_document_state() { + let mut app = app(); + let knots = closed_triangle(&mut app); + menu(&mut app, "edit.undo"); + let owner_valid = |app: &PhotocraftApp| app.ui.pen.as_ref().and_then(|p| p.owner.as_ref()).is_some_and(|o| o.valid(app)); + assert!(owner_valid(&app)); + assert!(!cancel_stale_pen(&mut app)); + finish_pen_if_left(&mut app); + assert_eq!(app.ui.pen.as_ref().map(|p| p.knots.clone()), Some(knots), "the draft is still being drawn"); + assert!(work_path(&app).is_none()); + press(&mut app, egui::Key::Enter, egui::Modifiers::NONE); + assert!(app.ui.pen.is_none() && !app.ui.status_error, "{}", app.ui.status); + assert_eq!(work_path(&app).unwrap().subpaths[0].knots.len(), 3); +} + +/// Three anchors drawn with the Pen and ended with ↩; their knots. +fn enter_path(app: &mut PhotocraftApp) -> Knots { + app.ui.tool = Tool::Pen; + for (x, y) in [(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)] { + pen_down(app, x, y, false); + pen_up(app); + } + let knots = app.ui.pen.as_ref().unwrap().knots.clone(); + press(app, egui::Key::Enter, egui::Modifiers::NONE); + assert!(app.ui.pen.is_none() && work_path(app).is_some()); + knots +} + +/// #6413 review: Edit › Step Backward and Step Forward (the History panel's too) step a Pen path +/// as Undo and Redo do, instead of deleting the finished path whole. +#[test] +fn step_backward_and_forward_step_a_pen_path_as_undo_and_redo_do() { + let mut app = app(); + let knots = closed_triangle(&mut app); + menu(&mut app, "history.stepBackward"); + assert_eq!(app.ui.pen.as_ref().map(|p| p.knots.clone()), Some(knots.clone()), "the open path is back on the Pen"); + assert!(work_path(&app).is_none()); + menu(&mut app, "history.stepForward"); + assert!(app.ui.pen.is_none()); + assert!(work_path(&app).unwrap().subpaths[0].closed, "Step Forward closes it again"); + menu(&mut app, "history.stepBackward"); + menu(&mut app, "history.stepBackward"); + assert_eq!(app.ui.pen.as_ref().unwrap().knots, knots[..2].to_vec(), "then the last anchor goes"); + + // A first path's anchors step back with no History step to go back to. + let mut app = self::app(); + app.ui.tool = Tool::Pen; + pen_down(&mut app, 20.0, 20.0, false); + pen_up(&mut app); + assert!(crate::menus::is_enabled(&app, "history.stepBackward")); + menu(&mut app, "history.stepBackward"); + assert!(app.ui.pen.is_none()); +} + +/// #6413 review: a path finished in another document leaves this document's Redo of a path given +/// back by Undo alone; the next Undo gives the path back again rather than deleting it. +#[test] +fn a_path_finished_in_another_document_keeps_this_documents_pen_redo() { + let mut app = app(); + let knots = enter_path(&mut app); + let finished = work_path(&app); + menu(&mut app, "edit.undo"); + for _ in 0..knots.len() { + menu(&mut app, "edit.undo"); + } + assert!(app.ui.pen.is_none() && work_path(&app).is_none(), "every anchor taken back"); + + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + enter_path(&mut app); + assert!(app.session.set_active(0)); + + menu(&mut app, "edit.redo"); + assert_eq!(work_path(&app), finished); + menu(&mut app, "edit.undo"); + assert_eq!(app.ui.pen.as_ref().map(|p| p.knots.clone()), Some(knots), "Undo gives the path back to the Pen"); + assert!(work_path(&app).is_none()); +} + +/// #6413 review: the same anchors redrawn in Shape mode after Undo took the path given back apart +/// are a new draft: Redo doesn't throw it away to bring back the Work Path. +#[test] +fn redo_leaves_the_same_anchors_redrawn_in_shape_mode_alone() { + let mut app = app(); + let knots = enter_path(&mut app); + menu(&mut app, "edit.undo"); + for _ in 0..knots.len() { + menu(&mut app, "edit.undo"); + } + assert!(app.ui.pen.is_none()); + app.ui.tool_options.vector_mode = "shape".into(); + for (x, y) in [(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)] { + pen_down(&mut app, x, y, false); + pen_up(&mut app); + } + assert_eq!(app.ui.pen.as_ref().unwrap().knots, knots); + assert!(!crate::menus::is_enabled(&app, "edit.redo"), "Redo greys out over the new draft"); + menu(&mut app, "edit.redo"); + assert_eq!(app.ui.pen.as_ref().map(|p| p.knots.clone()), Some(knots), "the Shape draft is still being drawn"); + assert!(work_path(&app).is_none(), "no Work Path brought back beside it"); +} + +/// #6413 review: a draft the document refuses (a locked shape layer) and Esc keeps as the Work +/// Path comes back to the Pen on Undo too. +#[test] +fn undo_gives_back_a_refused_draft_esc_kept_as_the_work_path() { + let mut app = app(); + app.ui.tool_options.vector_mode = "shape".into(); + close_triangle(&mut app); + app.run("layer.lockLayers", json!({"all": true})).unwrap(); + app.ui.tool_options.pen_path_op = "subtract".into(); + for (x, y) in [(40.0, 40.0), (100.0, 40.0), (100.0, 100.0)] { + pen_down(&mut app, x, y, false); + pen_up(&mut app); + } + let knots = app.ui.pen.as_ref().unwrap().knots.clone(); + press(&mut app, egui::Key::Escape, egui::Modifiers::NONE); + assert!(app.ui.pen.is_none() && work_path(&app).is_some(), "kept as the Work Path: {}", app.ui.status); + menu(&mut app, "edit.undo"); + assert_eq!(app.ui.pen.as_ref().map(|p| p.knots.clone()), Some(knots), "the draft is back on the Pen"); + assert!(work_path(&app).is_none()); +} diff --git a/crates/ui-egui/src/tools/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs index 0776227d04..0970dbb48b 100644 --- a/crates/ui-egui/src/tools/vector_ui/shapes.rs +++ b/crates/ui-egui/src/tools/vector_ui/shapes.rs @@ -86,29 +86,48 @@ pub(super) fn align_line_edges(a: [f64; 2], b: [f64; 2], weight: f64, keep_angle pub(super) fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) -> Option { Some(if tool == Tool::Line { let (mut dx, mut dy) = (end[0] - start[0], end[1] - start[1]); - if mods.shift { - // Snap to 45°. - let a = (dy.atan2(dx) / std::f64::consts::FRAC_PI_4).round() * std::f64::consts::FRAC_PI_4; - let len = dx.hypot(dy); - (dx, dy) = (len * a.cos(), len * a.sin()); - } + // Too short a drag draws nothing. Measured before ⇧ shortens a diagonal, so a short + // fractional drag still reaches `align_line_edges`, which rounds it to whole pixels. if dx.hypot(dy) < 1.0 { return None; } + if mods.shift { + // Snap to a multiple of 45°, as Photoshop does (#13243): a horizontal or vertical + // line keeps the drag's distance along its axis, a diagonal one the shorter of the two + // distances on both axes. A drag within 30° of an axis snaps to it: Photoshop flattens + // a 26.6° drag and keeps a 39.8° one diagonal; the exact boundary is not measured. + // An axis line is at least a pixel long: a drag of a pixel or more can keep as little + // as 0.87 px along its axis, and `align_line_edges` could round both ends together. + let tan30 = std::f64::consts::FRAC_PI_6.tan(); + (dx, dy) = if dy.abs() < dx.abs() * tan30 { + (dx.abs().max(1.0).copysign(dx), 0.0) + } else if dx.abs() < dy.abs() * tan30 { + (0.0, dy.abs().max(1.0).copysign(dy)) + } else { + let m = dx.abs().min(dy.abs()); + (m.copysign(dx), m.copysign(dy)) + }; + } let (from, to, weight) = align_line_edges(start, [start[0] + dx, start[1] + dy], f64::from(o.line_weight.max(1.0)), mods.shift)?; json!({"kind": "line", "from": from, "to": to, "weight": weight, "arrowStart": o.arrow_start, "arrowEnd": o.arrow_end, "arrowWidth": o.arrow_width, "arrowLength": o.arrow_length, - "arrowConcavity": o.arrow_concavity}) + // Settings saved with the old 0..100 range draw at the nearest value (#13258). + "arrowConcavity": if o.arrow_concavity.is_finite() { o.arrow_concavity.round().clamp(-50.0, 50.0) } else { 0.0 }}) } else { let (mut w, mut h) = (end[0] - start[0], end[1] - start[1]); if mods.shift { - let m = w.abs().max(h.abs()); + // The drag's shorter side sets the square, as in the reference application (#13222). + let m = w.abs().min(h.abs()); (w, h) = (m * w.signum(), m * h.signum()); } let (x0, y0) = if mods.alt { (start[0] - w, start[1] - h) } else { (start[0], start[1]) }; let (w, h) = if mods.alt { (w * 2.0, h * 2.0) } else { (w, h) }; - let rect = [x0.min(x0 + w).round(), y0.min(y0 + h).round(), w.abs().round(), h.abs().round()]; + let rect = [x0.min(x0 + w), y0.min(y0 + h), w.abs(), h.abs()]; + // Align Edges (#13370) is the Triangle tool's option, and only in Shape mode, where its + // checkbox is enabled. The other shape tools, and a greyed checkbox, still snap. + let keep_fraction = tool == Tool::Triangle && o.shape_mode == "shape" && !o.align_edges; + let rect = if keep_fraction { rect } else { rect.map(f64::round) }; if rect[2] < 1.0 || rect[3] < 1.0 { return None; } @@ -116,7 +135,15 @@ pub(super) fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end: Tool::Rectangle if o.corner_radius > 0.0 => json!({"kind": "roundedRect", "rect": rect, "radii": vec![o.corner_radius; 4]}), Tool::Rectangle | Tool::CustomShape => json!({"kind": "rect", "rect": rect}), Tool::EllipseShape => json!({"kind": "ellipse", "rect": rect}), - Tool::Triangle => json!({"kind": "polygon", "rect": rect, "sides": 3}), + // Shift: the equilateral triangle in the circle of the constrained square, as before the + // plain drag filled its box (#13350), sent as its tight box. Which side sizes the square + // is #13351's. + Tool::Triangle if mods.shift => { + let r = rect[2] / 2.0; + let half_base = r * 3f64.sqrt() / 2.0; + json!({"kind": "triangle", "rect": [rect[0] + r - half_base, rect[1], 2.0 * half_base, 1.5 * r]}) + } + Tool::Triangle => json!({"kind": "triangle", "rect": rect}), // PhotoCraft's star defaults; the Star Tool's own options are not measured yet (#11377). Tool::Star => json!({"kind": "star", "rect": rect, "sides": 5, "starRatio": 0.5}), _ => json!({"kind": "polygon", "rect": rect, "sides": o.polygon_sides.max(3)}), @@ -151,8 +178,17 @@ pub fn finish_shape(app: &mut PhotocraftApp, tool: Tool, start: [f64; 2], end: [ .and_then(|st| st.doc.work_path.clone()) .unwrap_or_else(|| photocraft_doc::vector::Path { fill_rule: outline.fill_rule, ..Default::default() }); let outline = as_one_component(&outline, path.fill_rule).unwrap_or(outline); + let first_new = path.subpaths.len(); path.subpaths.extend(outline.subpaths); - let r = app.run("path.set", json!({"name": "work", "path": photocraft_engine::vector_cmds::path_json(&path)})); + // The first component of a path always combines; the later ones take the drag's operation. + if first_new > 0 + && let Some(op) = drag_path_op(app) + && let Some(sp) = path.subpaths.get_mut(first_new) + { + sp.op = path_op_of(op); + } + let path = photocraft_engine::vector_cmds::path_json(&path); + let r = app.run("path.set", json!({"name": "work", "path": path, "historyName": line_history_name(tool)})); match r { Ok(_) => app.ui.selected_path = Some("work".into()), Err(e) => { @@ -164,6 +200,30 @@ pub fn finish_shape(app: &mut PhotocraftApp, tool: Tool, start: [f64; 2], end: [ } let Some(mut p) = shape_geometry(&app.ui.tool_options, tool, start, end, mods) else { return }; if tool == Tool::CustomShape { + // With an operation other than New Layer the shape joins the active shape layer as one + // component, its holes joined to it as in Path mode. + if let Some(op) = drag_path_op(app) + && let Some(id) = super::options::selected_shape(&app.session) + && let Some(outline) = shape_outline(app, tool, start, end, mods) + { + // `shape.create` gives every component the operation, so a shape of several components + // that can't be made one (its parts intersect or exclude) would change: refuse it. + let outline = match as_one_component(&outline, outline.fill_rule) { + Some(one) => one, + None if outline.subpaths.len() <= 1 => outline, + None => { + app.ui.status = tl!("This custom shape can't be added to a shape layer with a path operation: choose New Layer").into(); + app.ui.status_error = true; + return; + } + }; + let path = photocraft_engine::vector_cmds::path_json(&outline); + if let Err(e) = app.run("shape.create", json!({"kind": "path", "path": path, "addTo": id.0, "op": op})) { + app.ui.status = e; + app.ui.status_error = true; + } + return; + } // ⇧ keeps the shape's proportions (the rect is already squared). if let Ok(rect) = serde_json::from_value(p["rect"].take()) { let (fill, stroke) = (fill_param(app), stroke_param(app)); @@ -171,12 +231,42 @@ pub fn finish_shape(app: &mut PhotocraftApp, tool: Tool, start: [f64; 2], end: [ } return; } + p["historyName"] = json!(line_history_name(tool)); + // With an operation other than New Layer the drag joins the active shape layer. + if let Some(op) = drag_path_op(app) + && let Some(id) = super::options::selected_shape(&app.session) + { + p["addTo"] = json!(id.0); + p["op"] = json!(op); + } if let Err(e) = create_shape(app, p) { app.ui.status = e; app.ui.status_error = true; } } +/// The operation the next Shape-tool drag is added with (the options bar's Path operations); +/// None for a new shape layer. The one place press modifiers can override it (#13227). +fn drag_path_op(app: &PhotocraftApp) -> Option<&'static str> { + super::pen::shape_path_op(&app.ui.tool_options) +} + +fn path_op_of(op: &str) -> photocraft_doc::vector::PathOp { + use photocraft_doc::vector::PathOp; + match op { + "subtract" => PathOp::Subtract, + "intersect" => PathOp::Intersect, + "exclude" => PathOp::Exclude, + _ => PathOp::Combine, + } +} + +/// A Line tool drag is one History step named after the tool, as in Photoshop (#13244); the +/// other Shape tools keep the commands' own names. +fn line_history_name(tool: Tool) -> Option<&'static str> { + (tool == Tool::Line).then_some("Line Tool") +} + pub(super) fn fill_param(app: &PhotocraftApp) -> Value { if app.ui.tool_options.shape_fill { tool_paint_param(app, false) } else { Value::Null } } diff --git a/crates/ui-egui/src/tools/vector_ui/tests.rs b/crates/ui-egui/src/tools/vector_ui/tests.rs index b7d19a4d5f..486ce2e6d0 100644 --- a/crates/ui-egui/src/tools/vector_ui/tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/tests.rs @@ -491,7 +491,7 @@ fn shape_drag_creates_layers_with_modifiers() { finish_shape(&mut app, Tool::Rectangle, [10.0, 10.0], [60.0, 30.0], egui::Modifiers::SHIFT); let st = app.session.active().unwrap(); let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); - assert_eq!((b.width(), b.height()), (50, 50), "shift = square"); + assert_eq!((b.width(), b.height()), (20, 20), "shift = square of the shorter side (#13222)"); finish_shape(&mut app, Tool::EllipseShape, [100.0, 100.0], [120.0, 110.0], egui::Modifiers::ALT); let st = app.session.active().unwrap(); let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds(); @@ -539,7 +539,8 @@ fn path_mode_custom_shape_joins_its_hole_to_it() { app.ui.presets_ui.custom_shape = "Ring".into(); finish_shape(&mut app, Tool::CustomShape, [20.0, 20.0], [70.0, 70.0], egui::Modifiers::NONE); let ops: Vec = app.session.active().unwrap().doc.work_path.as_ref().unwrap().subpaths.iter().map(|s| s.op).collect(); - assert_eq!(ops, [PathOp::Combine, PathOp::Combine, PathOp::Join], "the rectangle, the ring and its hole"); + // The ring takes Path mode's default operation, Exclude Overlapping Shapes (#13235). + assert_eq!(ops, [PathOp::Combine, PathOp::Exclude, PathOp::Join], "the rectangle, the ring and its hole"); assert_eq!(work_covered(&app, 45, 45), 0.0, "the ring's hole"); assert_eq!(work_covered(&app, 22, 45), 1.0, "the ring"); } @@ -693,9 +694,9 @@ fn shift_pressed_during_a_shape_drag_constrains_it() { let l = st.doc.layer(st.active_layer.unwrap()).unwrap(); assert!(matches!(l.content, LayerContent::Shape(_)), "{tool:?} ({sides} sides): a shape layer"); let b = l.surface().unwrap().content_bounds(); - // The drag is 60 × 30; constrained, the shape's box is 60 × 60 (a hexagon is narrower - // than its box, so the height tells). - assert!(b.height().abs_diff(60) <= 1 && b.width() <= 61, "{tool:?}: ⇧ mid-drag keeps proportions: {b:?}"); + // The drag is 60 × 30; constrained, the shape's box is 30 × 30, the shorter side (#13222) + // (a hexagon is narrower than its box, so the height tells). + assert!(b.height().abs_diff(30) <= 1 && b.width() <= 31, "{tool:?}: ⇧ mid-drag keeps proportions: {b:?}"); } } diff --git a/crates/ui-egui/src/tools/vector_ui/triangle_align_edges_tests.rs b/crates/ui-egui/src/tools/vector_ui/triangle_align_edges_tests.rs new file mode 100644 index 0000000000..ef58c63393 --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/triangle_align_edges_tests.rs @@ -0,0 +1,81 @@ +//! #13370: the Triangle tool's Align Edges checkbox. On (the default) the drawn box snaps to whole +//! pixels; off it keeps the drag's fractional coordinates. It is greyed outside Shape mode. + +use egui::accesskit::Toggled; +use egui_kittest::kittest::{NodeT, Queryable}; + +use super::add_anchor_options_bar_tests::harness; +use super::shapes::shape_geometry; +use crate::state::{Tool, ToolOptions}; + +const START: [f64; 2] = [10.3, 10.6]; +const END: [f64; 2] = [40.7, 30.2]; + +fn rect(o: &ToolOptions, tool: Tool, start: [f64; 2], end: [f64; 2]) -> Option<[f64; 4]> { + let g = shape_geometry(o, tool, start, end, egui::Modifiers::NONE)?; + serde_json::from_value(g["rect"].clone()).ok() +} + +#[test] +fn align_edges_is_on_by_default_and_saved() { + assert!(ToolOptions::default().align_edges); + let off = ToolOptions { align_edges: false, ..Default::default() }; + let back: ToolOptions = serde_json::from_str(&serde_json::to_string(&off).unwrap()).unwrap(); + assert!(!back.align_edges, "a saved off survives a round trip"); + let empty: ToolOptions = serde_json::from_str("{}").unwrap(); + assert!(empty.align_edges, "an older file without the field gets the default"); +} + +#[test] +fn triangle_box_snaps_with_align_edges_and_stays_fractional_without() { + let mut o = ToolOptions::default(); + let r = rect(&o, Tool::Triangle, START, END).unwrap(); + assert!(r.iter().all(|v| v.fract() == 0.0), "whole pixels: {r:?}"); + o.align_edges = false; + let r = rect(&o, Tool::Triangle, START, END).unwrap(); + for (got, want) in r.iter().zip([10.3, 10.6, 30.4, 19.6]) { + assert!((got - want).abs() < 1e-9, "{r:?}"); + } +} + +#[test] +fn other_shape_tools_always_snap() { + let o = ToolOptions { align_edges: false, ..Default::default() }; + for tool in [Tool::Polygon, Tool::EllipseShape, Tool::Rectangle, Tool::Star] { + let r = rect(&o, tool, START, END).unwrap(); + assert!(r.iter().all(|v| v.fract() == 0.0), "{tool:?}: {r:?}"); + } +} + +#[test] +fn a_greyed_checkbox_keeps_snapping_in_path_mode() { + let o = ToolOptions { align_edges: false, shape_mode: "path".into(), ..Default::default() }; + let r = rect(&o, Tool::Triangle, START, END).unwrap(); + assert!(r.iter().all(|v| v.fract() == 0.0), "Path mode: {r:?}"); +} + +#[test] +fn a_sub_pixel_triangle_drag_still_draws_nothing() { + let o = ToolOptions { align_edges: false, ..Default::default() }; + assert!(rect(&o, Tool::Triangle, [10.0, 10.0], [10.4, 30.0]).is_none()); + assert!(rect(&o, Tool::Triangle, [10.0, 10.0], [30.0, 10.9]).is_none()); +} + +#[test] +fn options_bar_shows_align_edges_for_the_triangle_only() { + let mut h = harness(Tool::Triangle); + let node = h.get_by_label("Align Edges"); + assert!(!node.accesskit_node().is_disabled(), "enabled in Shape mode"); + assert_eq!(node.accesskit_node().toggled(), Some(Toggled::True)); + h.get_by_label("Align Edges").click(); + h.run_steps(3); + assert!(!h.state().ui.tool_options.align_edges, "clicking toggles the option"); + assert_eq!(h.get_by_label("Align Edges").accesskit_node().toggled(), Some(Toggled::False)); + + h.state_mut().ui.tool_options.shape_mode = "path".into(); + h.run_steps(4); + assert!(h.get_by_label("Align Edges").accesskit_node().is_disabled(), "greyed in Path mode"); + + let h = harness(Tool::Rectangle); + assert!(h.query_by_label("Align Edges").is_none()); +} diff --git a/crates/ui-egui/src/tools/vector_ui/triangle_box_geometry_tests.rs b/crates/ui-egui/src/tools/vector_ui/triangle_box_geometry_tests.rs new file mode 100644 index 0000000000..03c4bfe5fa --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/triangle_box_geometry_tests.rs @@ -0,0 +1,116 @@ +//! #13350: the Triangle tool's drag fills its box, apex at the top centre, in either direction and +//! from the centre with Alt, and Create Triangle sends the same triangle. Shift keeps the +//! equilateral triangle of the constrained square's circle. + +use egui::Modifiers; +use serde_json::{Value, json}; + +use super::{finish_shape, shape_geometry}; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +fn app(w: u32, h: u32) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": w, "height": h})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Triangle; + app +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.entries().len() +} + +/// `shape.info` of the active layer. +fn info(app: &mut PhotocraftApp) -> Value { + let id = app.session.active().unwrap().active_layer.unwrap().0; + app.session.execute("shape.info", json!({"layer": id})).unwrap() +} + +fn anchors(v: &Value) -> Vec<(f64, f64)> { + let knots = v["path"]["subpaths"][0]["knots"].as_array().unwrap(); + knots.iter().map(|k| (k["anchor"][0].as_f64().unwrap(), k["anchor"][1].as_f64().unwrap())).collect() +} + +fn close(got: &[(f64, f64)], want: &[(f64, f64)], tol: f64) { + assert_eq!(got.len(), want.len(), "{got:?}"); + for (g, w) in got.iter().zip(want) { + assert!((g.0 - w.0).abs() <= tol && (g.1 - w.1).abs() <= tol, "{got:?} vs {want:?}"); + } +} + +#[test] +fn a_drag_fills_its_box_in_either_direction() { + for (from, to) in [([400.0, 300.0], [600.0, 400.0]), ([600.0, 400.0], [400.0, 300.0])] { + let mut app = app(800, 600); + let n = steps(&app); + finish_shape(&mut app, Tool::Triangle, from, to, Modifiers::NONE); + let v = info(&mut app); + assert_eq!(anchors(&v), [(500.0, 300.0), (600.0, 400.0), (400.0, 400.0)]); + assert_eq!(v["live"]["kind"], "triangle"); + assert_eq!(steps(&app), n + 1); + } +} + +#[test] +fn alt_after_the_start_draws_from_the_centre() { + let mut app = app(800, 600); + finish_shape(&mut app, Tool::Triangle, [400.0, 300.0], [500.0, 350.0], Modifiers::ALT); + assert_eq!(anchors(&info(&mut app)), [(400.0, 250.0), (500.0, 350.0), (300.0, 350.0)]); +} + +#[test] +fn the_dialog_and_the_drag_send_the_same_triangle() { + let app = app(800, 600); + let fields = json!({"__createShape": "triangle", "__at": [400.0, 300.0], "width": 100.0, "height": 100.0, "fromCenter": false}); + let Value::Object(fields) = fields else { panic!("an object") }; + let dialog = crate::shape_dialog::geometry(&fields).unwrap(); + let drag = shape_geometry(&app.ui.tool_options, Tool::Triangle, [400.0, 300.0], [500.0, 400.0], Modifiers::NONE).unwrap(); + assert_eq!(dialog, drag); + let path = photocraft_engine::vector_cmds::shape_path(&dialog).unwrap(); + let got: Vec<(f64, f64)> = path.subpaths[0].knots.iter().map(|k| (k.anchor.x, k.anchor.y)).collect(); + assert_eq!(got, [(450.0, 300.0), (500.0, 400.0), (400.0, 400.0)]); +} + +#[test] +fn shift_still_draws_the_equilateral_triangle_of_the_squares_circle() { + for mods in [Modifiers::SHIFT, Modifiers::SHIFT | Modifiers::ALT] { + let mut app = app(800, 600); + let (start, end) = ([400.0, 300.0], [600.0, 400.0]); + // The square the Rectangle tool gets for the same drag, whichever side sizes it. + let sq = shape_geometry(&app.ui.tool_options, Tool::Rectangle, start, end, mods).unwrap(); + let [x, y, m, _]: [f64; 4] = serde_json::from_value(sq["rect"].clone()).unwrap(); + finish_shape(&mut app, Tool::Triangle, start, end, mods); + let v = info(&mut app); + assert_eq!(v["live"]["kind"], "triangle"); + let s60 = 60f64.to_radians().sin(); + let want = [(x + m / 2.0, y), (x + m / 2.0 + m / 2.0 * s60, y + 0.75 * m), (x + m / 2.0 - m / 2.0 * s60, y + 0.75 * m)]; + let got = anchors(&v); + close(&got, &want, 1e-9); + let d = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).hypot(a.1 - b.1); + let sides = [d(got[0], got[1]), d(got[1], got[2]), d(got[2], got[0])]; + assert!((sides[0] - sides[1]).abs() < 1e-9 && (sides[1] - sides[2]).abs() < 1e-9, "{sides:?}"); + } +} + +#[test] +fn the_corner_widget_rounds_a_live_triangle() { + let mut app = app(200, 200); + app.run("shape.create", json!({"kind": "triangle", "rect": [40, 40, 120, 120], "cornerRadius": 20})).unwrap(); + app.ui.tool = Tool::PathSelection; + let n = steps(&app); + let cy = 40.0 + 20.0 * 5f64.sqrt(); + let to = cy + 4.0 * 5f64.sqrt(); + tool_event(&mut app, ToolEvent::Down { x: 100.0, y: cy, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 100.0, y: to, pressure: 1.0 }, Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 100.0, y: to }, Modifiers::NONE); + let v = info(&mut app); + assert_eq!(v["live"]["kind"], "triangle"); + assert_eq!(v["live"]["rect"], json!([40.0, 40.0, 120.0, 120.0])); + assert!((v["live"]["corner_radius"].as_f64().unwrap() - 24.0).abs() < 1e-9, "{}", v["live"]); + assert_eq!(anchors(&v).len(), 6); + assert_eq!(steps(&app), n + 1); + assert!(app.session.undo()); + assert_eq!(info(&mut app)["live"]["corner_radius"].as_f64(), Some(20.0)); +} diff --git a/crates/ui-egui/src/tools/vector_ui/triangle_properties_fields_tests.rs b/crates/ui-egui/src/tools/vector_ui/triangle_properties_fields_tests.rs new file mode 100644 index 0000000000..49bdedc7b1 --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/triangle_properties_fields_tests.rs @@ -0,0 +1,162 @@ +//! #13360: a triangle's Properties Shape section shows one Corner radius field and no Sides and no +//! Star ratio field; Polygon tool (even with 3 sides) and Star tool shapes keep theirs. The +//! behaviour landed with the live triangle kind (#13578); these cases pin the issue's Done-when. + +use egui::accesskit::Role; +use egui::{Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::{LayerContent, LayerId, LiveShape}; +use serde_json::{Value, json}; + +use super::{finish_shape, shape_properties}; +use crate::PhotocraftApp; +use crate::state::Tool; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.sync_views(); + app +} + +fn active_id(app: &PhotocraftApp) -> LayerId { + app.session.active().unwrap().active_layer.unwrap() +} + +fn fonts_ready(ui: &egui::Ui) -> bool { + ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) +} + +fn harness(app: PhotocraftApp, id: LayerId) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(400.0, 900.0)).build_ui_state( + move |ui, app| { + if fonts_ready(ui) { + shape_properties(app, ui, id); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +fn labels(h: &Harness<'static, PhotocraftApp>) -> Vec { + h.query_all_by_role(Role::SpinButton).filter_map(|n| n.accesskit_node().label()).map(|l| l.to_string()).collect() +} + +fn only_corner_radius(h: &Harness<'static, PhotocraftApp>) { + let l = labels(h); + assert!(l.iter().any(|s| s == "Corner radius"), "{l:?}"); + assert!(!l.iter().any(|s| s == "Sides" || s == "Star ratio"), "{l:?}"); +} + +fn drag(tool: Tool, sides: u32) -> (PhotocraftApp, LayerId) { + let mut app = app(); + app.ui.tool = tool; + app.ui.tool_options.polygon_sides = sides; + finish_shape(&mut app, tool, [400.0, 300.0], [600.0, 400.0], Modifiers::NONE); + let id = active_id(&app); + (app, id) +} + +fn info(app: &mut PhotocraftApp) -> Value { + let id = active_id(app).0; + app.session.execute("shape.info", json!({"layer": id})).unwrap() +} + +fn knots(v: &Value) -> usize { + v["path"]["subpaths"][0]["knots"].as_array().unwrap().len() +} + +fn live(app: &PhotocraftApp, id: LayerId) -> LiveShape { + match &app.session.active().unwrap().doc.layer(id).unwrap().content { + LayerContent::Shape(sh) => sh.live.clone().expect("a live shape"), + _ => panic!("a shape layer"), + } +} + +fn corner_radius(app: &PhotocraftApp, id: LayerId) -> f64 { + match live(app, id) { + LiveShape::Triangle { corner_radius, .. } => corner_radius, + other => panic!("a live triangle, got {other:?}"), + } +} + +fn type_radius(h: &mut Harness<'static, PhotocraftApp>, text: &str) { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Corner radius")).expect("the Corner radius field").click(); + h.run_steps(1); + h.key_press_modifiers(Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +#[test] +fn a_dragged_triangle_shows_only_corner_radius() { + let (app, id) = drag(Tool::Triangle, 5); + assert!(matches!(live(&app, id), LiveShape::Triangle { .. })); + only_corner_radius(&harness(app, id)); +} + +#[test] +fn a_create_triangle_shape_shows_only_corner_radius() { + // Runs the command Create Triangle, OK sends (same geometry as the dialog, see + // triangle_box_geometry_tests) rather than driving the dialog. + let mut app = app(); + let fields = json!({"__createShape": "triangle", "__at": [400.0, 300.0], "width": 100.0, "height": 100.0, "fromCenter": false}); + let Value::Object(fields) = fields else { panic!("an object") }; + let geometry = crate::shape_dialog::geometry(&fields).unwrap(); + app.run("shape.create", geometry).unwrap(); + let id = active_id(&app); + assert!(matches!(live(&app, id), LiveShape::Triangle { .. })); + only_corner_radius(&harness(app, id)); +} + +#[test] +fn editing_corner_radius_rounds_the_triangle() { + let (mut app, id) = drag(Tool::Triangle, 5); + let before = knots(&info(&mut app)); + let mut h = harness(app, id); + type_radius(&mut h, "10"); + assert_eq!(corner_radius(h.state(), id), 10.0); + let after = knots(&info(h.state_mut())); + assert!(after > before, "{before} -> {after}"); + only_corner_radius(&h); +} + +#[test] +fn polygon_with_three_sides_and_star_keep_sides_and_star_ratio() { + for (tool, sides) in [(Tool::Polygon, 3), (Tool::Polygon, 6), (Tool::Star, 5)] { + let (app, id) = drag(tool, sides); + let h = harness(app, id); + let l = labels(&h); + assert!(l.iter().any(|s| s == "Sides") && l.iter().any(|s| s == "Star ratio") && l.iter().any(|s| s == "Corner radius"), "{tool:?} {sides}: {l:?}"); + } +} + +#[test] +fn the_triangle_stays_a_triangle_after_undo_redo_and_a_pcraft_round_trip() { + let (app, id) = drag(Tool::Triangle, 5); + let mut h = harness(app, id); + type_radius(&mut h, "10"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(corner_radius(h.state(), id), 0.0); + only_corner_radius(&h); + h.state_mut().run("edit.redo", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(corner_radius(h.state(), id), 10.0); + only_corner_radius(&h); + + // Document-level round trip with the format crate. + let bytes = photocraft_format::save_to_bytes(&h.state().session.active().unwrap().doc, &Default::default()).unwrap(); + let doc = photocraft_format::load_from_bytes(&bytes).unwrap(); + let loaded = match &doc.layer(id).unwrap().content { + LayerContent::Shape(sh) => sh.live.clone(), + _ => panic!("a shape layer"), + }; + assert!(matches!(loaded, Some(LiveShape::Triangle { corner_radius, .. }) if corner_radius == 10.0), "{loaded:?}"); +} diff --git a/crates/ui-egui/src/tools/vector_ui/triangle_shift_equilateral_tests.rs b/crates/ui-egui/src/tools/vector_ui/triangle_shift_equilateral_tests.rs new file mode 100644 index 0000000000..cf0a4db092 --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/triangle_shift_equilateral_tests.rs @@ -0,0 +1,84 @@ +//! #13351: Shift with the Triangle tool draws an equilateral triangle in the circle of the square +//! on the drag's shorter side, apex up; Shift+Alt centres the circle on the press. The preview +//! (`shape_bounds`) shows the same triangle, and a plain drag still fills its box (#13350). + +use egui::Modifiers; +use serde_json::{Value, json}; + +use super::{finish_shape, shape_bounds}; +use crate::PhotocraftApp; +use crate::state::Tool; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 1000, "height": 800})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Triangle; + app +} + +/// `shape.info` of the active layer. +fn info(app: &mut PhotocraftApp) -> Value { + let id = app.session.active().unwrap().active_layer.unwrap().0; + app.session.execute("shape.info", json!({"layer": id})).unwrap() +} + +fn anchors(v: &Value) -> Vec<(f64, f64)> { + let knots = v["path"]["subpaths"][0]["knots"].as_array().unwrap(); + knots.iter().map(|k| (k["anchor"][0].as_f64().unwrap(), k["anchor"][1].as_f64().unwrap())).collect() +} + +fn close(got: &[(f64, f64)], want: &[(f64, f64)]) { + assert_eq!(got.len(), want.len(), "{got:?}"); + for (g, w) in got.iter().zip(want) { + assert!((g.0 - w.0).abs() <= 0.05 && (g.1 - w.1).abs() <= 0.05, "{got:?} vs {want:?}"); + } +} + +fn drag(start: [f64; 2], end: [f64; 2], mods: Modifiers) -> Vec<(f64, f64)> { + let mut app = app(); + finish_shape(&mut app, Tool::Triangle, start, end, mods); + anchors(&info(&mut app)) +} + +#[test] +fn shift_sizes_the_circle_from_the_shorter_side() { + close(&drag([400.0, 300.0], [600.0, 400.0], Modifiers::SHIFT), &[(450.0, 300.0), (493.3, 375.0), (406.7, 375.0)]); +} + +#[test] +fn shift_alt_centres_the_circle_on_the_press() { + let got = drag([400.0, 300.0], [600.0, 400.0], Modifiers::SHIFT | Modifiers::ALT); + close(&got, &[(400.0, 200.0), (486.6, 350.0), (313.4, 350.0)]); +} + +#[test] +fn a_tall_narrow_drag_uses_its_width() { + let got = drag([400.0, 300.0], [450.0, 500.0], Modifiers::SHIFT); + close(&got, &[(425.0, 300.0), (446.65, 337.5), (403.35, 337.5)]); +} + +#[test] +fn the_preview_shows_the_result_triangle() { + let app = app(); + let b = shape_bounds(&app.ui.tool_options, Tool::Triangle, [400.0, 300.0], [600.0, 400.0], Modifiers::SHIFT).unwrap(); + for (g, w) in b.iter().zip([406.7, 300.0, 493.3, 375.0]) { + assert!((g - w).abs() <= 0.05, "{b:?}"); + } + let mut app = app; + finish_shape(&mut app, Tool::Triangle, [400.0, 300.0], [600.0, 400.0], Modifiers::SHIFT); + let got = anchors(&info(&mut app)); + let xs = got.iter().map(|p| p.0); + let (x0, x1) = (xs.clone().fold(f64::MAX, f64::min), xs.fold(f64::MIN, f64::max)); + let ys = got.iter().map(|p| p.1); + let (y0, y1) = (ys.clone().fold(f64::MAX, f64::min), ys.fold(f64::MIN, f64::max)); + for (g, w) in [x0, y0, x1, y1].iter().zip(b) { + assert!((g - w).abs() <= 1e-9, "{got:?} vs {b:?}"); + } +} + +#[test] +fn a_plain_drag_still_fills_its_box() { + let got = drag([400.0, 300.0], [600.0, 400.0], Modifiers::NONE); + close(&got, &[(500.0, 300.0), (600.0, 400.0), (400.0, 400.0)]); +} diff --git a/crates/ui-egui/src/tools/zoom_tool.rs b/crates/ui-egui/src/tools/zoom_tool.rs index 553e9ad781..e2b86f3b1b 100644 --- a/crates/ui-egui/src/tools/zoom_tool.rs +++ b/crates/ui-egui/src/tools/zoom_tool.rs @@ -2,8 +2,9 @@ //! //! With Scrubby Zoom on (the default, as in Photoshop) press-and-drag zooms continuously: right //! zooms in, left zooms out, anchored at the point where the button went down. With it off, the -//! drag draws a rectangle and the release zooms to fit it. A click (no drag) still steps the zoom -//! in, or out with ⌥ (handled by the canvas). +//! drag draws a rectangle and the release zooms to fit it, unless it zooms out (Zoom Out mode, or +//! ⌥ in Zoom In mode): then the release steps out once at the press point. A click (no drag) +//! steps the zoom in, or out in Zoom Out mode, ⌥ turning either around (handled by the canvas). use egui::{Pos2, Rect, vec2}; @@ -25,6 +26,8 @@ struct ZoomDrag { zoom0: f32, /// Scrubby Zoom off: a zoom rectangle, its current corner. rect_to: Option, + /// The release steps out (Zoom Out mode, or ⌥ in Zoom In mode): no rectangle is shown. + out: bool, } fn id() -> egui::Id { @@ -51,18 +54,29 @@ pub fn anchor_view(view: &mut View, xf: &ViewXform, screen: Pos2, doc: [f64; 2], } /// Route the canvas buttons for the Zoom tool. Returns true when it consumed the drag (the -/// canvas then handles only the click). -pub fn drag(app: &PhotocraftApp, ctx: &egui::Context, view: &mut View, xf: &ViewXform, b: &Buttons, pointer: Option) -> bool { +/// canvas then handles only the click). `zoom_out` is the canvas's direction for ⌥ held or not +/// (temporary zoom key, Zoom In / Zoom Out mode, latched ⌥). +pub fn drag( + app: &PhotocraftApp, + ctx: &egui::Context, + view: &mut View, + xf: &ViewXform, + b: &Buttons, + pointer: Option, + zoom_out: &dyn Fn(bool) -> bool, +) -> bool { let scrubby = app.ui.tool_options.zoom_scrubby; + let out = zoom_out(ctx.input(|i| i.modifiers.alt)); if b.started { let anchor = ctx.input(|i| i.pointer.press_origin()).filter(|p| xf.rect.contains(*p)).or(pointer); if let Some(anchor) = anchor { - let z = ZoomDrag { anchor, doc: xf.to_doc(anchor), zoom0: view.zoom, rect_to: (!scrubby).then_some(anchor) }; + let z = ZoomDrag { anchor, doc: xf.to_doc(anchor), zoom0: view.zoom, rect_to: (!scrubby).then_some(anchor), out }; ctx.data_mut(|d| d.insert_temp(id(), z)); } } let Some(mut z) = ctx.data(|d| d.get_temp::(id())) else { return b.started || b.dragged || b.stopped }; if let Some(p) = pointer.filter(|_| b.dragged || b.stopped) { + z.out = out; match z.rect_to.as_mut() { Some(to) => *to = p, None => { @@ -79,7 +93,6 @@ pub fn drag(app: &PhotocraftApp, ctx: &egui::Context, view: &mut View, xf: &View if b.stopped { ctx.data_mut(|d| d.remove::(id())); if let Some(to) = z.rect_to { - let out = crate::workspace_ui::sticky_mods(app, ctx.input(|i| i.modifiers)).alt; zoom_to_rect(view, xf, Rect::from_two_pos(z.anchor, to), z.anchor, out, app.ppp); } } @@ -87,7 +100,7 @@ pub fn drag(app: &PhotocraftApp, ctx: &egui::Context, view: &mut View, xf: &View } /// Scrubby Zoom off: zoom so the dragged rectangle fills the canvas (a tiny one steps the zoom -/// at the press point; ⌥ steps out). +/// at the press point; `out` steps out there). fn zoom_to_rect(view: &mut View, xf: &ViewXform, r: Rect, anchor: Pos2, out: bool, ppp: f32) { if out || r.width() < 4.0 || r.height() < 4.0 { let doc = xf.to_doc(anchor); @@ -103,12 +116,19 @@ fn zoom_to_rect(view: &mut View, xf: &ViewXform, r: Rect, anchor: Pos2, out: boo /// Scrubby Zoom off: the zoom rectangle being dragged, as marching ants. pub fn draw(ctx: &egui::Context, painter: &egui::Painter) { - let Some(z) = ctx.data(|d| d.get_temp::(id())) else { return }; - let Some(to) = z.rect_to else { return }; - let r = Rect::from_two_pos(z.anchor, to); + let Some(r) = shown_rect(ctx) else { return }; let r = Rect::from_min_max(r.min.round() + vec2(0.5, 0.5), r.max.round() + vec2(0.5, 0.5)); crate::tool_feedback::draw_ants(painter, &[r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()], true); } +/// The zoom rectangle on screen, if any: none for a drag that steps out at its release. +fn shown_rect(ctx: &egui::Context) -> Option { + let z = ctx.data(|d| d.get_temp::(id()))?; + let to = z.rect_to.filter(|_| !z.out)?; + Some(Rect::from_two_pos(z.anchor, to)) +} + #[cfg(test)] mod tests; +#[cfg(test)] +mod zoom_out_mode_tests; diff --git a/crates/ui-egui/src/tools/zoom_tool/zoom_out_mode_tests.rs b/crates/ui-egui/src/tools/zoom_tool/zoom_out_mode_tests.rs new file mode 100644 index 0000000000..44beb97553 --- /dev/null +++ b/crates/ui-egui/src/tools/zoom_tool/zoom_out_mode_tests.rs @@ -0,0 +1,285 @@ +//! Zoom tool › Zoom In / Zoom Out (#12066): a pair of toggles on the options bar. In Zoom Out mode +//! a click steps out and ⌥+click steps in, the cursor is the "-" magnifier ("+" with ⌥), and a +//! drag with Scrubby Zoom off steps out once at the press point, as ⌥+drag does in Zoom In mode. + +use super::*; +use egui::{Event, Key, Modifiers, PointerButton}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::state::{Tool, ToolOptions}; + +const DOC: [u32; 2] = [400, 300]; + +fn harness(tool: Tool, zoom_in: bool, scrubby: bool) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": DOC[0], "height": DOC[1]})).unwrap(); + // No animation, the clicked point stays under the pointer, and the view is never clamped: + // every step lands on the first frame where the tests can compare it. + app.run("prefs.set", json!({"values": {"general.animatedZoom": false, "tools.zoomClickedPointToCenter": false, "tools.overscroll": true}})).unwrap(); + app.sync_views(); + app.ui.extras.rulers = false; + app.ui.tool = tool; + app.ui.tool_options.zoom_in = zoom_in; + app.ui.tool_options.zoom_scrubby = scrubby; + let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::shortcuts::handle(app, &ctx); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + v.zoom = 1.0; + v.center = [200.0, 150.0]; + v.fit_pending = false; + v.fill_pending = false; + h.run_steps(2); + h +} + +fn xf(h: &Harness<'static, PhotocraftApp>) -> ViewXform { + ViewXform::active(h.state()).unwrap() +} + +/// The platform's modifiers for `Cmd` (⌘ on the Mac, Ctrl elsewhere), as egui-winit reports them. +fn platform(m: Modifiers) -> Modifiers { + let mut out = Modifiers { alt: m.alt, shift: m.shift, ctrl: m.ctrl, ..Default::default() }; + if m.command { + out.command = true; + if cfg!(target_os = "macos") { + out.mac_cmd = true; + } else { + out.ctrl = true; + } + } + out +} + +fn button(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, pressed: bool, m: Modifiers) { + h.event(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: platform(m) }); + h.step(); +} + +fn click(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, m: Modifiers) { + h.event(Event::ModifiersChanged(platform(m))); + h.event(Event::PointerMoved(p)); + h.step(); + button(h, p, true, m); + button(h, p, false, m); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); +} + +/// The view after one click at `p` with `m`, from zoom 1 centred on the document. +fn view_after_click(zoom_in: bool, m: Modifiers) -> (f32, [f32; 2]) { + let mut h = harness(Tool::Zoom, zoom_in, true); + let p = h.state().last_canvas_rect.center() + vec2(90.0, -45.0); + click(&mut h, p, m); + let v = &h.state().ui.views[0]; + (v.zoom, v.center) +} + +#[test] +fn zoom_out_mode_click_steps_out_and_alt_click_steps_in() { + let mut h = harness(Tool::Zoom, false, true); + let p = h.state().last_canvas_rect.center() + vec2(90.0, -45.0); + let doc = xf(&h).to_doc(p); + + click(&mut h, p, Modifiers::NONE); + let out = crate::zoom_levels::step(1.0, -1, DOC); + assert!(out < 1.0); + assert_eq!(h.state().current_zoom(), out, "a click steps one stop out"); + assert!(xf(&h).to_screen(doc[0] as f32, doc[1] as f32).distance(p) < 0.5, "about the clicked point"); + + click(&mut h, p, Modifiers::ALT); + assert_eq!(h.state().current_zoom(), crate::zoom_levels::step(out, 1, DOC), "⌥+click steps one stop in"); + assert!(xf(&h).to_screen(doc[0] as f32, doc[1] as f32).distance(p) < 0.5); + + assert_eq!(h.state().session.documents()[0].history.past_len(), 0, "zooming adds no history state"); +} + +#[test] +fn zoom_out_mode_click_is_zoom_in_mode_alt_click_and_the_reverse() { + assert_eq!(view_after_click(false, Modifiers::NONE), view_after_click(true, Modifiers::ALT)); + assert_eq!(view_after_click(false, Modifiers::ALT), view_after_click(true, Modifiers::NONE)); + // Zoom In mode keeps today's click: in, and out with ⌥. + assert_eq!(view_after_click(true, Modifiers::NONE).0, crate::zoom_levels::step(1.0, 1, DOC)); + assert_eq!(view_after_click(true, Modifiers::ALT).0, crate::zoom_levels::step(1.0, -1, DOC)); +} + +/// A cursor as the platform gets it: the icon, and the bitmap with its size where one is drawn. +type Cursor = (egui::CursorIcon, Option<([u16; 2], std::sync::Arc<[u8]>)>); + +/// The canvas cursor over the image with ⌥ held or not. +fn cursor(h: &mut Harness<'static, PhotocraftApp>, alt: bool) -> Cursor { + let p = h.state().last_canvas_rect.center() + vec2(alt as u8 as f32, 0.0); + h.event(Event::ModifiersChanged(if alt { Modifiers::ALT } else { Modifiers::NONE })); + h.event(Event::PointerMoved(p)); + h.run_steps(2); + let o = &h.output().platform_output; + (o.cursor_icon, o.cursor_image.clone().map(|i| (i.size, i.rgba))) +} + +#[test] +fn zoom_out_mode_cursor_is_the_minus_magnifier_and_plus_with_alt() { + let mut zoom_in = harness(Tool::Zoom, true, true); + let (plus, minus) = (cursor(&mut zoom_in, false), cursor(&mut zoom_in, true)); + assert_ne!(plus, minus, "the two magnifiers differ"); + let mut zoom_out = harness(Tool::Zoom, false, true); + assert_eq!(cursor(&mut zoom_out, false), minus, "Zoom Out mode shows \"-\""); + assert_eq!(cursor(&mut zoom_out, true), plus, "\"+\" while ⌥ is held"); +} + +/// Scrubby Zoom off: a drag from a point to 120 x 80 points away, with `m` held. Returns the +/// view at the release, and whether a zoom rectangle was on screen while dragging. +fn rect_drag(zoom_in: bool, m: Modifiers) -> ((f32, [f32; 2]), bool) { + let mut h = harness(Tool::Zoom, zoom_in, false); + let a = h.state().last_canvas_rect.center() + vec2(-80.0, -50.0); + let doc = xf(&h).to_doc(a); + h.event(Event::ModifiersChanged(platform(m))); + h.event(Event::PointerMoved(a)); + h.step(); + button(&mut h, a, true, m); + let mut shown = false; + for t in [0.25, 0.5, 1.0] { + h.event(Event::PointerMoved(a + vec2(120.0, 80.0) * t)); + h.step(); + shown |= shown_rect(&h.ctx).is_some(); + assert_eq!(h.state().current_zoom(), 1.0, "no zoom while dragging"); + } + button(&mut h, a + vec2(120.0, 80.0), false, m); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + if !zoom_in || m.alt { + assert!(xf(&h).to_screen(doc[0] as f32, doc[1] as f32).distance(a) < 0.5, "anchored at the press point"); + } + let v = &h.state().ui.views[0]; + ((v.zoom, v.center), shown) +} + +#[test] +fn zoom_out_mode_drag_without_scrubby_zoom_steps_out_once_like_alt_drag() { + let (out_mode, out_shown) = rect_drag(false, Modifiers::NONE); + let (alt_drag, alt_shown) = rect_drag(true, Modifiers::ALT); + assert_eq!(out_mode.0, crate::zoom_levels::step(1.0, -1, DOC), "one stop out"); + assert_eq!(out_mode, alt_drag, "the same view as ⌥+drag in Zoom In mode"); + assert!(!out_shown && !alt_shown, "no zoom rectangle for a drag that steps out"); + // Zoom In mode keeps its zoom rectangle. + let (rect, rect_shown) = rect_drag(true, Modifiers::NONE); + assert!(rect_shown); + assert!(rect.0 > 1.0, "the rectangle zooms in: {}", rect.0); +} + +#[test] +fn temporary_zoom_keys_ignore_the_zoom_out_mode() { + let mut h = harness(Tool::Brush, false, true); + let p = h.state().last_canvas_rect.center(); + let key = |h: &mut Harness<'static, PhotocraftApp>, pressed: bool, m: Modifiers| { + let m = platform(m); + h.event(Event::ModifiersChanged(m)); + h.event(Event::Key { key: Key::Space, physical_key: None, pressed, repeat: false, modifiers: m }); + h.step(); + }; + key(&mut h, true, Modifiers::COMMAND); + click(&mut h, p, Modifiers::COMMAND); + key(&mut h, false, Modifiers::COMMAND); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + let z = h.state().current_zoom(); + assert_eq!(z, crate::zoom_levels::step(1.0, 1, DOC), "⌘Space still zooms in"); + key(&mut h, true, Modifiers::COMMAND | Modifiers::ALT); + click(&mut h, p, Modifiers::COMMAND | Modifiers::ALT); + key(&mut h, false, Modifiers::COMMAND | Modifiers::ALT); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + assert_eq!(h.state().current_zoom(), crate::zoom_levels::step(z, -1, DOC), "⌘⌥Space still zooms out"); + assert_eq!(h.state().ui.tool, Tool::Brush); + assert!(!h.state().ui.tool_options.zoom_in); +} + +#[test] +fn held_z_ignores_the_zoom_out_mode() { + let mut h = harness(Tool::Brush, false, true); + let p = h.state().last_canvas_rect.center(); + let z_key = |h: &mut Harness<'static, PhotocraftApp>, pressed: bool| { + h.event(Event::Key { key: Key::Z, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + }; + z_key(&mut h, true); + assert_eq!(h.state().ui.tool, Tool::Zoom, "Z held springs to the Zoom tool"); + click(&mut h, p, Modifiers::NONE); + z_key(&mut h, false); + let z = h.state().current_zoom(); + assert_eq!(z, crate::zoom_levels::step(1.0, 1, DOC), "a click with Z held still zooms in"); + assert_eq!(h.state().ui.tool, Tool::Brush); + z_key(&mut h, true); + click(&mut h, p, Modifiers::ALT); + z_key(&mut h, false); + assert_eq!(h.state().current_zoom(), crate::zoom_levels::step(z, -1, DOC), "⌥+click with Z held still zooms out"); + assert_eq!(h.state().ui.tool, Tool::Brush); + assert!(!h.state().ui.tool_options.zoom_in); +} + +fn options_bar() -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.tool = Tool::Zoom; + let mut ready = false; + let mut h = Harness::builder().with_size(vec2(1400.0, 60.0)).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ready { + crate::theme::install_fonts(ui.ctx()); + crate::theme::apply(ui.ctx(), crate::theme::ThemeKind::ALL[0]); + ready = true; + return; + } + crate::panels::options_bar(app, ui); + }, + app, + ); + h.run_steps(4); + h +} + +fn left(h: &Harness<'static, PhotocraftApp>, label: &str) -> f64 { + h.get_by_label(label).accesskit_node().bounding_box().unwrap_or_else(|| panic!("{label} is laid out")).x0 +} + +#[test] +fn options_bar_has_the_zoom_in_and_zoom_out_pair_before_the_checkboxes() { + let mut h = options_bar(); + assert!(h.state().ui.tool_options.zoom_in, "Zoom In is pressed by default"); + let (zin, zout, fit) = (left(&h, "Zoom In"), left(&h, "Zoom Out"), left(&h, "Resize Windows to Fit")); + assert!(zin < zout && zout < fit, "Zoom In {zin}, Zoom Out {zout}, Resize Windows to Fit {fit}"); + + // Exactly one is pressed: clicking either selects it, clicking it again keeps it. + for (label, zoom_in) in [("Zoom Out", false), ("Zoom Out", false), ("Zoom In", true), ("Zoom In", true), ("Zoom Out", false)] { + h.get_by_label(label).click(); + h.run_steps(2); + assert_eq!(h.state().ui.tool_options.zoom_in, zoom_in, "after clicking {label}"); + } +} + +#[test] +fn zoom_mode_survives_reset_tool_and_defaults_to_zoom_in() { + let mut o = ToolOptions { zoom_in: false, zoom_scrubby: false, ..ToolOptions::default() }; + crate::tool_reset::reset_options(&mut o, Tool::Zoom); + assert!(o.zoom_scrubby, "Reset Tool resets Scrubby Zoom"); + assert!(!o.zoom_in, "but leaves Zoom Out selected"); + + assert!(ToolOptions::default().zoom_in); + let mut saved = serde_json::to_value(ToolOptions { zoom_in: false, ..ToolOptions::default() }).unwrap(); + assert!(!serde_json::from_value::(saved.clone()).unwrap().zoom_in, "the mode is saved"); + // Options saved before the mode existed load as Zoom In; a bad value is an error, not a panic. + saved.as_object_mut().unwrap().remove("zoom_in"); + assert!(serde_json::from_value::(saved.clone()).unwrap().zoom_in); + saved["zoom_in"] = json!("out"); + assert!(serde_json::from_value::(saved).is_err()); +} diff --git a/crates/ui-egui/src/transform_drag_start_tests.rs b/crates/ui-egui/src/transform_drag_start_tests.rs new file mode 100644 index 0000000000..0892e81ccf --- /dev/null +++ b/crates/ui-egui/src/transform_drag_start_tests.rs @@ -0,0 +1,304 @@ +//! Free Transform drag stalls (#11103). +//! +//! - Start: an open box moves from the first pointer move after the press, not once egui +//! recognises a drag (past its click distance), so it never jumps to catch up. Clicks keep their +//! rules: a click on the box moves nothing, a jittery click outside it on the image leaves it as +//! it was, a double-click on it commits. +//! - Mip levels: a level first needed mid-drag is built off the UI thread while the closest finer +//! level already uploaded stands in for it. + +use std::time::{Duration, Instant}; + +use egui::{Color32, ColorImage, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use photocraft_doc::LayerId; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::ViewXform; +use crate::state::Tool; +use crate::transform_tex::PreviewTextures; + +/// An 800 × 600 document at 100 % with a red block (x 100..300, y 100..300) on layer "Paint" and +/// Free Transform open on it. +fn harness() -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.sync_views(); + app.ui.extras.rulers = false; + app.ui.extras.snap = false; + app.ui.tool = Tool::Move; + let paint = LayerId(app.run("layer.new.layer", json!({"name": "Paint"})).unwrap()["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": paint.0})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap(); + app.run("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + // Frames 1/60 s apart, so two clicks make a double-click. + let mut h = Harness::builder().with_size(vec2(1100.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::shortcuts::handle(app, &ctx); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + v.zoom = 1.0; + v.center = [400.0, 300.0]; + v.fit_pending = false; + h.run_steps(2); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap(); + h.run_steps(2); + assert!(h.state().ui.transform.is_some(), "Free Transform is open"); + h +} + +fn view_xform(h: &Harness<'static, PhotocraftApp>) -> ViewXform { + let app = h.state(); + let v = &app.ui.views[0]; + ViewXform { + rect: crate::rulers::content_rect(app, app.last_canvas_rect), + zoom: v.zoom, + center: v.center, + flip: app.ui.view.flip_horizontal, + rotation: v.rotation, + aspect: app.ui.view.display_aspect(), + } +} + +fn screen(h: &Harness<'static, PhotocraftApp>, x: f32, y: f32) -> Pos2 { + view_xform(h).to_screen(x, y) +} + +fn quad(h: &Harness<'static, PhotocraftApp>) -> [[f64; 2]; 4] { + h.state().ui.transform.as_ref().expect("the box is open").quad +} + +fn steps(h: &Harness<'static, PhotocraftApp>) -> usize { + h.state().session.active().unwrap().history.past_len() +} + +fn button(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, down: bool) { + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: down, modifiers: Modifiers::NONE }); + h.run_steps(1); +} + +/// Hover document point `(x, y)`, then press there. +fn press(h: &mut Harness<'static, PhotocraftApp>, x: f32, y: f32) { + let p = screen(h, x, y); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); + button(h, p, true); +} + +/// One frame with the pointer at document point `(x, y)`. +fn move_to(h: &mut Harness<'static, PhotocraftApp>, x: f32, y: f32) { + let p = screen(h, x, y); + h.event(egui::Event::PointerMoved(p)); + h.run_steps(1); +} + +fn release(h: &mut Harness<'static, PhotocraftApp>, x: f32, y: f32) { + let p = screen(h, x, y); + button(h, p, false); + h.run_steps(1); +} + +/// How far the box's top-left corner is from `from`. +fn offset(h: &Harness<'static, PhotocraftApp>, from: [[f64; 2]; 4]) -> [f64; 2] { + let q = quad(h); + [q[0][0] - from[0][0], q[0][1] - from[0][1]] +} + +fn near(a: [f64; 2], b: [f64; 2]) -> bool { + (a[0] - b[0]).abs() < 1e-3 && (a[1] - b[1]).abs() < 1e-3 +} + +#[test] +fn the_box_moves_from_the_first_pointer_move_after_the_press() { + let mut h = harness(); + let start = quad(&h); + press(&mut h, 200.0, 200.0); + assert!(near(offset(&h, start), [0.0, 0.0]), "the press alone moves nothing: {:?}", offset(&h, start)); + // 3 px: inside egui's click distance, so no drag is recognised yet. + move_to(&mut h, 203.0, 200.0); + assert!(near(offset(&h, start), [3.0, 0.0]), "the first move moves the box: {:?}", offset(&h, start)); + move_to(&mut h, 240.0, 220.0); + assert!(near(offset(&h, start), [40.0, 20.0]), "{:?}", offset(&h, start)); + release(&mut h, 240.0, 220.0); + assert!(h.state().ui.transform.is_some(), "a drag doesn't close the box"); + assert!(near(offset(&h, start), [40.0, 20.0]), "{:?}", offset(&h, start)); +} + +#[test] +fn the_box_keeps_up_with_every_move_with_no_jump_when_the_drag_is_recognised() { + let mut h = harness(); + let start = quad(&h); + press(&mut h, 200.0, 200.0); + // One pixel a frame, through egui's click distance and past it. + for dx in 1..=16 { + move_to(&mut h, 200.0 + dx as f32, 200.0); + let got = offset(&h, start); + assert!(near(got, [f64::from(dx), 0.0]), "after a {dx} px move the box is {got:?} off"); + } + release(&mut h, 216.0, 200.0); + assert!(near(offset(&h, start), [16.0, 0.0]), "{:?}", offset(&h, start)); +} + +#[test] +fn a_click_on_the_box_moves_nothing_and_keeps_it_open() { + let mut h = harness(); + let (start, before) = (quad(&h), steps(&h)); + press(&mut h, 200.0, 200.0); + release(&mut h, 200.0, 200.0); + assert!(h.state().ui.transform.is_some()); + assert_eq!(quad(&h), start); + assert_eq!(steps(&h), before); +} + +#[test] +fn a_jittery_click_outside_the_box_on_the_image_leaves_it_as_it_was() { + let mut h = harness(); + let (start, pivot) = (quad(&h), h.state().ui.transform.as_ref().unwrap().pivot); + // Only the Background has pixels here (#11100): the box stays open. + press(&mut h, 600.0, 450.0); + move_to(&mut h, 601.0, 450.0); + release(&mut h, 601.0, 450.0); + let t = h.state().ui.transform.as_ref().expect("the box stays open"); + assert_eq!((t.quad, t.pivot), (start, pivot), "the jitter's turn is put back"); +} + +#[test] +fn a_double_click_on_the_box_still_commits() { + let mut h = harness(); + // Moved 10 px first: committing an unchanged box adds no History step. + let t = h.state_mut().ui.transform.as_mut().unwrap(); + t.quad = t.quad.map(|[x, y]| [x + 10.0, y]); + t.pivot[0] += 10.0; + h.run_steps(1); + let before = steps(&h); + press(&mut h, 200.0, 200.0); + let p = screen(&h, 200.0, 200.0); + button(&mut h, p, false); + button(&mut h, p, true); + button(&mut h, p, false); + h.run_steps(2); + assert!(h.state().ui.transform.is_none(), "committed"); + assert_eq!(steps(&h), before + 1); +} + +/// Waits until `t` has no mip level building off the UI thread. +fn wait_for_builds(t: &PreviewTextures) { + let start = Instant::now(); + while t.is_building() { + assert!(start.elapsed() < Duration::from_secs(10), "a mip level never finished building"); + std::thread::sleep(Duration::from_millis(2)); + } +} + +/// A 5 × 3 white image with background builds on: level 1 is 3 × 2 texels covering 6 × 4 base +/// texels, level 3 is 1 × 1 covering 8 × 8. +fn textures(ctx: &egui::Context) -> PreviewTextures { + let mut t = PreviewTextures::new(ctx, "drag-mips".into(), ColorImage::new([5, 3], vec![Color32::WHITE; 15]), [1.0, 1.0]); + t.set_background_builds(true); + t +} + +#[test] +fn a_mip_level_first_needed_mid_drag_is_built_off_the_ui_thread() { + let ctx = egui::Context::default(); + let t = textures(&ctx); + let (full, full_uv) = t.pick(&ctx, 1.0, 1.0, false); + // Shrunk past ½: level 1 is wanted, level 0 shows until it is ready. + let (shown, uv) = t.pick(&ctx, 0.3, 1.0, false); + assert_eq!((shown, uv), (full, full_uv), "the full-resolution level stands in"); + wait_for_builds(&t); + let (built, uv) = t.pick(&ctx, 0.3, 1.0, false); + assert_ne!(built, full, "level 1 has its own texture once built"); + assert!((uv[0] - 5.0 / 6.0).abs() < 1e-6 && (uv[1] - 3.0 / 4.0).abs() < 1e-6, "{uv:?}"); + assert_eq!(t.pick(&ctx, 0.3, 1.0, false).0, built, "cached"); + ctx.tex_manager().write().take_delta().clear(); +} + +#[test] +fn the_closest_finer_level_stands_in_while_a_level_builds() { + let ctx = egui::Context::default(); + let t = textures(&ctx); + let full = t.pick(&ctx, 1.0, 1.0, false).0; + let _ = t.pick(&ctx, 0.3, 1.0, false); + wait_for_builds(&t); + let level1 = t.pick(&ctx, 0.3, 1.0, false).0; + // log2(1 / 0.1) = 3.3: level 3 is wanted; level 1 is the closest one uploaded. + assert_eq!(t.pick(&ctx, 0.1, 1.0, false).0, level1); + wait_for_builds(&t); + let level3 = t.pick(&ctx, 0.1, 1.0, false).0; + assert!(level3 != level1 && level3 != full, "level 3 has its own texture once built"); + ctx.tex_manager().write().take_delta().clear(); +} + +#[test] +fn a_level_with_nothing_finer_uploaded_for_the_display_is_built_at_once() { + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 2, "height": 1})).unwrap(); + let doc = session.active().unwrap().doc.clone(); + session.color.settings.monitor_profile = "display-p3".into(); + let p3 = session.color.canvas_display(&doc).unwrap(); + assert!(!p3.is_identity()); + let ctx = egui::Context::default(); + let t = textures(&ctx); + let full = t.pick(&ctx, 1.0, 1.0, false).0; + // Only the unconverted level 0 is uploaded: nothing can stand in for this monitor. + let (shown, uv) = t.pick_display(&ctx, 0.3, 1.0, false, Some(&p3)); + assert!(!t.is_building(), "built in this frame"); + assert_ne!(shown, full); + assert!((uv[0] - 5.0 / 6.0).abs() < 1e-6 && (uv[1] - 3.0 / 4.0).abs() < 1e-6, "{uv:?}"); + ctx.tex_manager().write().take_delta().clear(); +} + +/// A box closed while two levels were still building: neither worker converts or uploads its +/// level, though each still holds the preview's shared state (#13382 review). Counted as uploads, +/// not as textures left, which an upload freed again at once would also pass. +#[test] +fn levels_finishing_after_the_box_closed_are_not_uploaded() { + let ctx = egui::Context::default(); + let t = textures(&ctx); + let _ = t.pick(&ctx, 1.0, 1.0, false); + let (gate, done, uploads) = t.worker_hooks(); + let held = gate.lock().unwrap(); + // Levels 1 and 3, each on its own worker, both paused before they check the box is open. + let _ = t.pick(&ctx, 0.3, 1.0, false); + let _ = t.pick(&ctx, 0.1, 1.0, false); + drop(t); + drop(held); + let start = Instant::now(); + while !done() { + assert!(start.elapsed() < Duration::from_secs(10), "the workers finish"); + std::thread::sleep(Duration::from_millis(2)); + } + assert_eq!(uploads.load(std::sync::atomic::Ordering::Relaxed), 0, "nothing uploaded for the closed box"); + ctx.tex_manager().write().take_delta().clear(); +} + +/// The same two workers with the box still open: both upload, so the count above means something. +#[test] +fn levels_finishing_while_the_box_is_open_are_uploaded() { + let ctx = egui::Context::default(); + let t = textures(&ctx); + let _ = t.pick(&ctx, 1.0, 1.0, false); + let (_, done, uploads) = t.worker_hooks(); + let _ = t.pick(&ctx, 0.3, 1.0, false); + let _ = t.pick(&ctx, 0.1, 1.0, false); + let start = Instant::now(); + while !done() { + assert!(start.elapsed() < Duration::from_secs(10), "the workers finish"); + std::thread::sleep(Duration::from_millis(2)); + } + assert_eq!(uploads.load(std::sync::atomic::Ordering::Relaxed), 2); + ctx.tex_manager().write().take_delta().clear(); +} diff --git a/crates/ui-egui/src/transform_type_tests.rs b/crates/ui-egui/src/transform_type_tests.rs index 44c6680a37..290acac66e 100644 --- a/crates/ui-egui/src/transform_type_tests.rs +++ b/crates/ui-egui/src/transform_type_tests.rs @@ -62,6 +62,7 @@ fn type_layers_offer_free_transform_but_not_distort_or_perspective() { sampler_at: None, color: None, inside_selection: false, + point: None, }; assert!(crate::canvas_tool_menu::available(&app, &menu, "edit.freeTransform")); assert!(!crate::canvas_tool_menu::available(&app, &menu, "edit.transform.distort")); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index e07e271ddf..de83de1931 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -46,7 +46,7 @@ pub use color::{ #[cfg(test)] use color::{checker_tile_id, checker_uv}; pub use dropdown::{ - combo_list, dropdown, dropdown_hovered, dropdown_literal, dropdown_wheel_grouped, dropdown_wheel_grouped_enabled, dropdown_wheel_hovered, + combo_list, dropdown, dropdown_enabled, dropdown_hovered, dropdown_literal, dropdown_wheel_grouped, dropdown_wheel_grouped_enabled, dropdown_wheel_hovered, dropdown_with_tooltips, menu_scroll, swatch_popup, }; pub(crate) use fields::compact_wrapping_value_field; @@ -54,7 +54,7 @@ pub(crate) use fields::compact_wrapping_value_field; use fields::{FieldOpts, NUMERIC_INPUT_LIMIT, value_field_in}; pub use fields::{ POPUP_ARROW_W, PopupFieldResponse, VALUE_FIELD_H, compact_value_field, elided_label, elided_label_sensed, popup_value_field, typed_text_parses, - value_field, value_field_named, value_field_whole_alerting, value_field_with_trailing, + value_field, value_field_alerting, value_field_named, value_field_whole, value_field_whole_alerting, value_field_with_trailing, }; pub use label_column::{LABEL_COLUMN_GAP, column_label, column_label_padded, label_column_width}; pub(crate) use panel::body_margin; @@ -74,7 +74,7 @@ pub use text_field::{ INPUT_EVENT_LIMIT, TEXT_FIELD_H, TEXT_FIELD_LIMIT, cap_text_events, focus_first_field, text_field, text_field_ex, text_field_with_trailing, }; pub use units::{ - FieldUnits, fmt_num, fmt_num_prec, fmt_num2, parse_num, set_field_resolution, unit_decimals, unit_of_key, value_field_extent, value_field_int, + FieldUnits, fmt_num, fmt_num_prec, fmt_num2, parse_num, set_field_resolution, unit_decimals, unit_of_key, value_field_extent, value_field_fixed, value_field_int, value_field_len, value_field_prec, value_field_prec_blank, value_field_units, }; diff --git a/crates/ui-egui/src/widgets/dropdown.rs b/crates/ui-egui/src/widgets/dropdown.rs index c79b3af338..96052a4327 100644 --- a/crates/ui-egui/src/widgets/dropdown.rs +++ b/crates/ui-egui/src/widgets/dropdown.rs @@ -15,6 +15,28 @@ pub fn dropdown_literal(ui: &mut Ui, id: &str, name: &str, !chosen.is_empty() } +/// [`dropdown`] whose open list greys the options `enabled` refuses: drawn disabled and never +/// picked, by the pointer or the keys (#12906, the Pen's Pixels mode). +pub fn dropdown_enabled( + ui: &mut Ui, + id: &str, + name: &str, + current: &mut T, + options: &[(T, &str)], + width: f32, + enabled: impl Fn(&T) -> bool, +) -> bool { + let before = current.clone(); + let (chosen, _) = dropdown_with(ui, id, name, current, options, width, false, true, &|_| false, &enabled); + // The arrow keys and type-ahead step onto greyed rows too; landing there keeps the value. + if !enabled(current) { + *current = before; + ui.ctx().request_repaint(); + return false; + } + !chosen.is_empty() +} + /// [`dropdown`], also returning the option under the pointer in its open list (live previews). pub fn dropdown_hovered(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> (bool, Option) { let (chosen, hovered) = dropdown_with(ui, id, name, current, options, width, false, true, &|_| false, &|_| true); diff --git a/crates/ui-egui/src/widgets/fields.rs b/crates/ui-egui/src/widgets/fields.rs index cca8c9bc8c..443d909649 100644 --- a/crates/ui-egui/src/widgets/fields.rs +++ b/crates/ui-egui/src/widgets/fields.rs @@ -2,7 +2,7 @@ use super::panel::{chevron_icon, surface}; use super::scrub::{label_scrub_response, take_label_scrub}; use super::slider::slider; use super::text_field::first_field_id; -use super::units::{FieldUnits, field_resolution_id, fmt_num, fmt_num_prec, fmt_num2, parse_num_in, plain, unit_of_suffix}; +use super::units::{FieldUnits, field_resolution_id, fmt_num, fmt_num_fixed, fmt_num_prec, fmt_num2, parse_num_in, plain, unit_of_suffix}; use super::{Align2, Color32, Rect, Response, Sense, Stroke, StrokeKind, Tokens, Ui, Vec2, pos2, theme, vec2}; /// Monospace numeric field with a dimmed unit suffix, Photoshop style. Drag to scrub. Typed @@ -12,11 +12,19 @@ pub fn value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive value_field_in(ui, value, range, suffix, width, 0.0, FieldOpts::default(), None).0 } +/// A [`value_field`] for a whole number: no decimals, and the arrow keys and a scrub (of the field +/// or of its caption) move it a whole step at a time, whatever its range. A small range such as +/// 1–10 would otherwise scrub in hundredths, which a whole-number setting rounds away (#11765). +pub fn value_field_whole(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, width: f32) -> Response { + value_field_in(ui, value, range, suffix, width, 0.0, FieldOpts { decimals: Some(0), step_from_decimals: true, ..Default::default() }, None).0 +} + /// A [`value_field_named`] for whole numbers that says when a typed value was past `range` /// (Photoshop's "Closest value inserted" alerts, #11938): it stores the closest whole number in /// range, and returns true once the field is left after such a value was typed, so the caller /// shows its alert. While the field has the keyboard it keeps the typed text (a `0` on the way to -/// `05` stays). A scrub past the ends just stops there and says nothing. +/// `05` stays). A scrub, an arrow-key or a wheel step past the ends just stops there and says +/// nothing. pub fn value_field_whole_alerting( ui: &mut Ui, name: &str, @@ -24,9 +32,35 @@ pub fn value_field_whole_alerting( range: std::ops::RangeInclusive, suffix: &str, width: f32, +) -> (Response, bool) { + value_field_alerting_in(ui, name, value, range, suffix, width, true) +} + +/// [`value_field_whole_alerting`] for a field that takes decimals (a corner radius, #13336): a +/// typed value past `range` becomes the closest end, unrounded. +pub fn value_field_alerting(ui: &mut Ui, name: &str, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, width: f32) -> (Response, bool) { + value_field_alerting_in(ui, name, value, range, suffix, width, false) +} + +fn value_field_alerting_in( + ui: &mut Ui, + name: &str, + value: &mut f32, + range: std::ops::RangeInclusive, + suffix: &str, + width: f32, + whole: bool, ) -> (Response, bool) { let (lo, hi) = (*range.start(), *range.end()); - let fit = |v: f32| if v.is_finite() { v.round().clamp(lo, hi) } else { lo }; + let fit = |v: f32| { + if !v.is_finite() { + lo + } else if whole { + v.round().clamp(lo, hi) + } else { + v.clamp(lo, hi) + } + }; *value = fit(*value); let draft_id = ui.make_persistent_id(egui::IdSalt::new(("whole-alerting-typed", name))); // Typed text only while its field still has the keyboard: one left without being drawn (a @@ -36,13 +70,17 @@ pub fn value_field_whole_alerting( let mut typed = draft.map_or(*value, |(typed, _, _)| typed); // The field's own range is wide, so the typed value reaches here unclamped. let r = value_field_named(ui, name, &mut typed, -1.0e9..=1.0e9, suffix, width); + // A step past the ends is no typed value (#13304). Only a step the field took counts: a wheel + // event that moves less than a notch (or not at all) steps nothing, and must not drop what was + // typed. + let stepped = stepped_this_pass(ui.ctx(), r.id); let out_id = r.id.with("out-of-range"); if r.gained_focus() { ui.ctx().data_mut(|d| d.remove_temp::(out_id)); } if r.changed() && typed.is_finite() { *value = fit(typed); - let typing = (r.has_focus() || r.lost_focus()) && ui.ctx().dragged_id().is_none(); + let typing = (r.has_focus() || r.lost_focus()) && ui.ctx().dragged_id().is_none() && !stepped; let out = typing && !(lo..=hi).contains(&typed); ui.ctx().data_mut(|d| d.insert_temp(out_id, out)); if typing && r.has_focus() { @@ -125,6 +163,8 @@ pub(super) struct FieldOpts { /// Show an unset value as an empty field rather than `0` (the Crop tool's free ratio sides, /// #10888). Editing, scrubbing and parsing are unchanged. pub(super) blank_when_zero: bool, + /// Keep the trailing zeros of `decimals` (`50.0`), where every other field drops them. + pub(super) keep_zeros: bool, } /// Arrow-key and drag step for a value field: [`FieldOpts::step_from_decimals`] uses `decimals`; @@ -316,6 +356,8 @@ fn value_field_box( // The text stays selected, as in Photoshop: typing after a step replaces the value. crate::field_tab::select_all(ui.ctx(), resp.id, &if fine { fmt_num2(f64::from(*value)) } else { fmt_num(f64::from(*value)) }); } + let pass = ui.ctx().cumulative_pass_nr(); + ui.data_mut(|d| d.insert_temp(stepped_id(resp.id), pass)); resp.mark_changed(); } if ui.memory(|m| m.has_focus(resp.id)) { @@ -324,6 +366,17 @@ fn value_field_box( (resp, rect) } +/// Where a value field records the pass in which an arrow key or wheel notch last stepped it. +fn stepped_id(field: egui::Id) -> egui::Id { + field.with("stepped-pass") +} + +/// Whether the value field `field` was stepped this pass by an arrow key or a wheel notch. +fn stepped_this_pass(ctx: &egui::Context, field: egui::Id) -> bool { + let pass = ctx.cumulative_pass_nr(); + ctx.data(|d| d.get_temp::(stepped_id(field))) == Some(pass) +} + /// Width of the ▾ that opens a [`popup_value_field`]'s slider, inside the field's box. pub const POPUP_ARROW_W: f32 = 14.0; @@ -467,7 +520,7 @@ fn number_edit( units: crate::numeric_expression::Units, opts: FieldOpts, ) -> Response { - let FieldOpts { decimals, wrap_drag, hold_typed, integer, blank_when_zero, .. } = opts; + let FieldOpts { decimals, wrap_drag, hold_typed, integer, blank_when_zero, keep_zeros, .. } = opts; let (id, ctx) = (ui.next_auto_id(), ui.ctx().clone()); // Focused before the DragValue is drawn, so it gains focus this frame and selects its text. if ui.data_mut(|d| d.remove_temp::(first_field_id())).unwrap_or(false) { @@ -487,6 +540,7 @@ fn number_edit( return String::new(); } let text = match decimals { + Some(d) if keep_zeros => fmt_num_fixed(v, d), Some(d) => fmt_num_prec(v, d), None if fine => fmt_num2(v), None => fmt_num(v), diff --git a/crates/ui-egui/src/widgets/tests.rs b/crates/ui-egui/src/widgets/tests.rs index 6a02717e58..7f7f79cd6d 100644 --- a/crates/ui-egui/src/widgets/tests.rs +++ b/crates/ui-egui/src/widgets/tests.rs @@ -1083,10 +1083,15 @@ fn typed_arithmetic_evaluates() { ("(2+3)*4", 20.0), ("2^3", 8.0), ("10%3", 1.0), + // A decimal comma (#10729). + ("0,3", 0.3), + ("1,5*2", 3.0), + ("−2,25", -2.25), ] { assert_eq!(parse_num(text), Some(want), "{text}"); } - for text in ["", "abc", "5+", "*2", "4/0", "0/0", "1+*2", "(2+3", "1e400"] { + // A comma beside a point, or two decimal separators, is not guessed at. + for text in ["", "abc", "5+", "*2", "4/0", "0/0", "1+*2", "(2+3", "1e400", "1.234,5", "1,2,3"] { assert_eq!(parse_num(text), None, "{text}"); } } @@ -1604,6 +1609,65 @@ fn value_field_applies_typed_arithmetic() { assert_eq!(type_and_press(1.0, "1280/3*2", Enter, true), 853.0); } +/// #10729: a field such as Feather takes a decimal comma, as typed where the comma is the decimal +/// separator. +#[test] +fn value_field_takes_a_decimal_comma() { + use egui::Key::{Enter, Tab}; + assert!((type_and_press(1.0, "0,3", Enter, false) - 0.3).abs() < 1e-6); + assert!((type_and_press(1.0, "2,5", Tab, false) - 2.5).abs() < 1e-6); +} + +/// Review on #10729: only where the system's separator is not the point. Where it is, a typed +/// `1,234` is a thousands group, and reading the comma as a decimal point would be out by a +/// factor of a thousand instead of invalid. Where the separator can't be read the field takes +/// both, as it did before. +#[test] +fn a_decimal_comma_is_read_only_where_the_system_uses_one() { + let parse = |text: &str| super::units::plain(text); + crate::i18n::with_decimal_separator(Some(','), || { + assert_eq!(parse("0,3"), Some(0.3), "a comma system reads the comma"); + }); + crate::i18n::with_decimal_separator(Some('.'), || { + assert_eq!(parse("0,3"), None, "a point system does not: 0,3 stays invalid, not 0.3"); + assert_eq!(parse("1,234"), None, "and a thousands group is not read as 1.234"); + assert_eq!(parse("0.3"), Some(0.3), "its own separator still works"); + }); + crate::i18n::with_decimal_separator(None, || { + assert_eq!(parse("0,3"), Some(0.3), "unknown: both are taken, as zoom_field does"); + assert_eq!(parse("0.3"), Some(0.3)); + }); +} + +/// Review on #10729: each number in an expression decides for itself, so a comma in one operand +/// and a point in another still computes. A single number holding both separators stays invalid +/// rather than being guessed at. +#[test] +fn a_decimal_comma_is_read_per_operand_not_per_entry() { + let close = |got: Option, want: f64, what: &str| { + let v = got.unwrap_or_else(|| panic!("{what}: refused")); + assert!((v - want).abs() < 1e-9, "{what}: {v} is not {want}"); + }; + for sep in [Some(','), None] { + crate::i18n::with_decimal_separator(sep, || { + close(super::parse_num("1,5+2.0"), 3.5, "a comma and a point in one expression"); + close(super::parse_num("2.0+1,5"), 3.5, "and the other way round"); + close(super::parse_num("1,5*2"), 3.0, "a comma against a whole number"); + close(super::parse_num("1,5"), 1.5, "a comma on its own"); + close(super::parse_num("1.5"), 1.5, "a point on its own"); + // One number carrying both is not guessed at, whichever side it sits on. + for text in ["1.234,5", "1,2,3", "1.234,5+1", "1+1.234,5"] { + assert_eq!(super::parse_num(text), None, "{text} stays invalid"); + } + }); + } + // A point system reads no comma at all, in an expression either: 1,5 is a thousands group. + crate::i18n::with_decimal_separator(Some('.'), || { + assert_eq!(super::parse_num("1,5+2.0"), None, "a point system refuses the comma operand"); + close(super::parse_num("1.5+2.0"), 3.5, "its own separator computes"); + }); +} + #[test] fn numbers_drop_trailing_zero() { // #2434: the unit keys map to Photoshop's places, and the shared formatter trims zeros. diff --git a/crates/ui-egui/src/widgets/tone.rs b/crates/ui-egui/src/widgets/tone.rs index 29d5a87cde..2dab176153 100644 --- a/crates/ui-egui/src/widgets/tone.rs +++ b/crates/ui-egui/src/widgets/tone.rs @@ -2,7 +2,8 @@ //! //! The adjustment editors themselves live in `adjust_editors` and the panel in `histogram_panel`; //! this module computes and caches the histograms they draw, in the channels of the adjustment's -//! space (RGB, CMYK ink brightness, Lab), and draws them. +//! space (RGB, CMYK ink brightness, Lab), and draws them. Photoshop keeps the two audiences apart +//! (see [`HistScope`]): the panel follows the selection, the editors' dialogs do not. use std::sync::Arc; @@ -29,11 +30,15 @@ pub struct Histograms { /// Photoshop's histogram cache level of a composite histogram: 1 when every document pixel /// was counted, `n` when a proxy 2^(n-1) times smaller stood in; 0 for a gray plane's. pub level: u32, + /// Every pixel the count kept — with a selection, those the mask covers ≥ ½ — regardless of + /// transparency, at the counted resolution (exact at level 1). This is what the panel's + /// Pixels statistic reports; the bins hold only the visible pixels. + pub pixel_count: u64, } impl Default for Histograms { fn default() -> Self { - Self { tag: 0, ch: Vec::new(), lum: [0; 256], level: 0 } + Self { tag: 0, ch: Vec::new(), lum: [0; 256], level: 0, pixel_count: 0 } } } @@ -61,13 +66,26 @@ pub enum HistSource { UpTo(LayerId), } +/// Whether a histogram counts the whole input or only the selected pixels. Photoshop's Histogram +/// panel follows the selection ("to display histogram data for a portion of the image, first +/// select that portion" — Adobe), while its Levels/Curves/Threshold dialogs show the +/// adjustment's whole input: with a selection active the histogram behind the curve is of the +/// entire image, not just the selected pixels. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum HistScope { + /// The whole input, unmasked by any selection (the tone editors' histograms). + WholeInput, + /// Only the selected pixels, partial coverage counting from ½ up (the Histogram panel). + Selection, +} + /// The whole composited image (the Histogram panel's Entire Image). pub const IMAGE: HistSource = HistSource::BelowLayer(LayerId(u64::MAX)); /// The highest histogram cache level: a proxy 2^7 = 128 times smaller. pub const MAX_CACHE_LEVEL: u32 = 8; -pub(crate) fn tag(source: HistSource, space: ToneSpace) -> u64 { +pub(crate) fn tag(source: HistSource, space: ToneSpace, scope: HistScope, sel: u64) -> u64 { let (k, id) = match source { HistSource::BelowLayer(l) => (1u64, l.0), HistSource::Colors { layer, colors } => (8, layer.0 ^ colors.indices().fold(0u64, |m, k| m | (1u64 << k))), @@ -85,7 +103,39 @@ pub(crate) fn tag(source: HistSource, space: ToneSpace) -> u64 { ToneSpace::Cmyk => 1, ToneSpace::Lab => 2, }; - id.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ (k << 60) ^ (s << 56) + let m = match scope { + HistScope::WholeInput => 0u64, + HistScope::Selection => 1, + }; + id.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ (k << 60) ^ (s << 56) ^ (m << 52) ^ sel.rotate_left(31) +} + +/// Cache identity of the current selection: the mask's default (what tile-less pixels read as), +/// its bounds, and which tiles it is built from. A clone shares its tiles, so an untouched +/// selection keeps its key across edits (the #125 fast path stays); any command that writes a +/// new mask replaces at least the tiles it touched, or the default (e.g. `select.inverse`'s +/// `prune` leaves a tile-less mask), which changes the key. 0 when nothing is selected. +/// +/// Tile identities are pointers, and an allocator can hand a freed tile's address to a new tile +/// (ABA), so two different selections can in principle hash alike. A stale hit needs that +/// collision inside the view-only span the caches promote across — where an identical +/// re-selection re-reads the same pixels anyway, and a different mask must still match the +/// bounds, default and tile set — and selection commands build the new mask before dropping the +/// old one (no free-then-allocate within one command); the default and bounds in the key keep +/// the pointer-less masks (all vs. none) apart regardless. +pub(crate) fn selection_key(doc: &Document) -> u64 { + use std::hash::{Hash, Hasher}; + let Some(m) = doc.selection.as_ref() else { return 0 }; + let mut h = std::collections::hash_map::DefaultHasher::new(); + 1u8.hash(&mut h); + m.default_bytes().hash(&mut h); + let b = m.tile_bounds(); + (b.x0, b.y0, b.x1, b.y1).hash(&mut h); + for (c, t) in m.tiles() { + (c.tx, c.ty).hash(&mut h); + std::ptr::hash(Arc::as_ptr(t), &mut h); + } + h.finish() } /// Shows only the branch of the layer tree holding `id`. Returns whether `id` is in `layers`. @@ -114,15 +164,18 @@ fn hide_above(layers: &mut [Layer], id: LayerId) -> bool { } /// Histograms of `doc` as seen by `source`, in the channels of `space`, at whatever cache level -/// the document's size calls for (up to [`MAX_CACHE_LEVEL`]). -pub fn compute_histograms(doc: &Document, source: HistSource, space: ToneSpace) -> Histograms { - compute_histograms_at(doc, source, space, MAX_CACHE_LEVEL) +/// the document's size calls for (up to [`MAX_CACHE_LEVEL`]). [`HistScope::Selection`] counts +/// only the selected pixels (the Histogram panel; partial coverage counts from ½ up); +/// [`HistScope::WholeInput`] ignores the selection, like Photoshop's Levels/Curves/Threshold +/// dialogs, which show the adjustment's whole input. +pub fn compute_histograms(doc: &Document, source: HistSource, space: ToneSpace, scope: HistScope) -> Histograms { + compute_histograms_at(doc, source, space, scope, MAX_CACHE_LEVEL) } /// [`compute_histograms`] at cache level `max_level` or below (Preferences › Performance › Cache /// Levels; 1 counts every pixel, the Histogram panel's Uncached Refresh). -pub fn compute_histograms_at(doc: &Document, source: HistSource, space: ToneSpace, max_level: u32) -> Histograms { - let mut level = 0; +pub fn compute_histograms_at(doc: &Document, source: HistSource, space: ToneSpace, scope: HistScope, max_level: u32) -> Histograms { + let (mut level, mut pixels) = (0, 0u64); let mut lum = [0u32; 256]; let mut h = vec![ [0u32; 256]; @@ -152,7 +205,7 @@ pub fn compute_histograms_at(doc: &Document, source: HistSource, space: ToneSpac } } // The gray plane itself: its levels are what the curve edits, whatever the document's - // colour mode (#5335). + // colour mode (#5335). A selection does not mask a plane the dialog edits directly. HistSource::Channel { layer, surface } => { let surf = match surface { photocraft_engine::channel_cmds::GraySurface::LayerMask => doc.layer(layer).and_then(|l| l.mask.as_ref()).map(|m| &m.surface), @@ -180,13 +233,14 @@ pub fn compute_histograms_at(doc: &Document, source: HistSource, space: ToneSpac HistSource::BelowLayer(_) | HistSource::Layer(_) | HistSource::UpTo(_) => { // Luminosity rides along as one more histogram after the space's channels. h.push([0; 256]); - level = composite_bins(doc, source, space, max_level, &mut h); + level = composite_bins(doc, source, space, scope, max_level, &mut h, &mut pixels); if let Some(l) = h.pop() { lum = l; } } } - Histograms { tag: tag(source, space), ch: h, lum, level } + let sel_tag = if scope == HistScope::Selection { selection_key(doc) } else { 0 }; + Histograms { tag: tag(source, space, scope, sel_tag), ch: h, lum, level, pixel_count: pixels } } /// The largest document counted pixel by pixel at the automatic cache level. The web build counts @@ -197,7 +251,8 @@ fn exact_limit() -> u64 { /// The cache level a histogram of `doc` is counted at: 1 (every pixel) up to the size a proxy /// would stand in for, else the level whose 2^(n-1) reduction leaves about 768 pixels on the -/// longest side, at most `max_level` (clamped to 1..=[`MAX_CACHE_LEVEL`]). +/// longest side, at most `max_level` (clamped to 1..=[`MAX_CACHE_LEVEL`]). A selection-masked +/// count never uses one (see [`composite_bins`]), so it stays at level 1. pub fn cache_level(doc: &Document, max_level: u32) -> u32 { let longest = doc.size.width.max(doc.size.height); let k = longest / 768; @@ -213,9 +268,13 @@ fn proxy_factor(doc: &Document, level: u32) -> u32 { } /// Bins of the composited image below (`BelowLayer`), up to (`UpTo`) or of one layer alone -/// (`Layer`), in `space`, then luminosity in the last of `h`. Returns the cache level counted -/// (see [`cache_level`]): 1 when every document pixel was counted, higher when a downsampled proxy -/// stood in (like Photoshop's histogram cache levels). +/// (`Layer`), in `space`, then luminosity in the last of `h`, counting the whole input or only +/// the selected pixels per `scope`; `pixels` counts every pixel the count kept, transparent ones +/// included. Returns the cache level counted (see [`cache_level`]): 1 when every document pixel +/// was counted, higher when a downsampled proxy stood in (like Photoshop's histogram cache +/// levels). The proxy only stands in while there is no selection mask to sample (the editors +/// always, the panel while nothing is selected): a masked count samples the mask in document +/// space and stays exact (level 1). /// /// The pixels are counted as they are, never blended: an area-averaged thumbnail invented greys /// that aren't in the image wherever an edge fell inside one of its cells (#6538). Documents up to @@ -223,7 +282,7 @@ fn proxy_factor(doc: &Document, level: u32) -> u32 { /// composited in bands and counted exactly, which costs what the thumbnail did (it reduced the /// same full composite). Larger ones count a nearest-neighbour proxy composite of about the old /// thumbnail's work: it only holds values the layers have. -fn composite_bins(doc: &Document, source: HistSource, space: ToneSpace, max_level: u32, h: &mut [[u32; 256]]) -> u32 { +fn composite_bins(doc: &Document, source: HistSource, space: ToneSpace, scope: HistScope, max_level: u32, h: &mut [[u32; 256]], pixels: &mut u64) -> u32 { let mut d = doc.clone(); match source { HistSource::BelowLayer(hide) => { @@ -239,27 +298,61 @@ fn composite_bins(doc: &Document, source: HistSource, space: ToneSpace, max_leve } HistSource::Channel { .. } | HistSource::Colors { .. } => {} } - let level = cache_level(&d, max_level); + let sel = match scope { + HistScope::WholeInput => None, + HistScope::Selection => d.selection.clone(), + }; + // The proxy stands in only while there is no selection mask to sample: the editors never + // have one, and the panel has none while nothing is selected — either way the count is the + // whole input. A masked count samples the mask in document space and stays exact (level 1). + let level = if sel.is_some() { 1 } else { cache_level(&d, max_level) }; let d = if level > 1 { photocraft_compose::proxy::proxy_document(&d, proxy_factor(&d, level)) } else { d }; - let _ = photocraft_compose::render_bands(&d, d.bounds(), 0, |band| -> Result<(), ()> { + // A selection whose default reads as unselected (marquee/lasso masks) can only pass the + // ≥ ½ threshold inside its content bounds, so composite just that region: a fraction of + // the canvas for a small selection. An inverted selection (default selected) still scans + // the whole canvas; an empty selection counts nothing. + let region = match &sel { + Some(m) if m.default_pixel().iter().all(|&v| v < 0.5) => m.content_bounds().intersect(&d.bounds()), + _ => d.bounds(), + }; + if region.is_empty() { + return level; + } + let _ = photocraft_compose::render_bands(&d, region, 0, |band| -> Result<(), ()> { + // Selection coverage per band pixel (≥ ½ counts), sampled from the mask in document + // coordinates: each band pixel is one document pixel at `rect` + index (a masked + // count is never proxied). + let sel_pass: Option> = sel.as_ref().map(|m| { + let w = band.rect.width().max(1) as usize; + band.px.iter().enumerate().map(|(i, _)| m.sample_channel(band.rect.x0 + (i % w) as i32, band.rect.y0 + (i / w) as i32, 0) >= 0.5).collect() + }); #[cfg(not(target_arch = "wasm32"))] - let part = { + let (part, n) = { use rayon::prelude::*; - band.px - .par_chunks(64 * 1024) - .map(|px| { - let mut part = vec![[0u32; 256]; h.len()]; - count_pixels(px, space, &mut part); - part - }) - .reduce(|| vec![[0u32; 256]; h.len()], add_bins) + let count = |px: &[[f32; 4]], mask: Option<&[bool]>| { + let mut part = vec![[0u32; 256]; h.len()]; + let mut n = 0u64; + count_pixels(px, mask, space, &mut part, &mut n); + (part, n) + }; + match sel_pass.as_deref() { + Some(mask) => band + .px + .par_chunks(64 * 1024) + .zip(mask.par_chunks(64 * 1024)) + .map(|(px, m)| count(px, Some(m))) + .reduce(|| (vec![[0u32; 256]; h.len()], 0), add_bins), + None => band.px.par_chunks(64 * 1024).map(|px| count(px, None)).reduce(|| (vec![[0u32; 256]; h.len()], 0), add_bins), + } }; #[cfg(target_arch = "wasm32")] - let part = { + let (part, n) = { let mut part = vec![[0u32; 256]; h.len()]; - count_pixels(&band.px, space, &mut part); - part + let mut n = 0u64; + count_pixels(&band.px, sel_pass.as_deref(), space, &mut part, &mut n); + (part, n) }; + *pixels = pixels.saturating_add(n); for (dst, src) in h.iter_mut().zip(&part) { for (a, b) in dst.iter_mut().zip(src) { *a = a.saturating_add(*b); @@ -270,14 +363,16 @@ fn composite_bins(doc: &Document, source: HistSource, space: ToneSpace, max_leve level } -/// Bin-wise sum of two sets of histograms (saturating: a hostile canvas can exceed `u32`). +/// Bin- and pixel-wise sum of two partial counts (saturating: a hostile canvas can exceed +/// `u32`). #[cfg(not(target_arch = "wasm32"))] -fn add_bins(mut a: Vec<[u32; 256]>, b: Vec<[u32; 256]>) -> Vec<[u32; 256]> { - for (dst, src) in a.iter_mut().zip(&b) { +fn add_bins(mut a: (Vec<[u32; 256]>, u64), b: (Vec<[u32; 256]>, u64)) -> (Vec<[u32; 256]>, u64) { + for (dst, src) in a.0.iter_mut().zip(&b.0) { for (x, y) in dst.iter_mut().zip(src) { *x = x.saturating_add(*y); } } + a.1 = a.1.saturating_add(b.1); a } @@ -285,8 +380,11 @@ fn add_bins(mut a: Vec<[u32; 256]>, b: Vec<[u32; 256]>) -> Vec<[u32; 256]> { pub const LUMINOSITY: [f32; 3] = [0.30, 0.59, 0.11]; /// Counts straight-alpha composite pixels into `h` (one histogram per channel of `space`, then -/// luminosity when `h` has room for it); transparent pixels are skipped. -fn count_pixels(px: &[[f32; 4]], space: ToneSpace, h: &mut [[u32; 256]]) { +/// luminosity when `h` has room for it); transparent pixels stay out of the bins. `sel`, when +/// given, keeps only the pixels whose mask coverage is ≥ ½ (the Histogram panel's +/// [`HistScope::Selection`]); `n` counts every kept pixel — the transparent ones too, which is +/// what the panel's Pixels statistic reports. +fn count_pixels(px: &[[f32; 4]], sel: Option<&[bool]>, space: ToneSpace, h: &mut [[u32; 256]], n: &mut u64) { let bin = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as usize; let lum_at = match space { ToneSpace::Rgb => 4, @@ -298,7 +396,11 @@ fn count_pixels(px: &[[f32; 4]], space: ToneSpace, h: &mut [[u32; 256]]) { *n = n.saturating_add(1); } }; - for p in px { + for (i, p) in px.iter().enumerate() { + if sel.is_some_and(|s| !s.get(i).copied().unwrap_or(true)) { + continue; + } + *n = n.saturating_add(1); // Skips NaN alpha too. if p[3].is_nan() || p[3] <= 0.0 { continue; @@ -379,11 +481,13 @@ fn gray_bins(surf: &photocraft_raster::Surface, area: photocraft_geom::Rect) -> } /// Cached histograms for a tone editor; recomputed only when something other than the editor's -/// own commits changed the document (see [`keep_after_commit`]). +/// own commits changed the document (see [`keep_after_commit`]). The editors' histograms show the +/// whole input ([`HistScope::WholeInput`]), so a selection change — view-only, no pixels moved — +/// keeps the cache (#125); only the panel's masked histogram tracks the selection. pub fn histograms(app: &mut PhotocraftApp, source: HistSource, space: ToneSpace) -> Arc { let Some(st) = app.session.active() else { return Arc::new(Histograms::default()) }; let (doc_id, rev) = (st.doc.id, st.revision); - let want = tag(source, space); + let want = tag(source, space, HistScope::WholeInput, 0); let layer = match source { HistSource::BelowLayer(l) | HistSource::Layer(l) | HistSource::UpTo(l) => l, HistSource::Channel { layer, .. } | HistSource::Colors { layer, .. } => layer, @@ -398,7 +502,7 @@ pub fn histograms(app: &mut PhotocraftApp, source: HistSource, space: ToneSpace) return h.clone(); } let t0 = crate::gpu_canvas::now_ms(); - let h = Arc::new(compute_histograms(&st.doc, source, space)); + let h = Arc::new(compute_histograms(&st.doc, source, space, HistScope::WholeInput)); app.perf.span("histogram", crate::gpu_canvas::now_ms() - t0); app.tone_hist = Some((doc_id, layer, rev, h.clone())); h @@ -495,7 +599,7 @@ mod tests { s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); // white s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); let st = s.active().unwrap(); - let h = compute_histograms(&st.doc, HistSource::BelowLayer(st.active_layer.unwrap()), ToneSpace::Rgb); + let h = compute_histograms(&st.doc, HistSource::BelowLayer(st.active_layer.unwrap()), ToneSpace::Rgb, HistScope::WholeInput); assert!(h[0][255] > 0 && h[0][0] == 0, "sees the white image, not the inverted result"); assert_eq!(h[9], [0; 256], "out-of-range channels are empty, not a panic"); } @@ -509,10 +613,124 @@ mod tests { s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 32})).unwrap(); s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); let st = s.active().unwrap(); - let h = compute_histograms(&st.doc, HistSource::Layer(bg), ToneSpace::Rgb); + let h = compute_histograms(&st.doc, HistSource::Layer(bg), ToneSpace::Rgb, HistScope::WholeInput); assert!(h[0][255] > 0 && h[0][0] == 0, "the black layer above is hidden"); - assert_eq!(compute_histograms(&st.doc, HistSource::Layer(bg), ToneSpace::Cmyk).ch.len(), 5); - assert_eq!(compute_histograms(&st.doc, HistSource::Layer(bg), ToneSpace::Lab).ch.len(), 3); + assert_eq!(compute_histograms(&st.doc, HistSource::Layer(bg), ToneSpace::Cmyk, HistScope::WholeInput).ch.len(), 5); + assert_eq!(compute_histograms(&st.doc, HistSource::Layer(bg), ToneSpace::Lab, HistScope::WholeInput).ch.len(), 3); + } + + #[test] + fn a_selection_restricts_the_panel_histogram_but_not_the_editors() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); // white background + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 16, "height": 32})).unwrap(); + s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); // left half black + s.execute("select.deselect", json!({})).unwrap(); + let st = s.active().unwrap(); + let whole = compute_histograms(&st.doc, IMAGE, ToneSpace::Rgb, HistScope::WholeInput); + assert!(whole[0][0] > 0 && whole[0][255] > 0, "black and white both count"); + assert_eq!(whole[1].iter().map(|v| *v as u64).sum::(), 32 * 32, "no selection: the whole canvas"); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 16, "height": 32})).unwrap(); + let st = s.active().unwrap(); + let left = compute_histograms(&st.doc, IMAGE, ToneSpace::Rgb, HistScope::Selection); + assert!(left[0][0] > 0 && left[0][255] == 0, "the panel counts only the selected black half"); + assert_eq!(left.pixel_count, 16 * 32, "Pixels counts the selection, transparent or not"); + let editor = compute_histograms(&st.doc, IMAGE, ToneSpace::Rgb, HistScope::WholeInput); + assert!(editor[0][255] > 0, "the editors show the adjustment's whole input (Photoshop)"); + assert_eq!(left[1].iter().map(|v| *v as u64).sum::(), 16 * 32, "Pixels counts the selection"); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 12, "y": 0, "width": 8, "height": 32, "feather": 2})).unwrap(); + let st = s.active().unwrap(); + let soft = compute_histograms(&st.doc, IMAGE, ToneSpace::Rgb, HistScope::Selection); + assert!(soft[0][0] > 0 && soft[0][255] > 0, "a feathered mask keeps its ≥ ½ core on both sides"); + } + + #[test] + fn the_selection_cache_key_tracks_the_selection() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + assert_eq!(selection_key(&s.active().unwrap().doc), 0, "no selection"); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 8, "height": 8})).unwrap(); + let a = s.active().unwrap().doc.clone(); + let k = selection_key(&a); + assert_ne!(k, 0); + assert_eq!(selection_key(&a), k, "a clone keeps the key"); + s.execute("select.rect", json!({"x": 8, "y": 8, "width": 8, "height": 8})).unwrap(); + assert_ne!(selection_key(&s.active().unwrap().doc), k, "a new mask is a new key"); + } + + /// Two masks with no tiles at all differ only in their default (what every pixel reads as): + /// the key must tell an all-selected mask from a none-selected one, or the panel's histogram + /// goes stale between them. + #[test] + fn tile_less_selection_masks_differ_by_their_default() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + let mut doc = s.active().unwrap().doc.as_ref().clone(); + doc.selection = Some(photocraft_raster::Surface::with_default(photocraft_color::PixelFormat::GRAY8, &[1.0])); + let all = selection_key(&doc); + doc.selection = Some(photocraft_raster::Surface::with_default(photocraft_color::PixelFormat::GRAY8, &[0.0])); + let none = selection_key(&doc); + assert_ne!(all, 0); + assert_ne!(none, 0, "a mask selecting nothing is still a selection, not `None`"); + assert_ne!(all, none, "tile-less masks differ by their default"); + } + + /// A tile-less mask that selects nothing (default 0; the engine's marquee deselects instead, + /// but Quick Mask and scripted documents can leave one) composites over an empty region: + /// every bin stays 0. A default-selected mask (inverse of a selection) counts everything. + #[test] + fn a_selection_outside_the_canvas_counts_nothing() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + let mut doc = s.active().unwrap().doc.as_ref().clone(); + doc.selection = Some(photocraft_raster::Surface::with_default(photocraft_color::PixelFormat::GRAY8, &[0.0])); + let h = compute_histograms(&doc, IMAGE, ToneSpace::Rgb, HistScope::Selection); + assert!(h.ch.iter().all(|b| b.iter().all(|&v| v == 0)), "nothing passes the threshold"); + assert_eq!(h.level, 1); + doc.selection = Some(photocraft_raster::Surface::with_default(photocraft_color::PixelFormat::GRAY8, &[1.0])); + let all = compute_histograms(&doc, IMAGE, ToneSpace::Rgb, HistScope::Selection); + assert!(all.ch.iter().all(|b| b.iter().sum::() > 0), "a default-selected mask scans the whole canvas"); + assert_eq!(all.level, 1); + } + + /// Photoshop's Pixels statistic counts the pixels the selection covers, transparent ones + /// included, while the histogram bins keep skipping them: a selection over a transparent + /// canvas must report the selection's size with an empty histogram. + #[test] + fn the_pixels_count_keeps_transparent_selected_pixels() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32, "background": "transparent"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 16, "height": 32})).unwrap(); + let st = s.active().unwrap(); + let h = compute_histograms(&st.doc, IMAGE, ToneSpace::Rgb, HistScope::Selection); + assert!(h.ch.iter().all(|b| b.iter().all(|&v| v == 0)), "nothing visible is selected"); + assert_eq!(h.pixel_count, 16 * 32, "the transparent selected pixels still count"); + } + + /// The key's tile identities are pointers, so two masks may only hash alike if a write kept a + /// tile's pointer while changing its bytes. Commands edit a staged clone whose tiles are + /// shared until written, and a COW write allocates a new tile (`raster` pins that). This test + /// pins the consequence the cache relies on: masks differing only in tile *content* — same + /// default, same bounds, same tile coordinates — get different keys. + #[test] + fn selection_key_distinguishes_content_only_changes() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + let mut doc = s.active().unwrap().doc.as_ref().clone(); + let mut mask = photocraft_raster::Surface::with_default(photocraft_color::PixelFormat::GRAY8, &[0.0]); + mask.try_write_region(photocraft_geom::Rect::new(0, 0, 64, 64), &vec![1.0; 64 * 64]).unwrap(); + doc.selection = Some(mask.clone()); + let before = selection_key(&doc); + // A staged edit writes through the shared tiles: same default, same bounds, same tile + // coordinates, different content in the first quarter only. + let mut staged = doc.clone(); + staged.selection.as_mut().unwrap().try_write_region(photocraft_geom::Rect::new(0, 0, 16, 64), &vec![0.5; 16 * 64]).unwrap(); + let after = selection_key(&staged); + assert_ne!(before, 0); + assert_ne!(after, 0); + assert_ne!(before, after, "a content-only mask change must change the key"); } /// #5335: the Curves histogram of a targeted gray plane describes that plane, not the @@ -537,19 +755,22 @@ mod tests { .unwrap(); let st = s.active().unwrap(); let layer = st.active_layer.unwrap(); - let h = compute_histograms(&st.doc, HistSource::Channel { layer, surface: GraySurface::Alpha(0) }, ToneSpace::Rgb); + let h = compute_histograms(&st.doc, HistSource::Channel { layer, surface: GraySurface::Alpha(0) }, ToneSpace::Rgb, HistScope::WholeInput); assert!(h[0][64] > 0, "a spike at 25% grey, got {:?}", &h[0][0..80]); assert_eq!(h[0][0], 0, "not the black layer beneath"); - let m = compute_histograms(&st.doc, HistSource::Channel { layer, surface: GraySurface::LayerMask }, ToneSpace::Rgb); + let m = compute_histograms(&st.doc, HistSource::Channel { layer, surface: GraySurface::LayerMask }, ToneSpace::Rgb, HistScope::WholeInput); assert!(m[0][0] > 0, "the hidden mask is black"); // Each plane keeps its own cache entry: switching targets recomputes. assert_ne!( - tag(HistSource::Channel { layer, surface: GraySurface::Alpha(0) }, ToneSpace::Rgb), - tag(HistSource::Channel { layer, surface: GraySurface::LayerMask }, ToneSpace::Rgb) + tag(HistSource::Channel { layer, surface: GraySurface::Alpha(0) }, ToneSpace::Rgb, HistScope::WholeInput, 0), + tag(HistSource::Channel { layer, surface: GraySurface::LayerMask }, ToneSpace::Rgb, HistScope::WholeInput, 0) + ); + assert_ne!( + tag(HistSource::Channel { layer, surface: GraySurface::LayerMask }, ToneSpace::Rgb, HistScope::WholeInput, 0), + tag(HistSource::Layer(layer), ToneSpace::Rgb, HistScope::WholeInput, 0) ); - assert_ne!(tag(HistSource::Channel { layer, surface: GraySurface::LayerMask }, ToneSpace::Rgb), tag(HistSource::Layer(layer), ToneSpace::Rgb)); // Every source of one layer has its own tag (the filter mask and the Adjustment - // Composite once shared one). + // Composite once shared one), and so does each scope of one source. let sources = [ HistSource::BelowLayer(layer), HistSource::Layer(layer), @@ -561,9 +782,16 @@ mod tests { ]; for (i, a) in sources.iter().enumerate() { for b in &sources[i + 1..] { - assert_ne!(tag(*a, ToneSpace::Rgb), tag(*b, ToneSpace::Rgb), "{a:?} and {b:?}"); + assert_ne!(tag(*a, ToneSpace::Rgb, HistScope::WholeInput, 0), tag(*b, ToneSpace::Rgb, HistScope::WholeInput, 0), "{a:?} and {b:?}"); } } + for source in sources { + assert_ne!( + tag(source, ToneSpace::Rgb, HistScope::WholeInput, 0), + tag(source, ToneSpace::Rgb, HistScope::Selection, 0), + "{source:?}: each scope has its own tag" + ); + } } /// #6574: bar heights scale linearly to the tallest bin. A 90/10 black/white @@ -610,12 +838,12 @@ mod tests { } fn panel_histograms(s: &photocraft_engine::Session) -> Histograms { - compute_histograms(&s.active().unwrap().doc, HistSource::BelowLayer(LayerId(u64::MAX)), ToneSpace::Rgb) + compute_histograms(&s.active().unwrap().doc, IMAGE, ToneSpace::Rgb, HistScope::Selection) } fn mean(h: &[u32; 256]) -> f64 { let n: u64 = h.iter().map(|v| u64::from(*v)).sum(); - h.iter().enumerate().map(|(i, v)| i as f64 * f64::from(*v)).sum::() / n as f64 + h.iter().enumerate().map(|(i, v)| i as f64 * u64::from(*v) as f64).sum::() / n as f64 } /// #6538: a black/white split counts only black and white, wherever the edge falls (the old @@ -627,6 +855,7 @@ mod tests { let s = split_doc(w, h, split, None); let hist = panel_histograms(&s); assert_eq!(hist.level, 1, "{w}x{h}: every pixel is counted"); + assert_eq!(hist.pixel_count, u64::from(w) * u64::from(h), "{w}x{h}: Pixels counts the whole canvas"); for c in 0..4 { let stray: Vec<(usize, u32)> = hist[c].iter().copied().enumerate().filter(|&(i, v)| v > 0 && i != 0 && i != 255).collect(); assert!(stray.is_empty(), "{w}x{h} split {split}, channel {c}: invented values {stray:?}"); @@ -655,18 +884,31 @@ mod tests { } /// Above the exact-count size a nearest-neighbour proxy stands in (cache level > 1): it is - /// smaller, yet still only holds black and white. + /// smaller, yet still only holds black and white. It stands in whenever no selection mask is + /// sampled — the editors always, the panel while nothing is selected — and a + /// selection-masked count stays exact (level 1). #[test] fn large_split_image_counts_a_nearest_proxy_without_inventing_greys() { let s = split_doc(6000, 3000, 2001, None); - let hist = panel_histograms(&s); - assert!(hist.level > 1, "a proxy stood in, level {}", hist.level); - let n: u64 = hist[0].iter().map(|v| u64::from(*v)).sum(); - assert!(n > 0 && n < 6000 * 3000, "counted {n} proxy pixels"); - for c in 0..4 { - let stray: Vec<(usize, u32)> = hist[c].iter().copied().enumerate().filter(|&(i, v)| v > 0 && i != 0 && i != 255).collect(); - assert!(stray.is_empty(), "channel {c}: invented values {stray:?}"); + let doc = &s.active().unwrap().doc; + for scope in [HistScope::WholeInput, HistScope::Selection] { + let hist = compute_histograms(doc, IMAGE, ToneSpace::Rgb, scope); + assert!(hist.level > 1, "{scope:?}: a proxy stood in, level {}", hist.level); + let n: u64 = hist[0].iter().map(|v| u64::from(*v)).sum(); + assert!(n > 0 && n < 6000 * 3000, "{scope:?}: counted {n} proxy pixels"); + for c in 0..4 { + let stray: Vec<(usize, u32)> = hist[c].iter().copied().enumerate().filter(|&(i, v)| v > 0 && i != 0 && i != 255).collect(); + assert!(stray.is_empty(), "{scope:?} channel {c}: invented values {stray:?}"); + } + assert!((mean(&hist[0]) - 255.0 * 3999.0 / 6000.0).abs() < 1.0, "{scope:?} mean {}", mean(&hist[0])); } - assert!((mean(&hist[0]) - 255.0 * 3999.0 / 6000.0).abs() < 1.0, "mean {}", mean(&hist[0])); + // A selection forces the exact count back on the same large document. + let mut sel = doc.as_ref().clone(); + sel.selection = Some(photocraft_raster::Surface::with_default(photocraft_color::PixelFormat::GRAY8, &[0.0])); + sel.selection.as_mut().unwrap().try_write_region(photocraft_geom::Rect::new(0, 0, 2001, 3000), &vec![1.0; 2001 * 3000]).unwrap(); + let masked = compute_histograms(&sel, IMAGE, ToneSpace::Rgb, HistScope::Selection); + assert_eq!(masked.level, 1, "a masked count samples the mask in document space"); + assert_eq!(masked.pixel_count, 2001 * 3000); + assert_eq!(masked[0][0], 2001 * 3000, "the selected half is black"); } } diff --git a/crates/ui-egui/src/widgets/units.rs b/crates/ui-egui/src/widgets/units.rs index cfc04103b4..fbcf8ef1e0 100644 --- a/crates/ui-egui/src/widgets/units.rs +++ b/crates/ui-egui/src/widgets/units.rs @@ -36,6 +36,12 @@ pub fn value_field_int(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclu value_field_in(ui, value, range, suffix, width, 0.0, FieldOpts { decimals: Some(0), integer: true, ..Default::default() }, None).0 } +/// A [`value_field_prec`] that keeps its trailing zeros (`50.0`, `0.0`): Warp's Bend, H and V, +/// which the reference shows to one decimal (#12503). +pub fn value_field_fixed(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, width: f32, decimals: u32) -> Response { + value_field_in(ui, value, range, suffix, width, 0.0, FieldOpts { decimals: Some(decimals), keep_zeros: true, ..Default::default() }, None).0 +} + /// A [`value_field_prec`] that shows an unset `0` as an empty field (Crop's free ratio sides, /// #10888). Everything else, including scrubbing and typed input, is identical. pub fn value_field_prec_blank(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, width: f32, decimals: u32) -> Response { @@ -129,6 +135,14 @@ pub fn fmt_num_prec(v: f64, decimals: u32) -> String { photocraft_engine::prefs::fmt_decimals(v, decimals as usize) } +/// [`fmt_num_prec`] keeping its trailing zeros: `50.0` at one place. +pub(super) fn fmt_num_fixed(v: f64, decimals: u32) -> String { + let s = fmt_num_prec(v, decimals); + let shown = s.split_once('.').map_or(0, |(_, frac)| frac.len()); + let pad = (decimals as usize).saturating_sub(shown); + if pad == 0 { s } else { format!("{s}{}{}", if shown == 0 { "." } else { "" }, "0".repeat(pad)) } +} + /// Two-decimal variant of [`fmt_num`] for small ranges: `1.05`, `0.78`, `2`. pub fn fmt_num2(v: f64) -> String { fmt_num_prec(v, 2) @@ -157,6 +171,36 @@ pub(super) fn plain(text: &str) -> Option { clean(text).parse().ok() } +/// The typed text without spaces (`1 234`), with a Unicode minus as `-`, and a decimal comma as a +/// point (`0,3`, as typed where the comma is the decimal separator, #10729) when the text has no +/// point; beside a point (`1.234,5`) a comma is left as it is, so the text stays invalid rather +/// than guessed. +/// +/// The comma is read that way only where the system's separator is not the point +/// ([`crate::i18n::decimal_separator`]): where it is, a typed `1,234` is a thousands group, and +/// reading it as `1.234` would be out by a factor of a thousand rather than invalid (review on +/// #10729). Where the separator can't be read (macOS, Linux, the web) the field takes both, as +/// `zoom_field` does. fn clean(text: &str) -> String { - text.chars().filter(|c| !c.is_whitespace()).map(|c| if c == '−' { '-' } else { c }).collect() + let bare: String = text.chars().filter(|c| !c.is_whitespace()).map(|c| if c == '−' { '-' } else { c }).collect(); + if crate::i18n::decimal_separator() == Some('.') { + return bare; + } + // Each number decides for itself, so `1,5+2.0` commits 3.5 rather than being refused for a + // point the other operand carries (CodeRabbit on #10729). A number holding both stays as it + // is, so `1.234,5` is still invalid rather than guessed at. + let mut out = String::with_capacity(bare.len()); + for part in bare.split_inclusive(|c: char| !matches!(c, '0'..='9' | ',' | '.')) { + let (number, tail) = match part.chars().next_back().filter(|c| !matches!(c, '0'..='9' | ',' | '.')) { + Some(end) => (&part[..part.len() - end.len_utf8()], Some(end)), + None => (part, None), + }; + if number.contains(',') && !number.contains('.') { + out.extend(number.chars().map(|c| if c == ',' { '.' } else { c })); + } else { + out.push_str(number); + } + out.extend(tail); + } + out } diff --git a/crates/ui-egui/tests/flatpak_updates.rs b/crates/ui-egui/tests/flatpak_updates.rs new file mode 100644 index 0000000000..d9c1df0b85 --- /dev/null +++ b/crates/ui-egui/tests/flatpak_updates.rs @@ -0,0 +1,27 @@ +//! Release and source Flatpaks must allow release checks and host update helpers. +fn finish_args(manifest: &str) -> Vec<&str> { + manifest + .split("finish-args:") + .nth(1) + .unwrap_or_default() + .lines() + .take_while(|line| line.is_empty() || line.starts_with(' ') || line.starts_with('#')) + .filter_map(|line| line.trim().strip_prefix("- ")) + .map(|arg| arg.trim_matches(['\'', '"'])) + .collect() +} + +#[test] +fn flatpak_update_permissions() { + let manifests = [ + include_str!("../../../packaging/linux/flatpak/ai.storyteller.photocraft.bundle.yml"), + include_str!("../../../packaging/linux/flatpak/ai.storyteller.photocraft.yml"), + ]; + let args = manifests.map(finish_args); + assert_eq!(args[0], args[1], "source and release permissions must agree"); + for permissions in args { + for required in ["--share=network", "--talk-name=org.freedesktop.Flatpak"] { + assert!(permissions.contains(&required), "missing update permission: {required}"); + } + } +} diff --git a/crates/ui-egui/tests/it/background_eraser_reset_tip.rs b/crates/ui-egui/tests/it/background_eraser_reset_tip.rs index f971412bc4..c47e7ce053 100644 --- a/crates/ui-egui/tests/it/background_eraser_reset_tip.rs +++ b/crates/ui-egui/tests/it/background_eraser_reset_tip.rs @@ -96,7 +96,7 @@ fn a_first_use_starts_with_the_tip() { #[test] fn other_tools_and_session_strokes_keep_their_tips() { - for tool in [Tool::Pencil, Tool::Eraser] { + for tool in [Tool::Eraser, Tool::Blur] { let mut a = app(); pick(&mut a, tool); scramble(&mut a); diff --git a/crates/ui-egui/tests/it/brush_reset_defaults.rs b/crates/ui-egui/tests/it/brush_reset_defaults.rs index 0c596a2102..745de07950 100644 --- a/crates/ui-egui/tests/it/brush_reset_defaults.rs +++ b/crates/ui-egui/tests/it/brush_reset_defaults.rs @@ -85,7 +85,7 @@ fn reset_all_tools_from_the_brush_gives_the_other_tools_the_default_tip() { let mut app = app(); pick(&mut app, Tool::Brush); control(&mut app, "ui.menu.invoke", json!({"id": "tool.resetAll", "params": {"confirmed": true}})); - for tool in [Tool::Pencil, Tool::Eraser] { + for tool in [Tool::Eraser, Tool::Blur] { pick(&mut app, tool); assert_eq!(tip(&mut app), DEFAULT_TIP, "{tool:?}"); } @@ -93,7 +93,7 @@ fn reset_all_tools_from_the_brush_gives_the_other_tools_the_default_tip() { #[test] fn other_painting_tools_keep_the_default_reset_tip() { - for tool in [Tool::Pencil, Tool::Eraser] { + for tool in [Tool::Eraser, Tool::Blur] { let mut a = app(); pick(&mut a, tool); scramble(&mut a); diff --git a/crates/ui-egui/tests/it/live_stroke_canvas.rs b/crates/ui-egui/tests/it/live_stroke_canvas.rs index 6942dba8a4..1a6a556095 100644 --- a/crates/ui-egui/tests/it/live_stroke_canvas.rs +++ b/crates/ui-egui/tests/it/live_stroke_canvas.rs @@ -158,13 +158,41 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) { times.sort_by(f64::total_cmp); // Pointer move → stroke rendered → frame built (canvas refresh and upload included). eprintln!("{c:?}: move-to-frame median {:.2} ms, max {:.2} ms", times[times.len() / 2], times[times.len() - 1]); - let drawing = canvas(h); + // The pointer stays held at its last point, as a mouse held still repeats its position. + let held = |h: &mut Harness| { + control(h, "ui.pointer", json!({"events": [{"kind": "move", "x": last.0, "y": last.1, "pressure": pressure(1.0)}]})); + canvas(h) + }; + let drawing = settled(h, held); let gpu = h.state().perf.gpu && !c.flip; control(h, "ui.pointer", json!({"events": [{"kind": "up", "x": last.0, "y": last.1}]})); let done = canvas(h); (before, drawing, done, gpu) } +/// The canvas once the live stroke has stopped changing (#13477). The stroke paints on its own +/// thread and a frame waits only a few real ms for it, so on a slow machine its newest step +/// arrives late, and only a later pointer event shows it; release would then paint the rest. +/// `picture` holds the pointer still and takes a picture, with short real waits between them, +/// until the stroke is idle and three pictures in a row match (matching pixels alone don't prove +/// a slow step has finished): at most `TRIES` times, so a canvas that never settles fails +/// instead of hanging or comparing an unsettled picture. +fn settled(h: &mut Harness, picture: impl Fn(&mut Harness) -> Pixels) -> Pixels { + const TRIES: usize = 80; + let mut last = picture(h); + let mut unchanged = 0; + for _ in 0..TRIES { + std::thread::sleep(std::time::Duration::from_millis(25)); + let next = picture(h); + unchanged = if next == last { unchanged + 1 } else { 0 }; + last = next; + if unchanged >= 2 && !h.state().live_stroke_busy() { + return last; + } + } + panic!("the live stroke did not settle before release"); +} + fn max_diff(a: &[[u8; 4]], b: &[[u8; 4]]) -> u8 { assert_eq!(a.len(), b.len()); a.iter().zip(b).flat_map(|(p, q)| (0..3).map(move |i| p[i].abs_diff(q[i]))).max().unwrap_or(0) diff --git a/crates/vector/src/edit.rs b/crates/vector/src/edit.rs index 30b200216b..83e7acbcc4 100644 --- a/crates/vector/src/edit.rs +++ b/crates/vector/src/edit.rs @@ -211,8 +211,9 @@ fn lerp(a: Point, b: Point, t: f64) -> Point { /// Add Anchor Point: inserts an anchor into the segment leaving `knot` at curve parameter `t` /// (strictly between 0 and 1) and returns the new knot's `[subpath, knot]`. A curve is split at -/// `t` (de Casteljau), so its shape does not change and the new anchor is smooth; on a straight -/// segment (both handles retracted) the new anchor is a corner on the line. +/// `t` (de Casteljau), so its shape does not change and the new anchor is smooth. A straight +/// segment (both handles retracted) is split the same way, with controls (start, start, end, end): +/// the new anchor is smooth with handles, and the neighbours keep their retracted handles. pub fn add_anchor(path: &mut Path, knot: [usize; 2], t: f64) -> Result<[usize; 2], String> { if !(t.is_finite() && t > 0.0 && t < 1.0) { return Err("`t` must be strictly between 0 and 1".into()); @@ -220,18 +221,15 @@ pub fn add_anchor(path: &mut Path, knot: [usize; 2], t: f64) -> Result<[usize; 2 let end = segment_end(path, knot)?; let a = *knot_mut(path, knot)?; let b = *knot_mut(path, end)?; - let new = if straight(&a, &b) { - // Hit testing and hover feedback use the cubic parameter, which is not linear even - // when both handles are retracted. Keep the inserted corner at that same point. - let p = eval(&[a.anchor, a.out_ctrl, b.in_ctrl, b.anchor], t); - Knot::corner(p.x, p.y) - } else { - let (p01, p12, p23) = (lerp(a.anchor, a.out_ctrl, t), lerp(a.out_ctrl, b.in_ctrl, t), lerp(b.in_ctrl, b.anchor, t)); - let (p012, p123) = (lerp(p01, p12, t), lerp(p12, p23, t)); - knot_mut(path, knot)?.out_ctrl = p01; - knot_mut(path, end)?.in_ctrl = p23; - Knot::smooth(lerp(p012, p123, t), p012, p123) - }; + // Straight or not, the segment is split by de Casteljau at `t`. A straight one has controls + // (start, start, end, end), so the neighbours' handles stay retracted and the new anchor is + // smooth with handles a quarter of the segment either side at the middle. The hit position + // stays the cubic point at `t`, which hit testing and hover feedback use. + let (p01, p12, p23) = (lerp(a.anchor, a.out_ctrl, t), lerp(a.out_ctrl, b.in_ctrl, t), lerp(b.in_ctrl, b.anchor, t)); + let (p012, p123) = (lerp(p01, p12, t), lerp(p12, p23, t)); + knot_mut(path, knot)?.out_ctrl = p01; + knot_mut(path, end)?.in_ctrl = p23; + let new = Knot::smooth(lerp(p012, p123, t), p012, p123); let [s, k] = knot; let at = k.checked_add(1).ok_or_else(|| format!("no segment leaves knot {k} of subpath {s}"))?; let sp = path.subpaths.get_mut(s).ok_or_else(|| format!("no subpath {s}"))?; @@ -648,19 +646,23 @@ mod tests { let added = add_anchor(&mut p, knot, hit_t).unwrap(); let inserted = at(&p, added[0], added[1]); assert!(dist(inserted.anchor, clicked) < 1e-9, "t={t}: inserted {:?}, clicked {clicked:?}", inserted.anchor); - assert_eq!(inserted, Knot::corner(clicked.x, clicked.y), "straight segments retain retracted handles"); + assert!(inserted.smooth, "a straight segment is split like any cubic"); + let handles = [inserted.in_ctrl, inserted.out_ctrl]; + assert!(handles.iter().all(|h| dist(*h, inserted.anchor) > 1e-6), "the new anchor has handles"); } } } #[test] - fn adding_to_a_straight_segment_makes_a_corner_on_the_line() { + fn adding_to_a_straight_segment_makes_a_smooth_anchor_on_the_line() { let mut p = tri(); // The closing segment (2 → 0) wraps: the new anchor goes last. assert_eq!(add_anchor(&mut p, [0, 2], 0.5).unwrap(), [0, 3]); - assert_eq!(at(&p, 0, 3), Knot::corner(25.0, 40.0)); + let k = at(&p, 0, 3); + assert!(k.smooth && dist(k.anchor, Point::new(25.0, 40.0)) < 1e-9, "{k:?}"); assert_eq!(add_anchor(&mut p, [0, 0], 0.25).unwrap(), [0, 1]); - assert_eq!(at(&p, 0, 1), Knot::corner(15.625, 0.0)); + let k = at(&p, 0, 1); + assert!(k.smooth && dist(k.anchor, Point::new(15.625, 0.0)) < 1e-9, "{k:?}"); assert_eq!(p.subpaths[0].knots.len(), 5); assert!(p.subpaths[0].closed); } @@ -766,3 +768,7 @@ mod tests { #[cfg(test)] #[path = "edit_delete_last_anchor_tests.rs"] mod edit_delete_last_anchor_tests; + +#[cfg(test)] +#[path = "edit_add_anchor_straight_tests.rs"] +mod edit_add_anchor_straight_tests; diff --git a/crates/vector/src/edit_add_anchor_straight_tests.rs b/crates/vector/src/edit_add_anchor_straight_tests.rs new file mode 100644 index 0000000000..05f1c3d8ec --- /dev/null +++ b/crates/vector/src/edit_add_anchor_straight_tests.rs @@ -0,0 +1,60 @@ +//! Add Anchor Point on a straight segment (#12706): the segment is split like any cubic (controls +//! start, start, end, end), so the new anchor is smooth with handles and the neighbours keep +//! their retracted handles. + +use photocraft_doc::{Path, Subpath}; + +use super::*; + +fn square() -> Path { + Path::new(vec![Subpath::polygon(&[(100.0, 300.0), (300.0, 300.0), (300.0, 500.0), (100.0, 500.0)])]) +} + +fn knot(p: &Path, k: usize) -> Knot { + p.subpaths[0].knots[k] +} + +fn near(a: Point, x: f64, y: f64, tol: f64) -> bool { + (a.x - x).abs() <= tol && (a.y - y).abs() <= tol +} + +#[test] +fn a_closed_square_edge_gets_a_smooth_anchor_with_quarter_length_handles() { + let mut p = square(); + let before = p.subpaths[0].segments()[0]; + let added = add_anchor(&mut p, [0, 0], 0.5).unwrap(); + assert_eq!(added, [0, 1]); + let k = knot(&p, 1); + assert!(near(k.anchor, 200.0, 300.0, 0.5), "anchor {:?}", k.anchor); + assert!(near(k.in_ctrl, 150.0, 300.0, 0.5), "in handle {:?}", k.in_ctrl); + assert!(near(k.out_ctrl, 250.0, 300.0, 0.5), "out handle {:?}", k.out_ctrl); + assert!(k.smooth, "the new anchor is smooth"); + let (first, last) = (knot(&p, 0), knot(&p, 2)); + assert_eq!(first.out_ctrl, first.anchor, "(100,300) keeps its handle retracted"); + assert_eq!(last.in_ctrl, last.anchor, "(300,300) keeps its handle retracted"); + assert_eq!(p.subpaths[0].knots.len(), 5); + // The outline is unchanged: both new cubics lie on the old line, and together cover it. + let segs = p.subpaths[0].segments(); + for i in 0..=100 { + let u = f64::from(i) / 100.0; + for q in [eval(&segs[0], u), eval(&segs[1], u)] { + assert!((q.y - 300.0).abs() < 1e-9 && (100.0..=300.0).contains(&q.x), "off the old line: {q:?}"); + } + } + let (a, b) = (eval(&segs[0], 1.0), eval(&segs[1], 0.0)); + assert!(dist(a, b) < 1e-9 && dist(eval(&segs[0], 0.0), eval(&before, 0.0)) < 1e-9 && dist(eval(&segs[1], 1.0), eval(&before, 1.0)) < 1e-9); +} + +#[test] +fn an_open_line_hit_at_650_gets_the_measured_handles() { + let mut p = Path::new(vec![Subpath::polyline(&[(400.0, 300.0), (700.0, 300.0)])]); + // `t` the way the Add tool finds it: `hit` on the clicked point, which returns the cubic + // parameter (not linear along a retracted segment), then `add_anchor` at that `t`. + let Some(Hit::Segment(seg, t)) = hit(&p, Point::new(650.0, 300.0), 1.0, &[]) else { panic!("no segment hit") }; + let added = add_anchor(&mut p, seg, t).unwrap(); + let k = knot(&p, added[1]); + assert!(near(k.anchor, 650.0, 300.0, 1.0), "anchor {:?}", k.anchor); + assert!(near(k.in_ctrl, 564.0, 300.0, 1.0), "in handle {:?}", k.in_ctrl); + assert!(near(k.out_ctrl, 679.6, 300.0, 1.0), "out handle {:?}", k.out_ctrl); + assert!(k.smooth); +} diff --git a/crates/vector/src/line_arrow_concavity_tests.rs b/crates/vector/src/line_arrow_concavity_tests.rs new file mode 100644 index 0000000000..a860af6480 --- /dev/null +++ b/crates/vector/src/line_arrow_concavity_tests.rs @@ -0,0 +1,138 @@ +//! Arrowhead Concavity is -50..50 % of the head's length, as in Photoshop (#13258): the middle of +//! the head's rear edge bends toward the tip for a positive value and away from it for a negative +//! one, and the shaft ends where that bent edge crosses the shaft's edge. Joining the shaft and +//! the heads into one outline is #13260; these tests check the anchors the reference outline has +//! and that the subpaths (each filled and combined, as the rasterizer does) cover what it covers. + +use super::*; + +/// The measured setup: weight 4, head width 5 and length 10, drag 400,300 to 600,300. +fn arrow(start: bool, end: bool, concavity: f64) -> Path { + arrow_line((400.0, 300.0), (600.0, 300.0), 4.0, start, end, 5.0, 10.0, concavity) +} + +fn anchors(sp: &Subpath) -> Vec<[f64; 2]> { + sp.knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect() +} + +fn close(a: [f64; 2], b: [f64; 2]) -> bool { + (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9 +} + +fn same(sp: &Subpath, want: &[[f64; 2]], what: &str) { + let got = anchors(sp); + assert!(got.len() == want.len() && got.iter().zip(want).all(|(g, w)| close(*g, *w)), "{what}: {got:?} != {want:?}"); +} + +/// Whether `pt` is inside any subpath of `p` (each a polygon, combined as a union). +fn covers(p: &Path, pt: [f64; 2]) -> bool { + p.subpaths.iter().any(|sp| { + let a = anchors(sp); + let mut inside = false; + for i in 0..a.len() { + let (p0, p1) = (a[i], a[(i + 1) % a.len()]); + if (p0[1] > pt[1]) != (p1[1] > pt[1]) && pt[0] < p0[0] + (pt[1] - p0[1]) / (p1[1] - p0[1]) * (p1[0] - p0[0]) { + inside = !inside; + } + } + inside + }) +} + +/// Every anchor of the reference's one-outline result is an anchor of `p`. +fn has_reference_anchors(p: &Path, reference: &[[f64; 2]]) { + let all: Vec<[f64; 2]> = p.subpaths.iter().flat_map(anchors).collect(); + for r in reference { + assert!(all.iter().any(|a| close(*a, *r)), "reference anchor {r:?} missing from {all:?}"); + } +} + +#[test] +fn minus_fifty_bends_the_base_away_from_the_tip_and_the_shaft_ends_where_it_crosses() { + let p = arrow(false, true, -50.0); + assert_eq!(p.subpaths.len(), 2); + same(&p.subpaths[0], &[[400.0, 302.0], [589.0, 302.0], [589.0, 298.0], [400.0, 298.0]], "shaft to 589"); + // Tip, outer corners, and the base's middle 5 px (50 % of 10) behind the base at 590. + same(&p.subpaths[1], &[[600.0, 300.0], [590.0, 302.5], [585.0, 300.0], [590.0, 297.5]], "end head"); + has_reference_anchors(&p, &[[400.0, 302.0], [400.0, 298.0], [589.0, 298.0], [590.0, 297.5], [600.0, 300.0], [590.0, 302.5], [589.0, 302.0]]); +} + +#[test] +fn fifty_bends_both_bases_toward_their_tips_by_five_px() { + let p = arrow(true, true, 50.0); + assert_eq!(p.subpaths.len(), 3); + // The shaft's ends follow the bent bases to their middles, filling the wedge in front of them. + same(&p.subpaths[0], &[[409.0, 302.0], [591.0, 302.0], [595.0, 300.0], [591.0, 298.0], [409.0, 298.0], [405.0, 300.0]], "shaft 409..591"); + same(&p.subpaths[1], &[[400.0, 300.0], [410.0, 302.5], [405.0, 300.0], [410.0, 297.5]], "start head"); + same(&p.subpaths[2], &[[600.0, 300.0], [590.0, 302.5], [595.0, 300.0], [590.0, 297.5]], "end head"); + has_reference_anchors( + &p, + &[ + [409.0, 302.0], + [410.0, 302.5], + [400.0, 300.0], + [410.0, 297.5], + [409.0, 298.0], + [591.0, 298.0], + [590.0, 297.5], + [600.0, 300.0], + [590.0, 302.5], + [591.0, 302.0], + ], + ); +} + +#[test] +fn zero_keeps_a_flat_base_and_the_shaft_ends_at_it() { + let p = arrow(false, true, 0.0); + assert!(close(anchors(&p.subpaths[0])[1], [590.0, 302.0])); + assert!(close(anchors(&p.subpaths[1])[2], [590.0, 300.0])); +} + +#[test] +fn values_past_fifty_draw_as_fifty_so_older_documents_still_open() { + assert_eq!(arrow(true, true, 80.0), arrow(true, true, 50.0)); + assert_eq!(arrow(true, true, 100.0), arrow(true, true, 50.0)); + assert_eq!(arrow(true, true, -90.0), arrow(true, true, -50.0)); + assert_eq!(arrow(true, true, f64::NAN), arrow(true, true, 0.0)); +} + +#[test] +fn a_head_no_wider_than_the_shaft_meets_it_at_the_base_whatever_the_concavity() { + for c in [-50.0, 0.0, 50.0] { + let p = arrow_line((400.0, 300.0), (600.0, 300.0), 6.0, false, true, 5.0, 10.0, c); + assert!(close(anchors(&p.subpaths[0])[1], [590.0, 303.0]), "concavity {c}"); + } +} + +#[test] +fn long_heads_bent_away_never_turn_the_shaft_inside_out() { + for (start, end) in [(true, true), (false, true), (true, false)] { + let p = arrow_line((0.0, 0.0), (20.0, 0.0), 4.0, start, end, 30.0, 50.0, -50.0); + let shaft = anchors(&p.subpaths[0]); + assert!(shaft[0][0] <= shaft[1][0], "{start} {end}: {shaft:?}"); + assert!(p.subpaths.iter().flat_map(anchors).all(|a| a[0].is_finite() && a[1].is_finite())); + } +} + +#[test] +fn a_base_bent_toward_the_tip_leaves_no_hole_and_nothing_past_the_flanks() { + let p = arrow(true, true, 50.0); + // The reference outline has no edge between the shaft's end and the bent base's middle. + for pt in [[593.0, 300.0], [594.5, 300.0], [592.0, 299.0], [407.0, 300.0], [405.5, 300.0], [408.0, 301.0]] { + assert!(covers(&p, pt), "{pt:?} is inside the reference outline"); + } + // Between x 591 and 600 the flanks are inside the shaft's width (298.25 at x 593). + for pt in [[593.0, 298.1], [593.0, 301.9], [407.0, 298.1], [407.0, 301.9]] { + assert!(!covers(&p, pt), "{pt:?} is outside the reference outline"); + } + // Outside the shaft's width, the notch stays open between the base and the flank's corner. + assert!(!covers(&p, [590.6, 297.9])); +} + +#[test] +fn a_head_no_wider_than_the_shaft_still_fills_the_wedge_its_bent_base_leaves() { + let p = arrow_line((400.0, 300.0), (600.0, 300.0), 6.0, false, true, 5.0, 10.0, 50.0); + same(&p.subpaths[0], &[[400.0, 303.0], [590.0, 303.0], [590.0, 302.5], [595.0, 300.0], [590.0, 297.5], [590.0, 297.0], [400.0, 297.0]], "shaft"); + assert!(covers(&p, [592.0, 300.0])); +} diff --git a/crates/vector/src/shapes.rs b/crates/vector/src/shapes.rs index 0b7e65a48d..c6660eccb2 100644 --- a/crates/vector/src/shapes.rs +++ b/crates/vector/src/shapes.rs @@ -99,7 +99,7 @@ pub fn polygon(x: f64, y: f64, w: f64, h: f64, sides: u32, star_ratio: f64) -> P let sides = sides.clamp(3, 100) as usize; let (rx, ry) = (w / 2.0, h / 2.0); let (cx, cy) = (x + rx, y + ry); - let star = star_ratio > 0.0 && star_ratio < 1.0; + let star = is_star(star_ratio); let count = if star { sides * 2 } else { sides }; let pts: Vec<(f64, f64)> = (0..count) .map(|i| { @@ -111,6 +111,27 @@ pub fn polygon(x: f64, y: f64, w: f64, h: f64, sides: u32, star_ratio: f64) -> P Path::new(vec![Subpath::polygon(&pts)]) } +/// Triangle filling the rectangle: the apex at the centre of the top edge, then the bottom right +/// and the bottom left corner. A negative size extends from the origin to the left or up, and the +/// apex stays on top. +pub fn triangle(x: f64, y: f64, w: f64, h: f64) -> Path { + let (x, w) = if w < 0.0 { (x + w, -w) } else { (x, w) }; + let (y, h) = if h < 0.0 { (y + h, -h) } else { (y, h) }; + Path::new(vec![Subpath::polygon(&[(x + w / 2.0, y), (x + w, y + h), (x, y + h)])]) +} + +/// Does `star_ratio` make [`polygon`] a star (inner points between its outer ones)? +fn is_star(star_ratio: f64) -> bool { + star_ratio > 0.0 && star_ratio < 1.0 +} + +/// Does vertex `i` of [`polygon`] with `star_ratio` take the corner radius? Every vertex of a +/// plain polygon; only a star's outer points (even `i`), its inner points stay sharp, as in +/// Photoshop. +pub fn polygon_rounds_vertex(star_ratio: f64, i: usize) -> bool { + !is_star(star_ratio) || i.is_multiple_of(2) +} + /// A rounded vertex: see [`fillet`]. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Fillet { @@ -168,6 +189,12 @@ pub fn fillet(prev: [f64; 2], v: [f64; 2], next: [f64; 2], r: f64) -> Option Path { + round_corners_where(path, r, |_| true) +} + +/// [`round_corners`] for the vertices `rounds` picks by their index in the subpath; the others +/// stay sharp corners. +pub fn round_corners_where(path: Path, r: f64, rounds: impl Fn(usize) -> bool) -> Path { if r.is_nan() || r <= 0.0 { return path; } @@ -183,7 +210,7 @@ pub fn round_corners(path: Path, r: f64) -> Path { let mut knots = Vec::with_capacity(n * 2); for i in 0..n { let (prev, v, next) = (pt(i + n - 1), pt(i), pt(i + 1)); - let Some(f) = fillet(prev, v, next, r) else { + let Some(f) = rounds(i).then(|| fillet(prev, v, next, r)).flatten() else { knots.push(Knot::corner(v[0], v[1])); continue; }; @@ -217,8 +244,10 @@ pub fn line(a: (f64, f64), b: (f64, f64), weight: f64) -> Path { /// 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. +/// `concavity` is -50..50 percent of `length`: the middle of the head's rear edge bends that far +/// toward the tip (positive) or away from it (negative); 0 is flat. Values outside are clamped, so +/// documents saved with the old 0..100 range still open (#13258). The shaft stops where the bent +/// rear edge crosses the shaft's edge, so a concave head stays open 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 { @@ -238,34 +267,41 @@ pub fn arrow_line(a: (f64, f64), b: (f64, f64), weight: f64, start: bool, end: b 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); + // The rear edge's bend toward the tip as a fraction of `size` (negative: away from the tip). + let notch = if concavity.is_finite() { concavity.clamp(-50.0, 50.0) / 100.0 } else { 0.0 }; + let hw = weight.max(0.1) / 2.0; + // The rear edge runs straight from each outer corner to its bent middle, so where it crosses + // the shaft's edge it is bent by `notch` times how far that edge is from the corner; a head no + // wider than the shaft meets it at its base. A head bent away from its tip reaches past its + // base, so the shaft is capped to never turn inside out. + let inner = (size * (1.0 - notch * (1.0 - (hw / half).min(1.0)))).min(if start && end { distance / 2.0 } else { distance }); 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 side = |p: (f64, f64), d: f64| (p.0 + vx * d, p.1 + vy * d); + // A head's tip, both outer corners and its rear edge's bent middle. Positive `sign` points + // toward the tail of the head (away from its tip). + let 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)])); + [tip, side(base, half), rear_middle, side(base, -half)] }; - if start { - head(a, 1.0); - } - if end { - head(b, -1.0); - } + let (start_head, end_head) = (start.then(|| head(a, 1.0)), end.then(|| head(b, -1.0))); + // A base bent toward the tip leaves a wedge between the shaft's end and the head that the + // reference fills: the shaft's end follows the bent base to its middle, so it fills the wedge + // without reaching past the head's flanks. A base bent away lies under the head already. + let wedge = |h: [(f64, f64); 4], from: usize, to: usize| -> Vec<(f64, f64)> { + if notch <= 0.0 { + return Vec::new(); + } + let corners = hw > half; + [(corners, h[from]), (true, h[2]), (corners, h[to])].into_iter().filter_map(|(keep, p)| keep.then_some(p)).collect() + }; + let mut shaft = vec![side(shaft_a, hw), side(shaft_b, hw)]; + shaft.extend(end_head.map_or_else(Vec::new, |h| wedge(h, 1, 3))); + shaft.extend([side(shaft_b, -hw), side(shaft_a, -hw)]); + shaft.extend(start_head.map_or_else(Vec::new, |h| wedge(h, 3, 1))); + let mut pieces = vec![Subpath::polygon(&shaft)]; + pieces.extend([start_head, end_head].into_iter().flatten().map(|h| Subpath::polygon(&h))); // 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()) { @@ -280,8 +316,9 @@ pub fn live_path(s: &LiveShape) -> Path { LiveShape::Rect { rect: [x, y, w, h], radii } => rounded_rect(*x, *y, *w, *h, *radii), LiveShape::Ellipse { rect: [x, y, w, h] } => ellipse(*x, *y, *w, *h), LiveShape::Polygon { rect: [x, y, w, h], sides, star_ratio, corner_radius } => { - round_corners(polygon(*x, *y, *w, *h, *sides, *star_ratio), *corner_radius) + round_corners_where(polygon(*x, *y, *w, *h, *sides, *star_ratio), *corner_radius, |i| polygon_rounds_vertex(*star_ratio, i)) } + LiveShape::Triangle { rect: [x, y, w, h], corner_radius } => round_corners(triangle(*x, *y, *w, *h), *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) @@ -368,9 +405,9 @@ mod tests { } #[test] - fn a_star_rounds_its_inner_vertices_too() { + fn a_star_rounds_its_outer_vertices_only() { let p = live_path(&LiveShape::Polygon { rect: [0.0, 0.0, 200.0, 200.0], sides: 5, star_ratio: 0.5, corner_radius: 6.0 }); - assert_eq!(p.subpaths[0].knots.len(), 20); + assert_eq!(p.subpaths[0].knots.len(), 15); } #[test] @@ -407,6 +444,18 @@ mod tests { } } +#[cfg(test)] +#[path = "star_outer_corner_radius_tests.rs"] +mod star_outer_corner_radius_tests; + +#[cfg(test)] +#[path = "triangle_box_geometry_tests.rs"] +mod triangle_box_geometry_tests; + +#[cfg(test)] +#[path = "line_arrow_concavity_tests.rs"] +mod line_arrow_concavity_tests; + #[cfg(test)] mod line_arrow_6408_tests { use super::*; diff --git a/crates/vector/src/star_outer_corner_radius_tests.rs b/crates/vector/src/star_outer_corner_radius_tests.rs new file mode 100644 index 0000000000..6718498c1a --- /dev/null +++ b/crates/vector/src/star_outer_corner_radius_tests.rs @@ -0,0 +1,61 @@ +//! A rounded star rounds only its outer points; its inner points stay sharp corners, as in +//! Photoshop (#13308). Plain polygons keep rounding every vertex. + +use super::*; + +fn star(corner_radius: f64) -> Path { + live_path(&LiveShape::Polygon { rect: [400.0, 300.0, 200.0, 100.0], sides: 5, star_ratio: 0.5, corner_radius }) +} + +fn has_handles(k: &Knot) -> bool { + k.in_ctrl != k.anchor || k.out_ctrl != k.anchor +} + +#[test] +fn a_rounded_five_point_star_has_two_anchors_per_outer_point_and_sharp_inner_points() { + let knots = &star(10.0).subpaths[0].knots; + assert_eq!(knots.len(), 15); + let sharp = &polygon(400.0, 300.0, 200.0, 100.0, 5, 0.5).subpaths[0].knots; + // Each outer point becomes an arc (two anchors with a handle each), then the inner point + // follows as a corner anchor exactly where the sharp star has it. + for (n, chunk) in knots.chunks(3).enumerate() { + let [from, to, inner] = chunk else { panic!("15 knots in threes") }; + assert!(has_handles(from) && has_handles(to), "outer point {n} is rounded"); + assert!(!has_handles(inner), "inner point {n} is a corner"); + assert_eq!(inner.anchor, sharp[2 * n + 1].anchor, "inner point {n} stays put"); + } + assert_eq!(knots.iter().filter(|k| has_handles(k)).count(), 10); +} + +#[test] +fn an_outer_point_is_rounded_by_the_arc_the_radius_asks_for() { + let knots = &star(10.0).subpaths[0].knots; + let sharp: Vec<[f64; 2]> = polygon(400.0, 300.0, 200.0, 100.0, 5, 0.5).subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); + for n in 0..5 { + let v = 2 * n; + let f = fillet(sharp[(v + 9) % 10], sharp[v], sharp[v + 1], 10.0).unwrap(); + assert_eq!([knots[3 * n].anchor.x, knots[3 * n].anchor.y], f.from, "outer point {n}"); + assert_eq!([knots[3 * n + 1].anchor.x, knots[3 * n + 1].anchor.y], f.to, "outer point {n}"); + } +} + +#[test] +fn a_plain_polygon_still_rounds_every_vertex() { + for star_ratio in [1.0, 0.0, 1.5] { + let p = live_path(&LiveShape::Polygon { rect: [400.0, 300.0, 200.0, 100.0], sides: 5, star_ratio, corner_radius: 10.0 }); + assert_eq!(p, round_corners(polygon(400.0, 300.0, 200.0, 100.0, 5, star_ratio), 10.0), "star ratio {star_ratio}"); + assert_eq!(p.subpaths[0].knots.len(), 10); + assert!(p.subpaths[0].knots.iter().all(has_handles)); + } +} + +#[test] +fn a_star_without_a_radius_stays_sharp() { + assert_eq!(star(0.0), polygon(400.0, 300.0, 200.0, 100.0, 5, 0.5)); +} + +#[test] +fn only_a_stars_outer_vertices_take_the_radius() { + assert!((0..10).all(|i| polygon_rounds_vertex(1.0, i))); + assert_eq!((0..6).map(|i| polygon_rounds_vertex(0.5, i)).collect::>(), [true, false, true, false, true, false]); +} diff --git a/crates/vector/src/trace.rs b/crates/vector/src/trace.rs index 1557af863d..38883d1252 100644 --- a/crates/vector/src/trace.rs +++ b/crates/vector/src/trace.rs @@ -10,8 +10,10 @@ //! Contours are emitted as subpaths: the first combines, the rest *exclude*, which is the //! even-odd area for nested, non-crossing contours regardless of their orientation. //! -//! [`fit_trace`] runs steps 2 and 3 on a freehand pointer trace (the Freeform Pen), open or -//! closed, with a corner window that grows with the tolerance. +//! [`fit_trace`] fits a freehand pointer trace (the Freeform Pen), open or closed, the way the +//! reference application places its anchors: corners only at turns sharper than 80°, then each +//! run segment by segment, every segment as long as one cubic follows the trace, ending on a +//! turning point in x or y (a wave's peak, a circle's top) where one is in reach. use std::collections::HashMap; @@ -190,14 +192,14 @@ fn walk(lp: &[P], i: usize, window: f64, fwd: bool, closed: bool) -> P { lp[cur] } -/// Indices of corner points: where the direction over ±`window` px turns by more than 60°. The -/// ends of an open polyline are never corners. -fn corners(lp: &[P], window: f64, closed: bool) -> Vec { +/// Indices of corner points: where the direction over ±`window` px turns by more than +/// `turn_deg`. The ends of an open polyline are never corners. +fn corners(lp: &[P], window: f64, closed: bool, turn_deg: f64) -> Vec { let n = lp.len(); if n < 3 || !window.is_finite() || lp.iter().any(|p| !p.0.is_finite() || !p.1.is_finite()) { return Vec::new(); } - let cos_thresh = (60f64).to_radians().cos(); + let cos_thresh = turn_deg.to_radians().cos(); let turn: Vec = (0..n) .map(|i| { if !closed && (i == 0 || i + 1 == n) { @@ -280,7 +282,7 @@ fn fit_closed(lp: &[P], tol: f64, window: f64) -> Subpath { if n < 3 || lp.iter().any(|p| !p.0.is_finite() || !p.1.is_finite()) { return Subpath { closed: true, knots: Vec::new(), op: PathOp::Combine }; } - let cs = corners(lp, window, true); + let cs = corners(lp, window, true, MASK_CORNER_TURN); let mut segs: Vec<[P; 4]> = Vec::new(); let mut corner_at_start: Vec = Vec::new(); if cs.is_empty() { @@ -329,9 +331,10 @@ pub const MAX_TRACE_POINTS: usize = 4096; /// Fits a freehand pointer trace (the Freeform Pen's drag) with cubic Béziers that stay within /// `tolerance` px of every sample: Photoshop's Curve Fit, clamped to 0.1–100 px (2 px when not -/// finite). Turns sharper than 60° over ±2 × `tolerance` become corner anchors, the other inner -/// anchors are smooth. A `closed` trace becomes a closed subpath. Non-finite samples are skipped; -/// `None` when fewer than two distinct points remain (three when `closed`). +/// finite). Turns sharper than 80° over ±2 × `tolerance` become corner anchors; the other inner +/// anchors are smooth and sit on the trace's turning points in x and y where they can. A `closed` +/// trace becomes a closed subpath whose release point stays an anchor. Non-finite samples are +/// skipped; `None` when fewer than two distinct points remain (three when `closed`). pub fn fit_trace(points: &[[f64; 2]], tolerance: f64, closed: bool) -> Option { let tol = if tolerance.is_finite() { tolerance.clamp(0.1, 100.0) } else { 2.0 }; let window = (2.0 * tol).max(1.5); @@ -359,16 +362,64 @@ pub fn fit_trace(points: &[[f64; 2]], tolerance: f64, closed: bool) -> Option 3 && lp.last().zip(lp.first()).is_some_and(|(a, b)| len(sub(*a, *b)) < min_step) { lp.pop(); } - return (lp.len() >= 3).then(|| fit_closed(&lp, tol, window)); + return (lp.len() >= 3).then(|| close_trace(&lp, fit_open(&lp, tol, window), window)); } (lp.len() >= 2).then(|| fit_open(&lp, tol, window)) } +/// Corners of [`trace_mask`]'s contours: turns sharper than this many degrees. +const MASK_CORNER_TURN: f64 = 60.0; + +/// Corners of a freehand trace: turns sharper than this many degrees. The reference application +/// rounds a 67° vee with two smooth anchors (#12838); a right angle stays a corner. +const FREEFORM_CORNER_TURN: f64 = 80.0; + +/// Most a freehand segment turns, in degrees per px of Curve Fit, up to [`MAX_SEGMENT_TURN`]. A +/// smooth stroke fits within any Curve Fit with few anchors, yet the reference application adds +/// anchors as Curve Fit goes down (its 324° arc: 12 segments at 0.5 px, 5 at 1 px, 3 at 2 px, +/// #12838). 75° per px reaches the cap at the default 2 px. +const SEGMENT_TURN_PER_PX: f64 = 75.0; + +/// Most a freehand segment turns, in degrees: a longer arc gets another anchor. A 180° arc fits +/// one cubic within 2 px, but the reference application gives a whole circle five anchors and +/// 324° of it four (#12838). +const MAX_SEGMENT_TURN: f64 = 150.0; + +/// Closes an open fit of a closed trace: the release point stays an anchor, and a segment joins it +/// to the first one, smooth unless the trace has a corner there. +fn close_trace(lp: &[P], mut sp: Subpath, window: f64) -> Subpath { + sp.closed = true; + let n = lp.len(); + let seam = corners(lp, window, true, FREEFORM_CORNER_TURN); + let corner = seam.first() == Some(&0) || seam.last() == Some(&(n - 1)); + let m = sp.knots.len(); + let (Some(first), Some(last)) = (sp.knots.first().copied(), sp.knots.last().copied()) else { return sp }; + if m < 2 { + return sp; + } + let (f, l) = ((first.anchor.x, first.anchor.y), (last.anchor.x, last.anchor.y)); + let third = len(sub(f, l)) / 3.0; + let (t_out, t_in) = if corner { + (norm(sub(f, l)), norm(sub(f, l))) + } else { + // Leave the release point as the trace arrived at it, reach the start as the trace left it. + let arrive = norm(sub(l, (last.in_ctrl.x, last.in_ctrl.y))); + let leave = norm(sub((first.out_ctrl.x, first.out_ctrl.y), f)); + (if len(arrive) > 0.0 { arrive } else { norm(sub(l, lp[n - 2])) }, if len(leave) > 0.0 { leave } else { norm(sub(lp[1], f)) }) + }; + let pt = |p: P| Point::new(p.0, p.1); + sp.knots[m - 1].out_ctrl = pt(add(l, mul(t_out, third))); + sp.knots[m - 1].smooth = !corner; + sp.knots[0].in_ctrl = pt(sub(f, mul(t_in, third))); + sp.knots[0].smooth = !corner; + sp +} + /// Fits an open polyline with cubic Béziers, one run between consecutive corners at a time. fn fit_open(lp: &[P], tol: f64, window: f64) -> Subpath { let n = lp.len(); let mut cuts = vec![0]; - cuts.extend(corners(lp, window, false)); + cuts.extend(corners(lp, window, false, FREEFORM_CORNER_TURN)); cuts.push(n - 1); cuts.dedup(); let mut segs: Vec<[P; 4]> = Vec::new(); @@ -387,11 +438,7 @@ fn fit_open(lp: &[P], tol: f64, window: f64) -> Subpath { let third = mul(sub(b, a), 1.0 / 3.0); segs.push([a, add(a, third), sub(b, third), b]); } else { - // End tangents over a stretch of the trace, not the first jittery sample. - let reach = (2.0 * window).min(len(sub(b, a)) / 3.0).max(window); - let t1 = norm(sub(walk(pts, 0, reach, true, false), a)); - let t2 = norm(sub(walk(pts, m - 1, reach, false, false), b)); - fit_cubic(pts, t1, t2, tol * tol, &mut segs, 0); + fit_run(pts, tol, window, &mut segs); } corner_at_start.extend((before..segs.len()).map(|k| k == before)); } @@ -407,6 +454,234 @@ fn fit_open(lp: &[P], tol: f64, window: f64) -> Subpath { Subpath { closed: false, knots, op: PathOp::Combine } } +/// Fits one freehand run (no corner inside) from its first sample to its last, a segment at a +/// time: each reaches as far along the trace as one cubic stays within `tol` and turns at most +/// [`SEGMENT_TURN_PER_PX`] × `tol` (up to [`MAX_SEGMENT_TURN`]), and ends on the first turning +/// point of the trace in x or y inside that reach (a wave's peak, a circle's top) when there is +/// one, as the reference application places its anchors (#12838); with the next turning point +/// just out of reach, halfway to it. Consecutive segments share their tangent, so inner anchors +/// are smooth. +fn fit_run(pts: &[P], tol: f64, window: f64, out: &mut Vec<[P; 4]>) { + let m = pts.len(); + if m < 2 { + return; + } + let max_turn = (SEGMENT_TURN_PER_PX * tol).min(MAX_SEGMENT_TURN); + let turns = turning_points(pts, tol); + let arc: Vec = pts + .iter() + .scan((0.0, pts[0]), |(acc, prev), &q| { + *acc += len(sub(q, *prev)); + *prev = q; + Some(*acc) + }) + .collect(); + // The first segment leaves as the trace does; the others continue the one before. + let mut t1: Option

= None; + // An anchor on a turning point leaves a segment of at least this length behind it. + let min_gap = 3.0 * window; + let mut a = 0; + while a + 1 < m { + let fit = |b: usize| fit_piece(pts.get(a..=b)?, t1, tol, max_turn); + // Farthest end that fits: doubling steps, then halving the gap to the first failure. The + // error does not always grow with the length (a few samples can fit worse than more), so + // a failed step looks one step further before it stops the doubling. + let mut good = a + 1; + let mut bad = m; + let mut step = 2; + while bad == m { + let b = (a + step).min(m - 1); + if b <= good { + break; + } + let ahead = (a + step.saturating_mul(2)).min(m - 1); + if fit(b).is_some() { + good = b; + } else if ahead > b && fit(ahead).is_some() { + good = ahead; + step = step.saturating_mul(2); + } else { + bad = b; + continue; + } + if good == m - 1 { + break; + } + step = step.saturating_mul(2); + } + while bad < m && bad - good > 1 { + let mid = good + (bad - good) / 2; + if fit(mid).is_some() { + good = mid; + } else { + bad = mid; + } + } + let end = if good + 1 == m { + good + } else { + let mut ahead = turns.iter().copied().filter(|&t| t > a && arc[t] - arc[a] >= min_gap); + let inside = ahead.clone().take_while(|&t| t <= good).take(4).find(|&t| fit(t).is_some()); + // A turning point within two reaches: halfway there, so no sliver is left before it. + let halfway = ahead.find(|&t| t > good).filter(|&t| arc[t] - arc[a] <= 2.0 * (arc[good] - arc[a])).and_then(|t| { + let mid = arc.partition_point(|&s| s < (arc[a] + arc[t]) / 2.0).clamp(a + 1, good); + fit(mid).map(|_| mid) + }); + inside.or(halfway).unwrap_or(good) + }; + // Two samples always fit; the chord stands in should a degenerate piece not. + let seg = fit(end).unwrap_or_else(|| thirds(pts[a], pts[end], t1)); + let into = sub(seg[3], seg[2]); + t1 = Some(if len(into) > 1e-12 { norm(into) } else { norm(sub(seg[3], seg[0])) }); + out.push(seg); + a = end; + } +} + +/// Indices where the trace turns back in x or in y by more than `tol` (a wave's peaks, a circle's +/// top, bottom and sides), in order. Jitter smaller than `tol` makes none. +fn turning_points(pts: &[P], tol: f64) -> Vec { + let mut out = Vec::new(); + for axis in 0..2 { + let v = |i: usize| if axis == 0 { pts[i].0 } else { pts[i].1 }; + // Direction of travel along the axis: 0 until the trace has moved by more than `tol`. + let mut dir = 0i8; + let (mut hi, mut lo) = (0usize, 0usize); + for i in 1..pts.len() { + if v(i) >= v(hi) { + hi = i; + } + if v(i) <= v(lo) { + lo = i; + } + if dir >= 0 && v(i) < v(hi) - tol { + if dir > 0 { + out.push(hi); + } + dir = -1; + lo = i; + } else if dir <= 0 && v(i) > v(lo) + tol { + if dir < 0 { + out.push(lo); + } + dir = 1; + hi = i; + } + } + } + out.sort_unstable(); + out.dedup(); + out +} + +/// One cubic from the first sample of `pts` to the last, leaving along `t1` when given, that stays +/// within `tol` of every sample and turns at most `max_turn` degrees. +fn fit_piece(pts: &[P], t1: Option

, tol: f64, max_turn: f64) -> Option<[P; 4]> { + let n = pts.len(); + if n < 2 { + return None; + } + let (p0, p3) = (pts[0], pts[n - 1]); + if n == 2 { + return Some(thirds(p0, p3, t1)); + } + let seg = len(sub(p3, p0)); + // A handle longer than the chord loops (a few samples leave least squares free to); even a + // 150° arc's handles are about half its chord. + let tame = |b: Option<[P; 4]>| match b { + Some(b) if len(sub(b[1], b[0])) <= seg && len(sub(b[2], b[3])) <= seg => b, + _ => thirds(p0, p3, t1), + }; + let err2 = tol * tol; + let mut u = chord_params(pts); + let mut b = tame(generate_free(pts, &u, t1)); + let mut e = max_error(pts, &b, &u).0; + for _ in 0..6 { + if e <= err2 { + break; + } + u = reparam(pts, &u, &b); + b = tame(generate_free(pts, &u, t1)); + e = max_error(pts, &b, &u).0; + } + (e <= err2 && turn_deg(&b) <= max_turn).then_some(b) +} + +/// A cubic from `p0` to `p3` with handles a third of the chord: leaving along `t1` when given, +/// otherwise along the chord, and arriving along the chord. +fn thirds(p0: P, p3: P, t1: Option

) -> [P; 4] { + let chord = sub(p3, p0); + let d = len(chord) / 3.0; + let c = norm(chord); + [p0, add(p0, mul(t1.unwrap_or(c), d)), sub(p3, mul(c, d)), p3] +} + +/// Least-squares control points through `pts` at parameters `u`. The second handle is free, so +/// how the piece arrives at its end comes from the whole piece, not from a direction estimated +/// from a few jittery samples there; the first lies along `t1` when given (a smooth join to the +/// segment before), and is free too otherwise. `None` when the samples cannot pin them down. +fn generate_free(pts: &[P], u: &[f64], t1: Option

) -> Option<[P; 4]> { + let (p0, p3) = (*pts.first()?, *pts.last()?); + let (mut a11, mut a12, mut a22) = (0.0, 0.0, 0.0); + let (mut r1, mut r2) = ((0.0, 0.0), (0.0, 0.0)); + for (q, &t) in pts.iter().zip(u) { + let mt = 1.0 - t; + let (b0, b1, b2, b3) = (mt * mt * mt, 3.0 * mt * mt * t, 3.0 * mt * t * t, t * t * t); + let res = sub(*q, add(mul(p0, b0), mul(p3, b3))); + (a11, a12, a22) = (a11 + b1 * b1, a12 + b1 * b2, a22 + b2 * b2); + r1 = add(r1, mul(res, b1)); + r2 = add(r2, mul(res, b2)); + } + if let ([_, q, _], [_, s, _], None) = (pts, u, t1) { + // One inner sample cannot pin down two free handles: the parabola through all three. + let ms = 1.0 - s; + let k = 2.0 * s * ms; + if k <= 1e-9 { + return None; + } + let c = mul(sub(*q, add(mul(p0, ms * ms), mul(p3, s * s))), 1.0 / k); + return Some([p0, add(p0, mul(sub(c, p0), 2.0 / 3.0)), add(p3, mul(sub(c, p3), 2.0 / 3.0)), p3]); + } + // b1·P1 + b2·P2 ≈ res, by least squares. + let det = a11 * a22 - a12 * a12; + if !det.is_finite() || det <= 1e-12 * a11 * a22 { + return None; + } + let Some(t) = t1 else { + let p1 = mul(sub(mul(r1, a22), mul(r2, a12)), 1.0 / det); + let p2 = mul(sub(mul(r2, a11), mul(r1, a12)), 1.0 / det); + return Some([p0, p1, p2, p3]); + }; + // P1 = P0 + α·t: solve for α and P2. + let (r1, r2) = (sub(r1, mul(p0, a11)), sub(r2, mul(p0, a12))); + let alpha = (dot(t, r1) * a22 - a12 * dot(t, r2)) / det; + if !alpha.is_finite() { + return None; + } + // A handle pointing back would cusp: the shortest that keeps the join smooth instead. + let alpha = alpha.max(1e-3 * len(sub(p3, p0))); + let p2 = mul(sub(r2, mul(t, a12 * alpha)), 1.0 / a22); + Some([p0, add(p0, mul(t, alpha)), p2, p3]) +} + +/// How far a cubic's direction turns along it, in degrees (both ways add up). +fn turn_deg(b: &[P; 4]) -> f64 { + const STEPS: usize = 32; + let mut total = 0.0; + let mut prev: Option

= None; + for k in 0..=STEPS { + let d = bezier_d1(b, k as f64 / STEPS as f64); + if len(d) < 1e-9 { + continue; + } + if let Some(p) = prev { + total += (p.0 * d.1 - p.1 * d.0).atan2(dot(p, d)).abs(); + } + prev = Some(d); + } + total.to_degrees() +} + /// Distance from `q` to the segment `a`–`b`. fn segment_distance(q: P, a: P, b: P) -> f64 { let ab = sub(b, a); @@ -662,7 +937,7 @@ mod tests { #[test] fn corners_have_bounded_work_for_many_tiny_segments() { let points: Vec

= (0..20_000).map(|i| (i as f64 * 0.01, if i % 2 == 0 { 0.0 } else { 1e-5 })).collect(); - let selected = corners(&points, 100.0, false); + let selected = corners(&points, 100.0, false, MASK_CORNER_TURN); assert!(selected.len() <= points.len()); } @@ -694,3 +969,7 @@ mod tests { } } } + +#[cfg(test)] +#[path = "trace_freeform_anchor_tests.rs"] +mod trace_freeform_anchor_tests; diff --git a/crates/vector/src/trace_freeform_anchor_tests.rs b/crates/vector/src/trace_freeform_anchor_tests.rs new file mode 100644 index 0000000000..83105442d6 --- /dev/null +++ b/crates/vector/src/trace_freeform_anchor_tests.rs @@ -0,0 +1,147 @@ +//! Freeform Pen anchors against the reference application's sample strokes (#12838): mouse moves +//! in document coordinates, fitted at Curve Fit 2 px unless said otherwise. + +use std::f64::consts::TAU; + +use super::*; + +/// (100,400) to (500,400) in 4 px steps. +fn line() -> Vec<[f64; 2]> { + (0..=100).map(|i| [100.0 + 4.0 * i as f64, 400.0]).collect() +} + +/// x from 100 to 500 in 4 px steps, y = 400 + 60·sin(2π(x − 100)/200): two periods. +fn sine() -> Vec<[f64; 2]> { + (0..=100).map(|i| 100.0 + 4.0 * i as f64).map(|x| [x, 400.0 + 60.0 * ((x - 100.0) / 200.0 * TAU).sin()]).collect() +} + +/// Centre (600,300), radius 100, `steps` of 60 around from (700,300): 60 is the whole circle +/// back to the start, 54 the open one. +fn circle(steps: usize) -> Vec<[f64; 2]> { + (0..=steps).map(|i| i as f64 * TAU / 60.0).map(|a| [600.0 + 100.0 * a.cos(), 300.0 + 100.0 * a.sin()]).collect() +} + +/// (100,450) to (250,550) to (400,450), 45 steps a leg. +fn vee() -> Vec<[f64; 2]> { + let legs = [[100.0, 450.0], [250.0, 550.0], [400.0, 450.0]]; + legs.windows(2) + .flat_map(|w| (0..45).map(move |k| k as f64 / 45.0).map(move |t| [w[0][0] + (w[1][0] - w[0][0]) * t, w[0][1] + (w[1][1] - w[0][1]) * t])) + .chain([legs[2]]) + .collect() +} + +/// The five strokes, with whether the drag ends on its start (closes). +fn strokes() -> [(&'static str, Vec<[f64; 2]>, bool); 5] { + [("line", line(), false), ("sine", sine(), false), ("circle", circle(60), true), ("circle-open", circle(54), false), ("vee", vee(), false)] +} + +/// The stroke as given and on the whole pixels a mouse delivers at 100 % zoom. +fn as_given_and_in_pixels(points: Vec<[f64; 2]>) -> [Vec<[f64; 2]>; 2] { + let pixels = points.iter().map(|p| [p[0].round(), p[1].round()]).collect(); + [points, pixels] +} + +fn fit(points: &[[f64; 2]], curve_fit: f64, closed: bool) -> Subpath { + let sp = fit_trace(points, curve_fit, closed); + assert!(sp.is_some(), "the stroke fits"); + sp.unwrap_or_else(|| Subpath { closed, knots: Vec::new(), op: PathOp::Combine }) +} + +fn anchors(sp: &Subpath) -> Vec<[f64; 2]> { + sp.knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect() +} + +/// Largest distance from a sample to the fitted subpath (each segment densely sampled). +fn max_deviation(sp: &Subpath, samples: &[[f64; 2]]) -> f64 { + let curve: Vec

= sp + .segments() + .iter() + .flat_map(|s| { + let b = [(s[0].x, s[0].y), (s[1].x, s[1].y), (s[2].x, s[2].y), (s[3].x, s[3].y)]; + (0..=1000).map(move |k| bezier(&b, k as f64 / 1000.0)) + }) + .collect(); + samples.iter().map(|q| curve.iter().map(|c| len(sub(*c, (q[0], q[1])))).fold(f64::MAX, f64::min)).fold(0.0, f64::max) +} + +#[test] +fn sine_anchors_sit_on_the_four_peaks() { + for samples in as_given_and_in_pixels(sine()) { + let sp = fit(&samples, 2.0, false); + let got = anchors(&sp); + assert_eq!(got.len(), 6, "{got:?}"); + assert_eq!((got.first(), got.last()), (samples.first(), samples.last()), "press and release are anchors"); + for (a, peak) in got[1..5].iter().zip([[150.0, 460.0], [250.0, 340.0], [350.0, 460.0], [450.0, 340.0]]) { + assert!((a[0] - peak[0]).hypot(a[1] - peak[1]) <= 3.0, "{a:?} is not on the peak {peak:?}: {got:?}"); + } + assert!(sp.knots[1..5].iter().all(|k| k.smooth)); + } +} + +#[test] +fn closed_circle_has_five_anchors_and_the_open_one_four() { + for samples in as_given_and_in_pixels(circle(60)) { + let sp = fit(&samples, 2.0, true); + assert!(sp.closed); + assert_eq!(sp.knots.len(), 5, "{:?}", anchors(&sp)); + assert!(sp.knots.iter().all(|k| k.smooth), "a circle has no corners"); + } + for samples in as_given_and_in_pixels(circle(54)) { + let sp = fit(&samples, 2.0, false); + assert!(!sp.closed); + assert_eq!(sp.knots.len(), 4, "{:?}", anchors(&sp)); + assert!(sp.knots[1..3].iter().all(|k| k.smooth)); + } +} + +/// On whole pixels the first segment past the turn fits worse over a few samples than over many; +/// the fit still reaches past them to the reference application's four anchors. +#[test] +fn vee_turns_with_a_rounded_join_not_a_cusp() { + for (i, samples) in as_given_and_in_pixels(vee()).into_iter().enumerate() { + let sp = fit(&samples, 2.0, false); + let got = anchors(&sp); + assert_eq!(got.len(), 4, "{got:?}"); + assert_eq!((got[0], got[3]), ([100.0, 450.0], [400.0, 450.0])); + assert!(sp.knots[1..3].iter().all(|k| k.smooth), "no corner anchor: {got:?}"); + if i == 0 { + // As measured, both inner anchors are near the turn, not along the legs. + assert!(got[1..3].iter().all(|a| (a[0] - 250.0).hypot(a[1] - 550.0) < 60.0), "{got:?}"); + } + } +} + +#[test] +fn line_is_unchanged_one_segment_with_handles_at_a_third() { + let sp = fit(&line(), 2.0, false); + assert_eq!(anchors(&sp), [[100.0, 400.0], [500.0, 400.0]]); + let (a, b) = (&sp.knots[0], &sp.knots[1]); + assert!((a.out_ctrl.x - (100.0 + 400.0 / 3.0)).abs() < 1e-9 && a.out_ctrl.y == 400.0); + assert!((b.in_ctrl.x - (500.0 - 400.0 / 3.0)).abs() < 1e-9 && b.in_ctrl.y == 400.0); +} + +#[test] +fn a_lower_curve_fit_gives_more_anchors() { + for (name, points, closed) in [("sine", sine(), false), ("circle-open", circle(54), false)] { + let at_2 = fit(&points, 2.0, closed).knots.len(); + for curve_fit in [0.5, 1.0] { + let n = fit(&points, curve_fit, closed).knots.len(); + assert!(n > at_2, "{name}: {n} anchors at Curve Fit {curve_fit}, {at_2} at 2"); + } + } +} + +/// Today's guarantee: the path stays within Curve Fit of every sample, on the strokes as given +/// and on the whole pixels a mouse delivers. +#[test] +fn every_sample_stays_within_curve_fit() { + for (name, points, closed) in strokes() { + for samples in as_given_and_in_pixels(points) { + for curve_fit in [0.5, 1.0, 2.0, 5.0, 10.0] { + let sp = fit(&samples, curve_fit, closed); + let d = max_deviation(&sp, &samples); + assert!(d <= curve_fit + 0.05, "{name} at Curve Fit {curve_fit}: a sample {d:.3} px away"); + } + } + } +} diff --git a/crates/vector/src/triangle_box_geometry_tests.rs b/crates/vector/src/triangle_box_geometry_tests.rs new file mode 100644 index 0000000000..32760fe092 --- /dev/null +++ b/crates/vector/src/triangle_box_geometry_tests.rs @@ -0,0 +1,89 @@ +//! The triangle fills its box: apex at the top centre, then bottom right, bottom left (#13350). + +use super::*; + +fn anchors(p: &Path) -> Vec<(f64, f64)> { + p.subpaths[0].knots.iter().map(|k| (k.anchor.x, k.anchor.y)).collect() +} + +fn close(got: &[(f64, f64)], want: &[(f64, f64)], tol: f64) { + assert_eq!(got.len(), want.len(), "{got:?}"); + for (g, w) in got.iter().zip(want) { + assert!((g.0 - w.0).abs() <= tol && (g.1 - w.1).abs() <= tol, "{got:?} vs {want:?}"); + } +} + +#[test] +fn the_triangle_fills_its_box_apex_then_bottom_right_then_bottom_left() { + let p = triangle(400.0, 300.0, 200.0, 100.0); + assert_eq!(p.subpaths.len(), 1); + assert!(p.subpaths[0].closed); + assert_eq!(anchors(&p), [(500.0, 300.0), (600.0, 400.0), (400.0, 400.0)]); + assert!(p.subpaths[0].knots.iter().all(|k| k.in_ctrl == k.anchor && k.out_ctrl == k.anchor)); + assert_eq!(p.control_bounds(), Some((400.0, 300.0, 600.0, 400.0))); +} + +#[test] +fn the_other_measured_boxes() { + assert_eq!(anchors(&triangle(400.0, 300.0, 100.0, 100.0)), [(450.0, 300.0), (500.0, 400.0), (400.0, 400.0)]); + assert_eq!(anchors(&triangle(300.0, 250.0, 200.0, 100.0)), [(400.0, 250.0), (500.0, 350.0), (300.0, 350.0)]); +} + +#[test] +fn a_negative_size_extends_from_the_origin_with_the_apex_still_up() { + assert_eq!(triangle(600.0, 400.0, -200.0, -100.0), triangle(400.0, 300.0, 200.0, 100.0)); +} + +#[test] +fn a_radius_of_20_rounds_with_arcs_tangent_to_the_edges() { + let p = live_path(&LiveShape::Triangle { rect: [400.0, 300.0, 200.0, 100.0], corner_radius: 20.0 }); + close(&anchors(&p), &[(485.858, 314.142), (514.142, 314.142), (565.858, 365.858), (551.716, 400.0), (448.284, 400.0), (434.142, 365.858)], 1e-3); + let k = &p.subpaths[0].knots; + assert_eq!(k[1].out_ctrl, k[1].anchor); + assert_eq!(k[2].in_ctrl, k[2].anchor); + let pts = crate::flatten_subpath(&p.subpaths[0], 0.01).pts; + let x0 = pts.iter().map(|q| q.0).fold(f64::MAX, f64::min); + let x1 = pts.iter().map(|q| q.0).fold(f64::MIN, f64::max); + let y0 = pts.iter().map(|q| q.1).fold(f64::MAX, f64::min); + let y1 = pts.iter().map(|q| q.1).fold(f64::MIN, f64::max); + for (g, w) in [(x0, 428.284), (y0, 308.284), (x1, 571.716), (y1, 400.0)] { + assert!((g - w).abs() < 0.05, "{g} vs {w}"); + } +} + +#[test] +fn a_huge_radius_is_capped_and_zero_or_nan_stays_sharp() { + let rect = [400.0, 300.0, 200.0, 100.0]; + let huge = live_path(&LiveShape::Triangle { rect, corner_radius: 1.0e9 }); + assert_eq!(huge.subpaths[0].knots.len(), 6); + assert!(huge.subpaths[0].knots.iter().all(|k| k.anchor.x.is_finite() && k.anchor.y.is_finite())); + for r in [0.0, f64::NAN] { + assert_eq!(live_path(&LiveShape::Triangle { rect, corner_radius: r }), triangle(400.0, 300.0, 200.0, 100.0)); + } +} + +#[test] +fn a_three_sided_polygon_keeps_its_inscribed_geometry() { + let p = live_path(&LiveShape::Polygon { rect: [400.0, 300.0, 200.0, 100.0], sides: 3, star_ratio: 1.0, corner_radius: 0.0 }); + close(&anchors(&p), &[(500.0, 300.0), (586.603, 375.0), (413.397, 375.0)], 1e-3); +} + +#[test] +fn a_box_with_no_width_or_height_has_no_corner_to_round() { + for rect in [[5.0, 5.0, 0.0, 0.0], [5.0, 5.0, 0.0, 50.0], [5.0, 5.0, 50.0, 0.0]] { + let [x, y, w, h] = rect; + let p = live_path(&LiveShape::Triangle { rect, corner_radius: 20.0 }); + assert_eq!(p, triangle(x, y, w, h), "{rect:?}"); + assert_eq!(p.subpaths[0].knots.len(), 3); + } + // A sliver: the apex is too sharp to round, and the path stays finite. + let p = live_path(&LiveShape::Triangle { rect: [0.0, 0.0, 1.0e-7, 1000.0], corner_radius: 20.0 }); + assert!(p.subpaths[0].knots.iter().all(|k| [k.anchor, k.in_ctrl, k.out_ctrl].iter().all(|q| q.x.is_finite() && q.y.is_finite()))); +} + +#[test] +fn a_tall_thin_box_caps_each_corner_on_its_own_edges() { + // The apex's tangent points stop at half of each side, the base corners' at half of the base. + let p = live_path(&LiveShape::Triangle { rect: [0.0, 0.0, 2.0, 1000.0], corner_radius: 20.0 }); + close(&anchors(&p), &[(0.5, 500.0), (1.5, 500.0), (1.999, 999.0), (1.0, 1000.0), (1.0, 1000.0), (0.001, 999.0)], 1e-3); +} diff --git a/docs/architecture.md b/docs/architecture.md index 603fd95f69..ce0547a379 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -124,7 +124,7 @@ photocraft/ │ ├─ gpu/ photocraft-gpu wgpu backend for the DrawOp plan + GPU kernels (WGSL), residency cache, memory budget │ ├─ viewport/ photocraft-viewport camera (zoom/pan/rotate), visible tiles/mips, renders a doc into a wgpu texture; toolkit-agnostic │ │ ── I/O ── -│ ├─ psd/ photocraft-psd PSD/PSB read + write; its OWN format-level model; depends on nothing in this workspace +│ ├─ psd/ craft-psd PSD/PSB read + write; its OWN format-level model; depends on nothing in this workspace │ ├─ adobe-assets/ photocraft-adobe-assets .abr .asl .aco/.ase .grd .pat .csh .atn .cube/.3dl, ACR .xmp presets (standalone, like psd) │ ├─ codecs/ photocraft-codecs flat raster decode/encode at format-supported depths; AVIF encode only (feature `avif`), HEIF/HEIC decode only (feature `heif`); no JPEG XL │ ├─ affinity/ photocraft-affinity bounded native Affinity reader: archive, object stream, layers, vectors, text, pixels (standalone; read only) @@ -158,7 +158,7 @@ photocraft/ **Crate granularity:** start with the crates above. Split `algo` into `-adjust`, `-filters`, `-select`, `-inpaint` and `-warp` once any module passes about 10k lines, or once compile times hurt. Its internal module boundaries should already follow those lines. -**Naming:** directories are short and packages are prefixed `photocraft-`. `photocraft-psd` gets a neutral, publishable name (such as `psd-rw`) if we release it to crates.io. +**Naming:** directories are short and packages are prefixed `photocraft-`. `craft-psd` gets a neutral, publishable name (such as `psd-rw`) if we release it to crates.io. --- @@ -179,7 +179,7 @@ photocraft/ 1. A crate may depend only on crates in **lower** layers. No cycles and no sideways dependencies, except where listed. 2. **Nothing below L6 may depend on any UI toolkit, winit, or a `platform` implementation.** Platform services reach the engine through traits defined in `engine` (or in `platform`'s trait-only core), and are injected at startup. -3. **`photocraft-psd` depends on no workspace crate.** The doc ⇄ PSD mapping lives in `io`. This keeps the PSD crate publishable and reusable by other projects. The same holds for every standalone crate; `STANDALONE_EXCEPTIONS` in `xtask/src/layers.rs` is empty since HEIF decoding moved to craft-libs' `craft-heif`. +3. **`craft-psd` depends on no workspace crate.** The doc ⇄ PSD mapping lives in `io`. This keeps the PSD crate publishable and reusable by other projects. The same holds for every standalone crate; `STANDALONE_EXCEPTIONS` in `xtask/src/layers.rs` is empty since HEIF decoding moved to craft-libs' `craft-heif`. 4. **wasm gate:** every crate in L0–L5 (except feature-gated native backends) must build for `wasm32-unknown-unknown`. CI runs `cargo build -p photocraft-engine --target wasm32-unknown-unknown --no-default-features --features web`. 5. `gpu` is optional for `engine`. Engine features are `gpu` (default on) and `cpu-only`, and `cpu-only` builds are what the headless CLI and CI tests use. 6. **C dependencies** (optional LibRaw) only behind features, only in `codecs`, `raw` or `io`, and never on by default for the web target. @@ -359,7 +359,7 @@ Both backends consume the same plan. This is the only place that encodes Photosh --- -## 8. `photocraft-psd`: standalone PSD/PSB crate +## 8. `craft-psd`: standalone PSD/PSB crate **Scope:** faithful, format-level read and write of PSD (v1) and PSB (v2, 64-bit lengths). It has no dependency on our document model. diff --git a/docs/atn.md b/docs/atn.md index a9c272aebd..85a0c1eb21 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -3,7 +3,7 @@ PhotoCraft loads and saves action sets in the reference application's `.atn` format: Load Actions and Save Actions in the Actions panel menu, `actions.load` / `actions.save` for agents, and `photocraft batch --actions set.atn` on the command line. Reading and writing the file lives in -`photocraft-psd` (`crates/psd/src/atn.rs`, version 16 sets, exact round trip); the mapping between the +`craft-psd` (`crates/psd/src/atn.rs`, version 16 sets, exact round trip); the mapping between the application's events and PhotoCraft commands lives in `photocraft-engine` (`crates/engine/src/cmd/atn_cmds/`, table `EVENTS` in `events.rs`). @@ -147,7 +147,8 @@ row; the action still adds only one Undo entry. | `CtTL` | cutToLayer | Layer Via Cut | `layer.new.layerViaCut` | | `LnsF` | lensFlare | Lens Flare | `filter.render.lensFlare` | | `Lvls` | levels | Levels | `image.adjustments.levels`, `image.autoTone`, `image.autoContrast` | -| `Mk ` | make | Make | `image.calculations`, `layer.layerStyle.createLayer`, `layer.new.layer`, `layer.new.group`, `layer.groupLayers`, `layer.duplicate`, `layer.new.layerViaCopy`, `layer.new.layerViaCut`, `layer.newFillLayer.solidColor`, `layer.newFillLayer.pattern`, `layer.newFillLayer.gradient`, `layer.newAdjustmentLayer.levels`, `layer.newAdjustmentLayer.curves`, `layer.newAdjustmentLayer.hueSaturation`, `layer.newAdjustmentLayer.brightnessContrast`, `layer.newAdjustmentLayer.threshold`, `layer.newAdjustmentLayer.posterize`, `layer.newAdjustmentLayer.invert`, `layer.newAdjustmentLayer.colorBalance`, `layer.newAdjustmentLayer.vibrance`, `layer.newAdjustmentLayer.exposure`, `layer.newAdjustmentLayer.photoFilter`, `layer.newAdjustmentLayer.blackWhite`, `layer.newAdjustmentLayer.channelMixer`, `layer.newAdjustmentLayer.selectiveColor`, `layer.newAdjustmentLayer.gradientMap`, `layer.layerMask.revealAll`, `layer.layerMask.hideAll`, `layer.layerMask.revealSelection`, `layer.layerMask.hideSelection`, `file.new`, `file.newFromClipboard`, `history.newSnapshot`, `type.convertToShape`, `type.createWorkPath` | +| `Mk ` | make | Make | `image.calculations`, `layer.layerStyle.createLayer`, `layer.new.layer`, `layer.new.group`, `layer.groupLayers`, `layer.new.frameFromLayers` (Layer › New › Frame from Layers), `layer.duplicate`, `layer.new.layerViaCopy`, `layer.new.layerViaCut`, `layer.newFillLayer.solidColor`, `layer.newFillLayer.pattern`, `layer.newFillLayer.gradient`, `layer.newAdjustmentLayer.levels`, `layer.newAdjustmentLayer.curves`, `layer.newAdjustmentLayer.hueSaturation`, `layer.newAdjustmentLayer.brightnessContrast`, `layer.newAdjustmentLayer.threshold`, `layer.newAdjustmentLayer.posterize`, `layer.newAdjustmentLayer.invert`, `layer.newAdjustmentLayer.colorBalance`, `layer.newAdjustmentLayer.vibrance`, `layer.newAdjustmentLayer.exposure`, `layer.newAdjustmentLayer.photoFilter`, `layer.newAdjustmentLayer.blackWhite`, `layer.newAdjustmentLayer.channelMixer`, `layer.newAdjustmentLayer.selectiveColor`, `layer.newAdjustmentLayer.gradientMap`, `layer.layerMask.revealAll`, `layer.layerMask.hideAll`, `layer.layerMask.revealSelection`, `layer.layerMask.hideSelection`, `file.new`, `file.newFromClipboard`, `history.newSnapshot`, `type.convertToShape`, `type.createWorkPath` | +| `Mk ` | make | Make | `image.calculations`, `layer.layerStyle.createLayer`, `layer.new.layer`, `layer.new.group`, `layer.groupLayers`, `layer.duplicate`, `layer.new.layerViaCopy`, `layer.new.layerViaCut`, `layer.newFillLayer.solidColor`, `layer.newFillLayer.pattern`, `layer.newFillLayer.gradient`, `layer.newAdjustmentLayer.levels`, `layer.newAdjustmentLayer.curves`, `layer.newAdjustmentLayer.hueSaturation`, `layer.newAdjustmentLayer.brightnessContrast`, `layer.newAdjustmentLayer.threshold`, `layer.newAdjustmentLayer.posterize`, `layer.newAdjustmentLayer.invert`, `layer.newAdjustmentLayer.colorBalance`, `layer.newAdjustmentLayer.vibrance`, `layer.newAdjustmentLayer.exposure`, `layer.newAdjustmentLayer.photoFilter`, `layer.newAdjustmentLayer.blackWhite`, `layer.newAdjustmentLayer.channelMixer`, `layer.newAdjustmentLayer.selectiveColor`, `layer.newAdjustmentLayer.gradientMap`, `layer.layerMask.revealAll`, `layer.layerMask.hideAll`, `layer.layerMask.revealSelection`, `layer.layerMask.hideSelection`, `file.new`, `file.newFromClipboard`, `history.newSnapshot`, `type.convertToShape`, `type.createWorkPath`, `layer.new.artboard` (Layer › New › Artboard), `layer.new.artboardFromLayers` (Layer › New › Artboard from Layers) | | (string ID only) | animationFramesFromLayers | Make Frames from Layers | | | (string ID only) | matchColor | Match Color | `image.adjustments.matchColor` | | `Mxm ` | maximum | Maximum | `filter.other.maximum` | @@ -239,6 +240,7 @@ row; the action still adds only one Undo entry. | (string ID only) | textSaveDefaultTypeStyles | Save Default Type Styles | `type.saveDefaultTypeStyles` | | (string ID only) | recordMeasurements | Record Measurements | `image.analysis.recordMeasurements` | | (string ID only) | CropPhotosAuto0001 | Crop and Straighten Photos | `file.automate.cropAndStraightenPhotos` | +| (string ID only) | 3caa3434-cb67-11d1-bc43-0060b0a13dc4 | Fit Image (script event; pixel box sides) | `file.automate.fitImage` | | (string ID only) | placedLayerExportContents | Export Contents | `layer.smartObjects.exportContents` | | (string ID only) | placedLayerConvertToLinked | Convert to Linked | `layer.smartObjects.convertToLinked` | | (string ID only) | placedLayerRelinkToFile | Relink to File | `layer.smartObjects.relinkToFile` | @@ -272,6 +274,20 @@ options are refused on export. Playback uses the native command's preconditions and current state. Isolate Layers toggles the panel view; type defaults remain session settings; Record Measurements uses the current measurement configuration. +Layer › New › Frame from Layers is a Make with `null` = the class +`framedGroupSection`, `From` = the layer by name and `Nm ` = the frame's name. It +plays as `layer.new.frameFromLayers` on that layer, and the frame fits that +layer's bounds whatever is selected. The dialog's width and height are not in the +step. `layerSectionStart` and `layerSectionEnd` are ids of the recording session: +a loaded step saves back its recorded descriptor, session ids included, while it +still frames the same layer with the same name, and a step recorded in PhotoCraft +writes `null`, `From` and `Nm ` (only for a name that isn't blank) without them. A +native step without a layer of its own frames the selected layers and writes +`From` = the target layer, a form the recordings don't show. Another `From`, a +repeated or extra key, or a value of another type stays a kept step; a native step +with a layer by id, or with the group options the command passes on (colour, mode, +opacity), refuses export. + Link Layers plays as the toggle the reference application performs (played twice on the same layers it links, then unlinks them; see the measurements below). Unlink is explicit and idempotent: it keeps an already unlinked selection unlinked and clears singleton link groups. @@ -307,6 +323,21 @@ Custom-shape playback requires the asset selected by its ID to be installed. Other unsupported dialog fields or origin values remain kept. Native explicit shape choices cannot be saved as radius-only descriptors. +Layer › New › Artboard and Layer › New › Artboard from Layers are a Make with +`null` = the class `artboardSection`. With `artboardRect` (`Top `, `Left`, +`Btom`, `Rght`: doubles holding whole pixels, a board of positive size in the +32-bit range) the step plays as `layer.new.artboard` with that `rect`; with `From` += the target layer it plays as `layer.new.artboardFromLayers` on the selected +layers, at their bounds. `Nm ` is the board's name. `layerSectionStart` and +`layerSectionEnd` are ids of the recording session: a loaded step saves back its +recorded descriptor, session ids included, while it still makes the same board, +and a step recorded in PhotoCraft writes the other keys without them (`Nm ` only +for a name of its own). Both or neither of `artboardRect` and `From`, another +`From` target, a repeated or extra key, or a value of another type stays a kept +step. The step records no background, preset or size of the dialog's own, so a +native step that sets one of those, takes the Background into the first board, or +(New Artboard) has no position of its own refuses export. + Crop and Straighten Photos executes the native scan operation once, creating one document per photo found inside the selection and leaving the source unchanged. It requires a selected, visible layer with no pixel or full lock, including @@ -315,6 +346,22 @@ The separate `CropPhotos0001` helper remains a complete kept Photoshop step. Playback stops at that enabled helper before subsequent duplicate/crop steps can run. This covers the parent event, not complete recordings with generated helpers. +Fit Image is the script event `3caa3434-cb67-11d1-bc43-0060b0a13dc4` that follows +the Image Size step it runs, which stays a step of its own. `Wdth` and +`Hght` (pixel unit floats above 0) and `limit` (Don't Enlarge) play as +`file.automate.fitImage`. With `limit` true it leaves a document that already fits +unchanged; with `limit` false it enlarges a smaller document to fit the box. +The descriptor's class is `cjsp` with an empty class name (measured, in two UI +languages). `Msge` is the script's own text, not a setting: the reference plays the +step the same with the recorded text, an empty one, unrelated text or the key +removed, so the three-key form without `Msge` maps too. A loaded step saves back +with its recorded descriptor (message or none, class, key order), and once its +settings change it saves them into that descriptor. A step recorded in PhotoCraft +saves class `cjsp` and an empty `Msge`. Another unit, a side of 0, a repeated `Msge`, +a missing `Wdth`, `Hght` or `limit`, or an extra key stays a kept step. A native +step with a missing or 0 side (the document's own size) or a resampling method +other than the default refuses export, because the event has no key for it. + Set Measurement Scale › Custom is a Set of the target document's `measurementScale` property. `T ` holds `pixelLength` (a long above 0), `logicalLength` (a double above 0) and `logicalUnits` (text that isn't blank), and the step plays as diff --git a/docs/brush-parity.md b/docs/brush-parity.md index e05942ec22..306057f175 100644 --- a/docs/brush-parity.md +++ b/docs/brush-parity.md @@ -1,6 +1,6 @@ # Brush and painting parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (Eraser's Erase to History, #10692; no estimate changed; Both Axes on Scatter headers, #3825 partial; Brush Tip Shape Spacing checkbox and percentage share one header, #3825 partial; Angle/Roundness fields left of the Brush Tip Shape widget, labels right-aligned, #3825 partial; the eraser end of the pen switches to the Eraser on Windows with Windows Ink on, #2285; no estimate changed; Art History Brush Opacity on the options bar, #10263; no estimate changed; Shift+right-click menu for every painting tool: Edit Brush… and the tool's own Mode list; Brush Shift+right-click Mode picker and Escape dismissal; Art History Brush row added as partial, 8 of 10 styles, TOOL-213-20, #1610; hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; Mode for Clone Stamp, Pattern Stamp, History Brush, Healing and Paint Bucket; named, stateful Brush Settings locks and visible keyboard focus; independent Brush Pose tilt-axis overrides; Transfer Wetness/Mix tool applicability; dragged preset tip preview; Hue Jitter amount track; Brush Settings minimum fields follow their Control; checkbox-only rows and non-destructive Smoothing switch; shaped-tip cursor follows the view; Color Replacement is a live toolbar tool; no brush-feel estimate changed; 2026-10-11: Pattern Stamp and Background Eraser draw live, TOOL-213-7) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (Eraser's Erase to History, #10692; no estimate changed; Both Axes on Scatter headers, #3825 partial; parity refresh retains the expanded painting-menu limitations; right-click Brush Preset picker is partial while a pen barrel right-click with Windows Ink on still often paints a dot (#5364); Brush Tip Shape Spacing checkbox and percentage share one header, #3825 partial; Angle/Roundness fields left of the Brush Tip Shape widget, labels right-aligned, #3825 partial; the eraser end of the pen switches to the Eraser on Windows with Windows Ink on, #2285; no estimate changed; Art History Brush Opacity on the options bar, #10263; no estimate changed; Clone Stamp and Healing Brush clone from a source set in another open document; Shift+right-click menu for every painting tool: Edit Brush… and the tool's own Mode list; Brush Shift+right-click Mode picker and Escape dismissal; Art History Brush row added as partial, 8 of 10 styles, TOOL-213-20, #1610; hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; Mode for Clone Stamp, Pattern Stamp, History Brush, Healing and Paint Bucket; named, stateful Brush Settings locks and visible keyboard focus; independent Brush Pose tilt-axis overrides; Transfer Wetness/Mix tool applicability; dragged preset tip preview; Hue Jitter amount track; Brush Settings minimum fields follow their Control; checkbox-only rows and non-destructive Smoothing switch; shaped-tip cursor follows the view; Color Replacement is a live toolbar tool; no brush-feel estimate changed; 2026-10-11: Pattern Stamp and Background Eraser draw live, TOOL-213-7) · **Target:** Adobe Photoshop 2026 Painting is where Photoshop users notice differences first, so it gets its own checklist: the brush engine (`crates/paint/src/brush.rs`), the Brush Settings UI @@ -48,7 +48,7 @@ tablets against Photoshop side by side. | Pressure drives size/opacity/flow per sample (no shared pressure within a frame) | done | #2112 | | Global pressure curve in Preferences | done | #2195 | | Per-control pressure curves | missing | TOOL-213-11 | -| Quick taps keep their pressure | partial | #1967 fixed one case; tap paints a full blob (#1798), tap sensitivity (#1933) | +| Quick taps keep their pressure | partial | #1967 fixed one case; a tap paints at its own pressure (#1798, #2757); tap sensitivity still open (#1933) | | Smooth pressure on Windows | partial | "jumpy" (#2046) | | Tilt and rotation drive angle/roundness | partial | macOS, X11, web; not Windows; rotation not applied (#1301) | | Eraser end of the pen switches to Eraser | partial | macOS, Windows (WinTab; Windows Ink not yet confirmed on hardware, #2285); X11 and web partial | @@ -58,7 +58,7 @@ tablets against Photoshop side by side. | Behaviour | Status | Evidence | |---|---|---| | No seams, hard edges stay hard, zero-scatter defaults, ABR tips never black | done | TOOL-213-13 | -| Smooth line weight along a pressure ramp | partial | stair-steps (#1776); 2026-10-23: the five hard-round built-in presets use 5% spacing (#8842), with rendered 150 px outline and pressure-opacity continuity regressions at 8/16/32-bit and 0/49% smoothing. Other brush-feel gaps remain open. | +| Smooth line weight along a pressure ramp | partial | stair-steps fixed by per-sample pressure (#1776, #2112); Windows still "jumpy" (#2046); 2026-10-23: the five hard-round built-in presets use 5% spacing (#8842), with rendered 150 px outline and pressure-opacity continuity regressions at 8/16/32-bit and 0/49% smoothing. Other brush-feel gaps remain open. | | Interpolation and smoothing match Photoshop | partial | #2138, #2057 | | Soft-edge falloff matches Photoshop's curve | partial | #2149, #1619 | | Brush preview and cursor crisp, not pixelated | partial | #1433 | @@ -80,8 +80,8 @@ tablets against Photoshop side by side. | Hold `~` with the Brush or Pencil to erase with its brush: Clear mode while held (rebindable under Tools › Temporary) | done | `hold_keys.rs`, #3439 | | Clear painting mode in the Brush and Pencil Mode menus | done | `paint_mode_dropdown` in `panels.rs`, `"mode": "clear"`, #3439 | | Shift+right-click opens the painting tool's menu: Edit Brush… and its own Mode list (Brush/Pencil painting modes with Behind and Clear, stamps and History Brush blend modes, Eraser Brush/Pencil/Block, Dodge/Burn Range, Sponge mode, Healing Brush, Gradient and Paint Bucket modes); Behind and Clear greyed on the Background; Alt and Command/Ctrl keep their existing gestures | partial | #4929, `brush_mode_menu.rs`; rows set the options-bar state (`tools.setBrush` or the tool option); kittest and control regressions. Missing because the options bar lacks the setting: Behind for the stamps, History Brush, Gradient and Paint Bucket; the Blur/Sharpen/Smudge modes; the Spot Healing modes (no menu); the Healing Brush's Sampled/Pattern source and Replace; the History Brush source | -| Right-click opens the Brush Preset picker | done | [`context-menu-parity.md`](context-menu-parity.md); XP-Pen right-click not (#1980), macOS issue #2360 | -| Precise / normal / full-size tip cursors, crosshair in the tip | partial | Caps Lock precise cursor not audited; round Pencil cursor requested (#2662, #1057) | +| Right-click opens the Brush Preset picker | partial | [`context-menu-parity.md`](context-menu-parity.md); mouse right-click works; a pen barrel right-click (Wacom, XP-Pen) with Windows Ink on still often paints a dot instead (#5364 open; #1980 closed as a duplicate of #5905); macOS trackpad taps fixed (#2360, #2772) | +| Precise / normal / full-size tip cursors, crosshair in the tip | partial | Caps Lock precise cursor not audited; round Pencil cursor done (#2662, #2694), parity request open (#1057) | | Brush choice kept per tool (Brush, Eraser, Blur each their own) | partial | #2542 | ## Symmetry @@ -90,7 +90,7 @@ tablets against Photoshop side by side. |---|---| | Vertical, Horizontal, Dual axis, Diagonal | done | | From a path (Make Symmetry Path) | done | -| Wavy, Circle, Spiral, Parallel Lines, Radial, Mandala | missing (#2659) | +| Wavy, Circle, Spiral, Parallel Lines, Radial, Mandala | missing (#2659 was closed after the existing symmetry control became available in every theme, #2704) | ## Brush-based tools @@ -103,7 +103,7 @@ tablets against Photoshop side by side. | Pattern Stamp (mode, aligned, impressionist) | done | | | History Brush (mode) | done | | | Art History Brush (styles, Area, Tolerance) | partial | 8 of 10 styles (no Tight Curl Long / Loose Curl Long); Area scales spacing, not Photoshop's coverage; no Mode on the options bar, no pen pressure (TOOL-213-20) | -| Spot Healing, Healing (Healing mode: Normal, Multiply, Screen, Darken, Lighten, Color, Luminosity) | partial | Healing's Replace mode and Spot Healing's Mode missing; grain not matched on flat colour (#2104), "horrible in general" (#1092), stops responding after switching (#1751) | +| Spot Healing, Healing (Healing mode: Normal, Multiply, Screen, Darken, Lighten, Color, Luminosity) | partial | Healing's Replace mode and Spot Healing's Mode missing; grain on flat colour kept by Create Texture (#2104, #2762); "horrible in general" (#1092), stops responding after switching (#1751) | | Blur, Sharpen, Smudge (premultiplied, Sample All Layers, spacing) | done | BUG-207-2/3, #2171 | | Dodge, Burn, Sponge | done | | | Background Eraser, Magic Eraser | done | | @@ -115,7 +115,7 @@ tablets against Photoshop side by side. | Behaviour | Status | Evidence | |---|---|---| | .abr import (v1/v2/v6) and export, persistent presets, folders | done | `psd/src/abr.rs` | -| Brushes panel: drag a folder into a folder | missing | #2014 | +| Brushes panel: drag a folder into a folder | done | #2014, #3851 | | Dragged brush preset preview | done | Cached, translucent tip thumbnail plus name in panel list/grid and the preset picker; `ui-egui/src/brushes_tab.rs`, real pointer-drag test in `brushes_tab_tests.rs` (#4225, partial) | | Tool presets (.tpl) | partial | Tool Presets panel exists; .tpl import not found | | Import 500 brushes without blocking the UI | not run | P24 | @@ -135,6 +135,7 @@ tablets against Photoshop side by side. | 2026-10-11 | minor | `~` held with the Brush or Pencil erases with that tool's brush, and Clear joins their Mode menus (#3439) | | 2026-10-12 | minor | Five Brush Settings switch rows toggle without selecting a properties pane; Smoothing has a default-on switch and retains its settings while disabled (#4283). No brush-feel estimate changed. | | 2026-10-12 | minor | A shaped tip's cursor outline turns and flips with a rotated or flipped view, and follows pixel aspect correction | +| 2026-10-12 | minor | Rows refreshed against main: quick taps, pressure-ramp stair-steps, macOS right-click, round Pencil cursor, Clone Source W/H link, Spot Healing grain, brush-folder drag; the symmetry row no longer cites #2659 as the tracker | | 2026-10-13 | minor | Shape Dynamics and Transfer minimum inputs follow their Control and retain their values while disabled (#3825, partial). No brush-feel estimate changed. | | 2026-10-13 | minor | Hue Jitter uses the same themed amount slider as other jitter controls (#3825, partial). No brush-feel estimate changed. | | 2026-10-13 | minor | Brush Tip Shape combines the Spacing checkbox and percentage into one header (#3825, partial), retaining the value while disabled. No brush-feel estimate changed. | @@ -147,4 +148,7 @@ tablets against Photoshop side by side. | 2026-10-13 | minor | Dragging a brush preset shows its cached tip thumbnail and name in the Brushes panel and preset picker (#4225, partial). No brush-feel estimate changed. | | 2026-10-23 | minor | Escape also consumes a held right-button release after a rapid second press, so the Brush Mode picker stays dismissed without painting or changing history (#4929). | | 2026-10-30 | minor | Shift+right-click works for every painting tool as in the reference application: Edit Brush… opens the Brush Preset picker, then the tool's own Mode list from its options bar; Behind and Clear greyed on the Background. Row marked partial for the settings the options bar lacks. No brush-feel estimate changed. | +| 2026-10-30 | minor | Clone Stamp and Healing Brush clone from a source ⌥-clicked in another open document (the slot remembers its document and layer; its colour mode is converted as Paste converts; a closed source document is an error, not a silent sample of the painted one). No brush-feel estimate changed. | +| 2026-10-31 | minor | Merge keeps the expanded Shift+right-click painting-menu limitations alongside the refreshed macOS right-click and Pencil cursor evidence; brush-feel estimates unchanged | | 2026-11-07 | minor | Eraser's Erase to History in Brush, Pencil and Block modes, with ⌥ at the press reversing it for that stroke; a layer missing from the source state paints from a single-layer state and is refused otherwise (#10692). No brush-feel estimate changed. | +| 2026-11-08 | minor | Right-click Brush Preset picker marked partial: a pen barrel right-click with Windows Ink on still often paints a dot (#5364) | diff --git a/docs/context-menu-parity.md b/docs/context-menu-parity.md index 1ef971ef33..f441a2bc81 100644 --- a/docs/context-menu-parity.md +++ b/docs/context-menu-parity.md @@ -28,7 +28,7 @@ The “PhotoCraft at branch point” column records behavior before this PR. Pic | Brush, Pencil, Eraser, Background Eraser, Spot Healing, Healing, Clone Stamp, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge | Brush preset, size and hardness where applicable | Picker | P0; [Adobe Brush Settings](https://helpx.adobe.com/photoshop/desktop/apply-painting-techniques/brushes-presets/create-brush-set-painting-options.html). Alt+secondary-drag on Windows and Control+Option-drag on macOS adjust size/hardness ([Adobe cursor shortcuts](https://helpx.adobe.com/in/photoshop/desktop/get-started/settings-and-preferences/change-tool-pointers.html)) | | Gradient, Paint Bucket | Gradient preset/type/mode or fill source/tolerance **(inferred context placement)** | No tool menu | P1 | | Type | In text: cut/copy/paste, spelling suggestions, text formatting; outside text: type-layer action **(inferred context placement)** | While editing text (canvas_tool_menu.rs `TYPE_EDIT_MENU`): Undo, Cut, Copy, Paste, Select All (on the text), Check Spelling…, Find and Replace Text…, Faux Bold/Italic (checked), Rasterize Type, Create Work Path, Convert to Shape, Horizontal/Vertical and the anti-alias modes (checked), Convert to Paragraph/Point Text, Warp Text…; Esc closes only the menu. Over a misspelled word the menu starts with up to 3 spelling suggestions (replace the word) and Add to Dictionary (#4370). Over committed type (no edit running, `TYPE_LAYER_MENU`, #7324): the same rows without Undo, Cut, Copy, Paste, Select All and Faux Bold/Italic; the clicked type becomes the active layer first (a layer multiselection stays). The Type Mask tools get no menu. Ignore / Ignore All remain open | P1; editing and nonediting states are separate; [Adobe type editing](https://helpx.adobe.com/photoshop/desktop/text-typography/get-started-with-text/edit-text.html) | -| Hand, Zoom | Fit on Screen, 100%, 200%, Print Size; zoom step choices **(inferred context placement)** | View menu (#3242, #6005): Fit on Screen, Fill Screen, 100%, 200%, Print Size, then Zoom In and Zoom Out after a separator. Zoom In/Out step about the right-clicked point (Preferences › Tools › Zoom Clicked Point to Center centres it). Outside the image the pasteboard menu still wins. | P1; view actions stay out of document history; row order still needs a dated Photoshop capture | +| Hand, Zoom | Fit on Screen, 100%, 200%, Print Size; zoom step choices **(inferred context placement)** | View menu (#3242, #6005): Fit on Screen, Fill Screen, 100%, 200%, Print Size, then Zoom In and Zoom Out after a separator. Zoom In/Out step about the right-clicked point (Preferences › Tools › Zoom Clicked Point to Center centres it). Outside the image the pasteboard menu still wins. Space's Hand over any tool opens it too, with the Hand's rows (#11271; the Hand's are the fixed zooms only since #12022), and outside the image the pasteboard menu. Under it a plain Esc closes only the menu and a plain Enter does nothing, so neither reaches a pending crop. A held zoom key opens none. | P1; view actions stay out of document history; row order still needs a dated Photoshop capture | | Pen, Path Selection | Path/point actions, Make Selection, Fill/Stroke Path, Free Transform Path **(inferred context placement)** | Pen canvas right-click follows the user-provided 20-row Photoshop capture below. Paths rows offer Make Selection, Fill and Stroke. The Path Selection and Direct Selection tools open the same path menu for the selected path (#1056, 2026-10-15); node- and segment-specific rows remain open. | P1; distinguish node, segment, path, and blank canvas | | Rectangle, Ellipse Shape, Triangle, Polygon, Line, Custom Shape | Shape/path operations, fill/stroke settings, transform **(inferred context placement)** | No tool menu | P2 | | Slice, Slice Select | Slice properties, duplicate/delete, divide, guides **(inferred context placement)** | No tool menu | P2 | diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 154453df05..ecf603fe9a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -17,6 +17,39 @@ photocraft --control 7878 --control-token-file /private/path/photocraft-control. If the file does not exist, PhotoCraft creates it with a fresh 256-bit token. On Unix the new file is mode `0600`; on Windows, protect it with an appropriate user-only ACL. An existing file is reused. If neither a token nor token file is configured, PhotoCraft generates a token for that launch and writes it to standard error. `PHOTOCRAFT_CONTROL_TOKEN` and `PHOTOCRAFT_CONTROL_TOKEN_FILE` are the environment-variable equivalents. A flag wins over its variable and an empty variable counts as unset; with `--control` (or `PHOTOCRAFT_CONTROL_PORT`), a token together with a token file, from flags or variables, is a usage error (exit status 2). Without it no token is read, so the pair is ignored. +### Without `--control`: the agents switch and Preferences › AI Integrations + +An app started from the Dock, the Start menu or a file manager has no command line. It starts and stops the control server while it runs. With the suite's `AI-MCP` flag, ArtCraft Launcher › Settings › AI agents › *Let AI agents use Craft apps* is the one switch (for every Craft app; PhotoCraft looks at it every 2 s); without the flag, as before, a saved Control Port. Turning it on or off, or changing the port or folders in Edit › Preferences › AI Integrations, applies at once, with no restart. + +| Preference | What it does | +|---|---| +| `integrations.connectAgents` (default off, not in the dialog) | Without the `AI-MCP` flag: serve agents on loopback without `--control`, and publish the connection (below). Set from a saved Control Port; with the flag only the launcher's switch counts | +| `integrations.controlPort` (default 0) | The port for that; 0 = any free port (clients read it from the connection file) | +| `integrations.readRoot` (default empty) | The agents' read folder; with `--control`, stands in for `--automation-read-root` | +| `integrations.writeRoot` (default empty) | The agents' write folder; with `--control`, stands in for `--automation-write-root` | +| `integrations.whenAppClosed` (default `launch`) | What `photocraft-cli mcp` does while agents may use the app but it is closed: `launch`, `headless` or `error` | +| `integrations.allowAgentControl` (default on, not in the dialog) | Off refuses `--control` too | + +A file whose `controlPort` (1 to 65535) started the server at launch, as on `main` before the agents switch, loads with `connectAgents` on, so that keeps working without the flag. Started with `--control`, the app leaves the connection to the launch flags and the dialog says so; only `--control` (or `PHOTOCRAFT_CONTROL_PORT`) opens a port at launch. + +With `--control`, each launch option, or its environment variable, wins over its preference; the two folders are decided separately (any `--automation-read-root` replaces the read folder). The same folder for both reading and writing shares one capability, as it does when given by flags, so an implicit save works there too. A folder named by a flag that can't be opened stops the launch (exit status 2), as before. A folder named only in the preferences that can't be opened, or isn't an absolute path, is left out, so that direction of file access fails closed; the app still starts, prints the reason on standard error and shows it in a notice. Automation can't change the two folders (`prefs.set` refuses `integrations.readRoot`, `integrations.writeRoot` and the whole `integrations` section): an agent must not widen its own file access. + +While agents may connect, the app keeps its token in its settings folder, in `agent-control.token`, exactly as `--control-token-file /agent-control.token` would (created mode `0600` with a fresh token when missing, reused otherwise, also when the port changes; delete it to get a new token). If that file can't be written or read (a read-only or full settings folder), agents can't connect and the dialog shows why. Otherwise the app publishes the connection beside it, in `agent-connection.json`, and removes it when the connection stops: + +```json +{ + "version": 1, + "pid": 41234, + "port": 7878, + "tokenFile": "/Users/me/Library/Application Support/Photocraft/agent-control.token", + "app": "0.20.1 (8e9277e20, 2026-11-04)" +} +``` + +A local client reads that file, then the token from `tokenFile`, connects to `127.0.0.1:` and authenticates as below. The file holds no secret. A `--control` launch publishes nothing: whoever started it chose the port and token. + +On Windows and Linux the app removes the file when it quits. On macOS (quitting ends the process inside AppKit) and after a crash the file stays behind, naming a `port` nothing listens on: a client should treat a refused connection as "not running", and the next launch replaces or removes the file. Until then, another local program could be listening on that port. A program running as the same user can read the token file anyway, so this matters only against one that can listen on a loopback port but can't read that `0600` file (another user's, or a sandboxed app). A client must check that the process `pid` names is still running before it sends the token, and treat the file as stale otherwise. That check narrows the gap but doesn't close it: the pid can be reused, and the app can quit between the check and the connection. A client that must rule this out should not send the token on the strength of this file at all; it should use challenge authentication (below), which never sends the token to the listener, with no fallback to sending the token. `version` changes only with an incompatible format. The settings folder is the one that holds `preferences.json` (see [Preferences](#preferences); `PHOTOCRAFT_CONFIG_DIR` moves it). + The first request on every TCP connection must authenticate. No other method is dispatched before this succeeds. There are two ways; a refused frame gets `{"ok": false, "error": "authentication required"}` and the connection is closed. **Challenge authentication** (what `photocraft-cli mcp --bridge` uses) never sends the token, and the server proves it holds the token before the client reveals anything derived from it, so a process that took the port (the app is not running yet, or has exited) learns nothing: @@ -74,8 +107,13 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i - `select.findLayers` (#10884, Select › Find Layers) filters the Layers panel by Name and selects none of the matches; as with any filter, a selected layer the filter hides is deselected (#10879). With `name` it sets the Name text; without it the text is kept. Through `engine.execute` or an action step that is all; through the menu, the shortcut or `ui.menu.invoke` without `name`, the Layers panel is also shown and its Name field takes the keyboard focus with the text selected (unless Filter Options › Hide hid the filter row, which stays hidden). The reply lists the ids of the layers the Name text matches in `selected` (trimmed, ignoring case: a blank text lists every layer, a text nothing matches none) and the Name filter applied in `layerFilter` (`{by: "name", name}`). - `ui.set` also accepts the Histogram panel: `histogramPanel` `{view?, channel?, showChannelsInColor?, showStatistics?, source?}` (any subset, kept with the preferences): `view` is `compact`, `expanded` or `allChannels`; `channel` is `composite`, `red`, `green`, `blue`, `cyan`, `magenta`, `yellow`, `black`, `a`, `b`, `luminosity` or `colors` (one the document's mode lacks shows as its composite); `source` is `entireImage`, `selectedLayer` or `adjustmentComposite` (Entire Image is counted in Compact View, when the document has one layer, or when no adjustment layer is selected for Adjustment Composite). `histogramRange` is `[from, to]` (levels 0..255) or `null`: the dragged tonal range whose Count and Percentile the statistics show. `histogramRefresh: true` is Uncached Refresh: the current state is recounted at cache level 1. `ui.inspect` › `histogram` reports the options, the channel and source as they apply, the channels the document offers, whether the shown histogram is `current` (counted for the document's revision, source and cache level the panel wants now), its `cacheLevel`, `maxCacheLevel` (Preferences › Performance › Cache Levels), `preview` (an adjustment's preview is counted) and `stats` (`mean`, `stdDev`, `median`, `pixels`, `level`, `count`, `percentile`, `clipped` percent at 0 and 255). Histograms are counted while the panel is shown. - Each painting tool keeps its own brush, as in Photoshop: `tools.setBrush` and `ui.set {brushSize}` change the active tool's brush, and switching tools swaps in that tool's own (size, hardness, mode, opacity, flow, dynamics, smoothing). A tool used for the first time starts from the brush in hand. The colours, the erase flag and the stroke seed stay shared. So `ui.set {tool: "eraser", brushSize: 12}` sets the Eraser's size, and `ui.set {tool: "brush"}` afterwards brings the Brush's own size back. +- For pixel-layer destinations, Clone Stamp and Healing Brush source slots remember the picked document and layer. A paint command uses the picked slot when both `source` and `offset` are omitted or null. Current Layer then reads the picked pixel layer even after switching destination layers. A non-null `source` or `offset` instead selects coordinates in the destination document, ignoring the slot's document and layer; Current Layer reads the destination surface unless `sourceLayer` selects another layer in that document. Null optional coordinates do not select this explicit-coordinate path. + A paint command's `sourceLayer` overrides the sampled layer for Current Layer and cross-document Current & Below sampling; without an override, slot-based sampling uses the picked layer. If the sampled layer has no pixel surface (such as a group or adjustment layer), Current Layer falls back to the destination surface for a same-document source and returns an error for a cross-document source; it does not sample the non-pixel layer itself. Current & Below composites the destination layer and everything below it for a same-document source; for a cross-document source it composites the picked source layer (or `sourceLayer` override) and everything below it. All Layers reads the entire sampled document composite. + Alt-click in one open document, switch tabs, and paint in another to clone across documents. Clone Stamp requires matching document color modes; Healing Brush additionally allows Grayscale on either side. Compatible cross-document colors use the document ICC profiles through the CMS. `cloneSource.set {"source":[x,y],"document":index}` selects an open source document explicitly; `cloneSource.list` reports its current index and `documentId`. A closed source document or deleted sampled layer returns an error until a new source is picked. Empty slots do not reuse an earlier slot's coordinates. Source canvas coverage is retained independently of stored alpha: no-alpha pixels inside the canvas are opaque, including black; pixels outside it do not paint. Wrapped sampling repeats the source canvas. Opaque destination surfaces retain their original native format after blending. Cross-document mask/channel destinations return an unsupported-target error instead of sampling the wrong document. + Both source overlays honor Pattern Preview. Unsupported cross-document mask/alpha-channel gestures have no source overlay. Healing Brush excludes absent source pixels from its solve and paint coverage, independently of alpha reconstructed by the solver. +- Clone Source X/Y are signed document-pixel offsets, using the existing `source - destination` convention. The panel derives the current preview/stroke pairing without anchoring it on hover. `cloneSource.list` exposes `anchor` (persistent Aligned pairing), `lastAnchor` (most recently used successful pairing), and `offset` (source minus that last reference). Unaligned strokes update the readout while restarting at the sample point each time; failed or canceled strokes do not commit a pairing. To edit the offset shown for a preview, use `cloneSource.set {"offset":[dx,dy],"anchor":[destinationX,destinationY]}`; without an explicit anchor an edit uses the last reported reference, then the existing aligned reference or sample point. Source picking clears both anchors; resetTransform retains them. Null optional coordinates are omitted consistently in mapping and source-document selection. Invalid coordinates, slot indexes, and oversized transformed sampling windows return errors without painting. - Brush Pose's `pose.overrideTiltX` and `pose.overrideTiltY` are independent booleans. For example, `engine.execute {"command":"tools.setBrush","params":{"pose":{"enabled":true,"tiltX":45,"overrideTiltX":true,"overrideTiltY":false}}}` fixes X at 45° while Y follows the stylus. Pose tilts are degrees (±90); the Brush Settings panel displays percentages (±100). Old stored `overrideTilt` values migrate to both axes. In command patches, `overrideTilt` sets both axes unless an explicit axis field in the same patch overrides it. `brush.get` includes both axis flags and the legacy combined readback (`overrideTilt` is true only when both flags are true). Axis-only journals omit that derived combined key so replay retains the other axis. Present flag values must be booleans; null and other types return an error. -- `ui.set` also accepts the Eyedropper options bar (#1649): `eyedropperSampleSize` (`"point"` or 1, 3, 5, 11, 31, 51, 101: the side of the averaged square, shared by the Eyedropper, a painting tool's Alt-click eyedropper, the Curves/Color Picker eyedroppers and the Info panel), `eyedropperSample` (`current`, `currentAndBelow`, `all`, `allNoAdjustments`, `currentAndBelowNoAdjustments`) and `eyedropperRing` (boolean, Show Sampling Ring). `ui.inspect` reports them under `toolOptions` (`eyedropper_size`, `eyedropper_sample`, `eyedropper_ring`). The engine command `document.sampleColor {x, y, size, sampleLayer}` returns the colour such a sample picks, as four floats 0..1 (not 0..255). +- `ui.set` also accepts the Eyedropper options bar (#1649): `eyedropperSampleSize` (`"point"` or 1, 3, 5, 11, 31, 51, 101: the side of the averaged square, shared by the Eyedropper, a painting tool's Alt-click eyedropper, the Curves/Color Picker eyedroppers and the Info panel), `eyedropperSample` (`current`, `currentAndBelow`, `all`, `allNoAdjustments`, `currentAndBelowNoAdjustments`) and `eyedropperRing` (boolean, Show Sampling Ring). `ui.inspect` reports them under `toolOptions` (`eyedropper_size`, `eyedropper_sample`, `eyedropper_ring`). The engine command `document.sampleColor {x, y, size, sampleLayer, zoom}` returns the colour such a sample picks, as four floats 0..1 (not 0..255). `zoom` is optional: the view zoom in screen pixels per document pixel (1 = 100 %, a positive number). Without it, an N by N Average reads the N × N square centred on the pixel. With it, the sample matches the Eyedropper at that zoom (#11751): above 100 % it is still the centred square, and at 100 % and below an N by N Average covers (N+1) × (N+1) *screen* pixels, so at 100 % 3 by 3 reads 4 × 4 document pixels and at 50 % 8 × 8. The side in document pixels is (N+1) ÷ `zoom` rounded to the nearest whole pixel, at least N+1 and at most 4096 (at 75 % a 3 by 3 Average reads 5 × 5). The box starts ⌈side ÷ 2⌉ − 1 pixels left of and above the sampled pixel, so an odd side is centred on it and an even side has one pixel more after it than before (at 100 % 3 by 3 reads x−1 … x+2). Like every sample, the box is clipped to the canvas, and a point off the canvas reads transparent. Point Sample reads one pixel at every zoom. To get what the Eyedropper picks, pass its `eyedropperSampleSize` as `size`, its `eyedropperSample` as `sampleLayer` and the document's zoom as `zoom`: left out, `size` is Point Sample (1) and `sampleLayer` is `all`. - `ui.set` also accepts the Crop tool's overlay menu (#1919): `cropOverlay` (`thirds`, `grid`, `diagonal`, `triangle`, `goldenRatio`, `goldenSpiral`), `cropOverlayShow` (`always`: the whole time a crop is pending, the default, as in the reference application; `auto`: only while the crop box is dragged; `never`) and `cropOverlayOrientation` (0..3; Triangle has two orientations and Golden Spiral four, the others ignore it). `ui.inspect` reports them under `toolOptions` (`crop_overlay`, `crop_overlay_show`, `crop_overlay_orientation`). In the app, O cycles the overlay and ⇧O its orientation while the Crop tool shows a box. - `ui.set` also accepts the Pen tools' options bar (#1397): `penMode` (`path` or `shape`) and `penPathOp`, the Path Operations menu (`newLayer`, `combine`, `subtract`, `intersect`, `exclude`): how the next Pen, Freeform Pen or Curvature Pen path joins the selected shape layer (Shape mode; `newLayer` makes a new one) or the targeted vector mask, selected path or Work Path (Path mode, where `newLayer` combines). `ui.inspect` reports them under `toolOptions` (`vector_mode`, `pen_path_op`). Merge Shape Components is the engine command `path.mergeShapeComponents` (work, saved or `layer` path) or `layer.combineShapes.mergeShapeComponents` (shape layers). - `ui.set` also accepts `cropFill` (`background`, the Fill dropdown's first entry, which reads Background (default), or Transparent (default) with Delete Cropped Pixels off, or `contentAware`), the Crop tool's Fill dropdown (#3823, #10872): with `contentAware`, committing a turned or extending frame passes `contentAware: true` to `image.crop`, which fills the area the image doesn't cover from its surroundings. `ui.inspect` reports it as `toolOptions.crop_content_aware`. @@ -283,6 +321,8 @@ the same commands work in the app, the CLI and headless MCP. Paths are dotted ca `unitsAndRulers`, `guidesGridAndSlices`, `plugIns`, `type`, `enhancedControls`, `rawDefaults`, `integrations`, plus `shortcuts.`, `menus` (`hidden`, `colors.`), `toolbar` (`hidden`, `order`) and `colorSettings` (Edit › Color Settings). +`integrations` drives the agent connection while the desktop app runs (`allowAgentControl` also +when it starts); see [Without `--control`](#without---control-preferences--integrations). | Command | Params | |---|---| @@ -380,8 +420,12 @@ magenta alignment lines. `ui.pointer` drives the same code, so agents get identi `photocraft-automation` provides an MCP server built on the official Rust SDK (`rmcp`). It runs in one of two modes: -- **Headless** (`photocraft-cli mcp`): an in-process `photocraft_engine::Session`. There is no window. CPU composition is the default; `--gpu` or `PHOTOCRAFT_GPU=1` enables optional GPU rendering with automatic CPU fallback. -- **Bridge** (`photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `): every tool is forwarded to a running `photocraft --control 7878 --control-token-file ` over this protocol, so agents see and drive the live app. Explicit `--gpu` / `--no-gpu` flags are rejected with a usage error because the desktop controls rendering; `PHOTOCRAFT_GPU` is ignored in bridge mode. `--bridge 7878` is short for `--bridge 127.0.0.1:7878`. With no `--bridge`, `PHOTOCRAFT_CONTROL_PORT` selects the bridge port (`127.0.0.1:`), and the CLI says so on standard error; with neither (or the variable empty), the MCP runs headless. A value that is not a port is a usage error naming the variable. `--automation-read-root` or `--automation-write-root` with the variable set is a usage error, since the bridge would drop the roots. +- **Headless** (`photocraft-cli mcp --headless`, always an isolated session; or plain `mcp` without the suite's `AI-MCP` flag or while agents may not use the app): an in-process `photocraft_engine::Session`. There is no window. CPU composition is the default; `--gpu` or `PHOTOCRAFT_GPU=1` enables optional GPU rendering with automatic CPU fallback. +- **Bridge** (`photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `): every tool is forwarded to a running `photocraft --control 7878 --control-token-file ` over this protocol, so agents see and drive the live app. Explicit `--gpu` / `--no-gpu` flags are rejected with a usage error because the desktop controls rendering; `PHOTOCRAFT_GPU` is ignored in bridge mode. `--bridge 7878` is short for `--bridge 127.0.0.1:7878`. With no `--bridge`, `PHOTOCRAFT_CONTROL_PORT` selects the bridge port (`127.0.0.1:`), and the CLI says so on standard error; with neither (or the variable empty), plain `mcp` uses the open window (below) or runs headless. A value that is not a port is a usage error naming the variable. `--automation-read-root` or `--automation-write-root` with the variable set is a usage error, since the bridge would drop the roots. + +- **The open window** (plain `photocraft-cli mcp`): the bridge, with the address and token read before every tool call from `agent-connection.json` in the app's settings folder, with the suite's `AI-MCP` flag and while the person lets agents use the app. With agents allowed and the app closed, `integrations.whenAppClosed` decides (`launch`, the default: start it and wait up to 45 s; `headless`: headless, with `--automation-read-root` / `--automation-write-root` where given and the app's agent folder for each direction without one; `error`: fail with "PhotoCraft isn't running"), and `--when-closed` overrides it. Otherwise headless, as above (`--headless` forces that). The app publishes that file while agents may connect (the ArtCraft Launcher's switch; without the `AI-MCP` flag a saved Control Port), not with `--control`, and removes it when the connection stops; a file left by a crash fails the connection probe and counts as no app. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). + +`ui.inspect` reports the connection as `agentLink`: `port` while agents can connect, `launchFlags` when `--control` manages it, `error`, `mcpFlag` and `launcher` (the ArtCraft Launcher's switch is on). The bridge keeps one authenticated TCP connection open, and drops and reconnects before a call once the connection has been idle long enough that the app (which closes idle connections after 30s) may have dropped it. A transport failure while sending a request or waiting for its reply, including a reply timeout, drops the connection and reports that the operation may have completed (a call abandoned before its reply, such as a cancelled MCP wait, also drops it, so the next call never queues behind it); inspect the document before retrying an edit. Edits are never automatically resent (#1007); a connection that could not be established is reported as "the request was not sent" instead. The MCP server opts its pure-read tools (`ui_inspect`, `doc_inspect`, `command_list`, `jobs_list`, `session_list`, `ui_screenshot`) into one automatic retry on a fresh connection, since a read applies nothing; clients driving `BridgeClient` directly opt in per call with `call_read`. The next separate call reconnects and authenticates, and reply lines whose `id` does not match the request are skipped. The client's call timeout is 55s, strictly below the server's 60s reply deadline, so the bridge's error is the one callers see. A waited MCP `command_run` (or `command_batch` step) of an engine command is not bound by it (#8130): the bridge sends `engine.execute` once with `"wait": false` and, when the app starts a background job, polls `jobs.list` until the job ends and returns its result, forwarding progress and cancelling the job (`jobs.cancel`) when the request is cancelled, at once, even while a poll still waits on the app. Limits: a command that does not run as a job, a UI command (not an engine command; the app waits on it) and a lost reply to the start itself still fail at the timeout, the last with "operation may have completed" (look for the job in `jobs_list` before retrying); a failed poll of an uncancelled wait reports the job id and leaves the job running; and an unresponsive app still times out. Clients driving `BridgeClient` directly pass `"wait": false` and poll `jobs.list` themselves. It only accepts the literal loopback addresses `127.0.0.1:` and `[::1]:`, because the app only listens on loopback; `localhost:` means `127.0.0.1:` and is never looked up, since a lookup may return `[::1]` first and reach another process listening there. Every connection authenticates by challenge (see above), so the token is never sent, and a listener that cannot prove it holds the token is reported as such ("the control token was not sent"); an app too old for challenge authentication is refused the same way, so update the app with the CLI. Supply its bearer token with `--control-token-file`, `--control-token`, `PHOTOCRAFT_CONTROL_TOKEN_FILE`, or `PHOTOCRAFT_CONTROL_TOKEN`: @@ -426,7 +470,10 @@ lines are visible. The protocol is unencrypted and must remain on loopback; do n it to an untrusted host. Filesystem access fails closed unless launch-time read and/or write roots are granted with -`--automation-read-root` and `--automation-write-root`. Repeat the read flag to grant an ordered +`--automation-read-root` and `--automation-write-root` (or, for the desktop app, Preferences › +Integrations' `readRoot` / `writeRoot`, see [Without `--control`](#without---control-preferences--integrations); +each names one folder and is used only when no flag or variable names a root in that direction). +Repeat the read flag to grant an ordered list of directories; both `--flag

` and `--flag=` syntax are supported by desktop, headless MCP and `serve`, and duplicate read roots are allowed. Headless reads try those roots in launch order and select the first existing regular file. Only a missing file (`NotFound`) @@ -446,6 +493,10 @@ One explicit write-root flag overrides `PHOTOCRAFT_AUTOMATION_WRITE_ROOT`. These variables are not supported by headless `photocraft-cli mcp` or `serve`; supply flags explicitly. In MCP bridge mode, configure roots on the desktop process. Supplying root flags to `photocraft-cli mcp --bridge` is a usage error; a bridge client cannot grant filesystem access. +While agents may use the app, the folders chosen in Preferences › AI Integrations (`readRoot` / +`writeRoot`) are the agents' roots; `mcp` uses them for a headless session only when the app's +*When PhotoCraft is closed* choice (or `--when-closed headless`) asks for one. Without the +person's consent, `mcp` works headless with only the roots given to it, as before. Request paths must be non-empty, forward-slash relative paths beneath the applicable root, or absolute paths beneath a corresponding granted root. An absolute path is compared with the diff --git a/docs/development.md b/docs/development.md index d95484af7d..f84208c8a1 100644 --- a/docs/development.md +++ b/docs/development.md @@ -322,8 +322,9 @@ At startup the desktop lists recovery metadata, then decodes one document at a t `photocraft-cli mcp` serves MCP on stdio using `crates/automation`, which is built on `rmcp`: -- **Headless:** `photocraft-cli mcp --automation-read-root --automation-read-root --automation-write-root `. It drives an in-process engine session with ordered read directories and one write directory. +- **Headless:** `photocraft-cli mcp --headless --automation-read-root --automation-read-root --automation-write-root `. Use `--headless` in scripts, tests and agent sessions: without it `mcp` works in the open window while the ArtCraft Launcher's agents switch is on, and may start PhotoCraft (When PhotoCraft Is Closed defaults to starting it). It drives an in-process engine session with ordered read directories and one write directory. - **Live app:** start `photocraft --control 7878 --control-token-file --automation-read-root --automation-read-root --automation-write-root `, then run `photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file `. The desktop process owns the roots; root flags on the bridging CLI are a usage error. See `docs/control-protocol.md#mcp-bridge`. +- **Live app, no flags:** with the `AI-MCP` flag, turn on ArtCraft Launcher › Settings › AI agents and add the MCP client there; plain `photocraft-cli mcp` then works in the open window. The app publishes its port and token file in `agent-connection.json` in the settings folder; `mcp` reads it on every call. Without a launcher, a scratch `CRAFT_MCP_DIR` with an `apps.json` naming `photocraft` (the format in storytold/craft-ai-integrations, crate `craft-ai-agents`) turns the switch on for a test. See [MCP conventions](mcp.md#connecting-the-desktop-app-no-terminal). Test it against a scratch settings folder with `PHOTOCRAFT_CONFIG_DIR`, which both the app and the CLI honour. For headless MCP clients, pass absolute paths to deliberately chosen trusted workspace directories in the launch arguments. Desktop `PHOTOCRAFT_AUTOMATION_READ_ROOT` and `PHOTOCRAFT_AUTOMATION_WRITE_ROOT` environment variables do **not** grant headless CLI access. Omitting a root flag deliberately denies that direction of access. @@ -367,7 +368,7 @@ Claude Code (`.mcp.json` in the repo root, or `claude mcp add`): "mcpServers": { "photocraft": { "command": "/path/to/photocraft/target/release/photocraft-cli", - "args": ["mcp", "--automation-read-root", "/absolute/path/to/trusted/workspace", "--automation-read-root", "/absolute/path/to/reference/library", "--automation-write-root", "/absolute/path/to/trusted/workspace"] + "args": ["mcp", "--headless", "--automation-read-root", "/absolute/path/to/trusted/workspace", "--automation-read-root", "/absolute/path/to/reference/library", "--automation-write-root", "/absolute/path/to/trusted/workspace"] }, "photocraft-live": { "command": "/path/to/photocraft/target/release/photocraft-cli", @@ -380,7 +381,7 @@ Claude Code (`.mcp.json` in the repo root, or `claude mcp add`): ```sh cargo build --release -p photocraft-cli mkdir -p "$PWD/photocraft-work" -claude mcp add photocraft -- "$PWD/target/release/photocraft-cli" mcp \ +claude mcp add photocraft -- "$PWD/target/release/photocraft-cli" mcp --headless \ --automation-read-root "$PWD/photocraft-work" \ --automation-write-root "$PWD/photocraft-work" ``` @@ -772,19 +773,19 @@ so a following `ui.inspect` observes their effect. ## Photoshop Actions (.atn) -`photocraft-psd` reads Photoshop Actions files (`atn`, versions 12 and 16) and writes version 16 +`craft-psd` reads Photoshop Actions files (`atn`, versions 12 and 16) and writes version 16 (Photoshop 6 and later); `photocraft-engine`'s `atn_cmds` maps their events onto commands (`actions.load`, `actions.save`; the Actions panel menu's Load/Save Actions…; `photocraft-cli batch --actions set.atn`). To see what a set holds (event ids, panel names, the parameter keys Photoshop recorded) when adding an event to the table: ```sh -cargo run -p photocraft-psd --example atn_dump -- "Default Actions.atn" -cargo run -p photocraft-psd --example atn_roundtrip -- "Default Actions.atn" # parse, write, diff +cargo run -p craft-psd --example atn_dump -- "Default Actions.atn" +cargo run -p craft-psd --example atn_roundtrip -- "Default Actions.atn" # parse, write, diff ``` The real-file oracles are `corpus/atn/` (16 sets from seven public repositories, see *Test -corpora*): `photocraft-psd`'s corpus test parses every file and rewrites it byte for byte; +corpora*): `craft-psd`'s corpus test parses every file and rewrites it byte for byte; `photocraft-engine`'s loads, saves and reloads every set and caps the steps that still have no PhotoCraft equivalent. @@ -809,7 +810,7 @@ recorded rectangle/preset are retained for saving, without resizing the target. `crates/psd/tests/it/atn_contract.rs` checks the parser's public API against small, independently encoded version-16 fixtures (the version-12 ones are read by `atn_v12::`) in `crates/psd/tests/fixtures/atn/` (provenance and checksums in -its README): `cargo test -p photocraft-psd --test it atn_contract::`. +its README): `cargo test -p craft-psd --test it atn_contract::`. Recorded layer indexes and ordinals resolve against the full stack, including collapsed children and hidden group-end positions. Indexed moves use the stack before the move. Recorded document indexes are one-based opening order; a native numeric `document` parameter remains a zero-based @@ -885,7 +886,7 @@ physical RAM (excluding swap) and, where measurable, system commit headroom: - These budgets apply to an import's **aggregate peak estimate**, not to one allocation: a peak may sum many layer, mask, merged and workspace buffers. Each individual buffer must still fit the target's layout limit (`isize::MAX`) and the decoder's own per-buffer allowance - (`photocraft-psd`'s `MAX_DECODED_BYTES`, `photocraft-codecs`' `Limits::max_alloc`), which is + (`craft-psd`'s `MAX_DECODED_BYTES`, `photocraft-codecs`' `Limits::max_alloc`), which is enforced by fallible allocation or an explicit cap where that buffer is created. A 64-bit native process has no measurable aggregate address-space cap, so admission relies on explicit approval plus those per-buffer checks; 32-bit native uses a 2 GiB project cap @@ -1051,7 +1052,7 @@ scripts/fetch-corpus.sh # the same as cargo xtask corpus --all **Opt-in locally, strict when opted in, always in CI.** -- The corpus tests sit behind the `corpus` cargo feature of `photocraft-psd`, `photocraft-codecs`, +- The corpus tests sit behind the `corpus` cargo feature of `craft-psd`, `photocraft-codecs`, `photocraft-io` and `photocraft-engine`, so plain `cargo test` neither compiles nor needs them. The HEIF ones also need the `heif` feature of `photocraft-codecs`/`photocraft-io` (test-corpus turns it on). diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 315aaa1e02..f1fe1e59ce 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-11-08 · **Change:** minor (PDF: spot plates described in XMP for converters, document XMP embedded; PDF: spot channels as overprinting `/Separation` plates, a Multichannel document as plates alone, FILE-215-17's PDF part; Fujifilm compressed RAF (lossless and lossy, X-Trans and Bayer) decodes instead of falling back to the embedded JPEG preview, #7377; Camera Raw: an `.xmp` sidecar's crop crops the opened raw, and `crs:RawFileName` is no longer named as unsupported, #9985; CLI `--metadata none|all` for `convert`, `run --out` and `batch`: `none` leaves the document XMP and free-form text out of flat exports, as Export As's Metadata: None, `all` the default, #9466; Hasselblad 3FR/FFF, the X2D II 100C, decodes; scripted PSD/PSB saves take `maximizeCompatibility`, and the CLI `--no-maximize-compatibility`, #8064; TIFF Options on Save As and Save a Copy: Image Compression None/LZW/ZIP, Save Image Pyramid, Save Transparency and Discard Layers, also `tiffTransparency`/`tiffPyramid` for scripts, the CLI and MCP, #8827; `.atn`: 145 supported events including Shear after Actions batch 12 (Groups A–I, command options, version 12 files, reference forms); the supported table and measured reference are in [atn.md](atn.md); 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 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-08 · **Change:** minor (JPEG Options shows the size the file will have, FILE-215-19 partial; PDF: spot plates described in XMP for converters, document XMP embedded; PDF: spot channels as overprinting `/Separation` plates, a Multichannel document as plates alone, FILE-215-17's PDF part; Fujifilm compressed RAF (lossless and lossy, X-Trans and Bayer) decodes instead of falling back to the embedded JPEG preview, #7377; Camera Raw: an `.xmp` sidecar's crop crops the opened raw, and `crs:RawFileName` is no longer named as unsupported, #9985; CLI `--metadata none|all` for `convert`, `run --out` and `batch`: `none` leaves the document XMP and free-form text out of flat exports, as Export As's Metadata: None, `all` the default, #9466; Hasselblad 3FR/FFF, the X2D II 100C, decodes; scripted PSD/PSB saves take `maximizeCompatibility`, and the CLI `--no-maximize-compatibility`, #8064; TIFF Options on Save As and Save a Copy: Image Compression None/LZW/ZIP, Save Image Pyramid, Save Transparency and Discard Layers, also `tiffTransparency`/`tiffPyramid` for scripts, the CLI and MCP, #8827; `.atn`: 145 supported events including Shear after Actions batch 12 (Groups A–I, command options, version 12 files, reference forms); the supported table and measured reference are in [atn.md](atn.md); 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. @@ -27,7 +27,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity. | 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, 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); TIFF Options on Save As and Save a Copy (Image Compression None/LZW/ZIP, Save Image Pyramid, Save Transparency, Discard Layers and Save a Copy; scripts pass `tiffCompression`, `tiffTransparency`, `tiffPyramid`, `tiffLayers`; #8827), no JPEG compression, Pixel Order or Byte Order (the encoder writes interleaved samples in the machine's byte order); 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); Save Transparency on keeps the transparency as the first extra sample ahead of the channels (a layered file marks it with `MTrn`, as Photoshop does), off mattes on white; unset, it is kept only without alpha or spot channels | -| JPEG | R/W | yes | yes | 8-bit Gray/RGB/CMYK, ICC/EXIF/XMP (the CLI's `--metadata none` leaves the document XMP out, #9466); 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 | +| JPEG | R/W | yes | yes | 8-bit Gray/RGB/CMYK, ICC/EXIF/XMP (the CLI's `--metadata none` leaves the document XMP out, #9466); 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. The dialog shows the size the file will have ("152.3K", "1.5M"), encoded in memory as OK would write it, on a worker thread in the desktop app and in the frame on the web, for documents up to 40 MP (4 MP on the web; larger ones read "—"). No Matte or progressive Scans (3–5) | | PNG | R/W | yes | yes | 8/16-bit, ICC/text (the CLI's `--metadata none` leaves the document XMP and text out, #9466); 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 | | BMP | R/W | yes | yes | 8-bit; palette BMPs open in Indexed Color mode and Indexed Color documents save as palette BMPs (no transparency) | @@ -198,6 +198,7 @@ The original reference entry retains its source date and historical totals; curr | 2026-10-31 | minor | `.atn`: Split Channels (`SplC`, its recorded `documentIDs` not replayed or written), Merge Spot Channel (`MSpt`), Trap (`Trap`, `Wdth` clamped to 32767 px) and Match Color without a source (`matchColor`, `noReference`) map to `channel.split`, `channel.mergeSpot`, `image.trap` and `image.adjustments.matchColor`; a Match Color step that matches another image stays a Photoshop step (#10609) | | 2026-10-31 | minor | `.atn`: Filter Gallery (`GEfc` with the effect in `GEfk`, or the effect's own event) maps all 47 effects to `filter.gallery.` with every key in recorded order, out-of-range values clamped and missing keys given Photoshop's defaults (was Spatter only); Glass maps the Frosted and Canvas textures (#10592) | | 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-28 | minor | JPEG Options shows the size the file will have (FILE-215-19 partial: no Matte or progressive Scans) | | 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) | diff --git a/docs/gaps.md b/docs/gaps.md index 1b0adf76a9..f41ac04fb6 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-11-10 · **Change:** minor (Image Processor accepts copies of the current or all open documents, including unsaved edits; G10: PDF writes spot channels as overprinting `/Separation` plates and a Multichannel document as plates alone, FILE-215-17's PDF Separation part; G9: Column Size preference and Image Size / Canvas Size Columns unit, #6214: 8 of 199 preferences do nothing; G14: Fujifilm compressed RAF decodes, #7377; G5: Warp mode edits Photoshop's Cylinder warp, #4112: the Warp menu lists it, five handles set its seven values as in the reference, and a smart object's stored cylinder opens in Warp mode as one; Average executes through shared filters on Smart Objects and imported PSD records; Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; G4: Both Axes on Scatter headers, #3825 partial; G4: combined Spacing checkbox and percentage header, #3825 partial; G14: Hasselblad 3FR/FFF, the X2D II 100C's uncompressed CFA, decodes; G4: Angle/Roundness fields left of the Brush Tip Shape widget, #3825 partial; G12: the eraser end of flipped pens selects the Eraser on Windows with Windows Ink on, #2285; no estimate changed; RGB and CMYK documents preview their spot inks as an overprint on the canvas and in the PSD thumbnail, FILE-215-17 narrows to PDF Separation, #10249; G2: compositor compilation moved off the first document refresh, with startup measurements pending, #9157; G11: Playback Options dialog with Step by Step and Pause For, #5212; G11: Stop step messages with Continue/Stop and nested resume, #8386; adjustment-layer Make keeps name, blend mode and clipping, #8384; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; G8: Type › OpenType › Stylistic Sets submenu, Set 1–20, #10285; G8: PhotoCraft-native PSDs keep stylistic sets and other Txt2-only OpenType flags through save/reopen, #10308; G10: TIFF Options dialog on Save As and Save a Copy, compression, Save Image Pyramid, Save Transparency, #8827; G11: Batch Esc Continue/Stop and read-only input previews; full live tabs remain open, #4579; G11: action recording folds Move-tool nudges, records relative keyboard document switches and scales point text placement; paragraph boxes remain open, #4514; G11: Batch measured output naming and UTF-16 log corrections; remaining progress and cancel prompt parity tracked, #4579; G11: Render ATN events mapped; Stylize/Pixelate ATN events mapped, current counts 128 supported/89 unmapped; G9: 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; G11: `.atn` document offsets preserve opening order after tab reordering, #7103; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; Smooth and Feather command masks cropped to selection bounds plus blur reach; G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; 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-11-10 · **Change:** minor (G10: JPEG Options shows the size the file will have; FILE-215-19 stays partial (Matte, Scans); Image Processor accepts copies of the current or all open documents, including unsaved edits; G10: PDF writes spot channels as overprinting `/Separation` plates and a Multichannel document as plates alone, FILE-215-17's PDF Separation part; G9: Column Size preference and Image Size / Canvas Size Columns unit, #6214: 8 of 199 preferences do nothing; G14: Fujifilm compressed RAF decodes, #7377; G5: Warp mode edits Photoshop's Cylinder warp, #4112: the Warp menu lists it, five handles set its seven values as in the reference, and a smart object's stored cylinder opens in Warp mode as one; Average executes through shared filters on Smart Objects and imported PSD records; Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; G4: Both Axes on Scatter headers, #3825 partial; G4: combined Spacing checkbox and percentage header, #3825 partial; G14: Hasselblad 3FR/FFF, the X2D II 100C's uncompressed CFA, decodes; G4: Angle/Roundness fields left of the Brush Tip Shape widget, #3825 partial; G12: the eraser end of flipped pens selects the Eraser on Windows with Windows Ink on, #2285; no estimate changed; RGB and CMYK documents preview their spot inks as an overprint on the canvas and in the PSD thumbnail, FILE-215-17 narrows to PDF Separation, #10249; G2: compositor compilation moved off the first document refresh, with startup measurements pending, #9157; G11: Playback Options dialog with Step by Step and Pause For, #5212; G11: Stop step messages with Continue/Stop and nested resume, #8386; adjustment-layer Make keeps name, blend mode and clipping, #8384; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; G8: Type › OpenType › Stylistic Sets submenu, Set 1–20, #10285; G8: PhotoCraft-native PSDs keep stylistic sets and other Txt2-only OpenType flags through save/reopen, #10308; G10: TIFF Options dialog on Save As and Save a Copy, compression, Save Image Pyramid, Save Transparency, #8827; G11: Batch Esc Continue/Stop and read-only input previews; full live tabs remain open, #4579; G11: action recording folds Move-tool nudges, records relative keyboard document switches and scales point text placement; paragraph boxes remain open, #4514; G11: Batch measured output naming and UTF-16 log corrections; remaining progress and cancel prompt parity tracked, #4579; G11: Render ATN events mapped; Stylize/Pixelate ATN events mapped, current counts 128 supported/89 unmapped; G9: 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; G11: `.atn` document offsets preserve opening order after tab reordering, #7103; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; Smooth and Feather command masks cropped to selection bounds plus blur reach; G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; 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 @@ -412,7 +412,7 @@ what an agent can't finish alone. ### G10. Missing and partial file formats - **Progress (2026-10-26):** Embedded SVG/PDF-compatible AI/PDF/EPS smart objects can be edited in VectorCraft, including nested PSD payloads. AI/PDF/EPS working copies retain their format with a separate source-bound SVG display preview; native bytes and previews persist through .pcraft and PSD/PSB saves. This does not add standalone EPS/DCS import or establish lossless Adobe round-trip compatibility. See [workflow and limits](embedded-vector-editing.md); estimates and parity percentages are unchanged. -- **Missing:** JPEG Options' Matte, progressive Scans and size preview (FILE-215-19 partial), TIFF Options' JPEG compression, Pixel Order and Byte Order (the rest landed 2026-11-02, #8827), Photoshop PDF read and its vector/text/multi-page +- **Missing:** JPEG Options' Matte and progressive Scans (FILE-215-19 partial), TIFF Options' JPEG compression, Pixel Order and Byte Order (the rest landed 2026-11-02, #8827), Photoshop PDF read and its vector/text/multi-page write (FILE-215-10, #2541; a single flattened page now saves via Save As / Save a Copy / CLI, 2026-10-11, #3401), AVIF read (#463) and default-build AVIF write, JPEG XL, JPEG 2000 (#1047), DICOM, EPS/DCS, Pixar, WBMP, MPO/JPS, PICT, Scitex CT, Photoshop @@ -437,7 +437,7 @@ what an agent can't finish alone. `.cin`), sharing the DPX header/packing (`crates/codecs/src/codecs/dpx.rs`); a Cineon frame saved back keeps its code values. - **Progress (2026-10-23):** Amiga IFF/ILBM (`FORM ... ILBM`/`PBM `) 1–8-plane paletted and - 24-plane RGB bitmaps open, stored or ByteRun1-compressed (`crates/codecs/src/codecs/iff.rs`); + 24-plane RGB bitmaps open, stored or ByteRun1-compressed (craft-libs' `craft-raster-codecs`, `iff`); Save As `.iff` writes a 24-plane ILBM with a 1-bit mask plane for alpha. - **Estimate:** 120–220 h. @@ -511,6 +511,7 @@ what an agent can't finish alone. | 2026-11-05 | minor | G8: Type > OpenType > Stylistic Sets submenu (Set 1–20) landed (TYPE-218-5, #10285); font-capability greying still missing; PhotoCraft-native PSDs already keep the sets since #10308 | | 2026-10-30 | minor | Art History Brush Opacity on the options bar, #10263; no estimate changed | | 2026-10-28 | minor | G2: prepare the GPU compositor in the background; startup performance baseline pending (#9157) | +| 2026-10-28 | minor | G10: JPEG Options shows the size the file will have ("152.3K"), worked out as Quality and Format Options change (on a worker thread on desktop, in the frame on the web); FILE-215-19 stays partial (Matte, progressive Scans); no readiness percentage or estimate changed | | 2026-10-27 | minor | Smooth/Feather command reads and replacement use selection bounds plus blur reach; full-canvas reference and release comparisons extended; percentages and scorecard budgets unchanged | | 2026-11-01 | minor | G9: 11 of 183 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-30 | minor | G10: visible spot channels of RGB and CMYK documents overprint the canvas composite and the PSD thumbnail, and open visible (#10249); FILE-215-17 stays partial, narrowed to PDF Separation; estimate unchanged | diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 91c47966da..f5e4608d89 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -1,6 +1,6 @@ # Hardware parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Windows: flipping the pen to its eraser end selects the Eraser with Windows Ink on, #2285, not yet confirmed on a pen with an eraser end; optional WinTab backend on Windows: pressure and the eraser end; tilt on devices with orientation axes; rotation only with a pen and driver that report twist, with Windows Ink off) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-08 · **Change:** minor (Graphics Adapter choice on Linux, #1885; Camera Raw's preview develops its per-pixel stages on the GPU; GPU, Wayland (tilt and eraser end via Xwayland) and monitor-profile rows refreshed against main; Windows: flipping the pen to its eraser end selects the Eraser with Windows Ink on, #2285, not yet confirmed on a pen with an eraser end; previously minor: optional WinTab backend on Windows: pressure and the eraser end; tilt on devices with orientation axes; rotation only with a pen and driver that report twist, with Windows Ink off) · **Target:** Adobe Photoshop 2026 Each hardware feature Photoshop 2026 (27.11.0) uses, per platform, against PhotoCraft. Photoshop side: its bundle (Metal and OpenCL paths, "Precise Color Management for HDR Display" and EDR @@ -23,19 +23,19 @@ HDR display to verify. | GPU compositing of layers, blend modes, effects | partial (Photoshop composites mostly on CPU) | wgpu compositor, ≤ 1/255 vs CPU oracle; Multichannel and > texture-limit regions fall back to CPU | done (ahead in places) | | GPU compositor startup | available | Pipeline preparation runs in the background on native hardware; the CPU composites until ready. Windows WARP probe: 0.329 ms p95, 6.860 ms maximum device-work stall during two FXC builds; hardware measurements remain pending (#9157, #9364, #6419) | partial | | GPU filters (Blur Gallery, Liquify, Smart Sharpen, Camera Raw) | yes | CPU (rayon) for filters; GPU for compose and effects. Camera Raw's preview runs its per-pixel stages (white balance to grain) in one wgpu pass, about 2-3 ms vs 11-28 ms on the CPU for the 858×572 proxy, depending on the machine, Shadows and Highlights (the local Laplacian filter) as fragment passes in front of it, 8.7-10.6 ms vs 147-300 ms, and Dehaze, Clarity and Texture (box, minimum and guided filters) as fragment passes too, 2.7-7.7 ms vs 7.6-17.7 ms each (Dehaze's dark channel opened as in the CPU develop, #9273); with all of them and every per-pixel stage 17-24 ms vs 222 ms on an RTX 5060 Ti. Detail, Calibration and OK still develop on the CPU (#6916) | partial | -| Documents larger than the GPU texture limit | yes (tiled) | CPU fallback; tiling in progress (#49) | partial | +| Documents larger than the GPU texture limit | yes (tiled) | paged GPU residency, composited page cell by page cell (`crates/gpu/src/lib.rs`, #49 closed) | done | | CPU-only fallback when no GPU | yes, reduced | `cpu` canvas preference; fails to start without an adapter on some Linux systems (#2519, #2412) | partial | | Choosing the GPU on a multi-GPU machine | Preferences › Performance › Use Graphics Processor | Linux only: Preferences › Performance › Advanced › GPU adapter and `PHOTOCRAFT_GPU_ADAPTER` (#1885); ignored on Windows and macOS | partial | -| Old / integrated GPUs | yes | black line on Intel HD (#2426), OpenCore Macs fail (#1859), Rgba32Float panic (#2020) | partial | +| Old / integrated GPUs | yes | black line on Intel HD (#2426), OpenCore Macs fail (#1859); the Rgba32Float panic is fixed (#2020) | partial | ## Pen tablets | Feature | Photoshop | macOS | Windows | Linux X11 | Linux Wayland | Web | |---|---|---|---|---|---|---| -| Pressure | yes | yes (AppKit monitor) | yes (WM_POINTER), jumpy (#2046) | yes (XInput2) | via Xwayland only; GNOME 50 pen doesn't click (#2622), KDE (#2297) | yes | -| Tilt | yes | yes | **no** (WinTab: with orientation axes, opt-in) | yes | no | yes | +| Pressure | yes | yes (AppKit monitor) | yes (WM_POINTER), jumpy (#2046) | yes (XInput2) | via Xwayland only; GNOME 50 pen doesn't click (#2622); KDE fixed in 0.6.0 (#2297, #1070) | yes | +| Tilt | yes | yes | **no** (WinTab: with orientation axes, opt-in) | yes | via Xwayland only (native Wayland: no) | yes | | Barrel rotation | yes | yes (not applied to tip angle, #1301) | no (WinTab: with a twist-reporting pen and driver, opt-in) | partial | no | yes (twist) | -| Eraser end | yes | yes | yes with Windows Ink, not yet confirmed on hardware (#2285); WinTab: yes (opt-in) | partial | no | partial | +| Eraser end | yes | yes | yes with Windows Ink, not yet confirmed on hardware (#2285); WinTab: yes (opt-in) | partial | partial, via Xwayland only (native Wayland: no) | partial | | WinTab driver mode | yes | – | yes (opt-in; Windows Ink off) | – | – | – | | Pressure curve | Windows Ink / driver | global curve in Preferences (#2195) | same | same | same | same | @@ -50,7 +50,7 @@ rotation; its eraser end comes from the pointer hooks (#2285). | Feature | Photoshop | PhotoCraft | Status | |---|---|---|---| | Colour-managed canvas (document → monitor profile) | yes | yes, folded into the GPU 3D LUT | done | -| Monitor profile detection | per display, live | macOS per display at launch; others sRGB or a chosen .icc | partial | +| Monitor profile detection | per display, live | macOS and Linux X11 (per XRandR output, #2962) per display, following each window's display (#591); Windows and Wayland: sRGB or a chosen .icc | partial | | HDR / EDR output for 32-bit and HDR images | yes ("Precise Color Management for HDR Display") | no; 8-bit sRGB-encoded canvas texture | missing | | High-DPI, physical 100% | yes | yes (#1943) | done | | Multiple monitors: documents in separate OS windows | yes | yes (`extra_windows`) | done | @@ -75,7 +75,9 @@ rotation; its eraser end comes from the pointer hooks (#2285). | 2026-11-05 | minor | Optional WinTab driver mode on Windows: pressure and eraser; tilt with orientation axes; rotation with a twist-reporting pen, with Windows Ink off | | 2026-10-28 | minor | Build GPU compositor pipelines in the background; benchmark baseline pending (#9157) | | 2026-10-10 | major | First version | +| 2026-10-12 | minor | GPU rows (documents past the texture limit, Rgba32Float panic), Wayland KDE pen and monitor-profile detection refreshed against main | | 2026-10-17 | minor | GPU filters: Camera Raw's preview, per-pixel stages (#6916 step 1) | | 2026-10-17 | minor | GPU filters: Camera Raw's preview, Shadows and Highlights (#6916 step 2) | | 2026-10-17 | minor | GPU filters: Camera Raw's preview, Dehaze, Clarity and Texture (#6916 step 3) | | 2026-10-19 | minor | Graphics Adapter choice on Linux (#1885) | +| 2026-11-08 | minor | Linux Wayland: tilt and the eraser end work through Xwayland, like pressure; native Wayland still has no pen | diff --git a/docs/images/SOURCES.md b/docs/images/SOURCES.md index 1d68651a57..7f11ca6b43 100644 --- a/docs/images/SOURCES.md +++ b/docs/images/SOURCES.md @@ -12,7 +12,7 @@ | `photocraft-type.jpg` | PhotoCraft UI screenshot (offscreen snapshot) with *Among the Sierra Nevada, California*, Albert Bierstadt, 1868 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Albert_Bierstadt_-_Among_the_Sierra_Nevada,_California_-_Google_Art_Project.jpg). UI: this project. | | `photocraft-export-light.jpg` | PhotoCraft UI screenshot (offscreen snapshot) with *The Kiss*, Gustav Klimt, 1907–1908 | Artwork: public domain, [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Gustav_Klimt_016.jpg). UI: this project. | -Screenshots must use famous public-domain artwork (or content made in the app), never personal photos. +Screenshots must use famous public-domain artwork (or content made in the app), never personal photos. Only images the README or a doc displays live here (a doc's own before/after comparison included); screenshots that only show a PR's change go in its PR description. # Other bundled data diff --git a/docs/images/clone-source/README.md b/docs/images/clone-source/README.md new file mode 100644 index 0000000000..1c3382616a --- /dev/null +++ b/docs/images/clone-source/README.md @@ -0,0 +1,44 @@ +# Clone source preview captures + +These screenshots use an original synthetic red circle on white, rendered offscreen with the +PhotoCraft `snapshot` example. UI and artwork: PhotoCraft contributors, MIT OR Apache-2.0; +see the repository license files. No external artwork or fonts are included here. + +- `opacity-flow-before.png`: the original hover renderer, with full-strength preview despite + the Clone Stamp's 50% opacity and 40% flow. The source sampler is held fixed to isolate the + preview-strength change. +- `opacity-flow-after.png`: the same capture with opacity and flow applied. The preview is + approximately 20% strength, matching a single hard-tip stamp on an empty destination layer. +- `cross-document.png`: a source picked in a separate document, previewed on an empty destination + layer with the same opacity/flow settings. +- `source-edge.png`: a source picked at its image's top-left corner. Missing source pixels produce + straight top and left clipping edges; the remaining preview has the brush's curved edge. +- `offsets-before.png` and `offsets-after.png`: the same unaligned stamp from source (32,32) at + destination (90,90), with the Clone Source panel open. The old panel reports zero; the corrected + panel reports the actual source-minus-destination displacement, (-58,-58) document pixels. + +For the opacity/flow comparison, pass the contents of `capture.json` to the snapshot example's +`--script` argument, with `--size 1000x760 --scale 1 --hover-at 434,493` and the desired `--out` path. +The before capture uses the original `canvas/strokes.rs`; the after capture uses the fix. +The engine source sampler is identical in these two captures. + +For the offset comparison, use `offset-capture.json` with the same size/scale, and +`--click-at 638,50 --hover-at 434,493`. The click clears Aligned in the options bar; the engine +stroke in the script also uses `aligned: false`. These capture assets use the existing signed +control-channel convention: sampling coordinates equal destination coordinates plus `offset` +at 100% scale without rotation or flips. + +The documented behavior is based on Adobe's [Clone Stamp help](https://helpx.adobe.com/photoshop/desktop/repair-retouch/heal-clone/retouch-images-with-the-clone-stamp-tool.html) +and [Photoshop reference](https://help.adobe.com/archive/en/photoshop/cs6/photoshop_reference.pdf#page=346) +(printed pages 339–341): Aligned continues the established pairing, unaligned strokes restart +from the sampling point, five sources are independent, and X/Y specify pixel offsets. Adobe's +text does not specify every pre-stroke readout or mode-toggle detail; no native-Photoshop +measurement of those undocumented details is claimed. + +The archived reference also requires matching document color modes for cross-document Clone +Stamp; Healing Brush additionally permits Grayscale on either side. The sampler and both +previews enforce those rules while converting compatible source/destination ICC profiles. +The current 2026 help omits that compatibility detail; this follows the explicit reference +rather than claiming a measurement of current Photoshop. + +Source-edge regressions also cover sources and destinations without stored alpha, including opaque black. Canvas coverage survives native-channel conversion, affine filtering and wrapping; the destination storage format is retained. diff --git a/docs/images/clone-source/capture.json b/docs/images/clone-source/capture.json new file mode 100644 index 0000000000..6858376907 --- /dev/null +++ b/docs/images/clone-source/capture.json @@ -0,0 +1,8 @@ +[ + ["engine.execute", {"command": "file.new", "params": {"name": "Clone Preview", "width": 128, "height": 128}}], + ["engine.execute", {"command": "paint.pencil", "params": {"points": [[32, 32]], "size": 60, "color": "#d02020"}}], + ["engine.execute", {"command": "cloneSource.set", "params": {"source": [32, 32]}}], + ["engine.execute", {"command": "layer.new.layer", "params": {}}], + ["ui.set", {"tool": "cloneStamp", "zoom": 3, "center": [64, 64]}], + ["engine.execute", {"command": "tools.setBrush", "params": {"size": 36, "hardness": 1, "opacity": 0.5, "flow": 0.4}}] +] diff --git a/docs/images/clone-source/cross-document.png b/docs/images/clone-source/cross-document.png new file mode 100644 index 0000000000..3b8749e523 Binary files /dev/null and b/docs/images/clone-source/cross-document.png differ diff --git a/docs/images/clone-source/offset-capture.json b/docs/images/clone-source/offset-capture.json new file mode 100644 index 0000000000..1d47aa9305 --- /dev/null +++ b/docs/images/clone-source/offset-capture.json @@ -0,0 +1,10 @@ +[ + ["engine.execute", {"command": "file.new", "params": {"name": "Clone Offsets", "width": 128, "height": 128}}], + ["engine.execute", {"command": "paint.pencil", "params": {"points": [[32, 32]], "size": 60, "color": "#d02020"}}], + ["engine.execute", {"command": "cloneSource.set", "params": {"source": [32, 32]}}], + ["engine.execute", {"command": "layer.new.layer", "params": {}}], + ["ui.set", {"tool": "cloneStamp", "zoom": 3, "center": [64, 64]}], + ["engine.execute", {"command": "tools.setBrush", "params": {"size": 36, "hardness": 1, "opacity": 0.5, "flow": 0.4}}], + ["engine.execute", {"command": "paint.cloneStamp", "params": {"points": [[90, 90]], "size": 36, "hardness": 100, "opacity": 50, "flow": 40, "aligned": false}}], + ["ui.menu.invoke", {"id": "window.panel.cloneSource"}] +] diff --git a/docs/images/clone-source/offsets-after.png b/docs/images/clone-source/offsets-after.png new file mode 100644 index 0000000000..2891fca7bb Binary files /dev/null and b/docs/images/clone-source/offsets-after.png differ diff --git a/docs/images/clone-source/offsets-before.png b/docs/images/clone-source/offsets-before.png new file mode 100644 index 0000000000..3d33e31ac9 Binary files /dev/null and b/docs/images/clone-source/offsets-before.png differ diff --git a/docs/images/clone-source/opacity-flow-after.png b/docs/images/clone-source/opacity-flow-after.png new file mode 100644 index 0000000000..7199ef487a Binary files /dev/null and b/docs/images/clone-source/opacity-flow-after.png differ diff --git a/docs/images/clone-source/opacity-flow-before.png b/docs/images/clone-source/opacity-flow-before.png new file mode 100644 index 0000000000..c04bdcc535 Binary files /dev/null and b/docs/images/clone-source/opacity-flow-before.png differ diff --git a/docs/images/clone-source/source-edge.png b/docs/images/clone-source/source-edge.png new file mode 100644 index 0000000000..d24391ca40 Binary files /dev/null and b/docs/images/clone-source/source-edge.png differ diff --git a/docs/images/gradient-overlay-method-after.png b/docs/images/gradient-overlay-method-after.png deleted file mode 100644 index 8d6107e7ab..0000000000 Binary files a/docs/images/gradient-overlay-method-after.png and /dev/null differ diff --git a/docs/images/gradient-overlay-method-before.png b/docs/images/gradient-overlay-method-before.png deleted file mode 100644 index 75a63d97b3..0000000000 Binary files a/docs/images/gradient-overlay-method-before.png and /dev/null differ diff --git a/docs/images/gradient-overlay-method-options.png b/docs/images/gradient-overlay-method-options.png deleted file mode 100644 index 1c7aaed68c..0000000000 Binary files a/docs/images/gradient-overlay-method-options.png and /dev/null differ diff --git a/docs/images/guide-position-after-tab.png b/docs/images/guide-position-after-tab.png deleted file mode 100644 index a0658b74b1..0000000000 Binary files a/docs/images/guide-position-after-tab.png and /dev/null differ diff --git a/docs/images/guide-position-before-tab.png b/docs/images/guide-position-before-tab.png deleted file mode 100644 index 2eca847845..0000000000 Binary files a/docs/images/guide-position-before-tab.png and /dev/null differ diff --git a/docs/images/preferences-apply-after.png b/docs/images/preferences-apply-after.png deleted file mode 100644 index 5abd1fd695..0000000000 Binary files a/docs/images/preferences-apply-after.png and /dev/null differ diff --git a/docs/images/preferences-apply-before.png b/docs/images/preferences-apply-before.png deleted file mode 100644 index 23d6c3f855..0000000000 Binary files a/docs/images/preferences-apply-before.png and /dev/null differ diff --git a/docs/localization-parity.md b/docs/localization-parity.md index d187c4221d..3f7f9af09b 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -1,6 +1,6 @@ # Localization parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-08 · **Change:** trivial (the catalogs moved to storytold/craft-i18n and are measured with `cargo xtask i18n-report`; Serbian is `sr-latn`; previously minor: Georgian interface catalog; previously minor: Azerbaijani UI catalog merged with current languages; native review pending; Bosnian UI catalog; previously minor: Swedish, Finnish, Danish and Norwegian Bokmål UI catalogs; previously minor: Arabic UI catalog) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-11-08 · **Last updated:** 2026-11-08 · **Change:** minor (the catalogs moved to storytold/craft-i18n and are measured with `cargo xtask i18n-report`; Serbian is `sr-latn`; coverage re-measured on the merged tree, 2,449 keys; Arabic 92.1%; 35 registered languages; Hindi partial; Georgian, Azerbaijani, Hebrew, Romanian, Tamil, Thai and Urdu measured; previously minor: Swedish, Finnish, Danish and Norwegian Bokmål UI catalogs) · **Target:** Adobe Photoshop 2026 Per-language status of PhotoCraft's UI. How catalogs work and how to add one: [`localization.md`](localization.md). Language notes: [Korean](localization-ko.md), [Spanish](localization-es.md), @@ -9,11 +9,11 @@ Per-language status of PhotoCraft's UI. How catalogs work and how to add one: **How measured.** `cargo xtask i18n-coverage` (now `cargo xtask i18n-report`, `xtask/src/i18n_report.rs`, which reads the craft-i18n catalogs in `CRAFT_I18N_DIR`) defines the key universe: `tl!("…")` literals and `trn(` plurals in `ui-egui` (tests excluded), menu-catalog labels and path segments, `menus.rs` UI commands, and engine `CommandSpec` labels and menu paths: -**1,608 English keys** on 2026-10-10. Each catalog (`crates/ui-egui/src/i18n/.tsv`) was -checked against that universe by a source script replicating the xtask (no build). Catalogs hold -more rows than the universe because they also translate dynamic `tl!(expr)` strings (~159 call +**2,449 English keys** on 2026-11-08 after merging main (2,431 earlier that day, 2,428 on 2026-11-07, 2,400 on this branch before that day's merge, 2,389 earlier, 2,369 on main earlier that day, 2,272 on 2026-11-05, 2,199 on 2026-10-31, 2,202 on 2026-10-29, 1,982 on 2026-10-22, 1,918 on 2026-10-21, 1,772 on 2026-10-12, 1,608 on 2026-10-10). Each catalog (`locales//photocraft.tsv` in craft-i18n) +is checked against that universe by the xtask itself; "rows" are the non-comment, non-blank lines +of the `.tsv`. Catalogs hold more rows than the universe because they also translate dynamic `tl!(expr)` strings (~159 call sites the tool can't enumerate). **Not covered anywhere:** engine error and status messages and -filter parameter help, which are English in every language; so no language is `full`. The report +filter parameter help, which are English in every language; so no translated language is `full`. The report also lists, per language, the keys its catalog lacks; those show in English. `cargo xtask ci` prints it as its last step and never fails on it. @@ -23,58 +23,59 @@ installed per Creative Cloud install, here `en_US`). It has no Hindi, Arabic, In Vietnamese UI; Arabic and Hebrew users get English "Middle East" builds with the World-Ready composer, and its text engine handles RTL, Devanagari and Indic scripts. -**Summary.** 7 of the 12 key languages at 100% of measured keys (status `partial` because of the -engine messages), 2 absent (Hindi, Vietnamese), plus 18 other registered languages. Weighted by -speakers, ~55% ready. Remaining: 80–140 h, plus native-speaker review (recorded only for Italian, +**Summary.** 1 of the 12 key languages at 100% of measured keys (English), 10 at 92.1–93.7% +(Arabic at 92.1%, 194 keys in English; Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, +German, Korean, Vietnamese at 93.3–93.7%, 155–164 keys each still show in English; status `partial` also +because of the engine messages), Hindi partial (400 of 2,449, 16.3%), plus the other shipped languages below. Weighted by +speakers, ~55% ready. Remaining: 90–143 h, plus native-speaker review (recorded only for Italian, 2026-10-12). ## The twelve key languages | Language | Code | UI strings (measured keys) | Catalog rows | Dialogs / tooltips / help | Script support | Native review | Status | To `full` | |---|---|---|---:|---|---|---|---|---:| -| English | `en` | 1,608 / 1,608 (100%) | source | all | Latin | – | full | 0 h | -| Simplified Chinese | `zh-hans` | 1,608 / 1,608 (100%) | 2,366 | dialogs, tooltips yes; engine messages English | CJK fonts (lazy loader), IME preedit/commit, vertical type | no | partial | 8–12 h | -| Spanish | `es` | 1,844 / 1,844 (100%) | 4,010 | as above; complete dynamic UI key set | Latin | no | partial | 6–10 h | -| Hindi | `hi` | partial | 448 | Top menus, toolbox tools, camera raw, dialogs, plurals | Devanagari shaping in the text engine (parley/HarfRust); no Devanagari fallback font (TYPE-218-3) | no | partial | 15–20 h | -| Arabic | `ar` | 2,175 / 2,175 (100%, 2026-10-28) | 3,410 | as above; combined from the community catalogs with one term per concept | Arabic shaping and bidi in the UI (egui 0.37) and the text engine, Arabic fallback font; RTL shell layout but not inside panels (DIST-220-4), paragraph direction buttons but no visual RTL caret (TYPE-218-2 partial) | no | partial | 15–25 h | -| French | `fr` | 1,608 / 1,608 (100%) | 2,766 | as above | Latin | no | partial | 6–10 h | -| Portuguese (Brazil) | `pt-br` | 1,608 / 1,608 (100%) | 2,788 | as above | Latin; every `pt` locale uses it | no | partial | 6–10 h | -| Indonesian | `id` | 1,608 / 1,608 (100%) | 2,764 | as above | Latin | no | partial | 6–10 h | -| Japanese | `ja` | 1,608 / 1,608 (100%) | 3,356 | as above | CJK fonts, IME (Windows IME broken, #590), vertical type (tategaki); installed Japanese fonts missing from the list (#2330) | no | partial | 10–16 h | -| German | `de` | 1,608 / 1,608 (100%) | 2,400 | as above | Latin | no | partial | 6–10 h | -| Korean | `ko` | 1,608 / 1,608 (100%) | 2,936 | as above; terminology from Photoshop's Korean UI ([notes](localization-ko.md)) | Hangul fonts, IME | no | partial | 6–10 h | -| Vietnamese | `vi` | 0 (0%) | – | – | Latin with stacked diacritics (shaping supported) | no | none | 12–18 h | +| English | `en` | 2,449 / 2,449 (100%) | source | all | Latin | – | full | 0 h | +| Simplified Chinese | `zh-hans` | 2,285 / 2,449 (93.3%) | 3,188 | dialogs, tooltips yes; engine messages English | CJK fonts (lazy loader), IME preedit/commit, vertical type | no | partial | 8–12 h | +| Spanish | `es` | 2,293 / 2,449 (93.6%) | 4,430 | as above; complete dynamic UI key set | Latin | no | partial | 6–10 h | +| Hindi | `hi` | 400 / 2,449 (16.3%) | 629 | Top menus, toolbox tools, Camera Raw, dialogs, plurals | Devanagari shaping in the text engine (parley/HarfRust); no Devanagari fallback font (TYPE-218-3) | no | partial | 15–20 h | +| Arabic | `ar` | 2,255 / 2,449 (92.1%) | 3,487 | as above; combined from the community catalogs with one term per concept | Arabic shaping and bidi in the UI (egui 0.37) and the text engine, Arabic fallback font; RTL shell layout but not inside panels (DIST-220-4), paragraph direction buttons but no visual RTL caret (TYPE-218-2 partial) | no | partial | 15–25 h | +| French | `fr` | 2,292 / 2,449 (93.6%) | 4,517 | as above | Latin | no | partial | 6–10 h | +| Portuguese (Brazil) | `pt-br` | 2,294 / 2,449 (93.7%) | 4,411 | as above | Latin; every `pt` locale uses it | no | partial | 6–10 h | +| Indonesian | `id` | 2,288 / 2,449 (93.4%) | 3,524 | as above | Latin | no | partial | 6–10 h | +| Japanese | `ja` | 2,291 / 2,449 (93.5%) | 4,141 | as above | CJK fonts, IME (Windows IME broken, #590), vertical type (tategaki) | no | partial | 10–16 h | +| German | `de` | 2,287 / 2,449 (93.4%) | 3,532 | as above | Latin | no | partial | 6–10 h | +| Korean | `ko` | 2,291 / 2,449 (93.5%) | 4,070 | as above; terminology from Photoshop's Korean UI ([notes](localization-ko.md)) | Hangul fonts, IME | no | partial | 6–10 h | +| Vietnamese | `vi` | 2,291 / 2,449 (93.5%) | 3,960 | as above | Latin with stacked diacritics (shaping supported) | no | partial | 6–10 h | ## Other shipped languages -18 registered languages are outside the twelve-language table. The following nine have -1,608 / 1,608 measured keys, status `partial` for the same reason: Traditional -Chinese `zh-hant` (2,329 rows), Russian `ru` (4,227 keys; also every dynamic label the -other catalogs translate, [notes](localization-ru.md)), Ukrainian `uk` (3,375), Czech `cs` (3,522), -Polish `pl` (3,366), Greek `el` (3,481), Dutch `nl` (3,568), Italian `it` (4,164; also every dynamic label the -other catalogs translate; reviewed by a native speaker, [notes](localization-it.md)). Hungarian -`hu` (4,347 rows) is also registered. Georgian `ka` (4,530 rows; every measured key on 2026-10-31; -Georgian UI fallback font: Noto Sans Georgian, Segoe UI, Sylfaen, SF Georgian, DejaVu Sans; on the web the first served font for `Geor`). Turkish `tr` -(3,731 rows) also covers every measured key. Serbian `sr` (4,022 rows, Latin script, Ekavian, added 2026-10-12) covers every -measured key and the union of the other catalogs' dynamic labels; its one/few/many plurals reuse -the Russian rule. Swedish `sv` (4,552 rows, added 2026-10-28) covers every measured key and the +23 more registered languages (35 with English), measured 2026-11-08, status `partial` for the same reason. Swedish, Finnish, Danish and Norwegian Bokmål miss 178 of the 2,449 measured keys, Bosnian 183, Georgian 176; the other eleven below miss 155–164: +Traditional Chinese `zh-hant` (3,143 rows), Russian `ru` (4,580; also every dynamic label the +other catalogs translate, [notes](localization-ru.md)), Ukrainian `uk` (4,122), Czech `cs` (4,205), +Polish `pl` (4,108), Greek `el` (4,216), Dutch `nl` (4,290), Hungarian `hu` (4,438), Italian `it` (4,580; +also every dynamic label the other catalogs translate; reviewed by a native speaker, +[notes](localization-it.md)), Turkish `tr` (4,294 rows). Georgian `ka` (4,642 rows, 2,273 of 2,449 measured keys; Georgian UI fallback font: Noto Sans Georgian, Segoe UI, Sylfaen, SF Georgian, DejaVu Sans; on the web the first served font for `Geor`; [notes](localization-ka.md)). Serbian `sr` (4,527 rows, Latin script, +Ekavian, added 2026-10-12) covers the union of the other catalogs' dynamic labels; its one/few/many plurals reuse +the Russian rule. Swedish `sv` (4,603 rows, added 2026-10-28) covers the other catalogs' dynamic labels; combined from the community catalogs in #5985 and #9536 with one term per concept; the contested terms follow a native speaker's questionnaire answers. Finnish -`fi` (4,552 rows, combined from #5666 and #6961), Danish `da` (4,552 rows, based on #7267 and -completed for the current UI) and Norwegian Bokmål `nb` (4,552 rows, combined from #8072 and #9025; +`fi` (4,603 rows, combined from #5666 and #6961), Danish `da` (4,603 rows, based on #7267 and +completed for the current UI) and Norwegian Bokmål `nb` (4,603 rows, combined from #8072 and #9025; `no` and `nn` locales resolve to it), all added 2026-10-29, cover the same keys with one term per -concept; none has had a native-speaker review yet. Bosnian `bs` (4,552 rows, Latin script, -Ijekavian, added 2026-10-30) covers the same keys; its one/few/other plurals reuse the Russian +concept; none has had a native-speaker review yet. Bosnian `bs` (4,622 rows, Latin script, +Ijekavian, added 2026-10-30) covers the same dynamic labels; its one/few/other plurals reuse the Russian rule, and Cyrillic `bs` locales read it too. It is AI-assisted, shares its wording with storytold/craft-i18n `locales/bs/`, and has not had a native-speaker review yet. -Azerbaijani `az` (Latin script) brings the runtime registry to 29 languages including -English. Its catalog has 4,606 entries, including the initial dynamic-label key union, current OpenType menus and five frame labels +Azerbaijani `az` (Latin script, 2,269 of 2,449 measured keys) brought the runtime registry to 29 languages including +English when it landed; it now has 35. Its catalog has 4,623 entries, including the initial dynamic-label key union, current OpenType menus and five frame labels and 32 plural messages. It uses one/other integer forms, with singular counted nouns. Complete menu keys, regional locale matching and English fallback are covered by tests. Native-speaker review remains pending; validation results and limits are recorded in the [language notes](localization-az.md). Readiness estimates and G13 remain unchanged. +Hebrew `he`, Romanian `ro` and Urdu `ur` are measured at 2,334 of 2,449 keys (95.3%), Thai `th` at 2,211 (90.3%) and Tamil `ta` at 2,133 (87.1%). + Czech UI follow-up (2026-10-11): status and notice wrappers, hardware labels, brush and transform accessibility names, rasterization prompts, profile mismatch messages and preset counts now translate at their render/assignment sites. Navigator's zoom level uses a context @@ -112,11 +113,21 @@ engine localization or native review is complete. | 2026-10-12 | minor | Spanish: 1,276 runtime-only labels added (filter and adjustment parameters, Camera Raw, panels, dialogs and status wrappers); generated-label coverage test added | | 2026-10-12 | minor | Italian native-speaker review: mistranslations (Trap, HDR Toning, Display Text) and phrasing fixed | | 2026-10-12 | minor | Serbian (`sr`, Latin, Ekavian) catalog: every measured key plus the dynamic labels of the other catalogs | +| 2026-10-12 | minor | Re-measured with `cargo xtask i18n-coverage`: 1,772 keys; Vietnamese catalog shipped (100%, replaces "none"); Simplified Chinese, French, Indonesian and Korean at 1,758 of 1,772; plug-in menu rows stay in Filter › Plug-ins in every language (#2540, #2627) and installed Japanese fonts are listed on Linux (#2330, #2961) | | 2026-10-13 | minor | Italian: the `Screen` blend mode read *Schermo* (the display) and is now *Scherma*; the Dodge/Burn/Sponge tool names were already Adobe's (*Scherma*, *Brucia*, *Spugna*) and stay. Pinned by a test | +| 2026-10-14 | minor | Re-measured with `cargo xtask i18n-coverage` after merging main: 1,871 keys; Simplified Chinese, French, Indonesian and Korean at 1,857, the other key languages at 100%; catalog rows re-counted; other shipped languages refreshed (Hungarian listed, Polish at 1,904) | | 2026-10-18 | minor | Russian: 1,229 dynamic labels added (filter and adjustment parameters, Camera Raw, lighting, History/Layers/paths menus, metadata, System Info, status templates, dialogs) with a terminology note ([localization-ru](localization-ru.md)) | +| 2026-10-21 | minor | Re-measured current main: 1,918 keys, 1,904 for French, Indonesian, Korean, Polish and Simplified Chinese; catalog rows recounted | | 2026-10-22 | minor | Arabic row: paragraph direction has Auto / Left-to-right / Right-to-left buttons in the Paragraph panel and Type options bar (#6793); the visual RTL caret is still missing (TYPE-218-2 partial) | | 2026-10-22 | minor | Georgian (`ka`) catalog | | 2026-10-28 | minor | Arabic (`ar`) UI catalog: every measured key, six plural forms; layer names and the title bar no longer reversed on egui 0.37 | | 2026-10-29 | minor | Swedish (`sv`) UI catalog: every measured key plus the dynamic labels, combined from #5985 and #9536 | | 2026-10-29 | minor | Finnish (`fi`), Danish (`da`) and Norwegian Bokmål (`nb`) UI catalogs: every measured key plus the dynamic labels, combined from #5666, #6961, #7267, #8072 and #9025 | | 2026-10-30 | minor | Bosnian (`bs`, Latin, Ijekavian) catalog: the same 4,552 keys as the newest catalogs, `bs-*` locales (Cyrillic included) and one/few/other plurals | +| 2026-11-05 | minor | Re-measured the merged tree with the `xtask/src/i18n_coverage.rs` reporter: 2,272 keys; Arabic at 96.9% (2,202); Bosnian, Swedish, Finnish, Danish and Norwegian Bokmål at 2,216 (Bosnian) and 2,212; Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,195–2,203 (69–77 keys still in English); Hindi 328; catalog rows recounted | +| 2026-11-07 | minor | Re-measured current main with `cargo xtask i18n-coverage`: 2,369 keys; Arabic 2,241 (94.6%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,264–2,272 (97–105 keys still in English); Hindi 387; Azerbaijani, Hebrew, Romanian, Tamil, Thai and Urdu added to the measurements; catalog rows recounted | +| 2026-11-07 | minor | Re-measured the tree merged with main using `cargo xtask i18n-coverage`: 2,389 keys; Arabic 2,252 (94.3%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,275–2,284 (105–114 keys still in English); Hindi 398; Hebrew, Romanian and Urdu 2,332, Thai 2,209, Tamil 2,131; catalog rows recounted | +| 2026-11-07 | minor | Re-measured after merging current main (Georgian catalog) with `cargo xtask i18n-coverage`: 2,400 keys; Arabic 2,252 (93.8%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,277–2,286 (114–123 keys still in English); Hindi 398; Georgian 2,271; Hebrew, Romanian and Urdu 2,332, Thai 2,209, Tamil 2,131; catalog rows recounted | +| 2026-11-07 | minor | Re-measured the merged tree with `cargo xtask i18n-coverage`: 2,428 keys; Arabic 2,252 (92.8%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,282–2,291 (137–146 keys still in English); Hindi 398; Georgian 2,271; Hebrew, Romanian and Urdu 2,332, Thai 2,209, Tamil 2,131; catalog rows recounted | +| 2026-11-08 | minor | Re-measured the tree merged with main using `cargo xtask i18n-coverage`: 2,431 keys; Arabic 2,252 (92.6%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,282–2,291 (140–149 keys still in English); Hindi 399; Georgian 2,270; Azerbaijani 2,266; Hebrew, Romanian and Urdu 2,331, Thai 2,208, Tamil 2,130; 35 registered languages; catalog rows recounted | +| 2026-11-08 | minor | Re-measured again after merging current main using `cargo xtask i18n-coverage`: 2,449 keys; Arabic 2,255 (92.1%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,285–2,294 (155–164 keys still in English); Hindi 400; Georgian 2,273; Azerbaijani 2,269; Hebrew, Romanian and Urdu 2,334, Thai 2,211, Tamil 2,133; catalog rows unchanged | diff --git a/docs/mcp.md b/docs/mcp.md index 14359d8ccd..64fd88baa5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,5 +1,66 @@ # MCP conventions +## Connecting the desktop app (no terminal) + +**One switch, in the ArtCraft Launcher.** Settings › AI agents › **Let AI agents use Craft apps** +is the person's consent for every Craft app, PhotoCraft included; PhotoCraft has no switch of its +own. **Add** next to an MCP client (Claude Desktop, Claude Code, Cursor, LM Studio) puts one entry +in it, `ArtCraft`, for every installed Craft app (the `craft-ai-mcp` gateway, which starts +`photocraft-cli mcp`); **Copy** gives the configuration for any other client. Then restart the +client. Adding to MCP clients is the launcher's job alone: PhotoCraft writes no client +configuration. The design is in storytold/craft-ai-integrations#195. + +This is behind the Craft suite's `AI-MCP` feature flag (`craft-flags`). Flags are set only in the +per-user `ArtCraft/flags.toml` (`AI-MCP = true` under `[flags]`; on Windows in +`%LOCALAPPDATA%\ArtCraft`), which every Craft app and the launcher read, or for one run with +`CRAFT_FLAGS=AI-MCP`; no app or launcher setting switches them. Without the flag, everything is as +it was: Preferences › AI Integrations shows Allow Agent Control and Control Port, a Control Port +already set keeps its connection, and the launcher's switch means nothing to PhotoCraft. + +While the launcher's switch is on, its app list `ArtCraft/mcp/apps.json` (in the per-user local +configuration folder; `CRAFT_MCP_DIR` moves it) names `photocraft`, read through +`craft-ai-agents`, the same crate the launcher writes it with and the gateway reads it with. +PhotoCraft then serves agents on loopback (any free port by default, or the Control Port) with a +token it keeps in its settings folder, and publishes both in `agent-connection.json` there. The +app looks at the launcher's files every 2 s, so switching there applies without a restart. Allow +Agent Control off still refuses agents. Started with `--control`, the app ignores all this and the +launch flags manage the connection, as before. + +**Edit › Preferences › AI Integrations** says whether agents can connect (and on which port), and +keeps what is PhotoCraft's own: the port, the folders agents can open from and save to, and what +happens when an agent needs PhotoCraft while it is closed (open it, work without a window, or ask +the user to open it). + +### `photocraft-cli mcp` + +Plain `photocraft-cli mcp` works in the open PhotoCraft window when the person lets agents use it, +and otherwise without a window, as it always did. It reads `agent-connection.json` before every +tool call, so the client configuration holds no port or token and keeps working when PhotoCraft +restarts or moves to another port. + +- **Agents allowed, PhotoCraft open:** tools work in the window. +- **Agents allowed, PhotoCraft closed:** When PhotoCraft Is Closed decides (`--when-closed + ` overrides it): start the app and wait for it, serve a headless + session, or say to open it. The headless session takes `--automation-read-root` and + `--automation-write-root` when given to `mcp`, each on its own: a given read root replaces the + app's read folder, a given write root its write folder, and the app's folder is used for any + direction without a flag. The app is started only on a tool + call, never when the MCP client starts. +- **Agents not allowed:** a headless session with only the roots given to `mcp`, exactly as + before; the app is never started and its folders aren't used. +- **`--headless`:** always headless, whatever the switch says. +- **`--bridge` (or `PHOTOCRAFT_CONTROL_PORT`):** a `photocraft --control` app, as before. + +A session that went headless stays headless until the MCP client restarts it, so documents don't +move under the agent. In the Flatpak the connection needs +`flatpak override --user --share=network ai.storyteller.photocraft`. + +When `mcp` starts the app, macOS goes through LaunchServices (`open -a`) and Windows through +Explorer, as a double-click would: the app is no child of the CLI, so it keeps running when the +MCP client ends the CLI's process tree (Claude Code does on Windows), and it stays out of a +Microsoft Store client's container, where new files under `%APPDATA%` would land in the client's +package instead of PhotoCraft's settings folder. Linux starts it in its own process group. + ## Install and register From the repository root, with the [source-build prerequisites](development.md#prerequisites) @@ -47,10 +108,12 @@ not put the CLI on `PATH`. ## Start a session -PhotoCraft follows the same conventions as FilmCraft #28. Start a headless session: +PhotoCraft follows the same conventions as FilmCraft #28. Start a headless session (`--headless`: +without it, `mcp` works in the open PhotoCraft window while the ArtCraft Launcher's agents switch is +on, and may start the app; scripts, tests and agents pass it): ```sh -photocraft-cli mcp \ +photocraft-cli mcp --headless \ --automation-read-root /work/project \ --automation-read-root /library/reference \ --automation-write-root /work/project diff --git a/docs/roadmap.md b/docs/roadmap.md index d2ca4a8435..6ffcdcfd09 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-11 · **Change:** minor (adaptive Unsharp Mask performance evidence linked; Photomerge status correction retained; alpha gate, focus and estimates unchanged) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-12 · **Change:** minor (M11: the desktop app connects to MCP clients from Edit › Preferences › AI Integrations, no terminal, no restart; alpha gate, focus and estimates unchanged) · **Target:** Adobe Photoshop 2026 - UI.5: Panels can detach, join other tab groups, split, resize and redock through shared docking transactions. Custom layouts persist with workspaces, respect workspace locking, and retain collapse flags for intact native groups. @@ -116,6 +116,7 @@ Each milestone has a **definition of done (DoD)** and must leave `main` green on | Date | Change | Summary | |---|---|---| +| 2026-11-12 | minor | M11: Edit › Preferences › AI Integrations connects MCP clients to the running app without a terminal or restart; milestones, alpha gate and estimates unchanged | | 2026-10-11 | minor | Linked adaptive Unsharp Mask performance and quality evidence; milestones, alpha gate and estimates unchanged | | 2026-10-10 | minor | Photomerge is implemented; real-world quality validation remains open | | 2026-10-10 | minor | Alpha gate table (core-workflow gate): passes, stage stays alpha | diff --git a/docs/scorecard.md b/docs/scorecard.md index b7fb8babd4..6fab0d544b 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -6,13 +6,13 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | Area | Done | Partial | Missing | Key numbers | |---|---:|---:|---:|---| -| [Performance](#performance) | 3 | 22 | 54 | 88 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 50 not run, 4 not measurable yet (baseline 2026-10-05) | +| [Performance](#performance) | 3 | 22 | 56 | 90 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 52 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: 8 of 199 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 8 of 203 (target 0) | | [Type](#type) | 5 | 5 | 0 | | -| [Automation](#automation) | 5 | 4 | 2 | 664 of 664 menu items live (100.0%) | -| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 29 of 29 crates; panic_hunt present | +| [Automation](#automation) | 6 | 4 | 2 | 664 of 664 menu items live (100.0%) | +| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present | | [Distribution](#distribution) | 5 | 5 | 1 | | | [Open bugs](#open-bugs) | 31 | 1 | 0 | | @@ -110,6 +110,8 @@ Baseline: 2026-10-05, 1 run, commit `f5d2bcb54a`, Apple M4 Pro (48 GB), GPU Appl | P87 | Toggle a masked adjustment mid-stack in the layered document + refresh | track only | – | – | – | – | – | not run | [#9329](https://github.com/storytold/photocraft/issues/9329) | | P88 | Bring forward / send backward a small layer in the many-layer document + refresh | track only | – | – | – | – | – | not run | [#9329](https://github.com/storytold/photocraft/issues/9329) | | P89 | App frame after Paste Into on 24 MP (CPU canvas) | track only | – | – | – | – | – | not run | [#9329](https://github.com/storytold/photocraft/issues/9329) | +| P90 | Free Transform begin, 2 layers on 24 MP (Ctrl+T + first preview frame) | ≤ 300 ms p95 | – | – | – | – | – | not run | [#11103](https://github.com/storytold/photocraft/issues/11103) | +| P91 | Free Transform drag update, 2 layers on 24 MP (scale through new mip levels) | ≤ 16 ms max | – | – | – | – | – | not run | [#11103](https://github.com/storytold/photocraft/issues/11103) | **Not measurable yet** (the code can't do it yet; no number is recorded): @@ -150,7 +152,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu | FILE-215-16 | Advanced Blending (knockout, blend as group, mask hides effects) end to end | partial | [#215](https://github.com/storytold/photocraft/issues/215) | doc advanced.rs + .pcraft + PSD/layered TIFF (knko infx clbl tsly lmgm vmgm), CPU compose advanced.rs (GPU falls back), blendingOptions command + dialog; 7 psd-tools knockout oracles now pass; knockout-isolated-groups (0.45 % AA edges), advanced-blending, blend-and-clipping still differ | | FILE-215-17 | CMYK/RGB documents preview spot inks; spot plates export (TIFF extra samples, PDF) | partial | [#215](https://github.com/storytold/photocraft/issues/215) | TIFF: spot channels written and read as extra samples with DisplayInfo (1077) ink colour and solidity, ink stored 0 = solid (#7415). PSD: spot planes stored and read 0 = solid as Photoshop does, identifiers in 1053; PhotoCraft 0.1.0–0.16.0 PSDs (straight planes) keep their ink. RGB/CMYK documents preview visible spot channels as inks printed over the canvas composite (compose multichannel::overprint, the Multichannel formula, in Channels panel order; ui-egui canvas/channel_view.rs), open with spot eyes on, and print them in the PSD thumbnail (multichannel::thumbnail_with_inks); flatten, export and the merged image stay free of them (#10249). Missing: PDF Separation | | FILE-215-18 | Save for Web per-slice settings remembered; Export As remembers and offers nearest scaling | done | [#215](https://github.com/storytold/photocraft/issues/215) | Save for Web settings survive a restart through the remembered dialog settings in prefs.dialogs (web_cmds::remember_web_settings stores them on a complete export, never the destination; file_ui.rs open_web seeds from the session's last export, else the preferences). export_dialog seeds Export As the same way (seed_remembered: format, quality, transparency, scale, resample, metadata, TGA bits) and confirm remembers them as used. Export As › Image Size › Resample offers Photoshop's six methods (Bicubic Automatic default, Nearest Neighbor included; export_preset_cmds::RESAMPLE, unknown values are errors) for the exported copy only; also layer.exportAs `resample` and export presets (#5838). Tests: export_dialog nearest_neighbor_doubles_each_pixel_into_an_exact_block (8/16-bit), resample_choices_are_checked, resample_is_remembered_and_a_bad_saved_value_falls_back; layer_menu_cmds export_layer_resamples_with_the_chosen_method; tests/it/export_as_scaling.rs export_as_resample_menu_writes_nearest_neighbor_blocks | -| FILE-215-19 | Save As JPEG opens a JPEG Options dialog (quality 0-12, format options) | partial | [#215](https://github.com/storytold/photocraft/issues/215) | jpeg_options_ui.rs: File > Save, Save As and Save a Copy to a JPEG ask for Quality 0-12 (Low/Medium/High/Maximum) and Baseline / Baseline Optimized / Progressive before writing, starting at an opened JPEG's own quality (file_encoding) or else the Export preference; scripts pass quality/jpegFormat (file.saveAs, file.saveACopy, app.save, CLI --jpeg-format) and recorded actions replay the answer (discard_ui/tests/jpeg_tests.rs, codecs roundtrip jpeg_format_options_round_trip). 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, so RGB Baseline Optimized writes the same file as Baseline. Missing: Matte, progressive Scans (3-5) and the size preview | +| FILE-215-19 | Save As JPEG opens a JPEG Options dialog (quality 0-12, format options) | partial | [#215](https://github.com/storytold/photocraft/issues/215) | jpeg_options_ui.rs: File > Save, Save As and Save a Copy to a JPEG ask for Quality 0-12 (Low/Medium/High/Maximum) and Baseline / Baseline Optimized / Progressive before writing, starting at an opened JPEG's own quality (file_encoding) or else the Export preference; scripts pass quality/jpegFormat (file.saveAs, file.saveACopy, app.save, CLI --jpeg-format) and recorded actions replay the answer (discard_ui/tests/jpeg_tests.rs, codecs roundtrip jpeg_format_options_round_trip). 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, so RGB Baseline Optimized writes the same file as Baseline. The dialog shows the size the file will have (152.3K, 1.5M), encoded in memory with its settings on a worker thread (in the frame on the web), up to 40 MP, 4 MP on the web (jpeg_options_ui/size_readout.rs). Missing: Matte and progressive Scans (3-5) | | FILE-215-20 | Artboard tool with handles and + buttons, Duplicate Artboard beside, vector PDF pages | partial | [#215](https://github.com/storytold/photocraft/issues/215) | artboard_tool.rs: Artboard tool draws, selects, moves and resizes boards by their handles (⇧ keeps proportions), its + buttons add a board or (⌥) a copy beside the selected one (#3033); Duplicate Artboard places the copy beside (#1584); raster PDF pages only | | FILE-215-21 | Local libraries of colours, patterns, images and layers, as linked items or copies | missing | [#215](https://github.com/storytold/photocraft/issues/215) | Only preset libraries (preset_store.rs) | | FILE-216-1 | Every corpus fetched and enforced in CI, cached by pin | done | [#216](https://github.com/storytold/photocraft/issues/216) | ci.yml has a corpus job (name: corpus tests) on every PR and on main: the corpora are pinned in xtask/src/corpus_pins.rs, sha256-verified after both a cache restore and a download, and a missing corpus fails the tests. The cache key follows the pins, so it is cached by pin as this row asks (#190) | @@ -171,7 +173,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu | TOOL-213-5 | Painting a type/shape/smart/fill layer offers to rasterize; OK converts it and the next click paints | done | [#213](https://github.com/storytold/photocraft/issues/213) | rasterize_prompt.rs: OK rasterizes only, the click that opened the prompt is not replayed (as in Photoshop, #8806), Cancel does nothing; drivable via ui.dialog.confirm | | TOOL-213-6 | Fill dialog: contents, blend, opacity, preserve transparency; remembered; Shift+Backspace | done | [#213](https://github.com/storytold/photocraft/issues/213) | fill_ui.rs dialog over edit.fill (fill_cmds.rs): all contents, mode, opacity, preserve; remembered in prefs; Shift+F5 / Shift+Backspace | | TOOL-213-7 | Live stroke preview for every brush-based retouch tool | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Live (canvas.rs strokes_live): Brush, Pencil, Mixer Brush, Eraser, Color Replacement, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Clone Stamp, Healing Brush, History Brush (#1026, #1040), Pattern Stamp (aligned and Impressionist) and Background Eraser (#3754); the release commits the live stroke's pixels (P32) or, for the retouch tools, the same pixels the live stroke showed (tested equal at 8 and 16 bits). Spot Healing Brush shows the area it heals as a dark overlay and heals on release, as Photoshop does. Mixer Brush uses its incremental transaction and commits the displayed result (#3627) | -| TOOL-213-8 | Clone Source: W/H link, drawn overlay (opacity/blend/clip/auto-hide), Alt target cursor | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Clone Source overlay drawn with opacity, inversion, circular clipping, auto-hide and the Normal/Darken/Lighten/Difference blend against the image under the brush (canvas.rs draw_clone_preview, clone_source::overlay_blend); a shaped tip (sampled bitmap, rotation, roundness) clips the overlay to its outline (brush_cursor::tip_mask, #4372); W/H link (cloneSource.set linked, panel chain button, #3298) | +| TOOL-213-8 | Clone Source: W/H link, drawn overlay (opacity/blend/clip/auto-hide), Alt target cursor | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Clone Source overlay drawn with opacity, inversion, circular clipping, auto-hide and the Normal/Darken/Lighten/Difference blend against the image under the brush (canvas.rs draw_clone_preview, clone_source::overlay_blend); a shaped tip (sampled bitmap, rotation, roundness) clips the overlay to its outline (brush_cursor::tip_mask, #4372); W/H link (cloneSource.set linked, panel chain button, #3298); a source ⌥-clicked in one open document is cloned (Clone Stamp, Healing Brush, the live stroke and the overlay) into another, using compatible document colour modes and ICC profile conversion (Clone Stamp requires matching modes; Healing Brush also permits Grayscale on either side), from the layer it was set on (cloneSource.set document; retouch_cmds/tests.rs clone_stamp_paints_from_the_document_the_source_was_set_in, ui alt_click_tests.rs alt_click_in_one_document_clones_into_another) | | TOOL-213-9 | Eyedropper comparison ring (new colour above, current below) while sampling | done | [#213](https://github.com/storytold/photocraft/issues/213) | eyedropper_ring (canvas.rs): the sampled colour on the upper arc, the foreground below, drawn for the Eyedropper and Alt-sampling while the button is held; the Precise-cursor preference keeps the crosshair | | TOOL-213-10 | Ctrl+Alt drag resizes brush size/hardness with an on-canvas readout | done | [#213](https://github.com/storytold/photocraft/issues/213) | brush_resize.rs (#297, #370): Alt+right-drag, or Control+Option-drag on macOS (Control+Alt everywhere), sets diameter horizontally and hardness vertically, circle plus Diameter/Hardness readout, one coalesced tools.setBrush, no paint or history; 9 tests there | | TOOL-213-11 | Editable pressure curve, global and per control | done | [#213](https://github.com/storytold/photocraft/issues/213) | Global: Preferences › Tools › Pressure Curve (prefs tools.pressureCurve; applied to every pen sample in ui-egui stylus.rs before any brush; editor pressure_curve_ui.rs with Linear/Soft/Hard presets). Per control: every brush Dynamic has its own curve (paint ResponseCurve, the same monotone cubic; Dynamic.curve, set by tools.setBrush, e.g. shapeDynamics.size.curve) applied to its Fade/Pressure/Tilt/Wheel/Rotation input in dynamics.rs dynamic_value; Brush Settings shows it behind each Control row's curve button (#3294) | @@ -212,7 +214,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 8 of 199** (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: 8 of 203** (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.legacy_compositing`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. @@ -274,10 +276,11 @@ Menu wiring (`docs/parity-checklist.md`): 664 of 664 menu items live (100.0%). T | AUTO-219-8 | xtask check that every panel button routes through a command id | partial | [#219](https://github.com/storytold/photocraft/issues/219) | cargo xtask panel-commands (run by xtask ci and CI) fails on a shell click handler that changes the document or session directly; 1 allowlisted function left (panels/color.rs color_field assigns the foreground/background colour instead of tools.setColors) | | AUTO-219-9 | Headless commands for in-canvas type editing, Liquify/Puppet strokes, transform handles | done | [#219](https://github.com/storytold/photocraft/issues/219) | type.hitTest, type.caret, type.navigate; filter.liquify strokes, edit.puppetWarp pins, type.edit, edit.transform | | AUTO-219-10 | Agent acceptance suite grown to 30-50 workflows | partial | [#219](https://github.com/storytold/photocraft/issues/219) | automation/tests/it/agent_tasks.rs runs 10 workflows over MCP | +| AUTO-MCP-LIVE | Connect an MCP client to the running app without a terminal (no flags, ports or tokens to copy) | done | | 2026-11-12 (#5525, #11363, craft-ai-integrations#195): the ArtCraft Launcher's agents switch (the one consent; read through craft-ai-agents) starts and stops the loopback control server while the app runs (no restart) and publishes agent-connection.json; plain photocraft-cli mcp works in the open app on every call while agents are allowed (launch / headless / error while it is closed) and headless otherwise (--headless forces it); the launcher's Add buttons register every Craft app, PhotoCraft writes no client configuration. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests | ## Reliability -Never-crash attribute on 29 of 29 crate roots. +Never-crash attribute on 28 of 28 crate roots. | Id | Target | Status | Issue | Note | |---|---|---|---|---| diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 720eb60ce0..03df152028 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-11-10 · **Change:** minor (Image Processor accepts copies of the current or all open documents, including unsaved edits; languages are measured with `cargo xtask i18n-report` over the craft-i18n catalogs; previously minor: Fujifilm compressed RAF decodes, #7377; Average executes through shared filters on Smart Objects and imported PSD records; Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; RGB and CMYK documents preview their spot inks as an overprint, FILE-215-17 narrows to PDF Separation, #10249; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; Automation Batch Esc Continue/Stop and read-only input previews now follow the measured cancellation flow; full live tabs remain partial, AUTO-219-5, #4579; Automation recording folds Move-tool nudge runs, records keyboard document switches by opening-order offset and scales point text placement; paragraph boxes remain open, #4514; Automation Batch output naming and UTF-16 logs now follow measured Photoshop behavior; progress and cancel prompt remain partial, AUTO-219-5, #4579; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; Smooth and Feather command masks cropped to selection bounds plus blur reach; Equalize with a selection asks Selected Area Only or Entire Image Based On Selected Area; cropped selection morphology and command mask conversion performance evidence added; 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; Print: Japanese paper sizes — はがき, 往復はがき, JIS B5/B4, A6, L判, 2L判, KG判, 六切, 四切; +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-10 · **Change:** minor (JPEG Options shows the size the file will have, FILE-215-19 partial; Image Processor accepts copies of the current or all open documents, including unsaved edits; languages are measured with `cargo xtask i18n-report` over the craft-i18n catalogs; previously minor: Fujifilm compressed RAF decodes, #7377; Average executes through shared filters on Smart Objects and imported PSD records; Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; RGB and CMYK documents preview their spot inks as an overprint, FILE-215-17 narrows to PDF Separation, #10249; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; Automation Batch Esc Continue/Stop and read-only input previews now follow the measured cancellation flow; full live tabs remain partial, AUTO-219-5, #4579; Automation recording folds Move-tool nudge runs, records keyboard document switches by opening-order offset and scales point text placement; paragraph boxes remain open, #4514; Automation Batch output naming and UTF-16 logs now follow measured Photoshop behavior; progress and cancel prompt remain partial, AUTO-219-5, #4579; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; Smooth and Feather command masks cropped to selection bounds plus blur reach; Equalize with a selection asks Selected Area Only or Entire Image Based On Selected Area; cropped selection morphology and command mask conversion performance evidence added; 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; Print: Japanese paper sizes — はがき, 往復はがき, JIS B5/B4, A6, L判, 2L判, KG判, 六切, 四切; 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); @@ -184,7 +184,7 @@ parity for the area and are already contained in the dimension rows above. | Camera Raw and computational photo (Photomerge, HDR, lens) | 45% | 120–200 | Raw for DNG/CR2/NEF/ARW/RW2/ORF/RAF(uncompressed)/PEF; no CR3; ACR dialog partial (no masking; no per-camera colour for non-DNG cameras); generic lens profiles only | | Automation, actions, batch, scripting | 45% | 120–200 | CLI/MCP/control channel ahead of Photoshop; recording uses implicit active layers, unique layer names, whole-text Type steps, bundled Move-tool nudges, relative keyboard document switches and canvas-relative point text (AUTO-219-1, #4514; duplicate names and paragraph boxes remain open); Actions panel remains partial (AUTO-219-2); `.atn` load/save since 2026-10-12 (112 events mapped, the rest kept verbatim); compound layer properties export as separate Set events with rename last (#8304, 2026-10-21; independent Photoshop replay pending); no ExtendScript/UXP | | File I/O | 60% | 300–500 | See [file-format-parity.md](file-format-parity.md) | -| Print, export, Save for Web | 50% | 60–100 | Paper sizes include the Japanese ones (はがき 100×148 mm, 往復はがき 148×200, JIS B5/B4, A6, L判 89×127, 2L判 127×178, KG判 102×152, 六切 203×254, 四切 254×305) by their customary names; JPEG Options without Matte, progressive Scans or size preview (FILE-215-19), no Photoshop PDF, no separations, Save for Web settings not remembered | +| Print, export, Save for Web | 50% | 60–100 | Paper sizes include the Japanese ones (はがき 100×148 mm, 往復はがき 148×200, JIS B5/B4, A6, L判 89×127, 2L判 127×178, KG判 102×152, 六切 203×254, 四切 254×305) by their customary names; JPEG Options without Matte, or progressive Scans (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 | 11 of 183 prefs do nothing (scorecard, 2026-11-01); no floating/OS-window panel groups; Libraries, Comments, Contextual Task Bar missing | | AI / generative | 10% | 300–600 | See the dimension row | @@ -609,6 +609,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md). | 2026-11-01 | minor | UI / UX and Workspace rows: 11 of 183 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-30 | minor | Art History Brush Opacity on the options bar, #10263; no estimate changed | | 2026-10-30 | minor | Colour management: RGB and CMYK spot channels preview as inks over the composite and in the PSD thumbnail (#10249); FILE-215-17 narrows to PDF Separation; percentages unchanged | +| 2026-10-28 | minor | JPEG Options shows the size the file will have (FILE-215-19 partial: no Matte or progressive Scans); percentages unchanged | | 2026-10-27 | minor | Smooth/Feather command reads and replacement use selection bounds plus blur reach; full-canvas reference and release comparisons extended; percentages and scorecard budgets unchanged | | 2026-10-26 | minor | Expand/Contract/Border distance work, mask reads and replacement cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across eight cases; percentages, estimates and scorecard budgets unchanged | | 2026-10-23 | minor | Frame Tool interaction and persistence work (#8864); documented remaining native Photoshop frame metadata and independent-oracle limits; no percentage changed | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d22ea9d20d..c527284369 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -12,8 +12,10 @@ Status: **done** (behaves as in Photoshop, with a test), **partial** (exists, di **missing**. Evidence is a file under `crates/ui-egui/src/` unless another path is given, a scorecard id, or an issue. Modifier names are macOS first (⌘ ⌥ ⇧); Windows/Linux use Ctrl and Alt. -**Summary (estimated, weights = how often the gesture is used):** ~40% ready. Tools 56/68 -present (82%, measured). Free Transform modifiers and Crop are close to Photoshop; the gaps are +**Summary (estimated, weights = how often the gesture is used):** ~40% ready. Tools 68/68 +present (100%, measured: the `Tool` enum has 69 variants, the 68 plus a separate Star tool, #11377; +Art History Brush is partial, TOOL-213-20). +Free Transform modifiers and Crop are close to Photoshop; the gaps are in the long tail of modifiers, in-transform UI, spring-loaded tools, panels and preferences. Remaining: 60–110 h for transforms and modifiers (gap G5), 60–100 h for tools (G6), 150–250 h for panels and workspace (G9). @@ -34,7 +36,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Frame | Frame: persistent handles, frame/image/both selection, transforms, fitting, replacement, solid strokes, shape/type conversion and modern shapes ([behavior and limits](frame-tool.md), #8864, 2026-10-23) | Native Photoshop frame metadata and independent Photoshop replay remain open | | Eyedropper | Eyedropper, Color Sampler, Ruler, Note, Count | | | Retouch | Remove, Spot Healing, Healing, Patch, Content-Aware Move, Red Eye | | -| Brush | Brush, Pencil, Mixer Brush | | +| Brush | Brush, Pencil, Color Replacement, Mixer Brush | | | Stamp | Clone Stamp, Pattern Stamp | | | History | History Brush, Art History Brush (partial: 8 of 10 styles, TOOL-213-20) | | | Eraser | Eraser, Background Eraser, Magic Eraser | | @@ -43,7 +45,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Pen | Pen, Freeform Pen, Curvature Pen (#1054), Convert Point (#3204; also ⌥ with Pen), Add Anchor Point, Delete Anchor Point (P cycles them; #4144 auto add/delete with the Pen itself) | | | Type | Horizontal, Vertical, Vertical Type Mask, Horizontal Type Mask | | | Path selection | Path Selection, Direct Selection | | -| Shapes | Rectangle, Ellipse, Triangle, Polygon, Line, Custom Shape | (Star is a Polygon option in Photoshop) | +| Shapes | Rectangle, Ellipse, Triangle, Polygon, Star (own tool, #11377), Line, Custom Shape | (Star is a Polygon option in Photoshop) | | View | Hand, Rotate View, Zoom | | | Toolbar controls | Edit Toolbar, colour chips, Quick Mask, Screen Mode | | @@ -74,19 +76,19 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Several layers selected: one box frames them all and moves every one (pixels, type, shapes, smart objects, groups), one history step; with a selection each pixel layer's selected pixels move; Transform Again repeats on them | partial | #6501, `transform_tool.rs` (`begin_several`), `transform_several_tests.rs`, engine `edit.transform` `layers` (`transform_multi_tests.rs`); the Background is left out, as Show Transform Controls leaves it; Warp and splits are greyed for several layers; the preview moves their styles past the frame and follows opacity, fill, visibility and style edits made while the box is open (`styles_past_the_frame_move_with_the_box`, `hiding_or_fading_a_moving_layer_shows_in_the_preview_at_once`), but draws the layers stacked between the moving ones under them (the commit keeps every layer's place) | | Options bar H/V skew fields | done | `transform_tool.rs` (`Parts`, `skew_about_pivot`): W/H, angle and skew read as Photoshop decomposes the box; `skew_fields_lean_the_box_about_the_reference_point` | | Interpolation in the options bar | partial | Bicubic/Bilinear/Nearest; no Bicubic Smoother/Sharper/Automatic, Preserve Details | -| Commit/cancel buttons in the options bar | missing | #2442 | -| Right-click menu during transform (Scale, Rotate, Skew, Distort, Perspective, Warp, flips, rotates) | missing | TOOL-214-5 | +| Commit/cancel buttons in the options bar | done | `transform_tool.rs` ("Commit transform", "Cancel transform"); #2442 | +| Right-click menu during transform (Scale, Rotate, Skew, Distort, Perspective, Warp, flips, rotates) | done | TOOL-214-5 (`canvas_tool_menu.rs`) | | Arrow keys nudge the box 1 px, ⇧ 10 px | done | `move_mods.rs` | -| Preview keeps layer order, blend mode and mask | partial | mask yes (BUG-205-2); order/blend not (#2439) | +| Preview keeps layer order, blend mode and mask | partial | mask yes (BUG-205-2); plain Normal layers above keep their place (#2439, #2480), adjustment layers and other blend modes still draw under the box | | Preview clipped to the canvas, follows edits while open | done | #2201, #2099 | -| Hand (space) mid-transform doesn't interrupt it | partial | #2302 | +| Hand (space) mid-transform doesn't interrupt it | done | `transform_undo_tests.rs::holding_space_still_pans_while_transforming`; the selected Hand no longer steals a resize drag (#2302, #2327) | | Blend mode / opacity edits while transforming | missing | #1384 | -| Locked layer refused before the drag | missing | fails only at commit (#2585) | +| Locked layer refused before the drag | done | #2585, #2609 | | Transform a copy (⌥⌘T), step and repeat (⌥⇧⌘T) | done | 2026-10-07 | -| Transform a targeted alpha channel | missing | BUG-207-4 | +| Transform a targeted alpha channel | done | BUG-207-4 (`edit.transform` follows the targeted channel) | | Smart object perspective (non-affine) | done | FILE-215-6; #579 fixed by #426: Distort / Perspective keep a projective placement, re-rendered from the source, read and written as the PSD `nonAffineTransform` | | Type-layer transform while editing (⌘ held), no ⌘-corner distort on type | done | `ui-design.md` | -| Puppet Warp mesh follows the outline | missing | block grid (TOOL-214-6) | +| Puppet Warp mesh follows the outline | done | TOOL-214-6 (`algo/puppet.rs` `build_mesh`, #3105) | ## Move tool and nudging @@ -96,18 +98,18 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Arrow nudge of a selection outline (selection tools) | done | #1502 | | Arrow nudge of the crop box, X swaps orientation | done | TOOL-214-19 | | Arrow nudge of path points with Direct Selection | missing | no arrow handling in `direct_select.rs` | -| ⌘-arrow nudges the layer from any tool | missing | #2474 | +| ⌘-arrow nudges the layer from any tool | done | #2474, #2556 | | ⌥-drag duplicates, ⇧ constrains to 45° | done | `move_mods.rs` | | Dragging selected pixels shrinks the selection to them (the selection limited to where the layer has pixels, so moving again leaves no edge behind) as the drag starts, also with ⌥; the move box, snapping and Show Transform Controls use the moved pixels' bounds | done | #7538, `canvas.rs` `floating_outline` and `transform_controls_rect`, `snap_ui.rs` `follow_cut`, engine `float_cmds.rs` `CutParts::outline` | | With several layers selected and a selection, the Move tool moves the layers whole and the selection with them (ants follow the drag; one Move step) | done | #7538, `move_ui.rs` `carries_selection`, engine `layer.translate` `selection` | -| Auto-Select with hover outline, box-select layers, double-click fit | missing | TOOL-214-4 | -| Auto-Select bounding box and snapping follow the picked layer | partial | follow the previous layer (#2666) | +| Auto-Select with hover outline, box-select layers, double-click fit | partial | hover outline and box-select done; double-click fit and drag to a tab open (TOOL-214-4) | +| Auto-Select bounding box and snapping follow the picked layer | done | #2666, #2675 | +| ⌘-drag temporary Move shows the box and snaps | done | #2681, #2684 | | View › Extras (⌘H) hides the Move tool's transform controls; Show Transform Controls keeps its setting | done | `canvas.rs` `transform_controls_layers`, `hiding_extras_hides_the_move_transform_controls` (#6699) | | Several layers selected (⇧-click adds, box-select): Show Transform Controls frames them all, with every selected shape's outline, and its handles transform them all | done | `canvas.rs` `transform_controls_layers`, `several_selected_layers_share_one_frame_that_transforms_them_all`; `move_auto_select_tests.rs`; #6501 | -| ⌘-drag temporary Move shows the box and snaps | partial | #2681 | | ⌘-right-click layer list under the pointer | done | `layer_pick_ui.rs` | | Double-click type to edit it (caret at the pointer, Type tool) | done | #1132, `type_tool::edit_at` | -| Moving a selection on a mask moves the mask, not the pixels | partial | #2468 | +| Moving a selection on a mask moves the mask, not the pixels | done | #2468, #2486 | ## Selection modifiers @@ -116,10 +118,10 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | ⇧ square/circle, ⌥ from centre, live W × H readout (marquee) | done | `marquee_tests.rs` | | ⇧ add, ⌥ subtract, ⇧⌥ intersect from modifiers at press | done | tested for the marquee (add, subtract, ⇧⌥ intersect: `marquee_tests.rs`), Lasso (all three: `lasso_ui/tests.rs`) and Polygonal Lasso (`polygon_lasso_tests.rs`) (BUG-208-4) | | Space repositions the marquee while dragging | done | `hold_keys.rs` | -| Polygonal Lasso ⇧ snaps to 45° | missing | #2352 | +| Polygonal Lasso ⇧ snaps to 45° | done | #2352, #2396 | | Autoscroll at the window edge while selecting | missing | #2231 | -| Single-pixel rows and columns kept on release | partial | #2391 | -| Esc deselects / ⌘Z undoes the last selection | partial | #2674, #1432 | +| Single-pixel rows and columns kept on release | done | #2391, #2562 | +| Esc deselects / ⌘Z undoes the last selection | partial | Esc deselects when nothing else needs cancelling (#2674, #2765); ⌘Z of a selection step not re-checked (#1432 was closed with a Pen-anchor answer) | | Select › Modify live preview | missing | #1752 | | Marching ants as Photoshop draws them: device pixels, every edge equally thick (1 px at 100 %, 2 px up to 200 %), black/white dashes 4× the thickness, slanted dash ends, same look for drag previews and committed selections | done | `ants.rs`, `tests/it/marching_ants_pixels.rs` (#7489) | @@ -128,7 +130,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Behaviour | Status | Evidence | |---|---|---| | Click corner, drag smooth, ⌥ breaks a handle, ⌘ direct-selects, ⇧ 45° | done | TOOL-214-10; `vector_ui.rs` (#3751) | -| Handle on the last point, close-drag handle | partial | #1482 | +| Handle on the last point, close-drag handle | done | `vector_ui.rs` (#1601, #3314); the rest of #1482 is a Make Selection dialog for paths | | Pen Auto Add/Delete: click a segment of the active path, or of the path being drawn, to add, an anchor to delete; ⇧ suspends it | done | #4144, #6140 | | Curvature Pen edits the active path with no modifier: drag an anchor (the curve reflows), click a segment to add an anchor, double-click smooth ↔ corner; cursor badge + on segments, four arrows on anchors | done: `direct_select.rs` (`curvature_press`, `curvature_hover`), `path.moveAnchors`/`path.convertPoint` with `curvature`, `direct_select_tests.rs` | | | Path operations in the options bar (combine, subtract, intersect, exclude) | partial: the Pen, Freeform Pen and Curvature Pen have Photoshop's Path Operations menu (New Layer in Shape mode, Combine, Subtract Front Shape, Intersect, Exclude, Merge Shape Components) for the selected shape layer, a targeted vector mask, the selected path or the Work Path (`vector_ui.rs` `path_operations_menu`, `pen_path_ops_tests.rs`, `path.mergeShapeComponents`). Path Selection has it too and selects components (click, ⇧-click, drag moves the selected ones); with components selected the menu, `+` (Combine) and `-` (Subtract Front Shape) change their operation (`path.setOperation`, `path_components.rs`, `path_components_tests.rs`); the first component always combines and keeps its operation, the Pen tools' menu and keys set only the next path's, and dragging every component of a live rectangle or ellipse keeps it live. A Pen draft the document refuses (a locked layer) stays the draft on ↩ and becomes the Work Path on Esc or a tool switch. The Shape tools don't have the menu yet, and Intersect and Exclude have no key | `layer.combineShapes.*`; #1397 | @@ -139,8 +141,8 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Shape Fill/Stroke popover: No Color / Solid Color / Gradient / Pattern, Color Picker button, Recently Used Colors, swatch folders | partial: types, Color Picker (full dialog with hex, eyedropper and live preview), Recently Used Colors and swatch folders as Photoshop; Gradient opens the gradient tab; Pattern is off (shapes don't render pattern paint), no gear menu or resize grip (`tools/paint_picker.rs`, `tools/vector_ui/paint_tests.rs`, 2026-10-27) | [`shape-strokes.md`](shape-strokes.md) | | Colour swatches in dialogs and panels open the Color Picker dialog | done: Photo Filter, Black & White tint, Gradient Map stop, Content-Aware Fill overlay, Filter Gallery glow and the Save for Web colour table; the swatch previews the picker's colour while it is open, Cancel restores the exact colour, OK is one history step (`widgets/color_button_tests.rs`, `adjust_editors/ui_tests.rs`, 2026-10-30) | | | Shape options-bar Fill/Stroke hex input | done | #6176; typed in the Color Picker the popover opens (`color_picker_ui.rs`), `tools/vector_ui/paint_tests.rs`: typed and pasted hex, partial/invalid input, alpha retention, next-shape defaults and selected-shape Undo | -| Rotated shape selection hints correct | partial | #2512 | -| Curved shape bounds exact | partial | one pixel too wide (#2537) | +| Rotated shape selection hints correct | done | #2512, #2732 | +| Curved shape bounds exact | done | #2537, #2641 | ## Crop @@ -172,11 +174,11 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | ⇧-drag a guide out of a ruler, or move one already placed: it lands on the nearest ruler tick, in a pixel ruler on whole pixels at least | done | `rulers.rs` `snap_to_tick`, `snap_tick`, `GuideDrag::follow_pointer` (#3770) | | A dragged guide shows its position beside the pointer (X for vertical, Y for horizontal, in the ruler unit) | done | `rulers.rs` `guide_drag_readout` (#7680) | | ⌥ while dragging a guide (out of a ruler, or with the Move tool) turns it; a guide dropped on either ruler is deleted | done | `rulers.rs` `GuideDrag::track`, `view.moveGuide` `toOrientation` (#5034) | -| Status bar follows the ruler unit | partial | #2602 | -| Ruler corner and gaps drawn as Photoshop | partial | #2600, #2601, #2551 | -| Guides stored as f64 | missing | `Vec` (UI-217-20) | +| Status bar follows the ruler unit | done | #2602, #2618 | +| Ruler corner and gaps drawn as Photoshop | partial | corner overlap fixed (#2600, #2617); the gap above the top ruler is open (#2551; #2601 closed as its duplicate) | +| Guides stored as f64 | done | `Vec`, kept through .pcraft and PSD (UI-217-20) | | Geometry precision | partial | `geom::Point` f64, paths f64; paint internals mostly f32 | -| Numeric fields: arithmetic, scrubby labels | partial | units in expressions and double-click reset missing (UI-217-13) | +| Numeric fields: arithmetic, scrubby labels | done | arithmetic with units, scrubby labels, double-click reset (UI-217-13, #3099) | | Wheel steps a value field, ⇧ ×10: clicked into, wherever the pointer is; not clicked, a gesture that starts over it | partial | `field_wheel.rs` (#5473, #4061). Photoshop: a field takes the wheel once clicked into (shortcut guides, user reports); whether the pointer must stay over it is unconfirmed. Stepping on hover alone is Photopea's, kept deliberately | | Font-name field: click selects the full name; typing searches in place | done | `type_tool.rs` `family_picker_in`, `type_font_picker_tests.rs` (#9338): one editable name above the list; unmatched queries show a compact message; Enter or a row applies to the selected characters even when the family matches their representative; both controls show the selected span and leave mixed families blank; caret font choices affect subsequent typing; Ctrl/Cmd+Enter accepts a valid pending font query and commits from a focused field; Escape/outside click discards pending text; existing navigation and previews retained | | Type options bar: drag the "T" icon to change the font size | done | `type_tool.rs` `options_bar`: the icon scrubs the size field like the Character panel's icons (Shift x10, Alt fine), at layer or selection scope, one history step per drag, within 1–1296 pt (#6437) | @@ -192,14 +194,14 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | Scrubby zoom | done | `zoom_tool.rs` | | Flick panning | done | `flick_pan.rs` (Preferences › Tools › Enable Flick Panning) | | Animated zoom | done | `canvas.rs`, `zoom_tool.rs`, `zoom_hold.rs`; discrete Zoom clicks and View zoom controls ease over 220 ms with anchored transitions and immediate direct navigation (#566); holding a Zoom press still past 0.3 s zooms continuously about the press point (2 doublings a second, ⌥ out) until release (#6210); General › Animated Zoom (default on) controls both behaviors; off snaps discrete zoom immediately, including when disabled mid-transition | -| Double-click Zoom tool = 100%, double-click Hand = fit | partial | Zoom missing (#2508) | +| Double-click Zoom tool = 100%, double-click Hand = fit | done | #2508, #2527; `panels.rs::double_clicking_the_hand_tool_fits_on_screen` | | ⌥-wheel zoom around the pointer | partial | ×1.1 per notch, measured on Photoshop (#1718; `wheel_nav.rs`, `input_tests.rs`); #217 asked for ~5 % steps (UI-217-18). Ctrl + Alt + wheel is accepted as the same gesture on Windows and Linux (2026-10-31, #10488): winit reports a held Ctrl as both ctrl and command, so `wheel_nav::alt_gesture` forgives `command` only together with `ctrl` and without `mac_cmd`; macOS ⌘ + ⌥ and ⌘ + ⌃ + ⌥ stay out of the gesture and keeps whatever scroll egui 0.37 gives it — with Alt held both scroll patterns match, so its delta is not folded sideways — and Ctrl + Alt + ⇧ + wheel is deliberately left as it was before #10488 (a plain vertical scroll with General › Zoom with Scroll Wheel off, nothing with it on; checked on origin/main and pinned in all four Zoom with Scroll Wheel / Animated Zoom combinations by tests in `wheel_nav/tests.rs`). Which Photoshop gesture that combination should map to is open on #10488 (the issue names only Ctrl + Alt, and nothing here has measured the combination), so no behaviour is claimed. AltGr does not arrive as Ctrl + Alt: winit's Windows `get_agnostic_mods` drops ctrl and alt from the modifier state while AltGr is down on a layout that has one, and X11/Wayland deliver it as ISO_Level3_Shift. It is not excluded from the Alt gesture, though: egui-winit also emits a `Key::AltRight` event for the physical key and `wheel_events` turns that into `alt`, so AltGr + wheel can zoom like ⌥ (not verified on a physical AltGr keyboard; same AltGr situation as in the Brush size/hardness keys row, Keyboard shortcuts) | | Wheel, smooth scrolling and pinch as in Photoshop | partial | #2485, #2463, #1989; #10488 (Ctrl + Alt + wheel) | | Trackpad rotate drives Rotate View | done | `rotate_view.rs:136` | | Zoom levels to 3200% and beyond | partial | #1813 | | Physical 100% at any display scale | done | #1943 | | Filter dialogs with a preview window (Smart Sharpen, Unsharp Mask, Reduce Noise…): over the image the pointer is a small square, and a press there centres the dialog's preview on that point (clamped to the image), whatever the tool, while dragging on afterwards leaves it; a click or drag the locator starts never reaches the tool or the history, while a tool drag (a Brush stroke, a Crop frame) begun before the dialog opened still ends along its own path | done | `dialogs/filter_preview_ui.rs` `center_at`, `filter_preview_locator_tests.rs` (#9648); `ui.pointer` does the same | -| ⌃Tab / ⌃⇧Tab switch document tabs | missing | #2340 | +| ⌃Tab / ⌃⇧Tab switch document tabs | done | #2340, #2353 | ## Selected colour channels @@ -241,8 +243,8 @@ Paragraph; the rest open as in-app floating windows. |---|---|---| | Character and Paragraph controls without a type target | done | #5556; persistent Type tool defaults feed new point, box and mask text; existing text still edits in its selected scope (`type_tool.rs`, `type_tool_tests.rs`) | | Panel groups float and tear off into OS windows | missing | UI-217-5, #1828, #1213 | -| Drag panels to reorder and regroup | partial | #2272, #2305 | -| Docked resize pushes the neighbour | partial | #2573 | +| Drag panels to reorder and regroup | partial | dock tabs reorder within their group (#2272, #2774); regrouping open (#2305) | +| Docked resize pushes the neighbour | done | #2573, #2624 | | Color panel modes from its panel menu (Hue Cube, Brightness Cube, Color Wheel, Grayscale/RGB/HSB/CMYK/Lab/Web Color sliders), colour ramp (RGB/CMYK Spectrum, Grayscale Ramp, Current Colors, Make Ramp Web Safe; Shift-click cycles, Alt-click picks the other colour), Copy Color as HTML / Hex Code; the out-of-gamut ⚠ with the nearest printable colour under the chips (sliders always; the cubes when the field is at least 53 pt tall); the same in every theme | done | `color_panel_ui.rs`, `color_panel_tests.rs`; UI-217-17, #2569, #6000, #8672 | | A colour picked in the Color or Swatches panel or the Color Picker recolours the selection: selected characters while editing; every selected type layer with a Type tool; every selected shape's fill with a shape, Pen or path selection tool; only the foreground with other tools, the Move tool too; a swatch click recolours the selected type layers and shape fills whatever the tool (#9238); one history step (a Color panel drag too) | done: `apply_color.rs`, `apply_color_tests.rs` | | | A Color Picker opened for another dialog's colour (Edit › Fill's Color…, Edit › Stroke, a filter's or adjustment's colour, Replace Color's Result, New Document, New Guide and guide layout colours, channel and spot colours, Preferences) or for the Crop shield's custom colour shows the colour under the cursor there before OK, as in Photoshop, so the dialog's swatch and its own preview follow it; Cancel puts back exactly what was there, OK keeps it without a history step of its own (the dialog's OK makes the one step), and the dialog's ⌘Z history records only the picker's OK (#9886) | partial | `dialogs/color_picker_ui/live_preview.rs`, `dialogs/color_picker_ui/live_preview/tests.rs`; differs: the pickers whose OK runs a command without a preview of its own (text colour and gradient stops, open in #9757; gradient preset stops, artboard background, count group colour) and the pasteboard's custom colour show the colour only after OK | @@ -255,10 +257,10 @@ Paragraph; the rest open as in-app floating windows. | Every preference takes effect | partial | 8 of 199 do nothing (scorecard, 2026-11-08); Column Size drives Image Size and Canvas Size's Columns width unit (#6214) | | 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; History Options' snapshot options (Automatically Create First Snapshot, New Snapshot When Saving, Show New Snapshot Dialog by Default) | partial | `history_cmds.rs`, `history_options_cmds.rs`, `snapshot_rows` in `panels.rs`, `snapshot_dialog.rs`; History Brush sources to come (#2966) | -| Themes: Photoshop's four greys | partial | five themes; #2661 | +| Themes: Photoshop's four greys | done | `theme.rs` `Pro`, `ProMedium`, `ProLightGray`, `ProLight` (#2661, #2892) | | Painting tools' options bar: Opacity right after Mode in every theme (Brush, Pencil, Eraser, Clone Stamp); the non-Pro themes keep Hardness beside Size | done | #9784, `tool_options_theme_tests.rs::every_theme_puts_opacity_right_after_mode` | | Document tabs: overflow, context menu, reorder | done | UI-217-6; middle-click close #2570 | -| Layers panel: wheel steps blend modes, drop on New/Trash | partial | UI-217-14 | +| Layers panel: wheel steps blend modes, drop on New/Trash | done | UI-217-14 | | Layers panel New Group button: click with 2+ layers selected groups them (CC 2014+), ⇧-click groups, one layer gives an empty group, ⌥-click opens the New Group dialog, ⌘-click adds the group below the active layer | done | #2561, `new_group_button_tests.rs` | | New Group dialog (Name, Color, Mode, Opacity) for Layer › New › Group… / Group from Layers…, the Layers panel menu and the row menu; ⌘G stays immediate | done | `dialogs/new_group_ui.rs`, `dialogs/new_group_ui/tests.rs` | | Groups made from layers (⌘G, New Group button, Group from Layers) start collapsed; selecting a layer inside opens the group | done | `group_options.rs` tests, `new_group_button_tests.rs` | @@ -336,18 +338,15 @@ Paragraph; the rest open as in-app floating windows. | 2026-10-11 | minor | Flick panning done: releasing a moving Hand drag (tool, Space or middle button) glides and decays, gated by Enable Flick Panning | | 2026-10-11 | minor | History snapshots: the camera button takes one, snapshot rows return to it as a new state, rename and delete it (#2966) | | 2026-10-11 | minor | Animated zoom done: 220 ms transitions per view for discrete Zoom clicks and View controls; GPU composites are reused, coordinates follow the displayed camera, and direct navigation interrupts immediately | -| 2026-10-14 | minor | History: a clicked snapshot stays selected and the trash deletes it; snapshot and state rows dragged onto the trash are deleted (#5324) | | 2026-10-11 | minor | ⇧-drag a guide out of a ruler lands on the nearest ruler tick (#3770) | | 2026-10-11 | minor | Layer and selection keys from Photoshop's shortcut set: ⌘, toggles, ⌘\, /, ⌘⌥2, ⌘⌥⌫, Tab rename-next, ⌥-click thumbnail to fit | | 2026-10-11 | minor | Tool keys from Photoshop's shortcut set: ← / → rotate the brush tip, ⇧-click for new type, Space+F canvas colour | -| 2026-10-12 | minor | General › Animated Zoom is visible and gates every discrete zoom transition; disabling it snaps all views to their target on the next frame | | 2026-10-11 | minor | Spring-loaded tool letters done (#2672): holding any tool letter (Z included) past 300 ms, or using the canvas while it is down, makes the tool temporary until release | | 2026-10-11 | minor | Type formatting keys done: ⇧⌘K, U, B, I and /, ⌥↑/↓, ⇧⌥↑/↓, ⌥←/→ over a selection and ⌥⇧⌘H format the selected type while editing, and no longer reach Color Settings, Desaturate, Auto Color or Inverse | | 2026-10-11 | minor | Selection modifiers at press: evidence now names the marquee, Lasso and Polygonal Lasso tests (still partial: no marquee ⇧⌥ intersect test). ⌥-wheel zoom: missing → partial (works at ×1.1 a notch; #217 asked for ~5 %) | -| 2026-10-21 | minor | Selection modifiers at press: partial → done; the marquee ⇧⌥ intersect test (`marquee_tests.rs` `shift_alt_before_the_drag_intersects_the_selection`) closed the gap the 2026-10-11 row names (BUG-208-4) | +| 2026-10-11 | minor | Pen ⇧ 45° done: ⇧-click puts the next anchor on the nearest 45° ray, ⇧-drag turns its handles in 45° steps (TOOL-214-10 done, #3751) | +| 2026-10-12 | minor | General › Animated Zoom is visible and gates every discrete zoom transition; disabling it snaps all views to their target on the next frame | | 2026-10-12 | minor | Pen Auto Add/Delete on the active path, with its options-bar checkbox, hover feedback and + / − cursor badge (#4144) | -| 2026-10-15 | minor | Animated zoom partial: with Animated Zoom on, holding the Zoom tool's button zooms continuously about the press point, ⌥ out (#6210) | -| 2026-10-15 | minor | Pen Auto Add/Delete works on the path being drawn: a click on its segment adds an anchor, on a middle anchor deletes it, and drawing carries on (#6140) | | 2026-10-12 | minor | Toolbar tool shortcuts can be reassigned, removed and reset in Keyboard Shortcuts (#4086); capture, restart, group cycling, conflict and text-focus regressions | | 2026-10-12 | minor | Smart filter rows can be selected, and dragged (⌥: copied) onto another smart object or onto Delete (#4271) | | 2026-10-12 | minor | Free Transform options bar: H and V skew fields; a sheared box reads as skew instead of a taller H | @@ -355,22 +354,26 @@ Paragraph; the rest open as in-app floating windows. | 2026-10-12 | minor | Crop tool Fill › Content-Aware Fill done (#3823); Delete Cropped Pixels off split into its own row, still partial | | 2026-10-12 | minor | Layers panel: Clip Thumbnails to Layer Bounds frames each layer's pixels instead of the canvas (#4281) | | 2026-10-12 | minor | Guides: ⌥-click turns a guide through the click; double-click opens Preferences › Guides, Grid & Slices | +| 2026-10-12 | minor | Rows refreshed against main (scorecard ids and merged PRs cited per row): transform commit/cancel, right-click menu, locked layer, alpha channel and Puppet Warp; Move, selection, Pen, Crop preset, ruler, numeric-field, navigation, dock and theme rows; the last-used tool per group | | 2026-10-13 | minor | Smart filter rows can be dragged up or down their stack to reorder the filters | | 2026-10-12 | minor | History snapshots: the New Snapshot dialog (⌥-click the camera), and the first snapshot of the document as opened as the panel's top row (#2966) | | 2026-10-13 | minor | On-canvas corner radius widgets on live rectangles (TOOL-214-12) | | 2026-10-13 | minor | Curvature Pen edits the active path: drag anchors, click a segment to add, double-click smooth/corner, cursor badges | -| 2026-10-11 | minor | Pen ⇧ 45° done: ⇧-click puts the next anchor on the nearest 45° ray, ⇧-drag turns its handles in 45° steps (TOOL-214-10 done, #3751) | -| 2026-10-14 | minor | Last selected tool restored across launches; temporary overrides excluded, explicit Eraser choices retained, and final selection flushed on normal exit | | 2026-10-13 | minor | Free Transform with a selection: the box is the selection's rectangle, and the marching ants follow it while it is transformed (#5297) | +| 2026-10-14 | minor | History: a clicked snapshot stays selected and the trash deletes it; snapshot and state rows dragged onto the trash are deleted (#5324) | +| 2026-10-14 | minor | Last selected tool restored across launches; temporary overrides excluded, explicit Eraser choices retained, and final selection flushed on normal exit | | 2026-10-14 | minor | Move › Show Transform Controls frames every selected layer and outlines the selected shapes | +| 2026-10-14 | minor | Rounded corners on live triangles, polygons and stars: Properties field and on-canvas widgets (TOOL-214-12) | +| 2026-10-15 | minor | Animated zoom partial: with Animated Zoom on, holding the Zoom tool's button zooms continuously about the press point, ⌥ out (#6210) | +| 2026-10-15 | minor | Pen Auto Add/Delete works on the path being drawn: a click on its segment adds an anchor, on a middle anchor deletes it, and drawing carries on (#6140) | +| 2026-10-15 | minor | ⌫/Delete with a smart filter row selected removes that filter (the Smart Filters row: all of them), as the Delete button does, instead of the smart object (#4751) | | 2026-10-21 | minor | Crop rows corrected against the code and the scorecard: saved custom crop presets (TOOL-214-9, #2723) and Delete Cropped Pixels off are done (#6562); no percentage changed | | 2026-10-20 | minor | Free Transform of an artboard child omits ancestor paper from the covering and isolated composites while retaining board clipping. The base canvas and whole-artboard backgrounds are preserved; synthetic regressions in `transform_tool.rs`. No parity percentage changed. | | 2026-10-24 | minor | Layers panel filter row: Artboard lists only the artboards that hold the selected layers, and the unfiltered tree when nothing is selected or a selected layer is in no artboard; drivable by `ui.set {layerFilter: {by: "artboard"}}`; no percentage changed | | 2026-10-18 | minor | Move tool: dragging selected pixels shrinks the marching ants to the moved pixels as the drag starts, and the dropped selection is theirs, as in Photoshop (#7538) | | 2026-10-18 | minor | Marching ants drawn in device pixels like Photoshop's: equally thick on every edge at 125 %/150 % display scale, thicker on HiDPI, slanted dash ends (#7489) | +| 2026-10-21 | minor | Selection modifiers at press: partial → done; the marquee ⇧⌥ intersect test (`marquee_tests.rs` `shift_alt_before_the_drag_intersects_the_selection`) closed the gap the 2026-10-11 row names (BUG-208-4) | | 2026-10-16 | minor | View › Extras (⌘H) hides the Move tool's transform controls and their handles stop responding; ⌘H again restores them, and Show Transform Controls keeps its setting (#6699) | -| 2026-10-15 | minor | ⌫/Delete with a smart filter row selected removes that filter (the Smart Filters row: all of them), as the Delete button does, instead of the smart object (#4751) | -| 2026-10-14 | minor | Rounded corners on live triangles, polygons and stars: Properties field and on-canvas widgets (TOOL-214-12) | | 2026-10-14 | minor | A colour picked in the Color or Swatches panel or the Color Picker recolours the selected type layers (Type tool) or shape fills (shape, Pen and path selection tools) | | 2026-10-15 | minor | Color panel: Photoshop's panel-menu modes, colour ramp and copy commands; the theme no longer picks the panel's layout (UI-217-17 done, #2569, #6000) | | 2026-10-24 | minor | Layers panel filter row: Smart Object lists linked, missing or embedded smart objects, drivable by `ui.set {layerFilter: {by: "smartObject", smart}}`; no percentage changed | @@ -385,6 +388,8 @@ Paragraph; the rest open as in-app floating windows. | 2026-11-03 | minor | Tools › Overscroll off centres an image smaller than the window on that axis, so zooming out around the pointer keeps it in the middle instead of where the zoom left it (#10488, #4799); this overrides #1718's Photoshop 25.4 measurement on the strength of two Photoshop users' reports, and Overscroll on keeps the free view; no percentage changed | | 2026-11-04 | minor | Each toolbar slot and tool key keeps its last tool across launches (`Preferences.groupTools`, #3569); the group row, stale since #2625, is done; no percentage changed | | 2026-10-31 | minor | Ctrl + Alt + wheel over the canvas zooms like ⌥ + wheel (#10488): ×1.1 a notch around the pointer with Animated Zoom off, eased with it on, and it follows the ⌥ swap when General › Zoom with Scroll Wheel is on. Windows and Linux report a held Ctrl as ctrl AND command (`wheel_nav::alt_gesture`), macOS ⌘ + ⌥ is left alone, plain ⌘/Ctrl + wheel still scrolls sideways; the combination was a dead gesture, so nothing existing was replaced. The centred-zoom half of the report is still open: `canvas.rs:1737` re-clamps the view centre each frame only when Tools › Overscroll is off (it is on by default), so the drift the reporter saw is more likely the deliberate nearest-image-point anchor (`view_xform.rs:239`, #3720) or Zoom Clicked Point to Center, which needs its own repro; no percentage changed | +| 2026-11-08 | minor | Tool inventory: Color Replacement listed in the Brush group, Star (#11377) in Shapes; the `Tool` enum count is now 69; tools present 56/68 → 68/68 (Star counted separately) | | 2026-11-04 | minor | Unsaved-changes prompt on macOS: ⌘D presses Don't Save, as in Photoshop (#11282); no percentage changed | +| 2026-11-11 | minor | Space's Hand view menu (#11271, after #11292): a plain Esc under it closes only the menu and a plain Enter does nothing, so neither reaches a pending crop (in Photoshop, Esc with a context menu open only closes the menu); outside the image Space's Hand opens the pasteboard menu over the selected tool, which stays open after Space is released; no percentage changed | diff --git a/packaging/linux/AppRun b/packaging/linux/AppRun index 94f7346218..3414c5acc7 100755 --- a/packaging/linux/AppRun +++ b/packaging/linux/AppRun @@ -112,5 +112,13 @@ integrate() { done } +# `PhotoCraft.AppImage --cli ` runs the bundled photocraft-cli: MCP clients start +# `--cli mcp` this way (the ArtCraft Launcher's app list), since the mount point that holds +# the CLI changes with every run. +if [ "${1:-}" = "--cli" ]; then + shift + exec "$APPDIR/usr/bin/photocraft-cli" "$@" +fi + integrate exec "$APPDIR/usr/bin/photocraft" "$@" diff --git a/packaging/linux/apprun-test.sh b/packaging/linux/apprun-test.sh index 17e4923cf3..473872ebfe 100755 --- a/packaging/linux/apprun-test.sh +++ b/packaging/linux/apprun-test.sh @@ -22,6 +22,8 @@ mkdir -p "$APPDIR/usr/share/icons" cp -R "$ROOT/assets/app-icon/hicolor" "$APPDIR/usr/share/icons/" printf '#!/bin/sh\necho "stub: $*"\n' >"$APPDIR/usr/bin/photocraft" chmod +x "$APPDIR/usr/bin/photocraft" +printf '#!/bin/sh\necho "cli stub: $*"\n' >"$APPDIR/usr/bin/photocraft-cli" +chmod +x "$APPDIR/usr/bin/photocraft-cli" APPIMAGE="$TMP/photocraft test.AppImage" # spaces on purpose: Exec must stay quoted : >"$APPIMAGE" @@ -152,4 +154,10 @@ rm -f "$am_desktop" "$APPDIR/AppRun" >/dev/null || fail "launch after AM removal exited non-zero" [[ -f "$DESKTOP" ]] || fail "no desktop entry after the AM launcher was removed" +# 12. `--cli` runs the bundled CLI (MCP clients start `--cli mcp`), without integrating. +rm -rf "$XDG_DATA_HOME" +out="$("$APPDIR/AppRun" --cli mcp --headless)" || fail "--cli exited non-zero" +[ "$out" = "cli stub: mcp --headless" ] || fail "--cli output: $out" +[ ! -e "$XDG_DATA_HOME" ] || fail "--cli integrated the desktop entry" + echo "AppRun desktop integration ok" diff --git a/packaging/linux/flatpak/ai.storyteller.photocraft.bundle.yml b/packaging/linux/flatpak/ai.storyteller.photocraft.bundle.yml index 52b70503f1..c2ee9d5473 100644 --- a/packaging/linux/flatpak/ai.storyteller.photocraft.bundle.yml +++ b/packaging/linux/flatpak/ai.storyteller.photocraft.bundle.yml @@ -17,6 +17,8 @@ runtime-version: '26.08' sdk: org.freedesktop.Sdk command: photocraft finish-args: + # The shared updater inspects and updates this installation via flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak - --filesystem=xdg-data/ArtCraft/versions:ro # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland diff --git a/packaging/linux/flatpak/ai.storyteller.photocraft.yml b/packaging/linux/flatpak/ai.storyteller.photocraft.yml index 90d07dca77..f1958d7709 100644 --- a/packaging/linux/flatpak/ai.storyteller.photocraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.photocraft.yml @@ -18,6 +18,8 @@ sdk-extensions: - org.freedesktop.Sdk.Extension.rust-stable command: photocraft finish-args: + # The shared updater inspects and updates this installation via flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak - --filesystem=xdg-data/ArtCraft/versions:ro # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland diff --git a/packaging/macos/import-cert.sh b/packaging/macos/import-cert.sh index d67e7a6893..7ada923bc8 100755 --- a/packaging/macos/import-cert.sh +++ b/packaging/macos/import-cert.sh @@ -19,7 +19,9 @@ fi TMP="${RUNNER_TEMP:-${TMPDIR:-/tmp}}" KEYCHAIN="$TMP/photocraft-signing.keychain-db" -CERT="$TMP/photocraft-signing.p12" +# A fresh, private file (mktemp creates it exclusively, mode 0600): a predictable name could be +# pre-created by another account, and redirection would keep that file's owner and mode. +CERT="$(mktemp "$TMP/photocraft-signing.XXXXXX")" KC_PASS="${KEYCHAIN_PASSWORD:-$(openssl rand -hex 24)}" trap 'rm -f "$CERT"' EXIT diff --git a/packaging/macos/package.sh b/packaging/macos/package.sh index b19c4baa0f..8cb4d6db70 100755 --- a/packaging/macos/package.sh +++ b/packaging/macos/package.sh @@ -120,6 +120,8 @@ echo "==> assembling $APP" mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" # Executable and icon carry the display name (CFBundleExecutable / CFBundleIconFile). cp "$WORK/bin/photocraft" "$APP/Contents/MacOS/PhotoCraft" +# The CLI too, beside the app: Preferences › AI Integrations points MCP clients at it +# (`photocraft-cli mcp`), and it starts the app when an agent needs it. cp "$WORK/bin/photocraft-cli" "$APP/Contents/MacOS/photocraft-cli" cp "$ROOT/assets/app-icon/photocraft.icns" "$APP/Contents/Resources/PhotoCraft.icns" # Notices for the bundled font fallback, included before the bundle is signed. diff --git a/perf/budgets.toml b/perf/budgets.toml index 0d3d665e2d..600203f7fb 100644 --- a/perf/budgets.toml +++ b/perf/budgets.toml @@ -303,7 +303,7 @@ bench = "perf_scenarios" row = "open 20 MP layered PSD (decode + first composite)" budget_ms = 3000 -# P20/P63: generated fixtures (`photocraft_psd::fixtures`, #5107); the row checks a pixel, so a +# P20/P63: generated fixtures (`craft_psd::fixtures`, #5107); the row checks a pixel, so a # blank document fails it. No time budget yet: the target is the behaviour (progress, editable). [[scenario]] id = "P20" @@ -882,3 +882,31 @@ issue = 9329 bench = "perf_scenarios" row = "app frame after Paste Into on 24 MP (CPU canvas)" enforce = false # new; no baseline yet + +# ---- #11103: Free Transform drag stalls ------------------------------------------------------- + +[[bench]] +name = "free_transform_bench" +package = "photocraft-ui-egui" +args = ["--reps", "9"] +quick_args = ["--size", "1200x800", "--reps", "3", "--steps", "20"] +note = "two selected layers on 24 MP: Ctrl+T + first preview frame, and drag updates (pointer move + preview frame) scaling through new mip levels or moving; CPU side, no GPU upload/present" + +[[scenario]] +id = "P90" +title = "Free Transform begin, 2 layers on 24 MP (Ctrl+T + first preview frame)" +issue = 11103 +bench = "free_transform_bench" +row = "Free Transform begin, 2 layers on 24 MP: Ctrl+T + first frame" +budget_ms = 300 +enforce = true # #11103: 166 ms p50, 173 ms max (2026-11-11); a regression guard until the press frame is reworked + +[[scenario]] +id = "P91" +title = "Free Transform drag update, 2 layers on 24 MP (scale through new mip levels)" +issue = 11103 +bench = "free_transform_bench" +row = "Free Transform drag update, 2 layers on 24 MP: scale through mip levels" +metric = "max" +budget_ms = 16 +enforce = true # #11103: max 43.2 ms before (a mip level built in the frame), 0.09 ms after (2026-11-11) diff --git a/scorecard/automation.toml b/scorecard/automation.toml index 0607d992fc..641ab762d7 100644 --- a/scorecard/automation.toml +++ b/scorecard/automation.toml @@ -80,3 +80,9 @@ target = "Agent acceptance suite grown to 30-50 workflows" status = "partial" issue = 219 note = "automation/tests/it/agent_tasks.rs runs 10 workflows over MCP" + +[[item]] +id = "AUTO-MCP-LIVE" +target = "Connect an MCP client to the running app without a terminal (no flags, ports or tokens to copy)" +status = "done" +note = "2026-11-12 (#5525, #11363, craft-ai-integrations#195): the ArtCraft Launcher's agents switch (the one consent; read through craft-ai-agents) starts and stops the loopback control server while the app runs (no restart) and publishes agent-connection.json; plain photocraft-cli mcp works in the open app on every call while agents are allowed (launch / headless / error while it is closed) and headless otherwise (--headless forces it); the launcher's Add buttons register every Craft app, PhotoCraft writes no client configuration. automation/tests/mcp_live.rs, apps/photocraft/src/agent_link.rs tests" diff --git a/scorecard/file_compat.toml b/scorecard/file_compat.toml index e8195e6b51..5cc2bf2060 100644 --- a/scorecard/file_compat.toml +++ b/scorecard/file_compat.toml @@ -136,7 +136,7 @@ id = "FILE-215-19" target = "Save As JPEG opens a JPEG Options dialog (quality 0-12, format options)" status = "partial" issue = 215 -note = "jpeg_options_ui.rs: File > Save, Save As and Save a Copy to a JPEG ask for Quality 0-12 (Low/Medium/High/Maximum) and Baseline / Baseline Optimized / Progressive before writing, starting at an opened JPEG's own quality (file_encoding) or else the Export preference; scripts pass quality/jpegFormat (file.saveAs, file.saveACopy, app.save, CLI --jpeg-format) and recorded actions replay the answer (discard_ui/tests/jpeg_tests.rs, codecs roundtrip jpeg_format_options_round_trip). 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, so RGB Baseline Optimized writes the same file as Baseline. Missing: Matte, progressive Scans (3-5) and the size preview" +note = "jpeg_options_ui.rs: File > Save, Save As and Save a Copy to a JPEG ask for Quality 0-12 (Low/Medium/High/Maximum) and Baseline / Baseline Optimized / Progressive before writing, starting at an opened JPEG's own quality (file_encoding) or else the Export preference; scripts pass quality/jpegFormat (file.saveAs, file.saveACopy, app.save, CLI --jpeg-format) and recorded actions replay the answer (discard_ui/tests/jpeg_tests.rs, codecs roundtrip jpeg_format_options_round_trip). 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, so RGB Baseline Optimized writes the same file as Baseline. The dialog shows the size the file will have (152.3K, 1.5M), encoded in memory with its settings on a worker thread (in the frame on the web), up to 40 MP, 4 MP on the web (jpeg_options_ui/size_readout.rs). Missing: Matte and progressive Scans (3-5)" [[item]] id = "FILE-215-20" diff --git a/scorecard/tools.toml b/scorecard/tools.toml index 376f05418a..bdc9dc399b 100644 --- a/scorecard/tools.toml +++ b/scorecard/tools.toml @@ -59,7 +59,7 @@ id = "TOOL-213-8" target = "Clone Source: W/H link, drawn overlay (opacity/blend/clip/auto-hide), Alt target cursor" status = "partial" issue = 213 -note = "Clone Source overlay drawn with opacity, inversion, circular clipping, auto-hide and the Normal/Darken/Lighten/Difference blend against the image under the brush (canvas.rs draw_clone_preview, clone_source::overlay_blend); a shaped tip (sampled bitmap, rotation, roundness) clips the overlay to its outline (brush_cursor::tip_mask, #4372); W/H link (cloneSource.set linked, panel chain button, #3298)" +note = "Clone Source overlay drawn with opacity, inversion, circular clipping, auto-hide and the Normal/Darken/Lighten/Difference blend against the image under the brush (canvas.rs draw_clone_preview, clone_source::overlay_blend); a shaped tip (sampled bitmap, rotation, roundness) clips the overlay to its outline (brush_cursor::tip_mask, #4372); W/H link (cloneSource.set linked, panel chain button, #3298); a source ⌥-clicked in one open document is cloned (Clone Stamp, Healing Brush, the live stroke and the overlay) into another, using compatible document colour modes and ICC profile conversion (Clone Stamp requires matching modes; Healing Brush also permits Grayscale on either side), from the layer it was set on (cloneSource.set document; retouch_cmds/tests.rs clone_stamp_paints_from_the_document_the_source_was_set_in, ui alt_click_tests.rs alt_click_in_one_document_clones_into_another)" [[item]] id = "TOOL-213-9" diff --git a/xtask/src/corpus.rs b/xtask/src/corpus.rs index 866c354c29..23df1eb898 100644 --- a/xtask/src/corpus.rs +++ b/xtask/src/corpus.rs @@ -15,7 +15,7 @@ use crate::pinned::{PinnedCorpus, USER_AGENT}; use crate::{cargo, root, run}; /// Crates with corpus tests (behind their `corpus` feature). -pub const CORPUS_CRATES: &[&str] = &["photocraft-psd", "photocraft-codecs", "photocraft-io", "photocraft-engine"]; +pub const CORPUS_CRATES: &[&str] = &["photocraft-codecs", "photocraft-io", "photocraft-engine"]; /// Opt-in corpus crates: fetched and tested only with `test-corpus --pixls`. pub const PIXLS_CRATES: &[&str] = &["photocraft-raw"]; @@ -25,7 +25,6 @@ const HEIF_CRATES: &[&str] = &["photocraft-codecs", "photocraft-io"]; /// Paths whose changes make `test-corpus --changed` run (the file-format and rendering crates, /// and the engine's `.atn` import and export). const CRITICAL: &[&str] = &[ - "crates/psd/", "crates/io/", "crates/codecs/", "crates/heif/", diff --git a/xtask/src/corpus_pins.rs b/xtask/src/corpus_pins.rs index 263cb926f3..76253d8497 100644 --- a/xtask/src/corpus_pins.rs +++ b/xtask/src/corpus_pins.rs @@ -268,7 +268,7 @@ pub const AFFINITY: PinnedCorpus = PinnedCorpus { }, }; /// Photoshop Actions files (`.atn`) from public repositories under permissive licences, the -/// real-file oracles of `photocraft-psd::atn` and the engine's `.atn` import (2026-10-12). +/// real-file oracles of `craft-psd::atn` and the engine's `.atn` import (2026-10-12). /// https://github.com/sbaril/Photoshop-Scripts (MIT): `Actions/`. pub const SBARIL_COMMIT: &str = "622493c9c617c9d2ff38500e8e512c0ad421eed9"; /// https://github.com/bjango/Bjango-Actions (BSD, `Help/License.md`): three sets at the root. diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index bf1a6f2b88..a01447431f 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -37,7 +37,6 @@ pub const TABLE: &[(&str, Class)] = &[ ("cms", Class::Layer(0)), ("color", Class::Layer(0)), ("raster", Class::Layer(0)), - ("psd", Class::Standalone), ("codecs", Class::Standalone), // Optional HEIF/HEIC decoder (heic-rs), used only by `codecs` behind its `heif` feature. // IPP client for CUPS printing (pure Rust, no dependencies), used by `engine` on Unix. @@ -303,7 +302,7 @@ mod tests { #[test] fn self_dev_dependency_ignored() { - assert!(check(&[c("photocraft-psd", &[("photocraft-psd", Dev, true)])]).is_empty()); + assert!(check(&[c("photocraft-codecs", &[("photocraft-codecs", Dev, true)])]).is_empty()); } #[test] @@ -314,7 +313,7 @@ mod tests { #[test] fn standalone_crates_have_no_workspace_deps() { - for s in ["photocraft-psd", "photocraft-codecs", "photocraft-adobe-assets"] { + for s in ["photocraft-codecs", "photocraft-adobe-assets"] { let v = check(&[c(s, &[("photocraft-geom", Normal, true)])]); assert!(matches!(v[..], [Violation::StandaloneHasWorkspaceDep { .. }]), "{s}"); assert!(check(&[c(s, &[("image", Normal, false)])]).is_empty()); @@ -324,7 +323,7 @@ mod tests { #[test] fn standalone_crates_have_no_exceptions() { // Standalone crates may not use each other, in either direction. - for (from, to) in [("photocraft-codecs", "photocraft-psd"), ("photocraft-psd", "photocraft-codecs")] { + for (from, to) in [("photocraft-codecs", "photocraft-adobe-assets"), ("photocraft-adobe-assets", "photocraft-codecs")] { let v = check(&[c(from, &[(to, Normal, true)])]); assert!(matches!(v[..], [Violation::StandaloneHasWorkspaceDep { .. }]), "{from} -> {to}"); } @@ -335,7 +334,7 @@ mod tests { #[test] fn standalone_is_usable_from_higher_layers() { - assert!(check(&[c("photocraft-io", &[("photocraft-psd", Normal, true)])]).is_empty()); + assert!(check(&[c("photocraft-io", &[("photocraft-codecs", Normal, true)])]).is_empty()); let v = check(&[c("photocraft-geom", &[("photocraft-codecs", Normal, true)])]); assert!(matches!(v[..], [Violation::Upward { from: 0, to: 0, .. }])); }