diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 385245a0338..1282fc662c9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -82,6 +82,10 @@ 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 @@ -197,6 +201,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,15 +222,16 @@ 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 @@ -232,7 +241,7 @@ jobs: # 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 + uses: step-security/sccache-action@ae2d64c53dbae979f387673f0aae7ebb52087f6b # v0.0.11 with: version: v0.18.0 @@ -253,7 +262,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 +299,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 +319,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 +354,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 +390,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,10 +403,11 @@ 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' }} @@ -446,11 +472,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 +506,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 +519,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 +542,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 +555,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 +583,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 +613,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 +643,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 +656,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 +695,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 +713,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 e93efc1018a..6b63223a3a1 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -31,8 +31,14 @@ jobs: name: mdBook build runs-on: ubuntu-latest steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit - uses: actions/checkout@v7 - - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 + with: + toolchain: stable - name: Install mdBook run: cargo install mdbook --version 0.4.52 --locked - name: Build documentation diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index 86619a3ad6e..980c3a24454 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 71afc03e142..488ca561266 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 d1efb21c080..298dd4bf870 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 e2b8e229a7f..fffe9b1daa5 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. diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 8c4a8e969be..99a8660929b 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -15,8 +15,9 @@ next to them. | `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/*.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` (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/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,12 +81,8 @@ 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/native-pipette-macos-*.png` | Text Color Picker on macOS before and after the native pipette fix (synthetic text, no artwork) | PhotoCraft contributors (UI); @SvenCarstensen (captures) | Local macOS screenshot and PhotoCraft control-channel capture | MIT OR Apache-2.0 | -| `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` | diff --git a/Cargo.lock b/Cargo.lock index f16fc583417..85eff8824ef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1406,12 +1406,12 @@ dependencies = [ [[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-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-heif" @@ -1425,7 +1425,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 +1448,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 +1466,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,7 +1478,7 @@ 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", @@ -1492,7 +1492,7 @@ dependencies = [ [[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 +1513,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,6 +1523,7 @@ dependencies = [ "image", "log", "plist", + "rustix 1.1.5", "semver", "serde", "serde_json", @@ -2974,7 +2975,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 +3005,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 +3023,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 +3047,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", @@ -5323,7 +5324,7 @@ dependencies = [ [[package]] name = "photocraft" -version = "0.20.1" +version = "0.23.0" dependencies = [ "arboard", "async-io", @@ -5378,7 +5379,7 @@ dependencies = [ [[package]] name = "photocraft-affinity" -version = "0.20.1" +version = "0.23.0" dependencies = [ "crc32fast", "flate2", @@ -5388,7 +5389,7 @@ dependencies = [ [[package]] name = "photocraft-algo" -version = "0.20.1" +version = "0.23.0" dependencies = [ "criterion", "photocraft-color", @@ -5403,7 +5404,7 @@ dependencies = [ [[package]] name = "photocraft-automation" -version = "0.20.1" +version = "0.23.0" dependencies = [ "base64 0.23.1", "cap-std", @@ -5436,7 +5437,7 @@ dependencies = [ [[package]] name = "photocraft-cli" -version = "0.20.1" +version = "0.23.0" dependencies = [ "clap", "clap_complete", @@ -5462,7 +5463,7 @@ dependencies = [ [[package]] name = "photocraft-cms" -version = "0.20.1" +version = "0.23.0" dependencies = [ "moxcms", "rayon", @@ -5470,7 +5471,7 @@ dependencies = [ [[package]] name = "photocraft-codecs" -version = "0.20.1" +version = "0.23.0" dependencies = [ "craft-heif", "craft-jpeg", @@ -5494,7 +5495,7 @@ dependencies = [ [[package]] name = "photocraft-color" -version = "0.20.1" +version = "0.23.0" dependencies = [ "photocraft-cms", "serde", @@ -5502,7 +5503,7 @@ dependencies = [ [[package]] name = "photocraft-compose" -version = "0.20.1" +version = "0.23.0" dependencies = [ "criterion", "photocraft-cms", @@ -5518,7 +5519,7 @@ dependencies = [ [[package]] name = "photocraft-doc" -version = "0.20.1" +version = "0.23.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5529,7 +5530,7 @@ dependencies = [ [[package]] name = "photocraft-engine" -version = "0.20.1" +version = "0.23.0" dependencies = [ "base64 0.22.1", "blake3", @@ -5572,7 +5573,7 @@ dependencies = [ [[package]] name = "photocraft-format" -version = "0.20.1" +version = "0.23.0" dependencies = [ "blake3", "craft-pcraft-format", @@ -5596,14 +5597,14 @@ dependencies = [ [[package]] name = "photocraft-geom" -version = "0.20.1" +version = "0.23.0" dependencies = [ "serde", ] [[package]] name = "photocraft-gpu" -version = "0.20.1" +version = "0.23.0" dependencies = [ "bytemuck", "half", @@ -5624,7 +5625,7 @@ dependencies = [ [[package]] name = "photocraft-io" -version = "0.20.1" +version = "0.23.0" dependencies = [ "blake3", "craft-docpath", @@ -5664,18 +5665,18 @@ dependencies = [ [[package]] name = "photocraft-ipp" -version = "0.20.1" +version = "0.23.0" [[package]] name = "photocraft-ops" -version = "0.20.1" +version = "0.23.0" dependencies = [ "photocraft-doc", ] [[package]] name = "photocraft-paint" -version = "0.20.1" +version = "0.23.0" dependencies = [ "photocraft-cms", "photocraft-color", @@ -5689,7 +5690,7 @@ dependencies = [ [[package]] name = "photocraft-plugins" -version = "0.20.1" +version = "0.23.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5705,7 +5706,7 @@ dependencies = [ [[package]] name = "photocraft-psd" -version = "0.20.1" +version = "0.23.0" dependencies = [ "encoding_rs", "flate2", @@ -5717,7 +5718,7 @@ dependencies = [ [[package]] name = "photocraft-raster" -version = "0.20.1" +version = "0.23.0" dependencies = [ "crc32fast", "lz4_flex", @@ -5733,7 +5734,7 @@ dependencies = [ [[package]] name = "photocraft-raw" -version = "0.20.1" +version = "0.23.0" dependencies = [ "flate2", "image", @@ -5748,7 +5749,7 @@ dependencies = [ [[package]] name = "photocraft-tablet" -version = "0.20.1" +version = "0.23.0" dependencies = [ "block2 0.6.2", "log", @@ -5763,7 +5764,7 @@ dependencies = [ [[package]] name = "photocraft-testkit" -version = "0.20.1" +version = "0.23.0" dependencies = [ "memory-stats", "serde_json", @@ -5771,7 +5772,7 @@ dependencies = [ [[package]] name = "photocraft-text" -version = "0.20.1" +version = "0.23.0" dependencies = [ "flate2", "parley", @@ -5786,7 +5787,7 @@ dependencies = [ [[package]] name = "photocraft-ui-egui" -version = "0.20.1" +version = "0.23.0" dependencies = [ "base64 0.23.1", "chrono", @@ -5835,7 +5836,7 @@ dependencies = [ [[package]] name = "photocraft-vector" -version = "0.20.1" +version = "0.23.0" dependencies = [ "photocraft-color", "photocraft-doc", @@ -5846,7 +5847,7 @@ dependencies = [ [[package]] name = "photocraft-web" -version = "0.20.1" +version = "0.23.0" dependencies = [ "eframe", "egui", @@ -5869,7 +5870,7 @@ dependencies = [ [[package]] name = "photocraft-web-boot" -version = "0.20.1" +version = "0.23.0" dependencies = [ "flate2", "js-sys", @@ -9488,7 +9489,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 +9504,7 @@ dependencies = [ "windows", "windows-core", "windows-implement", + "windows-numerics", "xml", ] @@ -9754,7 +9756,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "xtask" -version = "0.20.1" +version = "0.23.0" dependencies = [ "chrono", "craft-i18n", diff --git a/Cargo.toml b/Cargo.toml index 3a4bfceeb4a..02184763f29 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,13 +4,13 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"] [workspace.package] -version = "0.20.1" +version = "0.23.0" 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"] } # internal photocraft-geom = { path = "crates/geom" } photocraft-color = { path = "crates/color" } @@ -39,19 +39,19 @@ photocraft-tablet = { path = "crates/tablet" } photocraft-ipp = { path = "crates/ipp" } # external -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +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" @@ -211,7 +211,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/apps/photocraft/src/logging.rs b/apps/photocraft/src/logging.rs index f5f014a3c15..e525197a27f 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/assets/icons/vector-shape.svg b/assets/icons/vector-shape.svg new file mode 100644 index 00000000000..e05c3b8c1d7 --- /dev/null +++ b/assets/icons/vector-shape.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/crates/algo/src/artistic_fx.rs b/crates/algo/src/artistic_fx.rs index a2c98e3c393..9a15d55b256 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 7ca9d34f99c..e9e64aff9b3 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 1a16612cc14..b783f39a54c 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 15c81fbe9c9..2508897a310 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 c781140ac3a..54b6fe3a76e 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 cd0452ab4cc..c47e7eb079b 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 45690fac014..747e9c36cdc 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 a673c15b698..06df86e005c 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. diff --git a/crates/algo/src/panorama.rs b/crates/algo/src/panorama.rs index 86e3faea085..a965a9dde31 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 9b4be0262c9..4aa545209f9 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/resample.rs b/crates/algo/src/resample.rs index 635a5a30799..d153b78cb03 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 6e410f1c5df..f4406da0d29 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/warp.rs b/crates/algo/src/warp.rs index 0dafc188672..b4e1680eb41 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/automation/src/files.rs b/crates/automation/src/files.rs index a9ef67274d4..1913566f4a8 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/tests/it/linked_save_bytes.rs b/crates/automation/tests/it/linked_save_bytes.rs new file mode 100644 index 00000000000..42ecd8b89ae --- /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 ed98e61b6bf..9a551dd0876 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/cms/src/profile.rs b/crates/cms/src/profile.rs index 01b2327df8c..89512a0beef 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/codecs/src/codecs/exr.rs b/crates/codecs/src/codecs/exr.rs index 0d68d20ca96..15d352fad0e 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 62fd2e1e0d9..0a71f5ed382 100644 --- a/crates/codecs/src/codecs/exr_cryptomatte.rs +++ b/crates/codecs/src/codecs/exr_cryptomatte.rs @@ -124,25 +124,33 @@ fn parse_manifest(json: &str) -> Vec<(f32, String)> { out } -/// 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,41 +165,56 @@ 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". + // groups. The set only answers "seen before"; the result is sorted below. let mut seen = std::collections::HashSet::new(); for name in other.keys() { let full = name.to_string(); @@ -201,6 +224,7 @@ 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 +266,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 index ae6e9450548..8dc5253ed08 100644 --- a/crates/codecs/src/codecs/fits.rs +++ b/crates/codecs/src/codecs/fits.rs @@ -381,6 +381,8 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result match out16 { Some(out) => Image::from_u16(w, hgt, layout, &out)?, None => { + // Admission above assumed 16-bit samples; the float fallback is twice that. + limits.check(w, hgt, layout, SampleType::F32)?; let max = (0..n).filter_map(physical).fold(0.0f64, f64::max); let white = if max <= 2.0 { 1.0 diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rs index b4675dbbdab..b1d574de50b 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/vp8.rs b/crates/codecs/src/codecs/vp8.rs index a24fb727cc8..7e5ef59bdd0 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/resolution.rs b/crates/codecs/src/resolution.rs index 9efc4659d58..8428f624a01 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 dfd0cd9b90a..301e67a9b21 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/exr_cryptomatte.rs b/crates/codecs/tests/it/exr_cryptomatte.rs index 28ad71e191e..012f631818c 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 28c8203c969..af5165b8489 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 ed92d9f9737..1b93cd8ac64 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 99b0c6aa0b0..3403ebddb9d 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 83cef453ca7..9795262ed20 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 e1cd209002f..02dc8b21cc1 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 0e7fe319e3f..21a7401b6a5 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/engine/src/allocation.rs b/crates/engine/src/allocation.rs index bf5dc177f63..db9344d9a7a 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/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index b72254ba3b0..c854dfa6319 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 ef755b1954a..97e0cbebab6 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 f6e1351dad1..783d757991f 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) }) } @@ -372,14 +376,15 @@ 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) -> 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 } @@ -388,14 +393,16 @@ pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface) -> Option< let mut out = surf.clone(); 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 { diff --git a/crates/engine/src/cmd/align_cmds.rs b/crates/engine/src/cmd/align_cmds.rs index 485c2085f66..67da0dd7931 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 e456a708148..f8217b3caed 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 ee51e9e2d06..b933549b75a 100644 --- a/crates/engine/src/cmd/analysis_cmds.rs +++ b/crates/engine/src/cmd/analysis_cmds.rs @@ -1179,6 +1179,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 6978b4d0597..73a0202b30c 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/files.rs b/crates/engine/src/cmd/atn_cmds/files.rs index 6b051778fbd..3f342194ab8 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/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 97b4c3ed3ad..09c635208ef 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -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 diff --git a/crates/engine/src/cmd/automate_cmds.rs b/crates/engine/src/cmd/automate_cmds.rs index 9a5f94f68c7..785ed90f37b 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 6858b35e225..0a410926799 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -913,7 +913,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 20447a627fc..d2aeb8560dc 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/channel_cmds/refs.rs b/crates/engine/src/cmd/channel_cmds/refs.rs index a9552e6d62a..39a56e19285 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/contour_lib_cmds.rs b/crates/engine/src/cmd/contour_lib_cmds.rs index 370c4da5cfb..3b6ab539555 100644 --- a/crates/engine/src/cmd/contour_lib_cmds.rs +++ b/crates/engine/src/cmd/contour_lib_cmds.rs @@ -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/distort_cmds.rs b/crates/engine/src/cmd/distort_cmds.rs index 1b71aed4a05..0f74916c5d2 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/eraser_cmds.rs b/crates/engine/src/cmd/eraser_cmds.rs index 473699aa631..efd8d60df35 100644 --- a/crates/engine/src/cmd/eraser_cmds.rs +++ b/crates/engine/src/cmd/eraser_cmds.rs @@ -187,9 +187,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)) diff --git a/crates/engine/src/cmd/face_cmds.rs b/crates/engine/src/cmd/face_cmds.rs index 0ae0af3d356..1d7ef45dd82 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 572c70ae603..d61919070cc 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"))] diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index b8ad5a137d4..5eb6543c861 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 1f7f9677ffa..4203c61ae5a 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 diff --git a/crates/engine/src/cmd/file_cmds/place_steps.rs b/crates/engine/src/cmd/file_cmds/place_steps.rs index 8d35d54704e..f449eaee8ad 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 94680e496a8..57535c4b3c2 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() { @@ -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 9cfa5d3f964..f5dfa28d2f0 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/layer_menu_cmds.rs b/crates/engine/src/cmd/layer_menu_cmds.rs index 46aae07a715..58f253bb687 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/multichannel_cmds.rs b/crates/engine/src/cmd/multichannel_cmds.rs index b0d46c2e4f0..91570fc2455 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/paint_cmds.rs b/crates/engine/src/cmd/paint_cmds.rs index 505b74ba568..4282349e0d7 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)?; @@ -212,3 +219,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 00000000000..5149067238f --- /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/print_cmds.rs b/crates/engine/src/cmd/print_cmds.rs index ba09fdea232..48442af1091 100644 --- a/crates/engine/src/cmd/print_cmds.rs +++ b/crates/engine/src/cmd/print_cmds.rs @@ -1525,6 +1525,12 @@ 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)> { @@ -1544,7 +1550,7 @@ pub fn paths_to_ai(doc: &Document, which: &str) -> Result<(String, usize)> { } 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, @@ -1559,7 +1565,7 @@ pub fn paths_to_ai(doc: &Document, which: &str) -> Result<(String, usize)> { continue; } n += 1; - s.push_str(&format!("%%Note: {name}\n")); + s.push_str(&format!("%%Note: {}\n", ps_comment_text(name))); let compound = subs.len() > 1; if compound { s.push_str("*u\n"); diff --git a/crates/engine/src/cmd/print_cmds/tests.rs b/crates/engine/src/cmd/print_cmds/tests.rs index c3d6e536df1..20afcc9254a 100644 --- a/crates/engine/src/cmd/print_cmds/tests.rs +++ b/crates/engine/src/cmd/print_cmds/tests.rs @@ -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/retouch_cmds/clone.rs b/crates/engine/src/cmd/retouch_cmds/clone.rs index 399ccc9d071..1b61da1d6b6 100644 --- a/crates/engine/src/cmd/retouch_cmds/clone.rs +++ b/crates/engine/src/cmd/retouch_cmds/clone.rs @@ -13,6 +13,9 @@ pub(super) fn clone_mapping(s: &mut Session, p: &Value, stroke: &Stroke, cmd: &s crate::presets::clone_source::mapping(s, p, (f.x, f.y), cmd) } +/// 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)] @@ -41,7 +44,13 @@ pub(super) fn clone_sample( r.rect = rect; return Ok(r); } - let src = read(map.source_rect(rect))?; + // 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(&surf.format()))) } diff --git a/crates/engine/src/cmd/retouch_cmds/dab.rs b/crates/engine/src/cmd/retouch_cmds/dab.rs index a0fe5da71bf..082fa9a28e2 100644 --- a/crates/engine/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine/src/cmd/retouch_cmds/dab.rs @@ -316,10 +316,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 { diff --git a/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs index 8c05c99085c..fd982cd0e0b 100644 --- a/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs +++ b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs @@ -163,7 +163,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) } diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index a07b170b09d..e45add3e308 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -67,6 +67,22 @@ 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(); + // 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] }; + let r = clone_sample(&d.doc, Some(id), surf, which, 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; diff --git a/crates/engine/src/cmd/smart_cmds/contents.rs b/crates/engine/src/cmd/smart_cmds/contents.rs index cce8b7002a4..8f28fe2a261 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/swatch_cmds.rs b/crates/engine/src/cmd/swatch_cmds.rs index fc9a4c36b17..756e10883a3 100644 --- a/crates/engine/src/cmd/swatch_cmds.rs +++ b/crates/engine/src/cmd/swatch_cmds.rs @@ -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")); diff --git a/crates/engine/src/cmd/video_cmds.rs b/crates/engine/src/cmd/video_cmds.rs index 9e49c108dfa..7bf065a0371 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/web_cmds/quick.rs b/crates/engine/src/cmd/web_cmds/quick.rs index 916a06f8d25..afe499ffdb8 100644 --- a/crates/engine/src/cmd/web_cmds/quick.rs +++ b/crates/engine/src/cmd/web_cmds/quick.rs @@ -114,7 +114,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"); diff --git a/crates/engine/src/cmd/web_cmds/tests.rs b/crates/engine/src/cmd/web_cmds/tests.rs index 82c2a6c5a98..ef7e3c3ea61 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 00000000000..6103dfc8187 --- /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 4f464b79d77..4d98747394c 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 26fae8eeca3..ce73e2cae9b 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); } // 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 467b3a8dc18..ebe352a05b9 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/lib.rs b/crates/engine/src/lib.rs index 153009df3d9..ef4eae9be23 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 a66a67b9278..bb5f6924a50 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 f5330dfaa49..03efb8cb2c4 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/preset_store.rs b/crates/engine/src/preset_store.rs index cc935564122..e8944984fde 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 7f0ead6c6ba..e5481061ba1 100644 --- a/crates/engine/src/preset_store/tests.rs +++ b/crates/engine/src/preset_store/tests.rs @@ -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 1845daa6d08..aeb3bae90ea 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/tests.rs b/crates/engine/src/presets/tests.rs index 88647ef23e3..9b64b756d8d 100644 --- a/crates/engine/src/presets/tests.rs +++ b/crates/engine/src/presets/tests.rs @@ -995,3 +995,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/tests/live_dab_matches_replay.rs b/crates/engine/tests/live_dab_matches_replay.rs index aae7e32b53c..a7fca39818e 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/format/src/atomic.rs b/crates/format/src/atomic.rs index 5a77e24c34e..801dcf84723 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 1a7c5493b5b..65870d55aa1 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 b9571ee93bf..5c460fa5d5e 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 aa95cca9f35..3b6b0bd2a8d 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/lib.rs b/crates/format/src/lib.rs index d1e701d0ffa..c0468043322 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/noreplace.rs b/crates/format/src/noreplace.rs new file mode 100644 index 00000000000..75a54350c5c --- /dev/null +++ b/crates/format/src/noreplace.rs @@ -0,0 +1,378 @@ +//! 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 { + if error.kind() == io::ErrorKind::Unsupported { + return true; + } + #[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; + } + false +} + +/// 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 5d8856b58d1..e089af6ea3c 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 c41a9ecdee3..bc61ef438a6 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/gpu/src/fx_passes.rs b/crates/gpu/src/fx_passes.rs index db952febfdc..dbc61d08534 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 166e9778001..e5418aab4dc 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 02d25954b69..3fe3cee6c91 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 781d35d039f..c563fb289f5 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/src/affinity.rs b/crates/io/src/affinity.rs index 4e5ed90f86a..6e272fd6691 100644 --- a/crates/io/src/affinity.rs +++ b/crates/io/src/affinity.rs @@ -580,7 +580,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; } @@ -697,11 +698,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,7 +723,7 @@ 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"); } diff --git a/crates/io/src/multichannel_map.rs b/crates/io/src/multichannel_map.rs index dae96c47562..1681849bc0c 100644 --- a/crates/io/src/multichannel_map.rs +++ b/crates/io/src/multichannel_map.rs @@ -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)?; diff --git a/crates/io/src/ora.rs b/crates/io/src/ora.rs index 36ebbc7b0a0..48ea0550f63 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/pdn.rs b/crates/io/src/pdn.rs index 1e2d99f7af5..796c44f426e 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/psd_import.rs b/crates/io/src/psd_import.rs index 5e582ffd813..3306a3f4c52 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -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() { diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index bbbeeed4757..1b84bf6cfbb 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 3052ba9ca30..28c6a0bf89f 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/xcf.rs b/crates/io/src/xcf.rs index e9a6b92a21c..77614155637 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 24481f1956a..5ad14f19b28 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/paint/src/bg_erase.rs b/crates/paint/src/bg_erase.rs index 8e783a02c9a..a7597822c3b 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 ffedc57f7ce..7014ff0cf6b 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 ee95dd8c2e2..8159408aaf2 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 51e1bbc20d6..8a665c329d8 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 4f0cf43915c..86e190860c4 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/mixer.rs b/crates/paint/src/mixer.rs index 5e6956f0873..370f2dc3545 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; @@ -341,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 { @@ -370,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:?}"); @@ -391,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:?}"); } @@ -459,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); } @@ -477,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/replace.rs b/crates/paint/src/replace.rs index b41d7a13042..3dd2c8f17e6 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) } @@ -273,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 { @@ -302,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)); } @@ -329,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_lab_tests.rs b/crates/paint/src/replace_lab_tests.rs index caf024fb401..47373611bc6 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 1494ba99946..09440437fd5 100644 --- a/crates/paint/src/retouch.rs +++ b/crates/paint/src/retouch.rs @@ -253,7 +253,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 +262,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 +634,19 @@ mod tests { } } + #[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 +663,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 +678,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 +688,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 +701,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 +719,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 +738,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 +858,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 +896,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 e72ee1d13e5..dc36cc798ad 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/examples/atn_dump.rs b/crates/psd/examples/atn_dump.rs index bd341c7b006..0714ab160bb 100644 --- a/crates/psd/examples/atn_dump.rs +++ b/crates/psd/examples/atn_dump.rs @@ -7,6 +7,11 @@ use photocraft_psd::atn; use photocraft_psd::descriptor::{Descriptor, ReferenceItem, Value}; +/// Escapes control characters so a file's names cannot drive the terminal. +fn clean(s: &str) -> String { + s.chars().flat_map(char::escape_debug).collect() +} + fn summary(v: &Value) -> String { match v { Value::Integer(i) => i.to_string(), @@ -48,7 +53,7 @@ fn main() { let bytes = match std::fs::read(&path) { Ok(b) => b, Err(e) => { - eprintln!("{path}: {e}"); + eprintln!("{}: {e}", clean(&path)); failed = true; continue; } @@ -56,25 +61,26 @@ fn main() { match atn::parse(&bytes) { Ok(f) => { println!( - "== {path}: set {:?}, {} actions{}{}", + "== {}: set {:?}, {} actions{}{}", + clean(&path), 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("; ")) } + f.encoding.as_deref().map(|e| format!(", names in {}", clean(e))).unwrap_or_default(), + if f.warnings.is_empty() { String::new() } else { format!(" ({})", clean(&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)), + Some(d) => println!(" {:<22} {:<28}{flags} {}", clean(&item.event.id()), clean(&f.item_label(item)), clean(&keys(d))), + None => println!(" {:<22} {:<28}{flags}", clean(&item.event.id()), clean(&f.item_label(item))), } } } } Err(e) => { - println!("== {path}: {e}"); + println!("== {}: {}", clean(&path), clean(&e.to_string())); failed = true; } } diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 52aebd93d87..1c1b74d992a 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/tests.rs b/crates/raster/src/tests.rs index 145df22c5a2..6c9427d9630 100644 --- a/crates/raster/src/tests.rs +++ b/crates/raster/src/tests.rs @@ -1043,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/src/render.rs b/crates/text/src/render.rs index 47da2de811d..477568c8b0b 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/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 229ec724d77..a8cf267e46b 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -153,6 +153,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, diff --git a/crates/ui-egui/src/brush_refusal_alert_tests.rs b/crates/ui-egui/src/brush_refusal_alert_tests.rs index b24872ca6eb..8acfae65e98 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 00000000000..e46c60bedba --- /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/canvas.rs b/crates/ui-egui/src/canvas.rs index 3b2b5085d2a..c38f6c8d32d 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1043,7 +1043,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 { @@ -1952,12 +1955,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 { @@ -2616,6 +2622,9 @@ mod pattern_drag_tests; #[cfg(test)] mod tabs_tests; +#[cfg(test)] +mod doc_window_dialog_tests; + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index c66d036d948..d600445e757 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -467,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, @@ -492,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. @@ -507,8 +517,8 @@ pub const NO_SELECTION_MENU: &[Row] = &[ Some(("Load Selection…", "select.loadSelection")), ]; -/// The Count tool's canvas menu (#11772): Photoshop's generic layer menu, on a marker or off one, -/// in its order for a pixel layer without a selection. Each row is enabled as the Layers panel +/// 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 tool's 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")), @@ -533,6 +543,16 @@ pub const COUNT_MENU: &[Row] = &[ /// 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): +/// 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"; @@ -683,8 +703,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, @@ -706,6 +749,8 @@ pub fn applies(tool: Tool) -> bool { // Sample Size and Copy Color (#11747). | Tool::Eyedropper | Tool::ContentAwareMove + // The layer or selection menu, where measured (#12577). + | Tool::RedEye ) || path_menu(tool) } @@ -806,6 +851,8 @@ pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { SAMPLER_MENU } else if menu.tool == Tool::Count { COUNT_MENU + } else if menu.tool == Tool::RedEye { + if menu.has_selection { MEASURED_SELECTION_MENU } else { COUNT_MENU } } else if menu.tool == Tool::Eyedropper { EYEDROPPER_MENU } else if inside_selection(menu) { @@ -1254,24 +1301,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 @@ -1776,10 +1816,10 @@ pub fn menu_rect_if_open(app: &PhotocraftApp, ctx: &Context) -> Option (PhotocraftApp, egui::Context) { (app, egui::Context::default()) } -fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value { +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, @@ -26,13 +26,13 @@ fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Valu } } -fn right_click(app: &mut PhotocraftApp, ctx: &egui::Context, x: f64, y: f64) { +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. -fn listed(app: &mut PhotocraftApp, ctx: &egui::Context) -> Vec { +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() 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 3b893f39a7f..6a3c5075c52 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); 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 00000000000..9a5bab7400c --- /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/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index 835f76ae46e..b5cfab7f2ba 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -49,7 +49,9 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) { } None => { let opacity = if tool == Tool::ArtHistoryBrush { BrushSettings::default().opacity } else { current.opacity }; - BrushSettings { smoothing: first_smoothing(), mode: photocraft_color::BlendMode::Normal, opacity, ..current } + // 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, size, ..current } } }; // The picked preset was the outgoing tool's brush: forget it, so Update Brush can't overwrite @@ -85,12 +87,16 @@ const HEALING_BRUSH_TIP: (f32, f32, f32) = (19.0, 1.0, 0.25); 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; /// `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, Dodge and Sponge tools' [`TONING_TOOL_TIP`], the Clone Stamp's -/// [`CLONE_STAMP_TIP`] with no smoothing; the other tools keep the default tip. +/// [`CLONE_STAMP_TIP`] with no smoothing, the Remove tool's size [`REMOVE_TOOL_SIZE`]; 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 { @@ -102,6 +108,7 @@ pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings (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) diff --git a/crates/ui-egui/src/canvas/remove_cursor_tests.rs b/crates/ui-egui/src/canvas/remove_cursor_tests.rs index cc4670e5904..681f92ba819 100644 --- a/crates/ui-egui/src/canvas/remove_cursor_tests.rs +++ b/crates/ui-egui/src/canvas/remove_cursor_tests.rs @@ -15,6 +15,7 @@ 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; diff --git a/crates/ui-egui/src/canvas/sampler_cursor_tests.rs b/crates/ui-egui/src/canvas/sampler_cursor_tests.rs index 9ec90dd48be..52a255103ad 100644 --- a/crates/ui-egui/src/canvas/sampler_cursor_tests.rs +++ b/crates/ui-egui/src/canvas/sampler_cursor_tests.rs @@ -182,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/tabs.rs b/crates/ui-egui/src/canvas/tabs.rs index 40e7f471051..6eafa7b3c1e 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 6506b659879..67f38527848 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -3141,8 +3141,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_input.rs b/crates/ui-egui/src/canvas/tool_input.rs index 7d4b17e1662..b3b4c425443 100644 --- a/crates/ui-egui/src/canvas/tool_input.rs +++ b/crates/ui-egui/src/canvas/tool_input.rs @@ -459,6 +459,25 @@ fn red_eye_click(app: &mut PhotocraftApp, x: f64, y: f64) { } } +/// A Paint Bucket click. A Bitmap document gets the reference's alert (#12536), once even if +/// more clicks arrive while it is open (`ui.pointer` can send them). +fn bucket_click(app: &mut PhotocraftApp, x: f64, y: f64) { + use photocraft_engine::paint_cmds::BITMAP_REFUSAL; + 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 r = 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)})); + if r.is_err_and(|e| e == BITMAP_REFUSAL) { + app.ui.status.clear(); + app.ui.status_error = false; + let message = tl!(BITMAP_REFUSAL); + let kind = crate::state::DialogKind::Error; + if !app.ui.dialogs.iter().any(|d| d.kind == kind && d.fields.get("message").and_then(|m| m.as_str()) == Some(message)) { + app.ui.open_dialog(kind, json!({ "message": message }).as_object().cloned().unwrap_or_default()); + } + } +} + /// The Brush's chosen Clear paints as Normal on the Background, and its Mode then reads Normal /// (#11897): at the press of a Brush stroke on the Background's own pixels, Clear (chosen in the /// options bar, not a held `~`) is turned off, so the stroke is sent as Normal. A Background whose @@ -525,7 +544,12 @@ pub(super) fn tool_event_with_view(app: &mut PhotocraftApp, ev: ToolEvent, mods: if !sets_source && press_refused(app, tool) { return; } - if !sets_source && (crate::rasterize_prompt::intercept(app, tool, x, y, pressure) || refuse_group(app, tool)) { + // The Clone Stamp's no-source alert opens at the press, after any rasterize prompt. + if !sets_source + && (crate::rasterize_prompt::intercept(app, tool, x, y, pressure) + || refuse_group(app, tool) + || crate::retouch_ui::clone_stamp_without_source(app, tool)) + { return; } // ⌘ with a selection tool is the Move tool for the drag: outside the selection (or @@ -611,10 +635,7 @@ pub(super) fn tool_event_with_view(app: &mut PhotocraftApp, ev: ToolEvent, mods: return; } Tool::PaintBucket => { - 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 +821,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. +/// 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()) { 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 00000000000..f4d1bd29d9d --- /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/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 164d6de995c..43a219cc0e8 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); } @@ -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") @@ -564,7 +569,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") @@ -899,6 +904,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 +1152,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) => { @@ -1319,6 +1326,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; 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 c139a4e1e52..9d221f836ff 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/convert.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/convert.rs index 4fd1852aae9..f61c57e27d8 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/open.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs index 12e168bd7b4..2c04d0e268c 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs @@ -239,7 +239,7 @@ pub(super) fn commit_open_raw(app: &mut PhotocraftApp, params: &CameraRaw, raw: 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"))), @@ -561,3 +561,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/dont_show_again.rs b/crates/ui-egui/src/dialogs/dont_show_again.rs index da21ce4087d..ab6bd25bf98 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 e8bc29f831e..fc9bc5ab358 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -257,7 +257,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); } @@ -1175,3 +1177,23 @@ fn quick_export(app: &mut PhotocraftApp, p: Value) -> Result { #[cfg(test)] mod 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/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index b46087452c6..4cf9edc9cac 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -693,7 +693,10 @@ fn straighten_defaults(app: &PhotocraftApp, 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" })); } @@ -1158,7 +1161,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 +1221,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/live_shape_prompt.rs b/crates/ui-egui/src/dialogs/live_shape_prompt.rs new file mode 100644 index 00000000000..6db96b67607 --- /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/icon_data.rs b/crates/ui-egui/src/icon_data.rs index c29e2192fa3..3dd68269fb1 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")), diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 158079ddf0a..742061d8356 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -693,9 +693,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 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3910e8c289f..7a56e9b703d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -669,6 +669,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`). @@ -1097,3 +1100,6 @@ mod background_eraser_digit_keys_tests; mod clone_stamp_reset_tip_tests; #[cfg(test)] mod sponge_default_tip_tests; + +#[cfg(test)] +mod red_eye_context_menu_tests; diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 4d94412ebe3..43e22145043 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -132,9 +132,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 1b814c27e11..e4bdc7a66c7 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/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 8dc34da45ad..5d072f2f199 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/history_menu_ui.rs b/crates/ui-egui/src/panels/history_menu_ui.rs index fa865d42c45..15fe4e9886d 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/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index d0b2f6245ae..895e6b0a02f 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| { diff --git a/crates/ui-egui/src/panels/props_layout.rs b/crates/ui-egui/src/panels/props_layout.rs index 8d604995bc5..e74faec0539 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 50e9006875a..cc2cd61cee3 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/red_eye_context_menu_tests.rs b/crates/ui-egui/src/red_eye_context_menu_tests.rs new file mode 100644 index 00000000000..a7a5a209333 --- /dev/null +++ b/crates/ui-egui/src/red_eye_context_menu_tests.rs @@ -0,0 +1,205 @@ +//! #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", +]; + +/// The reference also greys Group from Layers… and Load Selection…, but their menu-bar twins are +/// live here (as in the Count tool's menu), and the rows follow the twins. +const NO_SELECTION_GREY: [&str; 5] = ["Blending Options…", "Convert to Layers", "Rasterize Layer", "Rasterize Layer Style", "Free Transform"]; + +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/tools.rs b/crates/ui-egui/src/tools.rs index 81dafc6bc98..d62f9542e35 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -71,3 +71,6 @@ mod crop_options_labels_tests; mod gradient_options_bar_mode_tests; #[cfg(test)] mod gradient_refusal_messages_tests; + +#[cfg(test)] +mod remove_default_size_tests; diff --git a/crates/ui-egui/src/tools/anchor_tools.rs b/crates/ui-egui/src/tools/anchor_tools.rs index 7713b80b0b4..6b1c554d105 100644 --- a/crates/ui-egui/src/tools/anchor_tools.rs +++ b/crates/ui-egui/src/tools/anchor_tools.rs @@ -220,6 +220,10 @@ fn apply(app: &mut PhotocraftApp, r: PathRef, hit: Hit, p: [f64; 2]) { if let (Some(o), Some(t)) = (params.as_object_mut(), r.params(app).as_object()) { o.extend(t.clone()); } + // A live shape becomes a regular path: ask first (#12768). + if id == "path.deleteAnchor" && crate::dialogs::live_shape_prompt::ask(app, r, ¶ms) { + return; + } match app.run(id, params) { Ok(v) if coalesce.is_some() => { let n = |f: &str| v["anchor"][f].as_u64().and_then(|v| usize::try_from(v).ok()); @@ -282,6 +286,8 @@ mod add_anchor_lock_tests; #[cfg(test)] mod add_anchor_targeted_path_tests; #[cfg(test)] +mod delete_anchor_live_shape_tests; +#[cfg(test)] mod delete_anchor_lock_tests; #[cfg(test)] pub(crate) mod delete_anchor_targeted_path_tests; 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 00000000000..fdccea07e09 --- /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_targeted_path_tests.rs b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_targeted_path_tests.rs index 38315eda914..156e3b9dad2 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 @@ -12,6 +12,14 @@ 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(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(); diff --git a/crates/ui-egui/src/tools/brush_refusal.rs b/crates/ui-egui/src/tools/brush_refusal.rs index e58eba61ff7..bfa63bb3abc 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,6 +14,8 @@ 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. @@ -57,26 +60,33 @@ 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)])) } +/// [`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 and Sponge 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 { @@ -90,7 +100,7 @@ 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"] @@ -99,3 +109,11 @@ mod sharpen_refusal_alert_tests; #[cfg(test)] #[path = "../sponge_refusal_alert_tests.rs"] mod sponge_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; diff --git a/crates/ui-egui/src/tools/direct_select.rs b/crates/ui-egui/src/tools/direct_select.rs index 9272d570fcd..06299d82dd5 100644 --- a/crates/ui-egui/src/tools/direct_select.rs +++ b/crates/ui-egui/src/tools/direct_select.rs @@ -480,17 +480,31 @@ fn targeted(app: &PhotocraftApp) -> Vec<(PathRef, Path)> { /// 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 tol = 6.0 / f64::from(app.point_zoom().max(0.01)); + 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, &shown).map(|h| (r, path, h)) - }) + 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 { @@ -927,6 +941,9 @@ mod convert_point_history_tests; #[cfg(test)] mod convert_point_targeted_path_tests; +#[cfg(test)] +mod convert_point_tolerance_tests; + #[cfg(test)] mod freeform_command_tests { use super::*; 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 00000000000..1b84d71c437 --- /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/remove_default_size_tests.rs b/crates/ui-egui/src/tools/remove_default_size_tests.rs new file mode 100644 index 00000000000..ddc5af2bc01 --- /dev/null +++ b/crates/ui-egui/src/tools/remove_default_size_tests.rs @@ -0,0 +1,86 @@ +//! #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"); +} + +#[test] +fn other_tools_keep_their_reset_sizes() { + for (tool, want) in + [(Tool::Brush, 13.0), (Tool::Pencil, 20.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_locked_alert_tests.rs b/crates/ui-egui/src/tools/remove_locked_alert_tests.rs new file mode 100644 index 00000000000..fc7e266fe54 --- /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 says so in the status bar, 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_eq!(app.ui.status, photocraft_engine::hidden_target::HIDDEN); + 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/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index 58aac368dbb..68abe3dfae2 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -198,6 +198,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) @@ -224,6 +239,9 @@ pub(crate) fn finish_stroke_with(app: &mut PhotocraftApp, tool: Tool, points: &[ 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") @@ -783,7 +801,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())); @@ -807,11 +826,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")); @@ -1207,3 +1226,7 @@ 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; diff --git a/crates/ui-egui/src/tools/retouch_ui/tests.rs b/crates/ui-egui/src/tools/retouch_ui/tests.rs index a6eba29bd24..4d77b6a0753 100644 --- a/crates/ui-egui/src/tools/retouch_ui/tests.rs +++ b/crates/ui-egui/src/tools/retouch_ui/tests.rs @@ -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| { 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 d8350ebb4a1..f79cae7c3a4 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 544d00ee377..113c788bb04 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 00000000000..b7de5cacbf7 --- /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/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index 54fe6527ce4..1cdf3c357e4 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; @@ -222,6 +223,9 @@ mod pen_rubber_band_tests; #[cfg(test)] mod paint_tests; +#[cfg(test)] +mod pen_resume_tests; + #[cfg(test)] mod add_anchor_options_bar_tests; @@ -231,7 +235,13 @@ mod delete_anchor_options_bar_tests; #[cfg(test)] mod pen_enter_deselects_tests; +#[cfg(test)] +mod pen_mode_menu_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/options.rs b/crates/ui-egui/src/tools/vector_ui/options.rs index cd0d4fbfe2e..fae9f132696 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:")); diff --git a/crates/ui-egui/src/tools/vector_ui/pen.rs b/crates/ui-egui/src/tools/vector_ui/pen.rs index c4640a8cfdc..6c99f9c5a48 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})"); 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 00000000000..f5eb0088211 --- /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 00000000000..a7465fd8a4d --- /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 00000000000..78a645dec5a --- /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/widgets.rs b/crates/ui-egui/src/widgets.rs index 022bf463f1d..9e8d8902592 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; @@ -74,8 +74,8 @@ 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_len, - value_field_prec, value_field_prec_blank, value_field_units, + 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_len, value_field_prec, value_field_prec_blank, value_field_units, }; #[cfg(test)] diff --git a/crates/ui-egui/src/widgets/dropdown.rs b/crates/ui-egui/src/widgets/dropdown.rs index c79b3af3389..96052a43270 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 f61b8886c88..078d4ef003b 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 @@ -120,6 +120,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`; @@ -462,7 +464,7 @@ fn number_edit( units: crate::numeric_expression::Units, opts: FieldOpts, ) -> Response { - let FieldOpts { decimals, wrap_drag, hold_typed, blank_when_zero, .. } = opts; + let FieldOpts { decimals, wrap_drag, hold_typed, 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) { @@ -482,6 +484,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 6a02717e586..7f7f79cd6da 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/units.rs b/crates/ui-egui/src/widgets/units.rs index 9d32c17197c..001912c1dd3 100644 --- a/crates/ui-egui/src/widgets/units.rs +++ b/crates/ui-egui/src/widgets/units.rs @@ -28,6 +28,12 @@ pub fn value_field_prec(ui: &mut Ui, value: &mut f32, range: std::ops::RangeIncl value_field_in(ui, value, range, suffix, width, 0.0, FieldOpts { decimals: Some(decimals), ..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 { @@ -121,6 +127,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) @@ -149,6 +163,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/docs/images/SOURCES.md b/docs/images/SOURCES.md index 1d68651a573..7f11ca6b439 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/gradient-overlay-method-after.png b/docs/images/gradient-overlay-method-after.png deleted file mode 100644 index 8d6107e7ab2..00000000000 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 75a63d97b31..00000000000 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 1c7aaed68c7..00000000000 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 a0658b74b17..00000000000 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 2eca8478455..00000000000 Binary files a/docs/images/guide-position-before-tab.png and /dev/null differ diff --git a/docs/images/native-pipette-macos-after.png b/docs/images/native-pipette-macos-after.png deleted file mode 100644 index 72eb8ba8212..00000000000 Binary files a/docs/images/native-pipette-macos-after.png and /dev/null differ diff --git a/docs/images/native-pipette-macos-before.png b/docs/images/native-pipette-macos-before.png deleted file mode 100644 index 7909b224497..00000000000 Binary files a/docs/images/native-pipette-macos-before.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 5abd1fd695f..00000000000 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 23d6c3f855b..00000000000 Binary files a/docs/images/preferences-apply-before.png and /dev/null differ diff --git a/packaging/macos/import-cert.sh b/packaging/macos/import-cert.sh index d67e7a6893c..7ada923bc82 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