diff --git a/.github/workflows/cache-prune.yml b/.github/workflows/cache-prune.yml index 7607488502..0bdea85721 100644 --- a/.github/workflows/cache-prune.yml +++ b/.github/workflows/cache-prune.yml @@ -21,7 +21,7 @@ jobs: # A fork's pull request from a branch named main also matches `branches`. if: github.event.workflow_run.event != 'pull_request' timeout-minutes: 10 - runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-trusted' || 'ubuntu-24.04' }} + runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-24.04' }} permissions: actions: write steps: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 51292cfb4e..d3041a1fc9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -97,7 +97,7 @@ jobs: if: github.event_name != 'schedule' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') timeout-minutes: 10 name: select platforms - runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-trusted' || 'ubuntu-latest' }} + runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }} outputs: windows: ${{ steps.pick.outputs.windows }} windows_gpu: ${{ steps.pick.outputs.windows_gpu }} @@ -181,7 +181,7 @@ jobs: # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: - os: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && '["artcraft-k8s-trusted"]' || '["ubuntu-24.04"]' }} + os: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && '["artcraft-k8s-main"]' || '["ubuntu-24.04"]' }} # On the cluster runners sccache uses the shared cluster cache, which main runs fill for # every app; PR runs on hosted runners can't reach it, so they leave it off. sccache: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' }} @@ -284,7 +284,7 @@ jobs: # A cold Windows build takes about an hour, and the watch ends when it does; `watch-minutes` # ends it before this limit. timeout-minutes: 120 - runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-trusted' || 'ubuntu-24.04' }} + runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-24.04' }} permissions: actions: write steps: @@ -338,7 +338,7 @@ jobs: timeout-minutes: 60 name: test (without heif) # The gate's runner: its cache entry is keyed on the OS. - runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-trusted' || 'ubuntu-24.04' }} + runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-24.04' }} env: # The gate sets these; rust-cache hashes CARGO_* and RUST* variables into its key. CARGO_INCREMENTAL: 0 @@ -396,7 +396,7 @@ jobs: # PRs run it only when web-relevant files change (see `platforms`); main always does. needs: platforms if: needs.platforms.outputs.web == 'true' - runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-trusted' || 'ubuntu-latest' }} + runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }} env: # Match release.yml so PR results reflect what would actually ship. TRUNK_VERSION: 0.21.14 @@ -464,7 +464,7 @@ jobs: name: fuzz (${{ matrix.target.crate }}/${{ matrix.target.name }}) # Placeholder: manual trigger only until a nightly schedule is enabled. if: github.event_name == 'workflow_dispatch' && inputs.fuzz - runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-trusted' || 'ubuntu-latest' }} + runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }} env: # cargo-fuzz needs nightly; the checkout's rust-toolchain.toml would pick the pinned release. RUSTUP_TOOLCHAIN: nightly @@ -521,7 +521,7 @@ jobs: color-range-performance: if: inputs.color_range == true - runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-trusted' || 'ubuntu-latest' }} + runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }} timeout-minutes: 45 env: RAYON_NUM_THREADS: "4" @@ -558,7 +558,7 @@ jobs: selection-morphology: if: inputs.selection_morphology == true - runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-trusted' || 'ubuntu-latest' }} + runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }} timeout-minutes: 45 env: RAYON_NUM_THREADS: "4" @@ -637,7 +637,7 @@ jobs: selection-combining: if: inputs.selection_combining == true - runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-trusted' || 'ubuntu-latest' }} + runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }} timeout-minutes: 30 env: RAYON_NUM_THREADS: "4" @@ -668,7 +668,7 @@ jobs: brush-tip: if: inputs.brush_tip == true - runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-trusted' || 'ubuntu-24.04' }} + runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-24.04' }} timeout-minutes: 30 env: RAYON_NUM_THREADS: "4" @@ -716,7 +716,7 @@ jobs: path: brush-tip.txt dry-mixer: if: inputs.dry_mixer == true - runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-trusted' || 'ubuntu-latest' }} + runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }} timeout-minutes: 90 env: RAYON_NUM_THREADS: "4" diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index d567f2c2c0..5ad2e53fc4 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -31,7 +31,7 @@ jobs: # Tracks @main so suite-wide CI fixes reach every app without a PR in each repository. uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: - os: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && '["artcraft-k8s-trusted"]' || '["ubuntu-24.04"]' }} + os: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && '["artcraft-k8s-main"]' || '["ubuntu-24.04"]' }} timeout-minutes: 15 # The book needs mdBook only: no craft-fonts, apt packages, wasm target or nextest. craft-fonts-ref: "" diff --git a/.github/workflows/packaging-lint.yml b/.github/workflows/packaging-lint.yml index a1a514af5a..560103c61e 100644 --- a/.github/workflows/packaging-lint.yml +++ b/.github/workflows/packaging-lint.yml @@ -27,7 +27,7 @@ jobs: verified-appimage-inputs: timeout-minutes: 10 name: Verified AppImage inputs - runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-trusted' || 'ubuntu-latest' }} + runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }} steps: - name: Harden runner uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 diff --git a/Cargo.lock b/Cargo.lock index 5a349ddc68..97e3ae5f2b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1365,12 +1365,12 @@ dependencies = [ [[package]] name = "craft" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-automation", "craft-behavior", "craft-browse", - "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", "craft-color-ui", "craft-control", "craft-dialogs", @@ -1406,7 +1406,7 @@ dependencies = [ [[package]] name = "craft-affinity" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "crc32fast", "flate2", @@ -1427,7 +1427,7 @@ dependencies = [ [[package]] name = "craft-atomic" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "rustix 1.1.5", ] @@ -1435,7 +1435,7 @@ dependencies = [ [[package]] name = "craft-automation" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "base64 0.22.1", "craft-behavior", @@ -1460,7 +1460,7 @@ dependencies = [ [[package]] name = "craft-behavior" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "accesskit", "bitflags 2.13.2", @@ -1478,7 +1478,7 @@ dependencies = [ [[package]] name = "craft-browse" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-docpath", @@ -1496,20 +1496,11 @@ dependencies = [ [[package]] name = "craft-cloud-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "egui", ] -[[package]] -name = "craft-cms" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" -dependencies = [ - "md-5", - "rayon", -] - [[package]] name = "craft-cms" version = "0.1.0" @@ -1519,10 +1510,19 @@ dependencies = [ "rayon", ] +[[package]] +name = "craft-cms" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" +dependencies = [ + "md-5", + "rayon", +] + [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" [[package]] name = "craft-color" @@ -1545,10 +1545,10 @@ dependencies = [ [[package]] name = "craft-color-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", - "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", "craft-host", "craft-i18n", "craft-keymap", @@ -1565,7 +1565,7 @@ dependencies = [ [[package]] name = "craft-control" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-ai-agents", "craft-atomic", @@ -1580,9 +1580,9 @@ dependencies = [ [[package]] name = "craft-crs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", "craft-xml", "thiserror 2.0.21", ] @@ -1590,7 +1590,7 @@ dependencies = [ [[package]] name = "craft-crw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "thiserror 2.0.21", ] @@ -1598,7 +1598,7 @@ dependencies = [ [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "rayon", ] @@ -1629,7 +1629,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "block2 0.6.2", "craft-atomic", @@ -1654,7 +1654,7 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "serde", ] @@ -1662,7 +1662,7 @@ dependencies = [ [[package]] name = "craft-draw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1681,12 +1681,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" [[package]] name = "craft-file-formats" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-eps", "craft-idml", @@ -1704,7 +1704,7 @@ dependencies = [ [[package]] name = "craft-flags" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-atomic", "dirs", @@ -1714,7 +1714,7 @@ dependencies = [ [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "fontique", "harfrust 0.13.3", @@ -1729,7 +1729,7 @@ dependencies = [ [[package]] name = "craft-font-manager" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-font-catalog", @@ -1748,7 +1748,7 @@ dependencies = [ [[package]] name = "craft-font-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "cap-primitives", "craft-atomic", @@ -1769,7 +1769,7 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" [[package]] name = "craft-geom" @@ -1782,7 +1782,7 @@ dependencies = [ [[package]] name = "craft-heif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "heic-rs", "rayon", @@ -1791,7 +1791,7 @@ dependencies = [ [[package]] name = "craft-host" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "bitflags 2.13.2", "craft-i18n", @@ -1804,7 +1804,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "chrono", "fixed_decimal", @@ -1832,7 +1832,7 @@ dependencies = [ [[package]] name = "craft-idml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-xml", "craft-zip", @@ -1842,13 +1842,13 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-dds", "craft-heif", "craft-jpeg", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", "crc32fast", "exr", "flate2", @@ -1870,7 +1870,7 @@ dependencies = [ [[package]] name = "craft-imaging" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-color-ui", @@ -1888,12 +1888,12 @@ dependencies = [ [[package]] name = "craft-ipp" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "thiserror 2.0.21", ] @@ -1901,7 +1901,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-host", "craft-i18n", @@ -1916,7 +1916,7 @@ dependencies = [ [[package]] name = "craft-kra" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-xml", "craft-zip", @@ -1926,7 +1926,7 @@ dependencies = [ [[package]] name = "craft-layers" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-i18n", @@ -1940,7 +1940,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-host", @@ -1955,18 +1955,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "craft-metadata" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" -dependencies = [ - "brotli-decompressor 6.3.2", - "chrono", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", - "quick-xml 0.41.0", - "serde", -] - [[package]] name = "craft-metadata" version = "0.1.0" @@ -1979,10 +1967,22 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-metadata" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" +dependencies = [ + "brotli-decompressor 6.3.2", + "chrono", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", + "quick-xml 0.41.0", + "serde", +] + [[package]] name = "craft-ora" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-xml", "craft-zip", @@ -1992,7 +1992,7 @@ dependencies = [ [[package]] name = "craft-pages" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-keymap", @@ -2007,7 +2007,7 @@ dependencies = [ [[package]] name = "craft-pcraft-bundle" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "blake3", "craft-atomic", @@ -2020,7 +2020,7 @@ dependencies = [ [[package]] name = "craft-pcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "flate2", "serde", @@ -2031,7 +2031,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "bytemuck", "flate2", @@ -2046,7 +2046,7 @@ dependencies = [ [[package]] name = "craft-pdn" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2055,7 +2055,7 @@ dependencies = [ [[package]] name = "craft-platform" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "async-channel", "async-io", @@ -2085,7 +2085,7 @@ dependencies = [ [[package]] name = "craft-plist" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "thiserror 2.0.21", ] @@ -2093,7 +2093,7 @@ dependencies = [ [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-host", @@ -2116,7 +2116,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "encoding_rs", "flate2", @@ -2127,7 +2127,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "dispatch2", "egui", @@ -2138,12 +2138,12 @@ dependencies = [ [[package]] name = "craft-raw" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "chrono", "craft-crw", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", "jxl-oxide", "miniz_oxide 0.9.1", "rayon", @@ -2156,7 +2156,7 @@ dependencies = [ [[package]] name = "craft-review" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-host", @@ -2174,7 +2174,7 @@ dependencies = [ [[package]] name = "craft-settings" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-atomic", "craft-host", @@ -2191,7 +2191,7 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-image-codecs", "craft-xml", @@ -2212,7 +2212,7 @@ dependencies = [ [[package]] name = "craft-table" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-keymap", @@ -2224,7 +2224,7 @@ dependencies = [ [[package]] name = "craft-text" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-font-manager", @@ -2247,7 +2247,7 @@ dependencies = [ [[package]] name = "craft-theme" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "bitflags 2.13.2", "craft-tracked", @@ -2262,7 +2262,7 @@ dependencies = [ [[package]] name = "craft-theme-editor" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-theme", @@ -2273,7 +2273,7 @@ dependencies = [ [[package]] name = "craft-theme-store" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-atomic", "craft-behavior", @@ -2288,7 +2288,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=c42c34bfa127b095fb0a8d5ccaba0c168c254062#c42c34bfa127b095fb0a8d5ccaba0c168c254062" dependencies = [ "serde", "thiserror 2.0.21", @@ -2297,7 +2297,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=c42c34bfa127b095fb0a8d5ccaba0c168c254062#c42c34bfa127b095fb0a8d5ccaba0c168c254062" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "serde", "thiserror 2.0.21", @@ -2306,7 +2306,7 @@ dependencies = [ [[package]] name = "craft-time" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "serde", "thiserror 2.0.21", @@ -2315,7 +2315,7 @@ dependencies = [ [[package]] name = "craft-timeline" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-keymap", @@ -2330,7 +2330,7 @@ dependencies = [ [[package]] name = "craft-tracked" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "serde", ] @@ -2338,7 +2338,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-cloud-ui", "craft-ui-canvas", @@ -2352,7 +2352,7 @@ dependencies = [ [[package]] name = "craft-ui-canvas" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-i18n", @@ -2368,7 +2368,7 @@ dependencies = [ [[package]] name = "craft-ui-contract" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "accesskit", "craft-behavior", @@ -2408,7 +2408,7 @@ dependencies = [ [[package]] name = "craft-ui-macros" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2419,7 +2419,7 @@ dependencies = [ [[package]] name = "craft-ui-panels" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-host", @@ -2437,7 +2437,7 @@ dependencies = [ [[package]] name = "craft-ui-patterns" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-host", @@ -2458,7 +2458,7 @@ dependencies = [ [[package]] name = "craft-ui-shell" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-host", @@ -2477,7 +2477,7 @@ dependencies = [ [[package]] name = "craft-ui-widgets" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-behavior", "craft-host", @@ -2494,7 +2494,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "chrono", "craft-host", @@ -2523,7 +2523,7 @@ dependencies = [ [[package]] name = "craft-win32" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "winsafe", ] @@ -2531,7 +2531,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "craft-atomic", "craft-behavior", @@ -2561,7 +2561,7 @@ dependencies = [ [[package]] name = "craft-xcf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2570,7 +2570,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2580,7 +2580,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "flate2", "thiserror 2.0.21", @@ -2970,7 +2970,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", "emath", @@ -2980,7 +2980,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -3017,7 +3017,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "accesskit", "ahash", @@ -3038,7 +3038,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -3057,7 +3057,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "accesskit_winit", "arboard", @@ -3083,7 +3083,7 @@ dependencies = [ [[package]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "egui", @@ -3097,7 +3097,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", "egui", @@ -3110,7 +3110,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "dify", "eframe", @@ -3136,7 +3136,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", "serde", @@ -3229,7 +3229,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -3256,7 +3256,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[package]] name = "equivalent" @@ -4043,7 +4043,7 @@ dependencies = [ [[package]] name = "hayro" version = "0.7.1" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "bytemuck", "hayro-interpret", @@ -4073,7 +4073,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -4091,7 +4091,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -4115,7 +4115,7 @@ checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "flate2", "hayro-ccitt", @@ -5199,7 +5199,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "arrayvec", "kurbo 0.13.1", @@ -6415,7 +6415,7 @@ dependencies = [ "clap", "core-graphics2", "craft", - "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", "craft-image-codecs", "craft-svg", "craft-update", @@ -6465,7 +6465,7 @@ dependencies = [ "craft", "craft-develop", "craft-develop-model", - "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", + "craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", "criterion", "photocraft-color", "photocraft-geom", @@ -6517,7 +6517,7 @@ dependencies = [ "clap_complete", "clap_mangen", "craft", - "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", "craft-image-codecs", "craft-psd", "photocraft-automation", @@ -6540,7 +6540,7 @@ dependencies = [ name = "photocraft-color" version = "0.23.1" dependencies = [ - "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", "craft-tracked", "craft-ui-macros", "serde", @@ -6550,7 +6550,7 @@ dependencies = [ name = "photocraft-compose" version = "0.23.1" dependencies = [ - "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", "criterion", "photocraft-color", "photocraft-doc", @@ -6584,7 +6584,7 @@ dependencies = [ "chrono", "craft", "craft-affinity", - "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", "craft-develop-model", "craft-file-formats", "craft-image-codecs", @@ -6665,7 +6665,7 @@ name = "photocraft-gpu" version = "0.23.1" dependencies = [ "bytemuck", - "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", "half", "log", "photocraft-algo", @@ -6688,7 +6688,7 @@ dependencies = [ "blake3", "craft", "craft-affinity", - "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", "craft-crs", "craft-docpath", "craft-file-formats", @@ -6699,7 +6699,7 @@ dependencies = [ "craft-pdn", "craft-psd", "craft-svg", - "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", + "craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", "craft-xcf", "craft-xml", "crc32fast", @@ -6757,7 +6757,7 @@ name = "photocraft-paint" version = "0.23.1" dependencies = [ "base64 0.23.1", - "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540)", + "craft-cms 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53)", "craft-tracked", "craft-ui-macros", "photocraft-color", @@ -9603,7 +9603,7 @@ dependencies = [ [[package]] name = "vello_common" version = "0.0.8" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "bytemuck", "fearless_simd", @@ -9651,7 +9651,7 @@ dependencies = [ [[package]] name = "vello_cpu" version = "0.0.8" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" dependencies = [ "bytemuck", "glifo 0.1.1", @@ -11272,29 +11272,29 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f#8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[patch.unused]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" [[patch.unused]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" [[patch.unused]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=77c7c62345c1f4213f59a07d9fdc156ecde0b540#77c7c62345c1f4213f59a07d9fdc156ecde0b540" +source = "git+https://github.com/storytold/craft-libs?rev=e953d47a378776dea207899b10baf969fc8cbe53#e953d47a378776dea207899b10baf969fc8cbe53" diff --git a/Cargo.toml b/Cargo.toml index 0eecf9c47d..5c0066c3a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,21 +12,21 @@ rust-version = "1.95" [workspace.dependencies] # The craft framework through its facade (`craft::ui::…`). The egui `[patch]` below must match # `craft::egui_fork::REV` (checked by `cargo xtask ci`). -craft = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540", default-features = false } -craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53", default-features = false } +craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } # internal photocraft-geom = { path = "crates/geom" } photocraft-color = { path = "crates/color" } photocraft-raster = { path = "crates/raster" } photocraft-doc = { path = "crates/doc" } photocraft-ops = { path = "crates/ops" } -craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } +craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] } photocraft-raw = { path = "crates/raw" } -craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } photocraft-compose = { path = "crates/compose" } photocraft-gpu = { path = "crates/gpu" } photocraft-paint = { path = "crates/paint" } @@ -45,36 +45,36 @@ photocraft-ipp = { path = "crates/ipp" } # external # ICC colour management: the shared crate (replaces crates/cms; craft-libs#779). -craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +craft-print = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } # HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784). -craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540", features = ["raster", "write-raster"] } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53", features = ["raster", "write-raster"] } +craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } # Keep the shared embedded-image validation API until the framework revision includes it. -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540", features = ["tree-render", "tree-render-system-fonts"] } -craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53", features = ["tree-render", "tree-render-system-fonts"] } +craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } # Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563. -craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "c42c34bfa127b095fb0a8d5ccaba0c168c254062" } craft-develop-model = { git = "https://github.com/storytold/craft-libs", rev = "c42c34bfa127b095fb0a8d5ccaba0c168c254062" } # 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. -craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } # 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 = "77c7c62345c1f4213f59a07d9fdc156ecde0b540", features = ["ui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e953d47a378776dea207899b10baf969fc8cbe53", features = ["ui"] } thiserror = "2" serde = { version = "1", features = ["derive", "rc"] } serde_json = "1" @@ -339,30 +339,30 @@ opt-level = 3 # Keep the complete egui family and native event bridge on reviewed fork commits. [patch.crates-io] -krilla = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -hayro = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -vello_common = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -emath = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "8a3c5ecb29ab8679d57035f2cb51d7ec8a5c080f" } +krilla = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +vello_common = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } diff --git a/README.md b/README.md index 04508f9637..47d9e13f7d 100644 --- a/README.md +++ b/README.md @@ -185,8 +185,8 @@ Every screenshot here is the real app at work on public-domain art, rendered off
-

🧰 69 tools

- Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Color Sampler · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Art History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Convert Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Star · Line · Custom Shape · Hand · Rotate View · Zoom +

🧰 70 tools

+ Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Color Sampler · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Art History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Adjustment Brush · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Convert Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Star · Line · Custom Shape · Hand · Rotate View · Zoom

🖌️ A real brush engine

@@ -353,7 +353,6 @@ sha256-verified. Fetch them with `cargo xtask corpus --all` and run the tests wi |---|---|---| | x64 (64-bit Intel/AMD) | `photocraft--windows-x64.msi` | `photocraft--windows-x64-portable.zip` | | arm64 (Snapdragon and other ARM PCs) | `photocraft--windows-arm64.msi` | `photocraft--windows-arm64-portable.zip` | -| x86 (32-bit) | `photocraft--windows-x86.msi` | `photocraft--windows-x86-portable.zip` | Installers and executables are code-signed. diff --git a/SECURITY.md b/SECURITY.md index 5080c9cdc4..79a72b5e69 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -6,7 +6,7 @@ PhotoCraft processes complex document and image formats and exposes CLI, JSON co Please give the repository maintainers a reasonable opportunity to investigate and coordinate a fix before publishing exploitable details, proof-of-concept code, or weaponized files. -This repository does not currently document a dedicated private security email or private reporting channel. Contact the repository maintainers through the repository owner/maintainer channels already listed in the project, provide only a minimal non-exploitable summary in public, and ask for an appropriate private transfer method before sharing sensitive details. Do not open a public issue containing a working exploit, secret, sensitive crash dump, or malicious attachment. +Report vulnerabilities through [GitHub private vulnerability reporting](https://github.com/storytold/photocraft/security/advisories/new). If you cannot access that channel, contact the repository maintainers through the repository owner/maintainer channels already listed in the project, provide only a minimal non-exploitable summary in public, and ask for an appropriate private transfer method before sharing sensitive details. Do not open a public issue containing a working exploit, secret, sensitive crash dump, or malicious attachment. If no private channel can be established, withhold weaponized material and report the smallest safe description that allows maintainers to make contact. diff --git a/apps/photocraft-cli/src/actions.rs b/apps/photocraft-cli/src/actions.rs index f8b900e49a..faad175a17 100644 --- a/apps/photocraft-cli/src/actions.rs +++ b/apps/photocraft-cli/src/actions.rs @@ -90,7 +90,8 @@ pub fn load_actions_file(path: &Path, name: Option<&str>) -> Result<(Steps, Vec< let is_atn = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("atn")) || matches!(bytes.get(..4), Some([0, 0, 0, 12 | 16])); if !is_atn { let text = String::from_utf8(bytes).map_err(|source| ActionsError::Utf8 { path: path.to_path_buf(), source })?; - let (steps, set) = load_actions(&text, name)?; + let text = text.strip_prefix('\u{feff}').unwrap_or(&text); + let (steps, set) = load_actions(text, name)?; return Ok((steps, set, Vec::new())); } let imp = photocraft_engine::atn_cmds::import(&bytes).map_err(|message| ActionsError::Atn { path: path.to_path_buf(), message })?; @@ -114,3 +115,23 @@ pub fn load_actions_file(path: &Path, name: Option<&str>) -> Result<(Steps, Vec< let play = vec![("actions.play".to_string(), json!({"action": action.name}))]; Ok((play, imp.actions, warnings)) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn load_actions_file_accepts_utf8_bom() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("actions.json"); + + std::fs::write(&path, b"\xEF\xBB\xBF[\"image.adjustments.invert\"]").unwrap(); + let (steps, set, warnings) = load_actions_file(&path, None).unwrap(); + assert_eq!(steps, vec![("image.adjustments.invert".to_owned(), json!({}))]); + assert!(set.is_empty()); + assert!(warnings.is_empty()); + + std::fs::write(&path, b"\xEF\xBB\xBF[").unwrap(); + assert!(matches!(load_actions_file(&path, None), Err(ActionsError::Json(_)))); + } +} diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 429fcb4547..88344574ab 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -308,6 +308,7 @@ pub(crate) struct McpArgs { /// Each request is a JSON line {"id", "method", "params"}. Methods: engine.execute, /// jobs.list/cancel, engine.commands, /// doc.open/new/place/save/exportLayers/exportDataSets/importDataSets/inspect/render/select/close, +/// doc.replaceSmartObject, /// session.list, batch, methods (docs/control-protocol.md#headless-server). The token flags require /// --port (or PHOTOCRAFT_CONTROL_PORT); stdio needs no control token. #[derive(Args)] diff --git a/apps/photocraft-cli/src/batch.rs b/apps/photocraft-cli/src/batch.rs index d64f3318d1..1e7ba9ef6d 100644 --- a/apps/photocraft-cli/src/batch.rs +++ b/apps/photocraft-cli/src/batch.rs @@ -21,10 +21,12 @@ fn same_dir(a: &Path, b: &Path) -> bool { pub(crate) fn is_input(p: &Path) -> bool { let known = |e: &str| { - matches!(e, "pcraft" | "psd" | "psb" | "pdn" | "ora" | "kra" | "krz" | "af" | "afdesign" | "afphoto" | "afpub") + matches!(e, "pcraft" | "psd" | "psb" | "pdn" | "ora" | "kra" | "krz" | "af" | "afdesign" | "afphoto" | "afpub" | "xcf" | "xcfgz") || photocraft_codecs::from_extension(e).is_some_and(|f| photocraft_codecs::caps(f).read) }; - p.is_file() && p.extension().is_some_and(|e| known(&e.to_string_lossy().to_ascii_lowercase())) + // Only GIMP's compound suffix is an image; an arbitrary .gz is not a batch input. + let gzipped_xcf = p.file_name().is_some_and(|name| name.to_string_lossy().to_ascii_lowercase().ends_with(".xcf.gz")); + p.is_file() && (gzipped_xcf || p.extension().is_some_and(|e| known(&e.to_string_lossy().to_ascii_lowercase()))) } /// Drops the Save and view steps the desktop records from `action` (Batch saves each result @@ -70,7 +72,8 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> for entry in entries { let path = entry.map_err(|source| CliError::ReadDir { path: in_dir.to_path_buf(), source })?.path(); if is_input(&path) { - images.push(photocraft_engine::file_cmds::BatchInput { path: path.to_string_lossy().into_owned(), rel_dir: String::new() }); + let input = path.to_str().ok_or_else(|| CliError::BatchOption(format!("batch input path must be valid UTF-8: {path:?}")))?; + images.push(photocraft_engine::file_cmds::BatchInput { path: input.to_owned(), rel_dir: String::new() }); } } // The tree listing already holds the engine's order (each folder's files, then its @@ -104,6 +107,9 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> photocraft_engine::file_cmds::validate_flat_outputs(&plan).map_err(|error| CliError::Naming(error.to_string()))?; if let Some(log) = &a.error_log { let same = |path: &Path| photocraft_engine::file_cmds::same_destination(log, path); + if same(&a.actions) { + return Err(CliError::BatchOption("--error-log must not replace the --actions file".into())); + } if inputs.iter().any(|input| same(Path::new(&input.path))) || targets.iter().any(|target| same(target)) { return Err(CliError::BatchOption("--error-log must not replace an input or batch output".into())); } @@ -295,6 +301,59 @@ mod tests { use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; + #[test] + fn batch_inputs_recognize_gimp_xcf_names_but_not_arbitrary_gzip() { + let dir = tempfile::tempdir().unwrap(); + for name in ["plain.xcf", "upper.XCF", "alias.xcfgz", "upper-alias.XCFGZ", "compressed.xcf.gz", "upper-compressed.XCF.GZ", "ordinary.PNG"] { + let path = dir.path().join(name); + std::fs::write(&path, b"").unwrap(); + assert!(is_input(&path), "{name} should be selected"); + } + for name in ["notes.txt.gz", "archive.tar.gz", "backup.xcf.gz.tmp", "notes.txt"] { + let path = dir.path().join(name); + std::fs::write(&path, b"").unwrap(); + assert!(!is_input(&path), "{name} should be skipped"); + } + let directory = dir.path().join("folder.xcf.gz"); + std::fs::create_dir(&directory).unwrap(); + assert!(!is_input(&directory), "a directory is not an input image"); + assert!(!is_input(&dir.path().join("missing.xcf.gz")), "a missing file is not an input image"); + #[cfg(unix)] + { + use std::os::unix::ffi::OsStringExt; + let path = dir.path().join(std::ffi::OsString::from_vec(b"non-utf8-\xff.XCF.GZ".to_vec())); + std::fs::write(&path, b"").unwrap(); + assert!(is_input(&path), "a non-UTF8 filename can still have the compound suffix"); + } + } + + #[cfg(target_os = "linux")] + #[test] + fn flat_batch_rejects_non_utf8_input_before_writing_output() { + use std::os::unix::ffi::OsStringExt; + + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("in"); + std::fs::create_dir(&input).unwrap(); + let original = input.join(std::ffi::OsString::from_vec(b"photo-\xff.xcf".to_vec())); + let alias = input.join("photo-\u{fffd}.xcf"); + std::fs::write(&original, b"original file").unwrap(); + std::fs::write(&alias, b"replacement-character file").unwrap(); + let actions = dir.path().join("actions.json"); + std::fs::write(&actions, "[]").unwrap(); + let output = dir.path().join("out"); + let crate::test_support::Invoke { code, stdout, stderr } = + crate::test_support::invoke(&["batch", "--actions", actions.to_str().unwrap(), "--in", input.to_str().unwrap(), "--out", output.to_str().unwrap()]); + + assert_eq!(code, 1, "{stdout}{stderr}"); + assert!(stderr.contains("batch input path must be valid UTF-8"), "{stderr}"); + assert!(stderr.contains(&format!("{original:?}")), "the diagnostic must distinguish the invalid bytes from the valid alias: {stderr}"); + assert!(stdout.is_empty(), "discovery must fail before processing any input: {stdout}"); + assert!(!output.exists(), "discovery must fail before creating the output directory"); + assert_eq!(std::fs::read(&original).unwrap(), b"original file"); + assert_eq!(std::fs::read(&alias).unwrap(), b"replacement-character file"); + } + struct RecordingRenderer { calls: Arc, } diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index c572c460fa..be29d2b862 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -715,6 +715,22 @@ fn batch_with(d: &Path, input: &Path, name: &str, actions: &str, extra: &[&str]) bin().args(["batch", "--actions"]).arg(&file).arg("--in").arg(input).arg("--out").arg(d.join(name)).args(extra).output().unwrap() } +#[test] +fn batch_error_log_cannot_replace_its_actions_file() { + let d = tmp("batch-log-actions-collision"); + let input = d.join("in"); + std::fs::create_dir_all(&input).unwrap(); + let actions = r#"[{"command":"image.adjustments.invert"}]"#; + let log = input.join("../actions.json"); + + let result = batch_with(&d, &input, "actions", actions, &["--error-log", &log.to_string_lossy()]); + let error = String::from_utf8_lossy(&result.stderr); + assert!(!result.status.success(), "{error}"); + assert!(error.contains("--error-log") && error.contains("--actions"), "{error}"); + assert_eq!(std::fs::read(d.join("actions.json")).unwrap(), actions.as_bytes()); + assert!(!d.join("actions").exists(), "the output folder must not be created"); +} + /// #489: `batch --actions` takes `[id, params]` steps and a droplet's steps, with the same results /// as the object form; a malformed step fails before anything is written. #[test] diff --git a/apps/photocraft-web-boot/index.html b/apps/photocraft-web-boot/index.html index 7d15b18daa..ff3e548534 100644 --- a/apps/photocraft-web-boot/index.html +++ b/apps/photocraft-web-boot/index.html @@ -26,10 +26,16 @@ #photocraft_stopped a { color: #ffffff; } #photocraft_stopped_detail { color: #b8b8b8; } +
+

Loading PhotoCraft…

This is taking longer than usual. If PhotoCraft doesn't start, its files may have failed to download or come from a different version of this page. Reload to try again; the browser diff --git a/apps/photocraft-web/index.html b/apps/photocraft-web/index.html index 30ea522b66..a608d4b665 100644 --- a/apps/photocraft-web/index.html +++ b/apps/photocraft-web/index.html @@ -26,10 +26,16 @@ #photocraft_stopped a { color: #ffffff; } #photocraft_stopped_detail { color: #b8b8b8; } +

+

Loading PhotoCraft…

This is taking longer than usual. If PhotoCraft doesn't start, its files may have failed to download or come from a different version of this page. Reload to try again; the browser diff --git a/apps/photocraft-web/src/diagnostics.rs b/apps/photocraft-web/src/diagnostics.rs index 134e0e4035..cd9c4da765 100644 --- a/apps/photocraft-web/src/diagnostics.rs +++ b/apps/photocraft-web/src/diagnostics.rs @@ -39,9 +39,26 @@ pub fn take_panic() -> Option { pub fn is_trap(name: &str, message: &str) -> bool { let message = message.to_ascii_lowercase(); name == "RuntimeError" - || ["unreachable", "memory access out of bounds", "maximum call stack", "could not allocate memory", "out of memory"] - .iter() - .any(|m| message.contains(m)) + // A failed request can call its host "unreachable" without stopping the module. + || matches!( + message.trim(), + "unreachable" + | "error: unreachable" + | "runtimeerror: unreachable" + | "uncaught error: unreachable" + | "uncaught runtimeerror: unreachable" + | "uncaught (in promise) runtimeerror: unreachable" + ) + || [ + "unreachable executed", + "unreachable code should not be executed", + "memory access out of bounds", + "maximum call stack", + "could not allocate memory", + "out of memory", + ] + .iter() + .any(|m| message.contains(m)) } /// Trap messages (lowercase, matched ignoring case) that mean an allocation failed: @@ -109,13 +126,38 @@ mod tests { fn only_traps_count() { assert!(is_trap("RuntimeError", "unreachable")); assert!(is_trap("RuntimeError", "")); + assert!(is_trap("RuntimeError", "divide by zero")); + for message in [ + "unreachable", + "Error: unreachable", + "RuntimeError: unreachable", + "Uncaught Error: unreachable", + "Uncaught RuntimeError: unreachable", + "Uncaught (in promise) RuntimeError: unreachable", + "RuntimeError: unreachable executed", + ] { + assert!(is_trap("", message), "{message}"); + } assert!(is_trap("RangeError", "Maximum call stack size exceeded")); assert!(is_trap("RangeError", "WebAssembly.Memory(): could not allocate memory")); // Matched ignoring case: Safari's wording, reported without the RuntimeError name. assert!(is_trap("Error", "Unreachable code should not be executed")); + assert!(is_trap("Error", "Unreachable code should not be executed (evaluating 'module.run()')")); assert!(is_trap("Error", "Out of memory")); assert!(!is_trap("TypeError", "Failed to fetch")); assert!(!is_trap("Error", "ResizeObserver loop completed")); + for (name, message) in [ + ("Error", "server unreachable"), + ("TypeError", "Failed to fetch: host unreachable"), + ("", "Error: endpoint unreachable"), + ("Error", "unreachable resource"), + ("Error", "Uncaught Error: server unreachable"), + ("Error", "network unreachable"), + ("", "server: unreachable"), + ("", "NetworkError: unreachable"), + ] { + assert!(!is_trap(name, message), "unrelated error classified as a trap: {name}: {message}"); + } } #[test] diff --git a/apps/photocraft/src/linux_libs.rs b/apps/photocraft/src/linux_libs.rs index 41e79d1b6f..3e87a711a6 100644 --- a/apps/photocraft/src/linux_libs.rs +++ b/apps/photocraft/src/linux_libs.rs @@ -227,7 +227,14 @@ pub fn missing_message(session: DisplaySession, missing: &[AnyOf], distro: Distr /// Library directories to search: `LD_LIBRARY_PATH`, then the usual system and Flatpak paths. fn search_dirs(ld_library_path: Option<&str>) -> Vec { - let mut dirs: Vec = ld_library_path.unwrap_or("").split(':').filter(|d| !d.is_empty()).map(PathBuf::from).collect(); + // ld.so accepts either separator; an empty entry in a nonempty list means the current directory. + // An unset or entirely empty variable adds no directories. + let mut dirs: Vec = ld_library_path + .filter(|value| !value.is_empty()) + .into_iter() + .flat_map(|value| value.split([':', ';'])) + .map(|dir| PathBuf::from(if dir.is_empty() { "." } else { dir })) + .collect(); let triplet = if cfg!(target_arch = "aarch64") { "aarch64-linux-gnu" } else if cfg!(target_arch = "riscv64") { @@ -398,7 +405,8 @@ mod tests { fn library_dirs_count_and_unread_cache_is_inconclusive() { let dirs = search_dirs(Some("/opt/x/lib::/nix/store/abc/lib")); assert_eq!(dirs[0], PathBuf::from("/opt/x/lib")); - assert_eq!(dirs[1], PathBuf::from("/nix/store/abc/lib")); + assert_eq!(dirs[1], PathBuf::from(".")); + assert_eq!(dirs[2], PathBuf::from("/nix/store/abc/lib")); // Found by file in a directory (no ldconfig, as on NixOS). let probe = Probe { ldconfig: None, dirs: vec![PathBuf::from("/nix/lib")] }; let present = ["/nix/lib/libwayland-client.so.0", "/nix/lib/libxkbcommon.so.0", "/nix/lib/libEGL.so.1"]; @@ -412,6 +420,44 @@ mod tests { assert!(msg.contains("dnf install libwayland-client libxkbcommon vulkan-loader"), "{msg}"); } + #[test] + fn library_path_separators_and_empty_entries_follow_the_loader() { + let defaults = search_dirs(None); + assert_eq!(search_dirs(Some("")), defaults, "an entirely empty variable adds no directories"); + for (value, entries) in [ + ("/opt/a:/opt/b", &["/opt/a", "/opt/b"][..]), + ("/opt/a;/opt/b", &["/opt/a", "/opt/b"][..]), + ("/opt/a;/opt/b:/opt/c", &["/opt/a", "/opt/b", "/opt/c"][..]), + (":/opt/b", &[".", "/opt/b"][..]), + ("/opt/a:", &["/opt/a", "."][..]), + ("/opt/a::/opt/b", &["/opt/a", ".", "/opt/b"][..]), + ("/opt/a;;/opt/b", &["/opt/a", ".", "/opt/b"][..]), + (":", &[".", "."][..]), + (";", &[".", "."][..]), + (" /opt/a ;relative/lib", &[" /opt/a ", "relative/lib"][..]), + (" ", &[" "][..]), + ] { + let mut expected: Vec = entries.iter().map(PathBuf::from).collect(); + expected.extend(defaults.iter().cloned()); + assert_eq!(search_dirs(Some(value)), expected, "LD_LIBRARY_PATH={value:?}"); + } + } + + #[test] + fn loader_search_paths_prevent_false_startup_errors() { + let soname = "libxkbcommon-x11.so.0"; + let names: Vec<&str> = ALL_X11.iter().copied().filter(|name| *name != soname).collect(); + let probe = Probe { ldconfig: Some(cache_for_this_arch(&names)), dirs: search_dirs(None) }; + let missing = check(DisplaySession::X11, &probe, |_| false); + assert!(decide(DisplaySession::X11, missing, || Distro::Debian).is_err(), "a genuinely missing library still blocks startup"); + for (value, directory) in [("/opt/a;/opt/b", "/opt/b"), (":/opt/a", "."), ("/opt/a:", ".")] { + let probe = Probe { ldconfig: Some(cache_for_this_arch(&names)), dirs: search_dirs(Some(value)) }; + let present = Path::new(directory).join(soname); + let verdict = check(DisplaySession::X11, &probe, |path| path == present); + assert_eq!(decide(DisplaySession::X11, verdict, || Distro::Debian), Ok(()), "LD_LIBRARY_PATH={value:?}, library at {}", present.display()); + } + } + #[test] fn unreadable_cache_never_warns_or_fails() { // Issue #1144: Alpine (musl) has no `ldconfig -p`, so a library that exists was reported missing. diff --git a/apps/photocraft/src/logging.rs b/apps/photocraft/src/logging.rs index e525197a27..868a6bbe0b 100644 --- a/apps/photocraft/src/logging.rs +++ b/apps/photocraft/src/logging.rs @@ -219,7 +219,7 @@ fn prune_instance_logs(dir: &Path) { // A missing lock file means nobody holds it; an unknown lock state counts as running. let running = match OpenOptions::new().read(true).write(true).open(instance_lock(dir, pid)) { Ok(lock) => !try_hold(&lock).unwrap_or(false), - Err(_) => false, + Err(e) => e.kind() != std::io::ErrorKind::NotFound, }; if !running { let modified = entry.metadata().and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH); @@ -542,6 +542,15 @@ mod tests { let held = File::create(instance_lock(&dir, 5)).expect("lock file"); held.try_lock().expect("hold"); + // An older log whose lock cannot be opened has an unknown owner, so keep it too. + let unknown = instance_log(&dir, 6); + std::fs::write(&unknown, "unknown owner").expect("write"); + File::options().write(true).open(&unknown).expect("open").set_modified(now - Duration::from_secs(1000)).expect("mtime"); + let unknown_lock = instance_lock(&dir, 6); + std::fs::create_dir(&unknown_lock).expect("unusable lock path"); + let error = OpenOptions::new().read(true).write(true).open(&unknown_lock).expect_err("a directory is not a lock file"); + assert_ne!(error.kind(), std::io::ErrorKind::NotFound); + let second = rotate(&dir).expect("second start"); assert_eq!(second.path, instance_log(&dir, std::process::id())); // The newest KEEP finished ones stay, the rest go with their lock files. @@ -549,6 +558,8 @@ mod tests { assert!(!instance_log(&dir, 2).exists() && !instance_log(&dir, 1).exists()); assert!(!instance_lock(&dir, 2).exists()); assert_eq!(read(&live), "live"); + assert_eq!(read(&unknown), "unknown owner"); + assert!(unknown_lock.is_dir()); drop((first, second, held)); let _ = std::fs::remove_dir_all(&dir); } diff --git a/book/src/architecture/automation.md b/book/src/architecture/automation.md index 01ceec6abc..678ed7f0d1 100644 --- a/book/src/architecture/automation.md +++ b/book/src/architecture/automation.md @@ -18,8 +18,9 @@ The control and headless TCP listeners are restricted to loopback addresses. Std Loopback is not authentication. TCP transports require a bearer token and enforce request-byte, batch-step, and active-connection limits. Remote file methods use an `AuthorizedWorkspace` with -independent read and write directory capabilities; paths are relative to a configured root and -fail closed when the applicable root is absent. General per-method scopes, client identity, +independent read and write directory capabilities; paths may be relative or absolute beneath an +applicable granted root. File methods fail closed when the applicable read or write authority is +absent. General per-method scopes, client identity, encryption, and operation budgets are not implemented. See the [Automation security model](../automation/security-model.md) and [Automation security](../security/automation-security.md) before exposing or extending these diff --git a/book/src/automation/cli.md b/book/src/automation/cli.md index c7278455ef..97540c0ecd 100644 --- a/book/src/automation/cli.md +++ b/book/src/automation/cli.md @@ -84,7 +84,7 @@ layers because that would lose their group's blending semantics. Paths supplied to the current CLI are ordinary operating-system paths. The CLI does not restrict them to a workspace root. Batch output creates the requested output directory, and save operations may create parent directories. `batch` refuses an output directory that is its input directory (the results would replace the originals) unless `--in-place` is given. Run untrusted action files only in an appropriately isolated account or environment. -CLI parsing checks the flags and their values before any work starts. A flag the subcommand doesn't take (a typo such as `--fromat`), a flag given twice (only `--cmd` and `--params` may repeat), a value out of range (`--quality 0`), malformed `--new` or `--params` JSON, `` together with `--new`, and `--control-token` together with `--control-token-file` are all usage errors (exit status 2), rather than being ignored or failing later. A value flag never takes the next flag as its value, so a value starting with `-` is written with `=` (`--out=-image.png`) or as `./-image.png`; negative numbers such as `--filter -1` still work. A path that is not valid Unicode reaches the command instead of being a usage error: `convert` reads and writes it, while `info`, `run` and `batch` open files through the automation layer, which still needs UTF-8 paths and fails with exit status 1 (`droplet` takes its arguments as text, so it refuses such a path as a usage error). `photocraft-cli --version` (or `-V`) prints the version; there is no `version` subcommand. +CLI parsing checks the flags and their values before any work starts. A flag the subcommand doesn't take (a typo such as `--fromat`), a flag given twice (`--cmd`, `--params` and `--automation-read-root` may repeat), a value out of range (`--quality 0`), malformed `--new` or `--params` JSON, `` together with `--new`, and `--control-token` together with `--control-token-file` are all usage errors (exit status 2), rather than being ignored or failing later. A value flag never takes the next flag as its value, so a value starting with `-` is written with `=` (`--out=-image.png`) or as `./-image.png`; negative numbers such as `--filter -1` still work. A path that is not valid Unicode reaches the command instead of being a usage error: `convert` reads and writes it, while `info`, `run` and `batch` open files through the automation layer, which still needs UTF-8 paths and fails with exit status 1 (`droplet` takes its arguments as text, so it refuses such a path as a usage error). `photocraft-cli --version` (or `-V`) prints the version; there is no `version` subcommand. `mcp` and `serve` reject positional arguments, empty values and options for the wrong mode before starting a server. Explicit control-token flags require `mcp --bridge` or `serve --port` (or diff --git a/book/src/automation/control-protocol.md b/book/src/automation/control-protocol.md index e7cf6ed2b9..f9331d572d 100644 --- a/book/src/automation/control-protocol.md +++ b/book/src/automation/control-protocol.md @@ -24,16 +24,21 @@ socket I/O and handler waits use timeouts; MCP and headless batches are limited JSON-lines replies and encoded MCP tool results are capped at 8 MiB, with aggregate batch reply budgets. Headless previews have source-pixel, requested-edge, and encoded-PNG ceilings. The bridge bounds incoming reply frames and screenshot decoding. -Automation file methods require separately configured read and write roots. Request paths are -relative, and absolute, traversal, alternate-separator, device-name, and link-escape paths are -rejected before file effects. +Automation file methods require separately configured read and write roots. Request paths may be +relative or absolute beneath the canonical or configured spelling of the applicable granted root. +Absolute paths outside that root are rejected. Accepted absolute paths are translated to relative +paths and resolved through the held directory capability. Relative requests reject empty or `.` +components and alternate separators. Absolute requests are split into native path components +before checking the root-relative remainder, so repeated separators and interior `.` components +are normalized. Both forms reject parent traversal in the remainder, disallowed component names +and link escapes before file effects. **Known limitations:** the token is a bearer credential and grants the complete non-filesystem control surface. There is no encryption, client identity, general per-method capability check, explicit JSON-depth policy, aggregate session-memory accounting, or command-duration/cancellation budget. Desktop capture/encoding and import/export still need their own operation budgets. -The listener creates one thread per authenticated -active connection, within the connection cap. Trusted one-shot CLI operations and interactive +The listener creates one thread per accepted active connection, including clients that are still +authenticating, within the connection cap. Trusted one-shot CLI operations and interactive desktop file pickers retain the launching user's normal filesystem authority. Use a private token file, enable `--control` only for a trusted local automation session, and never proxy the unencrypted protocol beyond loopback. See [Automation security](../security/automation-security.md) for the remaining gateway work. diff --git a/book/src/automation/mcp.md b/book/src/automation/mcp.md index 36d5e6be5e..57a76c5c5d 100644 --- a/book/src/automation/mcp.md +++ b/book/src/automation/mcp.md @@ -29,8 +29,8 @@ client's launch directory. In bridge mode the roots are configured on the deskto flags on `photocraft-cli mcp --bridge` are rejected. Explicit `--control-token` and `--control-token-file` flags require `--bridge` (or `PHOTOCRAFT_CONTROL_PORT`) and are mutually exclusive; bridge credentials can also come from `PHOTOCRAFT_CONTROL_TOKEN` or -`PHOTOCRAFT_CONTROL_TOKEN_FILE`. Each launch option -except `--help`/`-h` takes one non-empty value and cannot be repeated. Stray positional arguments, +`PHOTOCRAFT_CONTROL_TOKEN_FILE`. `--headless`, `--gpu`, `--no-gpu` and `--help`/`-h` take no value. Other launch options +take one non-empty value; only `--automation-read-root` may repeat, adding ordered read directories. Stray positional arguments, missing values and options for the wrong mode are usage errors (exit 2) reported on stderr before the server starts. diff --git a/book/src/formats/pcraft.md b/book/src/formats/pcraft.md index 8a0e40a5a2..0d01dbbad1 100644 --- a/book/src/formats/pcraft.md +++ b/book/src/formats/pcraft.md @@ -24,11 +24,15 @@ The manifest is versioned and describes the document tree. Tiles and blobs are c Default `LoadOptions` apply these maximums: -| Limit | Default | -|---|---:| -| `manifest.json` | 256 MiB | -| One decompressed blob | 1 GiB | -| Total decompressed tiles and blobs | 16 GiB | +| Limit | Desktop | Browser | +|---|---:|---:| +| `manifest.json` | 256 MiB | 256 MiB | +| One decompressed blob | 1 GiB | 512 MiB | +| Total decompressed tiles and blobs | Up to 16 GiB | 1 GiB | + +On desktop, the total-byte budget is lowered to the available RAM plus remaining scratch-disk +capacity, with a 1 GiB floor and a 16 GiB cap. If neither figure is available, the 16 GiB cap +applies. These are decoded tile and blob bytes, not a limit on the process's total memory. Layer groups may nest at most 100 levels (`MAX_GROUP_DEPTH`). Saving a deeper document fails with an error instead of writing a bundle that can't be opened, and a manifest whose JSON nesting goes beyond what that depth needs is rejected before it is parsed, so a hostile file can't exhaust the stack. diff --git a/book/src/security/automation-security.md b/book/src/security/automation-security.md index 9ba26e561a..e58bbc937f 100644 --- a/book/src/security/automation-security.md +++ b/book/src/security/automation-security.md @@ -43,9 +43,13 @@ Automation is a privilege boundary because requests can cause filesystem access, - A save without a `path` (MCP `doc_save`, `serve` `doc.save`, the control channel's `app.save`) writes back only to the document's own PSD, PSB or `.pcraft` file in its own format; any other save needs an explicit `path`, so automation never flattens or converts over the file it opened. -- Automation paths must be relative beneath the applicable root. Absolute paths, parent - traversal, alternate separators, Windows device names, malformed components, and link escapes - are rejected before file effects. +- Automation paths may be relative or absolute beneath the canonical or configured spelling of + the applicable granted root. Absolute paths outside that root are rejected. Accepted absolute + paths are translated to relative paths and resolved through the held directory capability. + Relative requests reject empty or `.` components and alternate separators. Absolute requests + are split into native path components before checking the root-relative remainder, so repeated + separators and interior `.` components are normalized. Both forms reject parent traversal in + the remainder, disallowed component names and link escapes before file effects. - Engine commands that still use ambient paths fail closed at the automation boundary. Synthetic UI input reaches the same command policy, and automation-triggered file hooks do not run user-configured script-event paths. The policy also covers every command a command runs on its diff --git a/book/src/security/secure-file-handling.md b/book/src/security/secure-file-handling.md index 36d81497c6..40b6181577 100644 --- a/book/src/security/secure-file-handling.md +++ b/book/src/security/secure-file-handling.md @@ -1,7 +1,7 @@ # Secure file handling PhotoCraft reads and writes documents in the desktop app, CLI, headless RPC server, and MCP server. -Remote automation paths are untrusted relative names resolved beneath explicitly granted roots. +Remote automation paths are untrusted names resolved beneath explicitly granted roots. ## Implemented @@ -11,11 +11,15 @@ Remote automation paths are untrusted relative names resolved beneath explicitly - Native `.pcraft` saves use temporary-file/rename patterns in relevant store paths. - `AuthorizedWorkspace` holds independent read and write directory capabilities for remote automation. -- Absolute paths, parent traversal, alternate separators, drive/device/stream prefixes, reserved - Windows device names, empty or dot components, and link escapes are rejected before file - effects. -- Non-existent output files are supported when their parent already exists beneath the write - root. Automation does not create caller-selected directory trees. +- Absolute paths beneath the canonical or configured spelling of the applicable granted root + are translated to relative paths and resolved through the held directory capability. Absolute + paths outside that root are rejected. +- Relative requests reject empty or `.` components and alternate separators. Absolute requests + are split into native path components before checking the root-relative remainder, so repeated + separators and interior `.` components are normalized. Both forms reject parent traversal in + the remainder, disallowed component names and link escapes before file effects. +- Ordinary single-file writes support non-existent output files when their parent already exists + beneath the write root; they do not create caller-selected directory trees. - Filesystem-bearing engine commands that have not migrated to capability I/O fail closed for automation. Trusted local CLI subcommands and user-driven desktop file pickers keep their intended ambient authority. @@ -40,9 +44,15 @@ AuthorizedWorkspace ``` The handle is created from an explicit launch-time grant, preserves separate read/write -permissions, rejects absolute and escaping paths, and performs operations relative to the held -directory capability. New files require an existing in-root parent because a non-existent target -cannot be canonicalized safely. +permissions, checks absolute paths against the granted root and rejects escaping paths. File +contents are read and written through the held directory capability. On Windows UNC write roots, +directory creation and atomic-save renames use guarded ambient paths beneath the canonical root, +with each ancestor verified through its parent handle and held open. See +[Windows UNC write roots](../automation/security-model.md#windows-unc-write-roots) for the +provider and WSL limitations. +Ordinary single-file writes require an existing in-root parent. Capability-scoped multi-file +exports create their required export directory and missing ancestors beneath the write root +before writing files. ## Design requirements diff --git a/book/src/security/vulnerability-reporting.md b/book/src/security/vulnerability-reporting.md index dd81cd6e88..697021d310 100644 --- a/book/src/security/vulnerability-reporting.md +++ b/book/src/security/vulnerability-reporting.md @@ -2,7 +2,7 @@ The repository-level [`SECURITY.md`](https://github.com/storytold/photocraft/blob/main/SECURITY.md) is the authoritative reporting policy. -Do not publish exploit details, weaponized files, secrets, or sensitive crash data before maintainers have had a reasonable opportunity to review and coordinate a fix. The repository currently documents no dedicated private security email or private reporting address. +Do not publish exploit details, weaponized files, secrets, or sensitive crash data before maintainers have had a reasonable opportunity to review and coordinate a fix. Use [GitHub private vulnerability reporting](https://github.com/storytold/photocraft/security/advisories/new); if you cannot access it, follow the fallback in `SECURITY.md`. A useful report identifies affected versions or commits, platform/build configuration, impact, exact reproduction steps, expected versus actual behavior, and relevant logs or backtraces. For a malicious test file, first provide a minimal description, hash, format, and safe transfer requirements; do not attach it publicly when it could harm users or contains non-redistributable data. diff --git a/crates/algo/src/content_aware/structure_continue_tests.rs b/crates/algo/src/content_aware/structure_continue_tests.rs index 895e9f5d02..62a097d5d8 100644 --- a/crates/algo/src/content_aware/structure_continue_tests.rs +++ b/crates/algo/src/content_aware/structure_continue_tests.rs @@ -67,14 +67,11 @@ fn window_buffers() -> (Vec, Vec, usize) { (img, hole, ww) } -/// Fill the measured document the way the command does with `opts` and Auto or Rectangular -/// sampling, and return the filled window. -fn fill_measured_document(sampling: &str, opts: &FillOptions) -> Vec { +/// Fill the measured document the way the command does with `opts` and Auto sampling, and return +/// the filled window. +fn fill_measured_document(opts: &FillOptions) -> Vec { let (img, hole, ww) = window_buffers(); - let source = match sampling { - "auto" => auto_sampling(ww, 400, 3, &img, &hole), - _ => hole.iter().map(|h| !h).collect(), - }; + let source = auto_sampling(ww, 400, 3, &img, &hole); fill(ww, 400, 3, &img, &hole, &source, opts) } @@ -169,49 +166,29 @@ fn boundary_mismatches(out: &[f32]) -> (usize, usize) { (green_above, cold_below) } +/// The measured fill, computed once: Auto and Rectangular give `fill` the same area on this +/// document ([`measured_auto_area_is_the_rectangular_one`]), so one fill stands for both. The +/// checks are collected first, so a failure reports every one that is off. #[test] -fn auto_fill_continues_the_bands_and_stripes_at_the_measured_samples() { +fn measured_fill_continues_the_bands_and_stripes_and_keeps_the_boundary_at_y_200() { assert_eq!(window(), Rect::new(100, 0, 500, 400), "the sampling window #14191 measured"); - let out = fill_measured_document("auto", &FillOptions::default()); + let out = fill_measured_document(&FillOptions::default()); + let mut failures = Vec::new(); let off = samples_off(&out); - assert!(off.is_empty(), "Auto sampling: {} of 9 samples off\n{}", off.len(), off.join("\n")); -} - -#[test] -fn rectangular_fill_continues_the_bands_and_stripes_at_the_measured_samples() { - let out = fill_measured_document("rectangular", &FillOptions::default()); - let off = samples_off(&out); - assert!(off.is_empty(), "Rectangular sampling: {} of 9 samples off\n{}", off.len(), off.join("\n")); -} - -#[test] -fn auto_fill_keeps_the_blue_green_boundary_at_y_200() { - let out = fill_measured_document("auto", &FillOptions::default()); + if !off.is_empty() { + failures.push(format!("{} of 9 samples off\n{}", off.len(), off.join("\n"))); + } let (green_above, cold_below) = boundary_mismatches(&out); - assert_eq!(green_above, 0, "pixels above y 200 that took a colour of the green half"); - assert_eq!(cold_below, 0, "pixels below y 200 that took a colour of the blue half"); -} - -#[test] -fn rectangular_fill_keeps_the_blue_green_boundary_at_y_200() { - let out = fill_measured_document("rectangular", &FillOptions::default()); - let (green_above, cold_below) = boundary_mismatches(&out); - assert_eq!(green_above, 0, "pixels above y 200 that took a colour of the green half"); - assert_eq!(cold_below, 0, "pixels below y 200 that took a colour of the blue half"); -} - -#[test] -fn auto_fill_keeps_the_band_and_stripe_phase_across_the_whole_hole() { - let out = fill_measured_document("auto", &FillOptions::default()); + if (green_above, cold_below) != (0, 0) { + failures.push(format!( + "the blue / green boundary moved: {green_above} pixels above y 200 took a colour of the green half, {cold_below} below it one of the blue half" + )); + } let (worst, within, n) = phase_through_the_hole(&out); - assert_eq!((within, n), (10_000, 10_000), "{within} of {n} hole pixels carry the document's own colour within 12 levels (worst {worst})"); -} - -#[test] -fn rectangular_fill_keeps_the_band_and_stripe_phase_across_the_whole_hole() { - let out = fill_measured_document("rectangular", &FillOptions::default()); - let (worst, within, n) = phase_through_the_hole(&out); - assert_eq!((within, n), (10_000, 10_000), "{within} of {n} hole pixels carry the document's own colour within 12 levels (worst {worst})"); + if within != n { + failures.push(format!("{within} of {n} hole pixels carry the document's own colour within 12 levels (worst {worst})")); + } + assert!(failures.is_empty(), "{}", failures.join("\n")); } /// Per-channel slack for the unmeasured pins below. The exact values hold bit for bit on Windows @@ -273,7 +250,7 @@ fn unmeasured_geometric_adaptation() -> Vec<(&'static str, FillOptions, [i32; 27 } fn check_unmeasured(what: &str, opts: &FillOptions, want: &[i32; 27]) { - let out = fill_measured_document("auto", opts); + let out = fill_measured_document(opts); let got: Vec = SAMPLES.iter().flat_map(|((x, y), _)| filled_at(&out, *x, *y)).collect(); let off: Vec = SAMPLES .iter() @@ -307,8 +284,8 @@ fn unmeasured_geometric_adaptation_keeps_todays_fill() { #[test] fn measured_auto_area_is_the_rectangular_one() { - // What the measured Auto and Rectangular fills above rest on: on this document Auto keeps the - // whole window, as in the reference application. + // What the measured fill above rests on: on this document Auto keeps the whole window, as in + // the reference application, so the Auto fill is the Rectangular one. let (img, hole, ww) = window_buffers(); assert_eq!(auto_sampling(ww, 400, 3, &img, &hole), hole.iter().map(|h| !h).collect::>()); } diff --git a/crates/algo/src/quantize.rs b/crates/algo/src/quantize.rs index 75bb09145c..1ddb62c8e5 100644 --- a/crates/algo/src/quantize.rs +++ b/crates/algo/src/quantize.rs @@ -404,6 +404,11 @@ pub fn build_palette(px: &[[f32; 4]], kind: PaletteKind, colors: usize, forced: if hist.len() > 256 { return Err(format!("the image has {} colours; Exact needs 256 or fewer", hist.len())); } + // Forced entries absent from the image still consume palette slots. + let required = hist.len() + pal.iter().filter(|color| !hist.iter().any(|(existing, _)| existing == *color)).count(); + if required > 256 { + return Err(format!("the image and forced colours need {required} entries; Exact needs 256 or fewer")); + } hist.iter().map(|h| h.0).collect() } PaletteKind::SystemMac => mac_palette(), diff --git a/crates/algo/src/quantize/tests.rs b/crates/algo/src/quantize/tests.rs index 5f27ff8f5d..4ab37d126c 100644 --- a/crates/algo/src/quantize/tests.rs +++ b/crates/algo/src/quantize/tests.rs @@ -270,6 +270,34 @@ fn exact_palette_and_failure() { assert!(build_palette(&gradient(64, 64), PaletteKind::Exact, 256, Forced::None).is_err()); } +#[test] +fn exact_palette_counts_forced_colours_without_dropping_image_colours() { + let pixels = |count: u16| (0..count).map(|r| [f32::from(r) / 255.0, 42.0 / 255.0, 7.0 / 255.0, 1.0]).collect::>(); + let px = pixels(256); + let error = build_palette(&px, PaletteKind::Exact, 256, Forced::BlackWhite).unwrap_err(); + assert!(error.contains("258") && error.contains("forced"), "{error}"); + + let boundary = pixels(254); + let palette = build_palette(&boundary, PaletteKind::Exact, 256, Forced::BlackWhite).unwrap(); + assert_eq!(palette.len(), 256); + assert_eq!(&palette[..2], &[[0, 0, 0], [255, 255, 255]], "forced colours retain their order"); + for r in 0..254u8 { + assert!(palette.contains(&[r, 42, 7]), "the source colour {r} was dropped"); + } + + let mut overlap = boundary; + overlap.extend([[0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0]]); + let palette = build_palette(&overlap, PaletteKind::Exact, 256, Forced::BlackWhite).unwrap(); + assert_eq!(palette.len(), 256, "forced colours already in the image count only once"); + for colors in [2, 256] { + let palette = build_palette(&px, PaletteKind::Exact, colors, Forced::None).unwrap(); + assert_eq!(palette.len(), 256, "Exact still retains every image colour regardless of the requested count"); + for r in 0..=255u8 { + assert!(palette.contains(&[r, 42, 7]), "the source colour {r} was dropped"); + } + } +} + #[test] fn adaptive_and_perceptual_respect_count_and_forced() { let px = gradient(40, 40); diff --git a/crates/automation/src/agent_link.rs b/crates/automation/src/agent_link.rs index 4bfad53079..038b61d13d 100644 --- a/crates/automation/src/agent_link.rs +++ b/crates/automation/src/agent_link.rs @@ -5,6 +5,11 @@ //! settings folder, and `photocraft-cli mcp` ([`crate::live`]) reads that file on every tool call, //! so MCP client configurations never hold a port or a token. Adding PhotoCraft to MCP clients is //! the ArtCraft Launcher's job (one entry for every Craft app). +//! +//! PhotoCraft's bridge uses challenge authentication: the listener proves it holds the token +//! before the client sends its own proof, and the token itself is never sent. The connection's +//! process id identifies the publisher and distinguishes restarts; it does not authenticate the +//! listener. See [`crate::bridge::BridgeClient`] and `docs/control-protocol.md`. use std::path::Path; diff --git a/crates/automation/src/app_dirs.rs b/crates/automation/src/app_dirs.rs index d493536eff..80b38c86a0 100644 --- a/crates/automation/src/app_dirs.rs +++ b/crates/automation/src/app_dirs.rs @@ -72,7 +72,9 @@ pub fn platform_dir(env: &impl Fn(&str) -> Option) -> Option if cfg!(windows) { return env("APPDATA").filter(|a| !a.is_empty()).map(|a| PathBuf::from(a).join("Photocraft")); } - env("XDG_CONFIG_HOME").filter(|x| !x.is_empty()).map(PathBuf::from).or_else(|| home.map(|h| h.join(".config"))).map(|c| c.join("photocraft")) + // XDG requires absolute paths. With Windows handled above, a root is sufficient, + // including on wasm where is_absolute does not recognize rooted paths. + env("XDG_CONFIG_HOME").map(PathBuf::from).filter(|x| x.has_root()).or_else(|| home.map(|h| h.join(".config"))).map(|c| c.join("photocraft")) } /// The first portable marker file in `exe_dir`, if any. @@ -112,3 +114,64 @@ pub fn from_env() -> DataDir { let exe = std::env::current_exe().ok(); resolve(|k| std::env::var_os(k), exe.as_deref().and_then(Path::parent)) } + +#[cfg(all(test, not(windows), not(target_os = "macos")))] +mod tests { + use super::*; + + #[test] + fn relative_xdg_config_home_is_ignored() { + for xdg in ["relative/config", ".", "~/config"] { + for (home, expected) in [(Some("/home/test"), Some("/home/test/.config/photocraft")), (None, None), (Some(""), None)] { + let env = |key: &str| { + match key { + "HOME" => home, + "XDG_CONFIG_HOME" => Some(xdg), + _ => None, + } + .map(OsString::from) + }; + assert_eq!(platform_dir(&env), expected.map(PathBuf::from), "HOME={home:?}, XDG_CONFIG_HOME={xdg:?}"); + } + } + } + + #[test] + fn absolute_and_default_xdg_config_home_still_work() { + for (xdg, home, expected) in [ + (Some("/config"), Some("/home/test"), Some("/config/photocraft")), + (Some("/config"), None, Some("/config/photocraft")), + (None, Some("/home/test"), Some("/home/test/.config/photocraft")), + (Some(""), Some("/home/test"), Some("/home/test/.config/photocraft")), + (None, None, None), + (Some(""), None, None), + ] { + let env = |key: &str| { + match key { + "HOME" => home, + "XDG_CONFIG_HOME" => xdg, + _ => None, + } + .map(OsString::from) + }; + assert_eq!(platform_dir(&env), expected.map(PathBuf::from), "HOME={home:?}, XDG_CONFIG_HOME={xdg:?}"); + } + } + + #[test] + fn custom_config_override_still_accepts_relative_paths() { + let env = |key: &str| { + match key { + "PHOTOCRAFT_CONFIG_DIR" => Some("custom/config"), + "XDG_CONFIG_HOME" => Some("/config"), + "HOME" => Some("/home/test"), + _ => None, + } + .map(OsString::from) + }; + let result = resolve(env, None); + assert_eq!(result.dir, Some(PathBuf::from("custom/config"))); + assert_eq!(result.mode, Mode::Override); + assert!(result.warning.is_none()); + } +} diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs index 1913566f4a..a3b3f5234a 100644 --- a/crates/automation/src/files.rs +++ b/crates/automation/src/files.rs @@ -146,7 +146,11 @@ pub fn save_with_renderer_keeping( .or_else(|| path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase())) .ok_or_else(|| AutomationError::BadRequest(format!("cannot tell the format of `{}`; pass a format", path.display())))?; if ext == photocraft_format::EXTENSION { - let named = named_for_output(doc, &path.to_string_lossy()); + let mut named = doc.clone(); + // Native filenames may contain a literal backslash on Unix. + if let Some(name) = path.file_name() { + named.name = name.to_string_lossy().into_owned(); + } let mut local = PcraftWriter::new(); let w = writer.unwrap_or(&mut local); w.save_path(&named, path, &native_options(&named, opts)?)?; diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 404891f61e..c79405a57e 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -167,6 +167,15 @@ impl Headless { } "doc.new" => self.command_run("file.new", p), "doc.save" => { + // A malformed Save As request must not become an implicit save to the stored path. + if !p.is_object() { + return Err(bad("doc.save params must be an object")); + } + for key in ["path", "format"] { + if p.get(key).is_some_and(|value| !value.is_null() && !value.is_string()) { + return Err(bad(format!("`{key}` must be a string"))); + } + } let tga_bits = photocraft_engine::file_cmds::tga_bits_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?; let pdf_spot_plates = photocraft_engine::file_cmds::pdf_spot_plates_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?; let mut opts = photocraft_io::ExportOptions { @@ -223,6 +232,15 @@ impl Headless { } "doc.inspect" => self.inspect(index_of(&p)?), "doc.render" => { + // Invalid file requests must not fall back to a base64 response. + if !p.is_object() { + return Err(bad("doc.render params must be an object")); + } + let path = match p.get("path") { + None | Some(Value::Null) => None, + Some(Value::String(path)) => Some(path.as_str()), + Some(_) => return Err(bad("`path` must be a string")), + }; let max = match p.get("maxSide") { None => 1024, Some(value) => { @@ -232,7 +250,7 @@ impl Headless { let png = self.render_png(index_of(&p)?, max)?; // A GPU to CPU fallback is reported with this reply, not on the next save. let warnings = self.drain_diagnostics(); - let mut reply = match str_of(&p, "path") { + let mut reply = match path { Some(path) => { self.write_render(&PathBuf::from(path), &png)?; json!({"path": path, "bytes": png.len()}) @@ -253,7 +271,13 @@ impl Headless { let i = index_of(&p)?.ok_or_else(|| bad("doc.select needs `index`"))?; self.select(i) } - "doc.close" => self.close(index_of(&p)?), + "doc.close" => { + // A non-object would look like a missing index and close the active document. + if !p.is_object() { + return Err(bad("doc.close params must be an object")); + } + self.close(index_of(&p)?) + } "batch" => self.batch(&p), "methods" => Ok(json!(METHODS)), other => Err(bad(format!("{} (try `methods`)", photocraft_engine::command_hints::unknown_method(other, METHODS)))), diff --git a/crates/automation/src/rpc/tests.rs b/crates/automation/src/rpc/tests.rs index 584247d6a5..8081a180dd 100644 --- a/crates/automation/src/rpc/tests.rs +++ b/crates/automation/src/rpc/tests.rs @@ -176,6 +176,32 @@ fn batch_rejects_too_many_steps() { assert!(error.to_string().contains("maximum is 256")); } +#[test] +fn render_rejects_malformed_requests_and_keeps_missing_or_null_path_behavior() { + let h = session(); + let mut g = h.lock().unwrap(); + g.handle("doc.new", json!({"width": 8, "height": 8})).unwrap(); + let before = g.inspect(None).unwrap(); + for params in [json!([]), json!([0]), json!(123), json!(false), json!("out.png")] { + let error = g.handle("doc.render", params.clone()).unwrap_err(); + assert!(matches!(&error, AutomationError::BadRequest(_)), "{params}: {error}"); + assert!(error.to_string().contains("doc.render params must be an object"), "{params}: {error}"); + assert_eq!(g.inspect(None).unwrap(), before, "invalid params {params} changed the document"); + } + for path in [json!(123), json!(false), json!([]), json!({})] { + let error = g.handle("doc.render", json!({"path": path})).unwrap_err(); + assert!(matches!(&error, AutomationError::BadRequest(_)), "{path}: {error}"); + assert!(error.to_string().contains("`path` must be a string"), "{path}: {error}"); + assert_eq!(g.inspect(None).unwrap(), before, "invalid path {path} changed the document"); + } + for params in [Value::Null, json!({}), json!({"path": null})] { + let reply = g.handle("doc.render", params.clone()).unwrap(); + assert_eq!(reply["mime"], "image/png", "{params}: {reply}"); + let png = base64::engine::general_purpose::STANDARD.decode(reply["base64"].as_str().unwrap()).unwrap(); + assert_eq!(photocraft_codecs::decode(&png).unwrap().dimensions(), (8, 8)); + } +} + #[test] fn render_to_file_and_base64() { let h = session(); @@ -1186,3 +1212,85 @@ fn doc_place_forwards_high_memory_approval() { drop(t); std::fs::remove_dir_all(root).unwrap(); } + +#[test] +fn doc_save_rejects_malformed_requests_without_writing_the_stored_path() { + let dir = std::env::temp_dir().join(format!("pc-rpc-save-path-{}", std::process::id())); + std::fs::create_dir(&dir).unwrap(); + let workspace = crate::AuthorizedWorkspace::new(Some(&dir), Some(&dir)).unwrap(); + let mut h = Headless::with_workspace(workspace); + h.handle("doc.new", json!({"width": 8, "height": 8})).unwrap(); + h.handle("doc.save", json!({"path": "saved.pcraft"})).unwrap(); + let path = dir.join("saved.pcraft"); + let original = std::fs::read(&path).unwrap(); + h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Unsaved"}})).unwrap(); + let unsaved = h.inspect(None).unwrap(); + + for field in ["path", "format"] { + for value in [json!(123), json!(false), json!([]), json!({})] { + let mut params = json!({}); + params[field] = value.clone(); + let error = h.handle("doc.save", params).unwrap_err().to_string(); + assert!(error.contains(field), "{field} {value}: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), original, "invalid {field} {value} wrote the stored file"); + assert_eq!(h.inspect(None).unwrap(), unsaved, "invalid {field} {value} changed the document"); + } + } + for params in [json!(123), json!(false), json!([]), json!("saved.pcraft")] { + let error = h.handle("doc.save", params.clone()).unwrap_err().to_string(); + assert!(error.contains("object"), "{params}: {error}"); + assert_eq!(std::fs::read(&path).unwrap(), original, "invalid params {params} wrote the stored file"); + assert_eq!(h.inspect(None).unwrap(), unsaved, "invalid params {params} changed the document"); + } + + let mut previous = original; + for params in [json!({}), json!({"path": null}), json!({"format": null}), Value::Null] { + h.handle("engine.execute", json!({"command": "layer.new.layer"})).unwrap(); + let saved = h.handle("doc.save", params).unwrap(); + assert_eq!(saved["path"], "saved.pcraft"); + let bytes = std::fs::read(&path).unwrap(); + assert_ne!(bytes, previous, "an implicit save did not write the edited document"); + previous = bytes; + } + let saved = h.handle("doc.save", json!({"path": "copy.pcraft", "format": "pcraft"})).unwrap(); + assert_eq!(saved["path"], "copy.pcraft"); + assert!(dir.join("copy.pcraft").is_file()); + drop(h); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn doc_close_rejects_non_object_params_without_closing_documents() { + let h = session(); + for _ in 0..2 { + assert_eq!(respond(&h, r#"{"method":"doc.new","params":{"width":8,"height":8}}"#)["ok"], true); + } + let before = h.lock().unwrap().session_list(); + for params in [json!([]), json!([0]), json!(true), json!(false), json!(1), json!("0")] { + let reply = respond(&h, &json!({"method": "doc.close", "params": params}).to_string()); + assert_eq!(reply["ok"], false, "{params}: {reply}"); + assert!(reply["error"].as_str().unwrap().contains("doc.close params must be an object"), "{reply}"); + assert_eq!(h.lock().unwrap().session_list(), before, "invalid params {params} changed the session"); + } + + // Missing/null params and indices close the active document; an explicit index selects its target. + for (params, remaining_index) in + [(None, 0), (Some(Value::Null), 0), (Some(json!({})), 0), (Some(json!({"index": null})), 0), (Some(json!({"index": 0})), 1)] + { + let h = session(); + for width in [8, 16] { + let request = json!({"method": "doc.new", "params": {"width": width, "height": 8}}); + assert_eq!(respond(&h, &request.to_string())["ok"], true); + } + let mut expected = h.lock().unwrap().session_list()["documents"][remaining_index].clone(); + expected["index"] = json!(0); + let mut request = json!({"method": "doc.close"}); + if let Some(params) = params { + request["params"] = params; + } + let reply = respond(&h, &request.to_string()); + assert_eq!(reply["ok"], true, "{request}: {reply}"); + assert_eq!(reply["result"]["documents"], json!([expected]), "{request}: {reply}"); + assert_eq!(reply["result"]["active"], 0, "{reply}"); + } +} diff --git a/crates/automation/tests/it/native_save_name.rs b/crates/automation/tests/it/native_save_name.rs index 18319c5f31..2a840d4b59 100644 --- a/crates/automation/tests/it/native_save_name.rs +++ b/crates/automation/tests/it/native_save_name.rs @@ -38,3 +38,28 @@ fn workspace_encoded_native_bundle_uses_requested_name_without_mutating_source() assert_eq!(reopened.name, "Renamed.pcraft"); assert_eq!(doc.name, "Original", "a copy should not retarget the open document"); } + +#[cfg(unix)] +#[test] +fn native_save_preserves_backslashes_in_the_written_filename() { + let dir = std::env::temp_dir().join(format!( + "pc-native-backslash-name-{}-{}", + std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + let filename = r"Renamed\Copy.pcraft"; + let path = dir.join(filename); + let mut headless = Headless::trusted_local(); + headless.handle("doc.new", json!({"width": 8, "height": 8, "name": "Original"})).unwrap(); + let doc = &headless.session.active().unwrap().doc; + + files::save(doc, &path, None, &Default::default(), None).unwrap(); + + let manifest = photocraft_format::read_manifest(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(manifest.document.name, filename); + assert_eq!(files::open(&path).unwrap().document.name, filename); + assert_eq!(doc.name, "Original", "saving a snapshot must not rename the source"); + drop(headless); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/color/src/convert.rs b/crates/color/src/convert.rs index 584dd40569..9e36d55651 100644 --- a/crates/color/src/convert.rs +++ b/crates/color/src/convert.rs @@ -42,7 +42,12 @@ impl CmykSpace { } } let space = Self::build(bytes); - cache.lock().unwrap_or_else(|e| e.into_inner()).push((Arc::downgrade(bytes), space.clone())); + let mut c = cache.lock().unwrap_or_else(|e| e.into_inner()); + // Another render may have cached this allocation while its transforms were built. + if let Some((_, cached)) = c.iter().find(|(w, _)| w.as_ptr() == Arc::as_ptr(bytes)) { + return cached.clone(); + } + c.push((Arc::downgrade(bytes), space.clone())); space } @@ -329,6 +334,32 @@ mod tests { }); } + #[test] + fn concurrent_profile_requests_share_the_cached_space() { + const CALLERS: usize = 4; + let params = craft_cms::synth::CmykParams { + description: "Concurrent CMYK cache".into(), + tvi: [0.26, 0.26, 0.26, 0.3], + grid_a2b: 5, + grid_b2a: 9, + ..Default::default() + }; + let bytes = craft_cms::synth::cmyk_profile(¶ms).unwrap().to_bytes(); + let start = std::sync::Barrier::new(CALLERS); + let spaces = std::thread::scope(|scope| { + let handles: Vec<_> = (0..CALLERS) + .map(|_| { + scope.spawn(|| { + start.wait(); + CmykSpace::for_profile(Some(&bytes)).expect("a synthetic CMYK space") + }) + }) + .collect(); + handles.into_iter().map(|h| h.join().unwrap()).collect::>() + }); + assert!(spaces.iter().all(|space| Arc::ptr_eq(space, &spaces[0])), "parallel first callers must share one cached CMYK space"); + } + /// Lab round-trips sRGB and puts white at L 100 and black at L 0. #[test] fn lab_roundtrip_and_anchors() { diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index bb95599702..0e361c4b01 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -18,7 +18,7 @@ pub fn dither_noise(x: i32, y: i32) -> f32 { h ^= h >> 15; h = h.wrapping_mul(0x2C1B_3C6D); h ^= h >> 12; - f32::from((h & 0xFFFF) as u16) / 65535.0 + f32::from((h & 0xFFFF) as u16) / 65536.0 } use serde::{Deserialize, Serialize}; @@ -225,6 +225,16 @@ impl Color { mod tests { use super::*; + #[test] + fn dither_noise_keeps_the_largest_hash_below_one() { + // This position hashes to 65535: a full-opacity probability must still include it. + assert_eq!(dither_noise(8, 246), 65535.0 / 65536.0); + assert_eq!(dither_noise(0, 0), 0.0); + for (x, y) in [(8, 246), (-8, -246), (i32::MIN, i32::MAX), (i32::MAX, i32::MIN)] { + assert!((0.0..1.0).contains(&dither_noise(x, y))); + } + } + #[test] fn colors_convert_into_a_document_mode() { let blue = Color::rgba(0.0, 0.0, 1.0, 0.5); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 0ce0aa8d6f..f7e81d719d 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -19,7 +19,7 @@ photocraft-geom = { workspace = true } photocraft-color = { workspace = true } craft-cms = { workspace = true } # PCTIP codec from craft-libs#1564; isolated pin until the shared revision is adopted workspace-wide. -craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-ops = { workspace = true } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index f8d68e604f..73158ece9a 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -19,6 +19,9 @@ pub mod actions_cmds; pub mod actions_edit_cmds; pub mod adjust_cmds; mod adjust_params; +pub mod adjustment_brush_cmds; +#[cfg(test)] +mod adjustment_brush_cmds_tests; pub mod align_cmds; pub mod analysis_cmds; pub mod artboard_cmds; diff --git a/crates/engine/src/cmd/adjustment_brush_cmds.rs b/crates/engine/src/cmd/adjustment_brush_cmds.rs new file mode 100644 index 0000000000..28c271e7c5 --- /dev/null +++ b/crates/engine/src/cmd/adjustment_brush_cmds.rs @@ -0,0 +1,262 @@ +//! The Adjustment Brush Tool (#12519): painting on the image makes an adjustment layer whose mask +//! is what was painted, or paints into the mask of the active adjustment layer of the chosen kind. +//! The kinds it offers, which of them a document's colour mode and bit depth grey out, and the +//! starting values a new layer gets, as measured in the reference application. + +use photocraft_doc::{Adjustment, ColorMode, Layer, LayerContent, LayerMask, SampleType}; +use serde_json::{Value, json}; + +use super::adjust_params::adjustment_kind; +use super::layer_params::{mask_at_depth, selection_mask}; +use crate::commands::CommandSpec; +use crate::{EngineError, Result, Session}; + +const CMD: &str = "paint.adjustmentBrush"; + +/// The history state of a stroke that makes the layer. +pub const NEW_LAYER_LABEL: &str = "New Adjustment Layer"; +/// The history state of a stroke into an existing adjustment layer's mask. +pub const STROKE_LABEL: &str = "Adjustment Brush"; + +/// The alert a stroke on an Indexed Color document shows; nothing changes. +pub const INDEXED_ALERT: &str = "Could not complete your request because the tool does not work with Indexed Color images. Please convert the image to RGB or another supported mode before using."; + +/// One entry of the options bar's Adjustment dropdown: the kind id (the `layer.newAdjustmentLayer` +/// suffix for the kinds that exist), its label, and whether a separator follows it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Entry { + pub kind: &'static str, + pub label: &'static str, + pub separator_after: bool, +} + +const fn entry(kind: &'static str, label: &'static str, separator_after: bool) -> Entry { + Entry { kind, label, separator_after } +} + +/// The dropdown in the reference application's order, separators after Grain, Exposure and +/// Selective Color. +pub const ENTRIES: [Entry; 18] = [ + entry("light", "Light", false), + entry("colorVibrance", "Color and vibrance", false), + entry("clarityDehaze", "Clarity and dehaze", false), + entry("grain", "Grain", true), + entry("levels", "Levels", false), + entry("curves", "Curves", false), + entry("exposure", "Exposure", true), + entry("hueSaturation", "Hue/Saturation", false), + entry("colorBalance", "Color Balance", false), + entry("blackWhite", "Black & White", false), + entry("photoFilter", "Photo Filter", false), + entry("channelMixer", "Channel Mixer", false), + entry("colorLookup", "Color Lookup", false), + entry("selectiveColor", "Selective Color", true), + entry("invert", "Invert", false), + entry("posterize", "Posterize", false), + entry("threshold", "Threshold", false), + entry("gradientMap", "Gradient Map", false), +]; + +/// Entries whose adjustment doesn't exist yet: always greyed. +const MISSING: [&str; 4] = ["light", "colorVibrance", "clarityDehaze", "grain"]; + +/// The entry the tool starts on: the reference application's default (Light) while it is +/// available, else the first enabled entry. +pub const DEFAULT_KIND: &str = "levels"; + +/// The entry with id `kind`. +pub fn entry_of(kind: &str) -> Option<&'static Entry> { + ENTRIES.iter().find(|e| e.kind == kind) +} + +/// Is `kind` offered (not greyed) in a document of `mode` and `depth`? Indexed Color refuses +/// the stroke as a whole ([`INDEXED_ALERT`]), so its entries stay as RGB's. Bitmap, Duotone and +/// Multichannel were not measured and grey nothing extra. +pub fn enabled_in(kind: &str, mode: ColorMode, depth: SampleType) -> bool { + if entry_of(kind).is_none() || MISSING.contains(&kind) { + return false; + } + let greyed: &[&str] = match mode { + ColorMode::Grayscale => &["hueSaturation", "colorBalance", "blackWhite", "photoFilter", "channelMixer", "colorLookup", "selectiveColor"], + ColorMode::Cmyk => &["exposure", "blackWhite"], + ColorMode::Lab => &["exposure", "blackWhite", "channelMixer", "selectiveColor"], + _ => &[], + }; + let float: &[&str] = if depth == SampleType::F32 { &["invert", "posterize", "threshold", "gradientMap"] } else { &[] }; + !greyed.contains(&kind) && !float.contains(&kind) +} + +/// The kind the dropdown shows when `kind` is greyed in this document: `kind` itself when it is +/// offered, else the first offered entry. +pub fn offered_kind(kind: &str, mode: ColorMode, depth: SampleType) -> &str { + if enabled_in(kind, mode, depth) { + return kind; + } + ENTRIES.iter().map(|e| e.kind).find(|k| enabled_in(k, mode, depth)).unwrap_or(kind) +} + +/// The params of the starting values a layer of `kind` gets (the layer already changes the +/// image; these are not Layer › New Adjustment Layer's identity values). Color Lookup starts on a +/// built-in film look: the reference application ships its own film-stock table, which is not +/// ours to copy. +pub fn starting_params(kind: &str) -> Option { + Some(match kind { + "levels" => json!({"inBlack": 20, "gamma": 1.0, "inWhite": 220, "outBlack": 0, "outWhite": 255}), + "curves" => json!({"points": [[0, 0], [127, 191], [255, 255]]}), + "exposure" => json!({"exposure": 1.0, "offset": 0.0, "gamma": 1.0}), + "hueSaturation" => json!({"hue": 0, "saturation": 30, "lightness": 0, "colorize": false}), + "colorBalance" => json!({"shadows": [0, 0, 0], "midtones": [20, -15, 15], "highlights": [0, 0, 0], "preserveLuminosity": true}), + "blackWhite" => json!({"reds": 40, "yellows": 60, "greens": 40, "cyans": 60, "blues": 20, "magentas": 80, "tint": false}), + // Warming Filter (85), the reference application's Lab (67.06, 32, 120) shown in sRGB. + "photoFilter" => json!({"filter": "warming85", "density": 25, "preserveLuminosity": true}), + "channelMixer" => json!({"red": [80, 10, 10, 5], "green": [0, 100, 0, 0], "blue": [0, 0, 100, 0], "monochrome": false}), + "colorLookup" => json!({"lut": "fadedFilm"}), + "selectiveColor" => json!({"method": "relative", "reds": [-20, 100, -60, 40]}), + "invert" => json!({}), + "posterize" => json!({"levels": 4}), + "threshold" => json!({"level": 128}), + "gradientMap" => json!({"stops": [[0, "#000000"], [1, "#ffffff"]], "reverse": false, "dither": false}), + _ => return None, + }) +} + +fn bad(msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: CMD.into(), msg: msg.into() } +} + +/// The adjustment a new layer of `kind` starts with in a document of `mode`. +pub fn starting_adjustment(kind: &str, mode: ColorMode) -> Result { + let p = starting_params(kind).ok_or_else(|| bad(format!("`{kind}` is not available yet")))?; + crate::adjust_params::from_params(kind, &p, None, mode) +} + +/// The mask colours of the stroke: white adds the adjustment, black (Subtract) takes it away. +fn paint_colors(subtract: bool) -> ([f32; 4], [f32; 4]) { + let (white, black) = ([1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]); + if subtract { (black, white) } else { (white, black) } +} + +/// The kind of the active layer when it is an adjustment layer (the dropdown follows it). +pub fn active_kind(s: &Session) -> Option<&'static str> { + let st = s.active()?; + let layer = st.doc.layer(st.active_layer?)?; + match &layer.content { + LayerContent::Adjustment(adj) => Some(adjustment_kind(adj)).filter(|k| entry_of(k).is_some()), + _ => None, + } +} + +fn kind_param(p: &Value) -> Result<&str> { + match p.get("kind") { + None | Some(Value::Null) => Ok(DEFAULT_KIND), + Some(Value::String(k)) => entry_of(k).map(|e| e.kind).ok_or_else(|| bad(format!("unknown adjustment `{k}`"))), + Some(other) => Err(bad(format!("`kind` must be an adjustment id, not {other}"))), + } +} + +fn subtract_param(p: &Value) -> Result { + match p.get("subtract") { + None | Some(Value::Null) => Ok(false), + Some(v) => v.as_bool().ok_or_else(|| bad("`subtract` must be true or false")), + } +} + +/// `paint.adjustmentBrush`. +fn run(s: &mut Session, p: &Value) -> Result { + if !p.is_object() { + return Err(bad("params must be an object")); + } + let (mode, depth) = { + let st = s.active().ok_or(EngineError::NoDocument)?; + (st.doc.mode, st.doc.depth) + }; + if mode == ColorMode::Indexed { + return Err(EngineError::Other(INDEXED_ALERT.into())); + } + let kind = kind_param(p)?; + if MISSING.contains(&kind) { + return Err(bad(format!("`{kind}` is not available yet"))); + } + if !enabled_in(kind, mode, depth) { + return Err(bad(format!("`{kind}` is not available in this document's color mode or bit depth"))); + } + let subtract = subtract_param(p)?; + let (fg, bg) = paint_colors(subtract); + // The stroke params without the tool's own keys, painting the mask in its colour. + let mut q = p.clone(); + if let Some(o) = q.as_object_mut() { + o.remove("kind"); + o.remove("subtract"); + o.remove("erase"); + o.remove("mode"); + o.remove("fill"); + o.insert("color".into(), json!([fg[0], fg[1], fg[2]])); + o.insert("target".into(), json!("mask")); + } + let pts = super::brush_cmds::parse_points(&q, CMD)?; + let mut brush = super::brush_cmds::resolve_brush(s, &q, CMD)?; + brush.color = fg; + brush.color_cmyk = None; + brush.erase = false; + brush.mode = photocraft_color::BlendMode::Normal; + brush.behind = false; + let zoom = q.get("zoom").and_then(Value::as_f64).filter(|z| z.is_finite() && *z > 0.0).unwrap_or(1.0) as f32; + + // An adjustment layer of this kind with a mask is active: paint into its mask. + let paints_active = + active_kind(s) == Some(kind) && s.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))).is_some_and(|l| l.mask.is_some()); + let result = if paints_active { + let mut r = super::brush_cmds::stroke_into(s, CMD, &q, STROKE_LABEL, brush, pts)?; + r["created"] = json!(false); + r + } else { + let adj = starting_adjustment(kind, mode)?; + let label = entry_of(kind).map_or(kind, |e| e.label); + let (id, damage) = s.edit(NEW_LAYER_LABEL, |doc, active| { + let mut l = Layer::new(doc.next_layer_name(label), LayerContent::Adjustment(adj)); + // The selection becomes the mask and goes away; the stroke adds to it unclipped. + let (mut mask, revealed) = match selection_mask(doc)? { + Some(mask) => { + let revealed = doc.selection.take().map_or(photocraft_geom::Rect::EMPTY, |sel| sel.content_bounds()); + (mask, revealed) + } + None => (mask_at_depth(LayerMask::hide_all(), doc.depth)?, photocraft_geom::Rect::EMPTY), + }; + let clip = doc.bounds().union(&mask.surface.tile_bounds()); + let painted = photocraft_paint::render_stroke_clipped(&mut mask.surface, &brush, &pts, None, false, zoom, Some(clip)); + l.mask = Some(mask); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); + *active = Some(id); + // The image changes where the mask reveals the adjustment: the selection and the stroke. + Ok((id, painted.union(&revealed).intersect(&doc.bounds()))) + })?; + s.hint_damage(damage); + json!({"layer": id.0, "created": true, "damage": [damage.x0, damage.y0, damage.width(), damage.height()]}) + }; + // The new layer's mask is the target, and the colours are the stroke's. + super::channel_cmds::target_layer_mask(s); + s.tools.foreground = fg; + s.tools.background = bg; + Ok(result) +} + +/// Enabled with a document open. +fn enabled(s: &Session) -> std::result::Result<(), String> { + if s.active().is_none() { + return Err("no document".into()); + } + Ok(()) +} + +pub fn specs() -> Vec { + vec![CommandSpec { + id: CMD, + label: "Adjustment Brush", + menu: &[], + shortcut: None, + params: r#"{"kind":"levels|curves|exposure|hueSaturation|colorBalance|blackWhite|photoFilter|channelMixer|colorLookup|selectiveColor|invert|posterize|threshold|gradientMap"="levels","subtract":bool=false (paint black: remove the adjustment),"points":[[x,y,pressure?],…],"size":px=tool size,"hardness":0..1,"opacity":0..1,"flow":0..1,"smoothing":0..1,"seed":u64?,"zoom":number=1} → {"layer"?,"created":bool,"damage"?} (with an adjustment layer of this kind active, the stroke paints its mask; else it makes the layer above the active one, its mask black or the selection, and paints the stroke white)"#, + enabled, + run, + journal: true, + }] +} diff --git a/crates/engine/src/cmd/adjustment_brush_cmds_tests.rs b/crates/engine/src/cmd/adjustment_brush_cmds_tests.rs new file mode 100644 index 0000000000..bc927059b9 --- /dev/null +++ b/crates/engine/src/cmd/adjustment_brush_cmds_tests.rs @@ -0,0 +1,300 @@ +//! Tests of `paint.adjustmentBrush`, the Adjustment Brush Tool's stroke (#12519). Reference +//! values measured in the reference application: a 100 px soft dab centred at (600, 450) on an +//! 1200 x 900 document. + +use photocraft_doc::{Adjustment, ColorMode, LayerContent, SampleType}; +use serde_json::{Value, json}; + +use super::adjustment_brush_cmds::{ENTRIES, INDEXED_ALERT, NEW_LAYER_LABEL, STROKE_LABEL, enabled_in, starting_adjustment}; +use crate::Session; + +const CMD: &str = "paint.adjustmentBrush"; + +fn doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1200, "height": 900, "background": "white"})).unwrap(); + s +} + +fn dab(kind: &str) -> Value { + json!({"kind": kind, "points": [[600, 450, 1.0]], "size": 100, "hardness": 0.0, "opacity": 1.0, "flow": 1.0}) +} + +fn active(s: &Session) -> &photocraft_doc::Layer { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap() +} + +fn mask_at(s: &Session, x: i32, y: i32) -> f32 { + active(s).mask.as_ref().expect("a layer mask").surface.sample_channel(x, y, 0) * 255.0 +} + +fn layer_count(s: &Session) -> usize { + s.active().unwrap().doc.walk().len() +} + +fn past(s: &Session) -> usize { + s.active().unwrap().history.past_len() +} + +#[test] +fn first_stroke_makes_a_masked_adjustment_layer_in_one_history_state() { + let mut s = doc(); + let before = (layer_count(&s), past(&s)); + let bg = s.active().unwrap().active_layer.unwrap(); + let r = s.execute(CMD, dab("levels")).unwrap(); + assert_eq!(r["created"], json!(true)); + assert_eq!(layer_count(&s), before.0 + 1); + assert_eq!(past(&s), before.1 + 1, "one history state"); + let st = s.active().unwrap(); + assert_eq!(st.history.undo_label(), Some(NEW_LAYER_LABEL)); + let l = active(&s); + assert_eq!(l.name, "Levels 1"); + assert!(matches!(l.content, LayerContent::Adjustment(Adjustment::Levels { .. }))); + assert_eq!((l.blend, l.opacity, l.clipped), (photocraft_doc::BlendMode::Normal, 1.0, false)); + // Directly above the Background. + let order: Vec<_> = st.doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(order, vec![bg, l.id]); + // Black outside the dab, white at its centre. + assert_eq!(mask_at(&s, 10, 10), 0.0); + assert_eq!(mask_at(&s, 680, 450), 0.0); + assert!(mask_at(&s, 600, 450) >= 250.0, "centre {}", mask_at(&s, 600, 450)); + // The mask is the target, white over black. + assert!(st.channel_view.target == crate::channel_cmds::ChannelTarget::LayerMask); + assert_eq!((s.tools.foreground, s.tools.background), ([1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0])); +} + +#[test] +fn a_soft_dab_falls_off_like_the_reference() { + let mut s = doc(); + s.execute(CMD, dab("levels")).unwrap(); + // The reference row: 550: 22, 570: 119, 590: 237, 600: 254, 620: 172, 640: 52, 660: 2, 670: 0. + let row: Vec = [550, 570, 590, 600, 620, 640, 660, 670].iter().map(|&x| mask_at(&s, x, 450)).collect(); + for w in row[..4].windows(2) { + assert!(w[0] <= w[1], "rises to the centre: {row:?}"); + } + for w in row[3..].windows(2) { + assert!(w[0] >= w[1], "falls off past it: {row:?}"); + } + assert!(row[7] <= 3.0 && row[0] < 128.0 && row[3] > 240.0, "{row:?}"); +} + +#[test] +fn layer_names_count_per_label() { + let mut s = doc(); + s.execute(CMD, dab("levels")).unwrap(); + s.execute(CMD, dab("blackWhite")).unwrap(); + assert_eq!(active(&s).name, "Black & White 1"); + s.execute("layer.select", json!({"layer": {"background": true}})).unwrap(); + s.execute(CMD, dab("levels")).unwrap(); + assert_eq!(active(&s).name, "Levels 2"); +} + +#[test] +fn the_selection_becomes_the_mask_and_the_dab_is_not_clipped_to_it() { + let mut s = doc(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 400, "height": 900})).unwrap(); + let before = past(&s); + s.execute(CMD, json!({"kind": "curves", "points": [[400, 450, 1.0]], "size": 100, "hardness": 0.0})).unwrap(); + assert_eq!(past(&s), before + 1, "still one history state"); + assert!(s.active().unwrap().doc.selection.is_none(), "the selection is gone"); + assert_eq!(mask_at(&s, 100, 100), 255.0, "inside the selection"); + assert_eq!(mask_at(&s, 900, 100), 0.0, "outside it"); + // The dab reaches past the selection edge at x 400. + assert!(mask_at(&s, 420, 450) > 100.0, "{}", mask_at(&s, 420, 450)); +} + +#[test] +fn inside_an_active_group_the_layer_goes_into_the_group() { + let mut s = doc(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.groupLayers", json!({})).unwrap(); + let group = s.active().unwrap().active_layer.unwrap(); + // An open group takes new layers, as Layer › New Adjustment Layer puts them. + s.execute("layer.setExpanded", json!({"expanded": true})).unwrap(); + s.execute(CMD, dab("invert")).unwrap(); + let id = active(&s).id; + let st = s.active().unwrap(); + let children = st.doc.layer(group).and_then(|g| g.children()).unwrap(); + assert!(children.iter().any(|l| l.id == id), "the new layer is inside the group"); +} + +#[test] +fn starting_values_are_read_back_from_the_new_layer() { + for e in ENTRIES.iter().filter(|e| enabled_in(e.kind, ColorMode::Rgb, SampleType::U8)) { + let mut s = doc(); + s.execute(CMD, dab(e.kind)).unwrap(); + let LayerContent::Adjustment(adj) = &active(&s).content else { panic!("{}: an adjustment layer", e.kind) }; + assert_eq!(adj.label(), e.label, "{}", e.kind); + assert_eq!(*adj, starting_adjustment(e.kind, ColorMode::Rgb).unwrap(), "{}", e.kind); + } +} + +#[test] +fn starting_values_match_the_reference() { + let close = |a: f32, b: f32| (a - b).abs() < 1e-3; + let adj = |kind: &str| starting_adjustment(kind, ColorMode::Rgb).unwrap(); + let Adjustment::Levels { master, .. } = adj("levels") else { panic!() }; + assert!(close(master.in_black * 255.0, 20.0) && close(master.in_white * 255.0, 220.0) && close(master.gamma, 1.0)); + assert!(close(master.out_black, 0.0) && close(master.out_white, 1.0)); + let Adjustment::Curves { master, .. } = adj("curves") else { panic!() }; + let pts: Vec<(f32, f32)> = master.iter().map(|p| (p.input * 255.0, p.output * 255.0)).collect(); + assert_eq!(pts.len(), 3); + assert!(close(pts[1].0, 127.0) && close(pts[1].1, 191.0), "{pts:?}"); + assert_eq!(adj("exposure"), Adjustment::Exposure { exposure: 1.0, offset: 0.0, gamma: 1.0 }); + let Adjustment::HueSaturation { hue, saturation, lightness, colorize, .. } = adj("hueSaturation") else { panic!() }; + assert_eq!((hue, saturation, lightness, colorize), (0.0, 30.0, 0.0, false)); + let Adjustment::ColorBalance { shadows, midtones, highlights, preserve_luminosity } = adj("colorBalance") else { panic!() }; + assert_eq!((shadows, midtones, highlights, preserve_luminosity), ([0.0; 3], [20.0, -15.0, 15.0], [0.0; 3], true)); + assert_eq!(adj("blackWhite"), Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: None }); + let Adjustment::PhotoFilter { density, preserve_luminosity, .. } = adj("photoFilter") else { panic!() }; + assert!(close(density, 0.25) && preserve_luminosity); + let Adjustment::ChannelMixer { matrix, monochrome } = adj("channelMixer") else { panic!() }; + assert!(!monochrome); + let want = [[0.8, 0.1, 0.1, 0.05], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]; + assert!(matrix.iter().flatten().zip(want.iter().flatten()).all(|(a, b)| close(*a, *b)), "{matrix:?}"); + assert!(matches!(adj("colorLookup"), Adjustment::ColorLookup { lut: Some(_), .. })); + let Adjustment::SelectiveColor { relative, adjustments } = adj("selectiveColor") else { panic!() }; + assert!(relative); + assert_eq!(adjustments[0], [-20.0, 100.0, -60.0, 40.0]); + assert_eq!(adj("invert"), Adjustment::Invert); + assert_eq!(adj("posterize"), Adjustment::Posterize { levels: 4 }); + assert!(matches!(adj("threshold"), Adjustment::Threshold { level } if close(level * 255.0, 128.0))); + let Adjustment::GradientMap { stops, reverse, dither, .. } = adj("gradientMap") else { panic!() }; + assert_eq!((stops.first().map(|s| s.1), stops.last().map(|s| s.1), reverse, dither), (Some([0.0; 3]), Some([1.0; 3]), false, false)); +} + +#[test] +fn a_later_stroke_paints_the_active_layers_mask() { + let mut s = doc(); + s.execute(CMD, dab("levels")).unwrap(); + let (id, n, depth) = (active(&s).id, layer_count(&s), past(&s)); + assert_eq!(mask_at(&s, 900, 450), 0.0); + let r = s.execute(CMD, json!({"kind": "levels", "points": [[900, 450, 1.0]], "size": 100, "hardness": 0.0})).unwrap(); + assert_eq!(r["created"], json!(false)); + assert_eq!((active(&s).id, layer_count(&s), past(&s)), (id, n, depth + 1), "no new layer, one more state"); + assert_eq!(s.active().unwrap().history.undo_label(), Some(STROKE_LABEL)); + assert!(mask_at(&s, 900, 450) >= 250.0); +} + +#[test] +fn a_layer_made_by_new_adjustment_layer_takes_the_stroke_too() { + let mut s = doc(); + s.execute("layer.newAdjustmentLayer.curves", json!({})).unwrap(); + let (id, n) = (active(&s).id, layer_count(&s)); + s.execute(CMD, dab("curves")).unwrap(); + assert_eq!((active(&s).id, layer_count(&s)), (id, n)); +} + +#[test] +fn another_kind_makes_a_new_layer_above_the_active_one() { + let mut s = doc(); + s.execute(CMD, dab("levels")).unwrap(); + let first = active(&s).id; + s.execute(CMD, dab("exposure")).unwrap(); + let st = s.active().unwrap(); + let order: Vec<_> = st.doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(order.len(), 3); + assert_eq!(order[1], first); + assert_eq!(active(&s).name, "Exposure 1"); +} + +#[test] +fn subtract_paints_black_and_swaps_the_colours() { + let mut s = doc(); + s.execute(CMD, json!({"kind": "levels", "points": [[600, 450], [800, 450]], "size": 100, "hardness": 1.0})).unwrap(); + assert!(mask_at(&s, 700, 450) >= 250.0); + s.execute(CMD, json!({"kind": "levels", "subtract": true, "points": [[700, 450]], "size": 40, "hardness": 1.0})).unwrap(); + assert_eq!(mask_at(&s, 700, 450), 0.0); + assert!(mask_at(&s, 610, 450) >= 250.0, "the rest stays"); + assert_eq!((s.tools.foreground, s.tools.background), ([0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0])); + s.execute(CMD, json!({"kind": "levels", "points": [[700, 450]], "size": 40, "hardness": 1.0})).unwrap(); + assert!(mask_at(&s, 700, 450) >= 250.0, "Add paints white again"); + assert_eq!(s.tools.foreground, [1.0, 1.0, 1.0, 1.0]); +} + +#[test] +fn entries_grey_out_per_mode_and_depth() { + let off = |mode, depth| -> Vec<&str> { ENTRIES.iter().map(|e| e.kind).filter(|k| !enabled_in(k, mode, depth)).collect() }; + let missing = ["light", "colorVibrance", "clarityDehaze", "grain"]; + let with = |more: &[&'static str]| -> Vec<&'static str> { ENTRIES.iter().map(|e| e.kind).filter(|k| missing.contains(k) || more.contains(k)).collect() }; + assert_eq!(off(ColorMode::Rgb, SampleType::U8), with(&[])); + assert_eq!(off(ColorMode::Rgb, SampleType::U16), with(&[])); + assert_eq!(off(ColorMode::Rgb, SampleType::F32), with(&["invert", "posterize", "threshold", "gradientMap"])); + assert_eq!( + off(ColorMode::Grayscale, SampleType::U8), + with(&["hueSaturation", "colorBalance", "blackWhite", "photoFilter", "channelMixer", "colorLookup", "selectiveColor"]) + ); + assert_eq!(off(ColorMode::Cmyk, SampleType::U8), with(&["exposure", "blackWhite"])); + assert_eq!(off(ColorMode::Lab, SampleType::U8), with(&["exposure", "blackWhite", "channelMixer", "selectiveColor"])); +} + +#[test] +fn a_greyed_entry_is_refused_and_an_offered_one_works_in_other_modes() { + for (mode, refused, works) in [ + ("image.mode.grayscale", "hueSaturation", "levels"), + ("image.mode.cmyk", "exposure", "curves"), + ("image.mode.lab", "channelMixer", "invert"), + ("image.mode.bits32", "posterize", "exposure"), + ("image.mode.bits16", "", "gradientMap"), + ] { + let mut s = doc(); + s.execute(mode, json!({})).unwrap(); + if !refused.is_empty() { + let before = layer_count(&s); + assert!(s.execute(CMD, dab(refused)).is_err(), "{mode}: {refused}"); + assert_eq!(layer_count(&s), before); + } + s.execute(CMD, dab(works)).unwrap_or_else(|e| panic!("{mode}: {works}: {e}")); + assert!(matches!(active(&s).content, LayerContent::Adjustment(_))); + } +} + +#[test] +fn indexed_color_refuses_the_stroke_with_the_alert() { + let mut s = doc(); + s.execute("image.mode.indexedColor", json!({})).unwrap(); + let (n, depth) = (layer_count(&s), past(&s)); + let e = s.execute(CMD, dab("levels")).unwrap_err().to_string(); + assert!(e.contains(INDEXED_ALERT), "{e}"); + assert_eq!((layer_count(&s), past(&s)), (n, depth), "nothing changes"); +} + +#[test] +fn bad_params_are_errors_not_panics() { + let mut s = Session::new(); + assert!(s.execute(CMD, dab("levels")).is_err(), "no document"); + let mut s = doc(); + for p in [ + json!(null), + json!([]), + json!("levels"), + json!({}), + json!({"kind": "levels"}), + json!({"kind": "levels", "points": []}), + json!({"kind": "levels", "points": "x"}), + json!({"kind": "levels", "points": [[f64::MAX, 1.0]]}), + json!({"kind": "levels", "points": [[1e30, -1e30]]}), + json!({"kind": "light", "points": [[10, 10]]}), + json!({"kind": "grain", "points": [[10, 10]]}), + json!({"kind": "nope", "points": [[10, 10]]}), + json!({"kind": 7, "points": [[10, 10]]}), + json!({"kind": "levels", "subtract": "yes", "points": [[10, 10]]}), + json!({"kind": "levels", "points": [[10, 10]], "size": -5}), + json!({"kind": "levels", "points": [[10, 10]], "size": 1e12}), + json!({"kind": "levels", "points": [[10, 10]], "zoom": -1}), + json!({"kind": "levels", "points": [[10, 10]], "preset": "no such preset"}), + json!({"kind": "levels", "points": [[10, 10]], "brush": {"size": "big"}}), + ] { + let _ = s.execute(CMD, p.clone()); + } + for p in [json!({"kind": "light", "points": [[10, 10]]}), json!({"kind": "nope", "points": [[10, 10]]}), json!({"kind": "levels", "subtract": 1})] { + let n = layer_count(&s); + assert!(s.execute(CMD, p).is_err()); + assert_eq!(layer_count(&s), n, "a refused stroke leaves no layer behind"); + } + // Painting off the canvas still makes the layer, with nothing painted. + let mut s = doc(); + s.execute(CMD, json!({"kind": "levels", "points": [[-5000, -5000]]})).unwrap(); + assert_eq!(mask_at(&s, 0, 0), 0.0); +} diff --git a/crates/engine/src/cmd/atn_cmds/adjustments.rs b/crates/engine/src/cmd/atn_cmds/adjustments.rs index 21bebcb5c8..6115166271 100644 --- a/crates/engine/src/cmd/atn_cmds/adjustments.rs +++ b/crates/engine/src/cmd/atn_cmds/adjustments.rs @@ -242,12 +242,12 @@ fn color_balance_to(p: &Value) -> Option { } const BW: &[F] = &[ - F("Rd ", "reds", Kind::Long), - F("Yllw", "yellows", Kind::Long), - F("Grn ", "greens", Kind::Long), - F("Cyn ", "cyans", Kind::Long), - F("Bl ", "blues", Kind::Long), - F("Mgnt", "magentas", Kind::Long), + F("Rd ", "reds", Kind::ExactLong), + F("Yllw", "yellows", Kind::ExactLong), + F("Grn ", "greens", Kind::ExactLong), + F("Cyn ", "cyans", Kind::ExactLong), + F("Bl ", "blues", Kind::ExactLong), + F("Mgnt", "magentas", Kind::ExactLong), F("useTint", "tint", Kind::Bool), F("tintColor", "tintColor", Kind::Color), ]; diff --git a/crates/engine/src/cmd/atn_cmds/steps_doc.rs b/crates/engine/src/cmd/atn_cmds/steps_doc.rs index 671d9153fe..2625254fb0 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_doc.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_doc.rs @@ -527,6 +527,11 @@ pub(super) fn image_size_to(_: &str, p: &Value) -> Option { Some(Value::String(unit)) if unit == "pt" => PT, _ => return None, }; + // Native playback validates a supplied percentage even when explicit sides override it. + // Dropping an invalid percentage would turn a refused action into a different, valid edit. + if p.get("percent").is_some_and(|value| !value.is_null() && value.as_f64().is_none_or(|pc| !pc.is_finite() || pc <= 0.0)) { + return None; + } // Resolution only with Resample on imports as keep-print-size; a command without it cannot be told apart. if jnum(p, "resolution").is_some() && jnum(p, "width").is_none() @@ -560,7 +565,18 @@ pub(super) fn image_size_to(_: &str, p: &Value) -> Option { return None; } if let Some(pc) = jnum(p, "percent").filter(|_| !resolution_only) { - d = d.with("Wdth", pct(pc)).with("Hght", pct(pc)).with("CnsP", D::Boolean(true)); + // An explicit side wins in the native command; never write duplicate dimension keys. + let width_percent = jnum(p, "width").is_none(); + let height_percent = jnum(p, "height").is_none(); + if width_percent { + d = d.with("Wdth", pct(pc)); + } + if height_percent { + d = d.with("Hght", pct(pc)); + } + if width_percent || height_percent { + d = d.with("CnsP", D::Boolean(width_percent && height_percent)); + } } if let Some(w) = jnum(p, "width").filter(|_| !resolution_only) { if unit == PT && w <= 0.0 { diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index 7cbd32b06d..59a7a66b16 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -2445,6 +2445,73 @@ fn black_white_adjustment_layer_saves_as_photoshops_class_and_old_class_still_im assert_eq!(t.actions.list.actions()[0].steps[1].params["reds"], 17, "{r}"); } +/// #11517: a native Black & White coefficient may be fractional, but an ATN long cannot. +#[test] +fn black_white_fractional_coefficients_refuse_lossy_export() { + for key in ["reds", "yellows", "greens", "cyans", "blues", "magentas"] { + for id in ["layer.newAdjustmentLayer.blackWhite", "image.adjustments.blackWhite", "layer.setAdjustment"] { + let mut params = json!({key: 40.4}); + if id == "layer.setAdjustment" { + params["kind"] = json!("blackWhite"); + } + let action = Action::new("Fractional BW", vec![ActionStep::new(id, params.clone())]); + let error = export("BW", &[&action], &[], false).unwrap_err(); + assert!(error.contains(id) && error.contains("skipUnsupported"), "{id} {key}: {error}"); + let (bytes, skipped) = export("BW", &[&action], &[], true).unwrap(); + assert_eq!(skipped, vec![Skipped { action: "Fractional BW".into(), step: 0, id: id.into() }]); + assert!(import(&bytes).unwrap().actions[0].steps.is_empty()); + assert_eq!(action.steps[0].params, params, "export must preserve the native action"); + } + } +} + +#[test] +fn black_white_whole_coefficients_and_defaults_round_trip() { + for id in ["layer.newAdjustmentLayer.blackWhite", "image.adjustments.blackWhite", "layer.setAdjustment"] { + for mut params in [ + json!({}), + json!({"reds": 40.0}), + json!({"reds": 17, "yellows": 83, "greens": -12, "cyans": 107, "blues": 51, "magentas": 133, "tint": true, "tintColor": "#c08040"}), + ] { + if id == "layer.setAdjustment" && params == json!({}) { + continue; + } + if id == "layer.setAdjustment" { + params["kind"] = json!("blackWhite"); + } + let action = Action::new("Whole BW", vec![ActionStep::new(id, params.clone())]); + let (bytes, skipped) = export("BW", &[&action], &[], false).unwrap(); + assert!(skipped.is_empty()); + let imported = import(&bytes).unwrap(); + assert!(imported.unsupported.is_empty() && imported.warnings.is_empty()); + let step = &imported.actions[0].steps[0]; + let (back_id, back) = (&step.command, &step.params); + assert_eq!(back_id, id); + for key in ["reds", "yellows", "greens", "cyans", "blues", "magentas"] { + assert_eq!(back.get(key).and_then(Value::as_f64), params.get(key).and_then(Value::as_f64), "{id} {key}: {back}"); + } + for key in ["tint", "tintColor"] { + assert_eq!(back.get(key), params.get(key), "{id} {key}"); + } + } + } +} + +/// The reported fraction remains a real native edit at every supported document depth. +#[test] +fn black_white_native_fraction_keeps_its_pixels_at_every_depth() { + for depth in [8, 16, 32] { + let mut samples = Vec::new(); + for reds in [40.4, 40.0] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1, "height": 1, "background": "#ff0000", "depth": depth})).unwrap(); + s.execute("layer.newAdjustmentLayer.blackWhite", json!({"reds": reds})).unwrap(); + samples.push(photocraft_compose::flatten(&s.active().unwrap().doc).into_px()); + } + assert_ne!(samples[0], samples[1], "{depth}-bit native 40.4 must differ from rounded 40"); + } +} + /// Smart Blur's quality uses Photoshop's `SmBQ` codes (`SBQL`/`SBQM`/`SBQH`): measured in /// Photoshop, the old `Hgh `/`Mdm `/`Low ` play back as its fallback quality. Old codes still read. #[test] @@ -3502,6 +3569,80 @@ fn image_size_resolution_only_does_not_gain_keep_print_size() { assert_eq!(image_size_round_trip(¶ms), None); } +/// Explicit sides override percent in native commands; strict ATN export must keep that edit. +#[test] +fn image_size_explicit_sides_keep_precedence_over_percent() { + for depth in [8, 16, 32] { + for (params, expected) in [ + (json!({"width": 20, "percent": 50, "resample": "nearest"}), (20, 12)), + (json!({"height": 18, "percent": 50, "resample": "nearest"}), (16, 18)), + (json!({"width": 20, "height": 18, "percent": 50, "resample": "nearest"}), (20, 18)), + (json!({"percent": 50, "resample": "nearest"}), (16, 12)), + (json!({"width": 20, "resample": "nearest"}), (20, 15)), + (json!({"height": 18, "resample": "nearest"}), (24, 18)), + (json!({"width": 20, "percent": 50, "resample": "none", "resolution": 144}), (32, 24)), + ] { + let mut native = Session::new(); + native.execute("file.new", json!({"width": 32, "height": 24, "depth": depth})).unwrap(); + native.execute("image.imageSize", params.clone()).unwrap(); + let size = native.active().unwrap().doc.size; + assert_eq!((size.width, size.height), expected, "native {params} at {depth} bits"); + + let mut recorded = Session::new(); + recorded.actions.list.push(Action::new("Resize", vec![ActionStep::new("image.imageSize", params.clone())])).unwrap(); + let before = recorded.actions.list.clone(); + let saved = recorded.execute("actions.save", json!({"action": "Resize"})).unwrap(); + assert_eq!(saved["skipped"], json!([])); + assert_eq!(saved["steps"], 1); + assert_eq!(recorded.actions.list, before); + + let mut replay = Session::new(); + let loaded = replay.execute("actions.load", json!({"data": saved["data"]})).unwrap(); + assert_eq!(loaded["unsupported"], json!([])); + replay.execute("file.new", json!({"width": 32, "height": 24, "depth": depth})).unwrap(); + let played = replay.execute("actions.play", json!({"action": "Resize"})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + assert!(played.get("failed").is_none(), "{played}"); + assert_eq!(replay.active().unwrap().doc.size, size, "ATN {params} at {depth} bits"); + } + } +} + +#[test] +fn image_size_explicit_sides_do_not_hide_invalid_percent() { + for percent in [json!(0), json!(-1), json!("50"), json!(false)] { + let params = json!({"width": 20, "height": 18, "percent": percent, "resample": "nearest"}); + let mut native = Session::new(); + native.execute("file.new", json!({"width": 32, "height": 24})).unwrap(); + assert!(native.execute("image.imageSize", params.clone()).is_err(), "{params}"); + let action = Action::new("Resize", vec![ActionStep::new("image.imageSize", params.clone())]); + assert!(export("Size", &[&action], &[], false).is_err(), "{params}"); + let (_, skipped) = export("Size", &[&action], &[], true).unwrap(); + assert_eq!(skipped.len(), 1, "{params}"); + } +} + +#[test] +fn image_size_dimensions_have_unique_atn_keys() { + for (params, width, height, constrained) in [ + (json!({"width": 20, "percent": 50}), D::UnitFloat { unit: PX, value: 20.0 }, pct(50.0), Some(false)), + (json!({"height": 18, "percent": 50}), pct(50.0), D::UnitFloat { unit: PX, value: 18.0 }, Some(false)), + (json!({"width": 20, "height": 18, "percent": 50}), D::UnitFloat { unit: PX, value: 20.0 }, D::UnitFloat { unit: PX, value: 18.0 }, None), + (json!({"percent": 50}), pct(50.0), pct(50.0), Some(true)), + ] { + let action = Action::new("Resize", vec![ActionStep::new("image.imageSize", params.clone())]); + let (bytes, skipped) = export("Size", &[&action], &[], false).unwrap(); + assert!(skipped.is_empty()); + let file = atn::parse(&bytes).unwrap(); + let d = file.actions[0].items[0].descriptor.as_ref().unwrap(); + for (key, value) in [("Wdth", width), ("Hght", height)] { + assert_eq!(d.items.iter().filter(|(id, _)| id.is(key)).count(), 1, "{key}: {params}"); + assert_eq!(d.get(key), Some(&value), "{key}: {params}"); + } + assert_eq!(get_bool(d, "CnsP"), constrained, "{params}"); + } +} + #[test] fn image_size_intentional_controls_still_round_trip() { for params in [ diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 7aaf0d026a..356b1222d6 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -275,6 +275,12 @@ pub(crate) fn doc_cmyk_space(s: &Session) -> Option) -> Result { + stroke_with(s, cmd, p, label, brush, pts, false) +} + /// Stroke with a resolved brush onto the target layer (pixels or mask). fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushSettings, pts: Vec, auto_erase: bool) -> Result { let raw_bg = s.tools.background; diff --git a/crates/engine/src/cmd/channel_cmds.rs b/crates/engine/src/cmd/channel_cmds.rs index 17508a3106..78303b0201 100644 --- a/crates/engine/src/cmd/channel_cmds.rs +++ b/crates/engine/src/cmd/channel_cmds.rs @@ -141,7 +141,7 @@ use spot::{is_flat, merge, merge_spot, mergeable, split}; use targeting::{SLOT_KEY, target_cmd, target_slot}; pub(crate) use targeting::{ Target, channel_surface_for_filter, clear_channel, clear_color_channel, color_restriction, edits_channel, filter_mask_layer, inject_target, invert_region, - is_channel_target, is_spot_target, mask_target_enabled, restrict_to_color, routed, target_of, target_surface, targeted_channel, + is_channel_target, is_spot_target, mask_target_enabled, restrict_to_color, routed, target_layer_mask, target_of, target_surface, targeted_channel, }; pub use targeting::{follows_filter_mask, follows_target, follows_vector_mask_target, gray_target, read_target_surface}; pub use tone_target::{ToneTarget, resolve_tone_target}; diff --git a/crates/engine/src/cmd/channel_cmds/targeting.rs b/crates/engine/src/cmd/channel_cmds/targeting.rs index 80215708f7..b4e7880c5e 100644 --- a/crates/engine/src/cmd/channel_cmds/targeting.rs +++ b/crates/engine/src/cmd/channel_cmds/targeting.rs @@ -399,6 +399,11 @@ pub(crate) fn edits_channel(s: &Session) -> bool { }) } +/// Target the active layer's mask, as clicking its thumbnail does. +pub(crate) fn target_layer_mask(s: &mut Session) { + target(s, ChannelTarget::LayerMask); +} + /// Make `t` the edit target and show it the way Photoshop does when its row is clicked. pub(super) fn target(s: &mut Session, t: ChannelTarget) { if let Some(st) = s.active_mut() { diff --git a/crates/engine/src/cmd/color_cmds/profile_dither.rs b/crates/engine/src/cmd/color_cmds/profile_dither.rs index 791374e30a..82874d27fe 100644 --- a/crates/engine/src/cmd/color_cmds/profile_dither.rs +++ b/crates/engine/src/cmd/color_cmds/profile_dither.rs @@ -136,8 +136,8 @@ fn dither_tile(s: &Surface, out: &Surface, t: &Transform, bounds: Rect, c: TileC *d = f32::from(*s) / 255.0; } t.eval_fast(&input[..ni], &mut output[..no]).map_err(super::cms_err)?; - // The hash can return 1.0; recenter its 65536 bins strictly inside (0, 1). - let threshold = (f64::from(photocraft_color::dither_noise(x, y)) * 65535.0 + 0.5) / 65536.0; + // Recenter the hash's 65536 bins strictly inside (0, 1). + let threshold = (f64::from(photocraft_color::dither_noise(x, y)) * 65536.0 + 0.5) / 65536.0; for (d, value) in dp.iter_mut().zip(output).take(no) { *d = quantize(value, threshold); } diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 680d5e404f..7b92b586fa 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -7,12 +7,36 @@ use super::{Arc, Document, EngineError, Result, Session, Value, batch_naming, js /// Inputs of a batch command: `"input"` is a folder or an array of files. pub(crate) fn batch_inputs(p: &Value, cmd: &str) -> Result> { match p.get("input").or_else(|| p.get("files")) { - Some(Value::Array(a)) => Ok(a.iter().filter_map(Value::as_str).map(str::to_string).collect()), + Some(Value::Array(a)) => a + .iter() + .enumerate() + .map(|(i, v)| { + v.as_str() + .map(str::to_string) + .ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("input file {} must be a path string", i + 1) }) + }) + .collect(), Some(Value::String(dir)) => list_images(dir), _ => Err(EngineError::BadParams { cmd: cmd.into(), msg: "missing \"input\" (folder or array of files)".into() }), } } +#[test] +fn batch_rejects_a_non_path_input_before_writing() { + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("source.png"); + let image = photocraft_codecs::Image::from_u8(4, 4, photocraft_codecs::ChannelLayout::Rgb, vec![255; 48]).unwrap(); + let bytes = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + std::fs::write(&input, bytes).unwrap(); + for (cmd, format) in [("file.automate.batch", "png"), ("file.scripts.imageProcessor", "jpg")] { + let output = dir.path().join(format); + let mut s = Session::new(); + let err = s.execute(cmd, json!({"steps": [], "input": [&input, 17], "output": &output, "format": format})).unwrap_err(); + assert!(matches!(&err, EngineError::BadParams { cmd: name, msg } if name == cmd && msg == "input file 2 must be a path string"), "{err}"); + assert!(!output.exists()); + } +} + /// One input of a batch run: the file, and the folder it sits in relative to the input folder /// (`""` at the top level, `"a/b"` two levels down), which its result keeps under `output`. #[derive(Clone, Debug, PartialEq)] diff --git a/crates/engine/src/cmd/fill_cmds/tests.rs b/crates/engine/src/cmd/fill_cmds/tests.rs index e14eda7192..8247c78c8c 100644 --- a/crates/engine/src/cmd/fill_cmds/tests.rs +++ b/crates/engine/src/cmd/fill_cmds/tests.rs @@ -84,6 +84,25 @@ fn opacity_mode_and_preserve_transparency() { })); } +#[test] +fn opaque_dissolve_fill_covers_the_largest_noise_sample_at_every_depth() { + // (8, 246) hashes to the largest noise sample: it must still be below full coverage. + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 9, "height": 247, "depth": depth, "background": "transparent"})).unwrap(); + s.execute(CMD, json!({"contents": "white", "mode": "dissolve", "opacity": 0})).unwrap(); + assert_eq!(px(&s, 8, 246)[3], 0.0, "{depth}-bit zero-opacity fill"); + + s.execute(CMD, json!({"contents": "white", "mode": "dissolve", "opacity": 100})).unwrap(); + assert_eq!(px(&s, 8, 246), [1.0; 4], "{depth}-bit opaque fill at the largest noise sample"); + assert_eq!(px(&s, 0, 0), [1.0; 4], "{depth}-bit opaque fill at an ordinary sample"); + assert!(s.undo()); + assert_eq!(px(&s, 8, 246)[3], 0.0, "{depth}-bit undo"); + assert!(s.redo()); + assert_eq!(px(&s, 8, 246), [1.0; 4], "{depth}-bit redo"); + } +} + #[test] fn preserve_transparency_blends_source_atop_on_semi_transparent_pixels() { // White at 50%, then black at 50% keeping alpha: Photoshop gives (127,127,127,128), the diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index c87de3a02a..7aa0608111 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -257,7 +257,8 @@ fn image_size(s: &mut Session, p: &Value) -> Result { ph = scaled_dimension(p, "height", scale, "image.imageSize")?; } // `percent` scales both sides (what a Photoshop action records as "200%"); an explicit side wins. - if let Some(pc) = p.get("percent") { + // A null `percent` is omitted, like a null side or resolution. + if let Some(pc) = p.get("percent").filter(|value| !value.is_null()) { let pc = pc.as_f64().filter(|v| v.is_finite() && *v > 0.0).ok_or_else(|| bad("image.imageSize", "`percent` must be a positive number"))?; pw = pw.or(Some(ow as f64 * pc / 100.0)); ph = ph.or(Some(oh as f64 * pc / 100.0)); diff --git a/crates/engine/src/color_channels.rs b/crates/engine/src/color_channels.rs index d95007c70f..4212b33187 100644 --- a/crates/engine/src/color_channels.rs +++ b/crates/engine/src/color_channels.rs @@ -200,7 +200,7 @@ fn restrict_surface_impl(before: &Surface, after: &mut Surface, colors: ColorCha .map(|(c, _)| *c) .chain(before.tiles().filter(|(c, _)| after.tile(**c).is_none()).map(|(c, _)| *c)) .collect(); - restrict_coords(before, after, colors, coords)?; + restrict_coords(before, after, colors, coords, None)?; after.prune(); Ok(()) } @@ -218,10 +218,18 @@ pub fn restrict_region(before: &Surface, after: &mut Surface, colors: ColorChann _ => true, }) .collect(); - restrict_coords(before, after, colors, coords) + restrict_coords(before, after, colors, coords, Some(damage)) } -fn restrict_coords(before: &Surface, after: &mut Surface, colors: ColorChannels, coords: BTreeSet) -> Result<()> { +/// Restore the unselected components of each tile in `coords`, inside `area` only, or across the +/// whole tile when `area` is `None`. +fn restrict_coords( + before: &Surface, + after: &mut Surface, + colors: ColorChannels, + coords: BTreeSet, + area: Option, +) -> Result<()> { if before.default_bytes() != after.default_bytes() { return Err(EngineError::Other("a colour-channel edit cannot change unstored pixels".into())); } @@ -231,15 +239,27 @@ fn restrict_coords(before: &Surface, after: &mut Surface, colors: ColorChannels, if stride == 0 { return Err(EngineError::Other("invalid pixel format".into())); } + let row = (photocraft_geom::TILE_SIZE as usize).saturating_mul(stride); for c in coords { let old = before.tile(c); let old_bytes = old.map(|t| t.bytes()); let tile = after.try_tile_mut(c).map_err(|e| EngineError::Other(e.to_string()))?; - for (i, pixel) in tile.bytes_mut().chunks_exact_mut(stride).enumerate() { - let original = old_bytes.as_deref().and_then(|t| t.get(i * stride..(i + 1) * stride)).unwrap_or(before.default_bytes()); - for (ch, (out, src)) in pixel.chunks_exact_mut(bytes).zip(original.chunks_exact(bytes)).enumerate() { - if !colors.contains(ch) { - out.copy_from_slice(src); + let tile_rect = c.rect(); + let part = area.map_or(tile_rect, |a| a.intersect(&tile_rect)); + if !part.is_empty() { + let mut dest = tile.bytes_mut(); + let (x0, x1) = ((part.x0 - tile_rect.x0) as usize, (part.x1 - tile_rect.x0) as usize); + for y in (part.y0 - tile_rect.y0) as usize..(part.y1 - tile_rect.y0) as usize { + let span = y.saturating_mul(row).saturating_add(x0.saturating_mul(stride))..y.saturating_mul(row).saturating_add(x1.saturating_mul(stride)); + let Some(pixels) = dest.get_mut(span.clone()) else { continue }; + let originals = old_bytes.as_deref().and_then(|t| t.get(span)); + for (i, pixel) in pixels.chunks_exact_mut(stride).enumerate() { + let original = originals.and_then(|t| t.get(i * stride..(i + 1) * stride)).unwrap_or(before.default_bytes()); + for (ch, (out, src)) in pixel.chunks_exact_mut(bytes).zip(original.chunks_exact(bytes)).enumerate() { + if !colors.contains(ch) { + out.copy_from_slice(src); + } + } } } } diff --git a/crates/engine/src/color_channels/tone.rs b/crates/engine/src/color_channels/tone.rs index 62ecf3174b..06618da39a 100644 --- a/crates/engine/src/color_channels/tone.rs +++ b/crates/engine/src/color_channels/tone.rs @@ -19,6 +19,10 @@ struct Component { lab_invert: bool, } +/// Building all 65,536 U16 entries amortizes well on large edits. Tiny selections instead use tile-local buffers, +/// avoiding a full table's setup cost for a handful of pixels. +const U16_TABLE_AREA: u64 = 65_536; + struct IntegerTable { adjusted: Vec, encoded: Vec<[u8; 4]>, @@ -27,6 +31,18 @@ struct IntegerTable { /// Evaluate independent tones together, cloning each destination tile once. Untouched native /// samples and the surface default retain their original bytes, including NaN payloads. pub(super) fn adjust(surface: &mut Surface, colors: ColorChannels, adjustment: &Adjustment, selection: Option<&Surface>, bounds: Rect) -> Result<()> { + adjust_with(surface, colors, adjustment, selection, bounds, U16_TABLE_AREA) +} + +/// [`adjust`] with the smallest edit area, in pixels, that builds a U16 table. +fn adjust_with( + surface: &mut Surface, + colors: ColorChannels, + adjustment: &Adjustment, + selection: Option<&Surface>, + bounds: Rect, + table_area: u64, +) -> Result<()> { let fmt = surface.format(); if colors.indices().any(|k| k >= fmt.mode.color_channels()) { return Err(EngineError::Other("invalid colour component".into())); @@ -39,10 +55,8 @@ pub(super) fn adjust(surface: &mut Surface, colors: ColorChannels, adjustment: & (SampleType::F32, _) | (SampleType::U16, Adjustment::Threshold { .. } | Adjustment::Posterize { .. }) => Some(fmt.sample), _ => None, }; - // Building all 65,536 U16 entries amortizes well on large edits. Tiny selections instead - // use tile-local buffers, avoiding a full table's setup cost for a handful of pixels. let area = selection.filter(|s| s.default_pixel().first().is_none_or(|v| *v <= 0.0)).map_or(bounds, |s| s.content_bounds().intersect(&bounds)); - let use_table = fmt.sample == SampleType::U8 || (fmt.sample == SampleType::U16 && u64::from(area.width()) * u64::from(area.height()) >= 65_536); + let use_table = fmt.sample == SampleType::U8 || (fmt.sample == SampleType::U16 && u64::from(area.width()) * u64::from(area.height()) >= table_area); let mut components: Vec = Vec::new(); for index in colors.indices() { let scalar = scalar_adjustment(adjustment, index); @@ -267,8 +281,11 @@ mod tests { for (si, sample) in [SampleType::U8, SampleType::U16, SampleType::F32].into_iter().enumerate() { let fmt = PixelFormat::new(mode, sample, true); let mut source = Surface::with_default(fmt, &vec![0.3; fmt.channels()]); - // 256 x 256 is exactly the U16 table's area threshold (`use_table`), so the table path still runs (#15652). - let bounds = Rect::from_xywh(-128, -128, 256, 256); + // A small area that extends past the data and the masks on every side, so default pixels around them are + // adjusted too. The U16 table threshold is exactly its area: the whole area and the holes mask take the + // table path, the sparse mask (content bounds below it) the tiled path (#15652). + let bounds = Rect::from_xywh(-8, 0, 48, 40); + let table_area = u64::from(bounds.width()) * u64::from(bounds.height()); let data: Vec<_> = (0..32 * 24 * fmt.channels()) .map(|i| { let v = (i * 37 % 257) as f32 / 256.0; @@ -287,11 +304,16 @@ mod tests { if ti != (mi + si) % 3 && !(mode == ColorMode::Rgb && sample == SampleType::U16 && selection.is_none()) { continue; } - for adjustment in &adjustments { + // Each adjustment meets every mode once and every sample type once: Invert at Lab/F32 (`lab_invert`), + // Threshold at RGB/U16 and Posterize at Lab/U16 (the U16 `depth`), Levels and Curves at U16 (table). + for (ai, adjustment) in adjustments.iter().enumerate() { + if (ai + mi) % 3 != si { + continue; + } let mut expected = source.clone(); let mut actual = source.clone(); super::super::adjust_reference(&mut expected, colors, adjustment, selection, bounds).unwrap(); - adjust(&mut actual, colors, adjustment, selection, bounds).unwrap(); + adjust_with(&mut actual, colors, adjustment, selection, bounds, table_area).unwrap(); assert!(expected == actual, "{mode:?} {sample:?} {adjustment:?} selection={}", selection.is_some()); } } diff --git a/crates/engine/src/color_channels/tone_dialog_tests.rs b/crates/engine/src/color_channels/tone_dialog_tests.rs index c419da9a14..057c5c0ddc 100644 --- a/crates/engine/src/color_channels/tone_dialog_tests.rs +++ b/crates/engine/src/color_channels/tone_dialog_tests.rs @@ -15,13 +15,16 @@ fn tone_dialog_normalization_matches_native_execution() { continue; } let colors = ColorChannels::from_indices((0..count).filter(|k| bits & (1 << k) != 0), count).unwrap(); - for raw in [ + for (ri, raw) in [ json!({"gray":{"gamma":2},"gamma":1.25,"inBlack":8}), json!({"gray":{"gamma":1.234567},"gamma":1.25,"inBlack":8.123456}), json!({"gray":"ignored","points":[[0,20],[255,240]]}), json!({"gray":[[0,0],[100.123456,200.654321],[255,255]]}), json!({"gray":(0..256).map(|i| (i * 37 % 256) as f32).collect::>(),"pencil":true,"smooth":3}), - ] { + ] + .into_iter() + .enumerate() + { let kind = if raw.get("gamma").is_some() { "levels" } else { "curves" }; let mut raw = raw; for (index, key) in keys.iter().enumerate() { @@ -44,17 +47,18 @@ fn tone_dialog_normalization_matches_native_execution() { assert_eq!(canonical_records[*key], original_records[*key], "{mode:?} {bits} {kind}: unselected component {index}"); } let parsed = |p| tone_adjustment(kind, p, crate::adjust_params::from_params(kind, p, None, mode).unwrap(), mode, colors).unwrap(); - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - let bounds = Rect::new(0, 0, 8, 8); - let mut original = Surface::new(PixelFormat::new(mode, depth, true)); - let values: Vec<_> = (0..count).map(|i| (i as f32 + 1.0) / 7.0).chain([0.65]).collect(); - original.fill_rect(bounds, &values); - let mut expected = original.clone(); - tone::adjust(&mut expected, colors, &parsed(&raw), None, bounds).unwrap(); - let mut actual = original; - tone::adjust(&mut actual, colors, &parsed(&canonical), None, bounds).unwrap(); - assert_eq!(actual, expected, "{mode:?} {depth:?} {bits} {kind}"); - } + // One depth per (subset, record), rotating with their sum: every mode and kind still reaches every + // depth across the subsets. + let depth = [SampleType::U8, SampleType::U16, SampleType::F32][(bits as usize + ri) % 3]; + let bounds = Rect::new(0, 0, 8, 8); + let mut original = Surface::new(PixelFormat::new(mode, depth, true)); + let values: Vec<_> = (0..count).map(|i| (i as f32 + 1.0) / 7.0).chain([0.65]).collect(); + original.fill_rect(bounds, &values); + let mut expected = original.clone(); + tone::adjust(&mut expected, colors, &parsed(&raw), None, bounds).unwrap(); + let mut actual = original; + tone::adjust(&mut actual, colors, &parsed(&canonical), None, bounds).unwrap(); + assert_eq!(actual, expected, "{mode:?} {depth:?} {bits} {kind}"); } } } diff --git a/crates/engine/src/install.rs b/crates/engine/src/install.rs index b9faf312e0..4191b59fae 100644 --- a/crates/engine/src/install.rs +++ b/crates/engine/src/install.rs @@ -56,6 +56,7 @@ const TABLES: &[Table] = &[ ("actions_edit_cmds", crate::actions_edit_cmds::specs), ("swatch_cmds", crate::swatch_cmds::specs), ("retouch_cmds", crate::retouch_cmds::specs), + ("adjustment_brush_cmds", crate::adjustment_brush_cmds::specs), ("redeye_cmds", crate::redeye_cmds::specs), ("image_cmds", crate::image_cmds::specs), ("perspective_crop_cmds", crate::perspective_crop_cmds::specs), diff --git a/crates/engine/src/install/command_ids.txt b/crates/engine/src/install/command_ids.txt index 58b40d1444..b482eadd30 100644 --- a/crates/engine/src/install/command_ids.txt +++ b/crates/engine/src/install/command_ids.txt @@ -407,6 +407,7 @@ paint.sharpen paint.smudge paint.historyBrush paint.artHistoryBrush +paint.adjustmentBrush paint.redEye image.imageSize image.canvasSize diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index f23eabd7d5..02d7c2605a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -70,6 +70,7 @@ pub use cmd as commands; pub use cmd::actions_cmds; pub use cmd::actions_edit_cmds; pub use cmd::adjust_cmds; +pub use cmd::adjustment_brush_cmds; pub use cmd::align_cmds; pub use cmd::analysis_cmds; pub use cmd::artboard_cmds; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index bd1e3e41ed..4bdaf390f3 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -1390,6 +1390,7 @@ pub const DEFAULT_TOOLBAR: &[&[&str]] = &[ &["Eraser", "BackgroundEraser", "MagicEraser"], &["Gradient", "PaintBucket"], &["Blur", "Sharpen", "Smudge"], + &["AdjustmentBrush"], &["Dodge", "Burn", "Sponge"], &["Pen", "FreeformPen", "CurvaturePen", "AddAnchorPoint", "DeleteAnchorPoint", "ConvertPoint"], &["Type", "VerticalType", "VerticalTypeMask", "HorizontalTypeMask"], diff --git a/crates/engine/src/shell_commands.rs b/crates/engine/src/shell_commands.rs index 278a5292b1..718454fba3 100644 --- a/crates/engine/src/shell_commands.rs +++ b/crates/engine/src/shell_commands.rs @@ -140,6 +140,7 @@ pub const TOOLS: &[(&str, &str, Option<&str>)] = &[ ("tools.select.blur", "Blur Tool", None), ("tools.select.sharpen", "Sharpen Tool", None), ("tools.select.smudge", "Smudge Tool", None), + ("tools.select.adjustmentBrush", "Adjustment Brush Tool", None), ("tools.select.dodge", "Dodge Tool", Some("O")), ("tools.select.burn", "Burn Tool", Some("O")), ("tools.select.sponge", "Sponge Tool", Some("O")), diff --git a/crates/engine/tests/it/atn_mapped_identifiers.rs b/crates/engine/tests/it/atn_mapped_identifiers.rs index daed23a2e6..6fb8097bb2 100644 --- a/crates/engine/tests/it/atn_mapped_identifiers.rs +++ b/crates/engine/tests/it/atn_mapped_identifiers.rs @@ -94,6 +94,31 @@ fn review_point_resize_exports_with_null_optional_values() { } } +/// A null percentage is omitted at playback too, so an exported step and the native command agree. +#[test] +fn review_null_percent_is_omitted_by_the_native_resize() { + for params in + [json!({"width":72,"units":"pt","resample":"nearest","scaleStyles":false,"percent":null}), json!({"width":30,"resample":"nearest","percent":null})] + { + let mut without = params.clone(); + without.as_object_mut().unwrap().remove("percent"); + let mut expected = sized_document(20, 10, 144); + expected.execute("image.imageSize", without).unwrap(); + let mut actual = sized_document(20, 10, 144); + actual.execute("image.imageSize", params.clone()).expect("a null percent must not refuse the resize"); + assert_eq!(actual.active().unwrap().doc.size, expected.active().unwrap().doc.size); + let action = Action::new("Recorded", vec![ActionStep::new("image.imageSize", params)]); + let (bytes, skipped) = atn_cmds::export("Identifiers", &[&action], &[], false).unwrap(); + assert!(skipped.is_empty()); + let imported = atn_cmds::import(&bytes).unwrap(); + let mut replayed = sized_document(20, 10, 144); + replayed.actions.list = ActionList::from_file(ActionsFile::new(imported.actions, Vec::new())); + let result = replayed.execute("actions.play", json!({"action":"Recorded"})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert_eq!(replayed.active().unwrap().doc.size, expected.active().unwrap().doc.size); + } +} + /// The native default resampler must be explicit in a physical-size recording. #[test] fn review_point_resize_exports_the_default_resampler() { diff --git a/crates/engine/tests/it/camera_raw_baseline_pin.rs b/crates/engine/tests/it/camera_raw_baseline_pin.rs index a7152da043..e0e26cd252 100644 --- a/crates/engine/tests/it/camera_raw_baseline_pin.rs +++ b/crates/engine/tests/it/camera_raw_baseline_pin.rs @@ -148,6 +148,50 @@ fn camera_raw_smart_filter_migrates_to_shared_develop_settings() { assert_eq!(migrated.settings.vignette.style, craft_develop_model::VignetteStyle::HighlightPriority); } +#[test] +fn camera_raw_migration_preserves_exposure_presence_after_native_reopen() { + use std::sync::Arc; + + use craft_develop_model::{DevelopSettings, Process}; + use photocraft_color::{BlendMode, ColorMode, SampleType}; + use photocraft_doc::{Document, Layer, Size, SmartFilter, SmartObject, SmartSource}; + use photocraft_geom::Affine; + + // Original synthetic content. Exercise the native serializer, not the PSD importer. + let size = Size::new(2, 2); + let mut source = Session::new(); + source.execute("file.new", json!({"width": 2, "height": 2, "depth": 16})).unwrap(); + let embedded = Arc::new(photocraft_format::save_to_bytes(&source.active().unwrap().doc, &Default::default()).unwrap()); + let mut base = DevelopSettings { process: Process::V8.version(), ..Default::default() }; + base.light.exposure = -0.75; + base.light.contrast = 12.0; + for (params, expected) in [(json!({"encodingGamma": 1.8}), -0.75), (json!({"encodingGamma": 1.8, "exposure": 0.0}), 0.0)] { + let source = SmartSource::Embedded { file_name: "generated.pcraft".into(), bytes: embedded.clone() }; + let mut smart = SmartObject::new(source, Affine::IDENTITY, None); + smart.smart_filters.push(SmartFilter { + command: "filter.cameraRaw".into(), + params: params.clone(), + blend: BlendMode::Normal, + opacity: 1.0, + visible: true, + }); + let mut doc = Document::new("Saved Camera Raw exposure", size, ColorMode::Rgb, SampleType::U16); + doc.layers.push(Layer::new("Stored filter", LayerContent::Smart(smart))); + + let saved = photocraft_format::save_to_bytes(&doc, &Default::default()).unwrap(); + let reopened = photocraft_format::load_from_bytes(&saved).unwrap(); + let LayerContent::Smart(smart) = &reopened.layers[0].content else { panic!("expected reopened Smart Object") }; + let [filter] = smart.smart_filters.as_slice() else { panic!("expected one stored Camera Raw filter") }; + assert_eq!(filter.command, "filter.cameraRaw"); + assert_eq!(filter.params, params); + let migrated = photocraft_algo::camera_raw::migrate_to_develop_settings(&base, &filter.params).unwrap(); + assert!(migrated.unmapped_fields.is_empty(), "{:?}", migrated.unmapped_fields); + assert_eq!(migrated.settings.process, base.process); + assert_eq!(migrated.settings.light.exposure, expected); + assert_eq!(migrated.settings.light.contrast, base.light.contrast); + } +} + #[test] fn reopened_camera_raw_smart_filter_keeps_legacy_close_curve_knots() { use std::sync::Arc; diff --git a/crates/engine/tests/it/cmyk_flatten_profile.rs b/crates/engine/tests/it/cmyk_flatten_profile.rs index bb088ec1a6..0afa7d029e 100644 --- a/crates/engine/tests/it/cmyk_flatten_profile.rs +++ b/crates/engine/tests/it/cmyk_flatten_profile.rs @@ -43,6 +43,8 @@ fn profile() -> Arc> { craft_cms::synth::cmyk_profile(&craft_cms::synth::CmykParams { description: "Test Uncoated".into(), tvi: [0.26, 0.26, 0.26, 0.3], + grid_a2b: 5, + grid_b2a: 9, ..Default::default() }) .unwrap() diff --git a/crates/engine/tests/it/live_dab_matches_replay.rs b/crates/engine/tests/it/live_dab_matches_replay.rs index f9003d66d3..42242cd010 100644 --- a/crates/engine/tests/it/live_dab_matches_replay.rs +++ b/crates/engine/tests/it/live_dab_matches_replay.rs @@ -31,54 +31,66 @@ fn pixels(s: &Session) -> Vec { st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().read_region(st.doc.bounds()) } +/// The six sequential-dab commands every test here strokes with. +const CMDS: [&str; 6] = ["paint.smudge", "paint.blur", "paint.sharpen", "paint.dodge", "paint.burn", "paint.sponge"]; + +/// The tests cross commands with one more axis (stroke case, colour mode or target) and depth +/// pairwise: each command meets each value of the axis once, at the depth `(i + j) % 3` picks, so +/// every command and every value of the axis still runs at 8, 16 and 32 bits (32 is the float path). +const DEPTHS: [u32; 3] = [8, 16, 32]; + +/// The commands that meet value `i` of the other axis at `DEPTHS[d]`. +fn cmds_at(i: usize, d: usize) -> impl Iterator { + CMDS.into_iter().enumerate().filter(move |(j, _)| (i + j) % 3 == d).map(|(_, cmd)| cmd) +} + #[test] fn pressure_shape_and_smoothing_match_replay() { let mut failures = Vec::new(); - for cmd in ["paint.smudge", "paint.blur", "paint.sharpen", "paint.dodge", "paint.burn", "paint.sponge"] { - for case in ["pressure", "locked", "ellipse", "smoothing", "scattering"] { - for depth in [8, 16, 32] { - let mut s = setup(depth, "rgb"); - match case { - "locked" => { - s.edit("lock alpha", |doc, active| { - doc.layer_mut(active.unwrap()).unwrap().locks.transparency = true; - Ok(()) - }) - .unwrap(); - } - "ellipse" => { - s.tools.brush.roundness = 0.2; - s.tools.brush.angle = 37.0; - } - "smoothing" => { - s.tools.brush.smoothing.amount = 0.6; - } - "scattering" => { - s.tools.brush.scattering.enabled = true; - s.tools.brush.scattering.scatter.jitter = 1.0; - } - _ => {} + for (i, cmd) in CMDS.into_iter().enumerate() { + for (j, case) in ["pressure", "locked", "ellipse", "smoothing", "scattering"].into_iter().enumerate() { + let depth = DEPTHS[(i + j) % 3]; + let mut s = setup(depth, "rgb"); + match case { + "locked" => { + s.edit("lock alpha", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().locks.transparency = true; + Ok(()) + }) + .unwrap(); } - let points = [[40.0, 40.0, 0.1], [65.0, 50.0, 0.4], [100.0, 60.0, 1.0], [140.0, 70.0, 0.7], [60.0, 40.0, 0.2]]; - let params = json!({"points":points,"size":40,"hardness":70,"strength":80,"opacity":55,"spacing":25}); - s.execute(cmd, params.clone()).unwrap(); - let want = pixels(&s); - s.execute("edit.undo", json!({})).unwrap(); - let mut start = params.clone(); - start["points"] = json!([points[0]]); - let mut live = LiveDab::begin(&s, cmd, &start).unwrap(); - for q in &points[1..] { - live.push(&[StrokePoint::new(q[0], q[1], q[2] as f32)]).unwrap(); + "ellipse" => { + s.tools.brush.roundness = 0.2; + s.tools.brush.angle = 37.0; } - s.offer_live_dab(live).unwrap(); - let result = s.execute(cmd, params).unwrap(); - assert_eq!(result["fromLive"], true); - let got = pixels(&s); - let count = got.iter().zip(&want).filter(|(a, b)| a != b).count(); - let max = got.iter().zip(&want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - if count > 0 { - failures.push(format!("{cmd} {case} depth={depth}: {count} channels differ, max={max}")); + "smoothing" => { + s.tools.brush.smoothing.amount = 0.6; } + "scattering" => { + s.tools.brush.scattering.enabled = true; + s.tools.brush.scattering.scatter.jitter = 1.0; + } + _ => {} + } + let points = [[40.0, 40.0, 0.1], [65.0, 50.0, 0.4], [100.0, 60.0, 1.0], [140.0, 70.0, 0.7], [60.0, 40.0, 0.2]]; + let params = json!({"points":points,"size":40,"hardness":70,"strength":80,"opacity":55,"spacing":25}); + s.execute(cmd, params.clone()).unwrap(); + let want = pixels(&s); + s.execute("edit.undo", json!({})).unwrap(); + let mut start = params.clone(); + start["points"] = json!([points[0]]); + let mut live = LiveDab::begin(&s, cmd, &start).unwrap(); + for q in &points[1..] { + live.push(&[StrokePoint::new(q[0], q[1], q[2] as f32)]).unwrap(); + } + s.offer_live_dab(live).unwrap(); + let result = s.execute(cmd, params).unwrap(); + assert_eq!(result["fromLive"], true); + let got = pixels(&s); + let count = got.iter().zip(&want).filter(|(a, b)| a != b).count(); + let max = got.iter().zip(&want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + if count > 0 { + failures.push(format!("{cmd} {case} depth={depth}: {count} channels differ, max={max}")); } } } @@ -87,8 +99,8 @@ fn pressure_shape_and_smoothing_match_replay() { #[test] fn native_modes_selection_and_lock_match_replay() { - for mode in ["rgb", "gray", "cmyk", "lab"] { - for depth in [8, 16, 32] { + for (i, mode) in ["rgb", "gray", "cmyk", "lab"].into_iter().enumerate() { + for (d, depth) in DEPTHS.into_iter().enumerate() { let mut s = setup(depth, mode); s.edit("lock alpha", |doc, active| { doc.layer_mut(active.unwrap()).unwrap().locks.transparency = true; @@ -97,7 +109,7 @@ fn native_modes_selection_and_lock_match_replay() { .unwrap(); s.execute("select.rect", json!({"x":30,"y":20,"width":110,"height":60})).unwrap(); let points = [[-10.0, 30.0], [80.0, 50.0], [160.0, 80.0], [60.0, 60.0]]; - for cmd in ["paint.blur", "paint.sharpen", "paint.dodge", "paint.burn", "paint.sponge", "paint.smudge"] { + for cmd in cmds_at(i, d) { let params = json!({"points":points,"size":30,"hardness":40,"strength":70,"opacity":37}); let expected_damage = s.execute(cmd, params.clone()).unwrap()["damage"].clone(); let want = pixels(&s); @@ -178,7 +190,7 @@ fn pressure_sized_live_dabs_commit_only_the_requested_mask_or_channel() { let values: Vec = (0..120).flat_map(|y| (0..200).map(move |x| ((x * 7 + y * 3) % 31) as f32 / 31.0)).collect(); surface.write_region(photocraft_geom::Rect::new(0, 0, 200, 120), &values); }; - for depth in [8, 16, 32] { + for (d, depth) in DEPTHS.into_iter().enumerate() { let mut s = setup(depth, "rgb"); s.execute("layer.new.layer", json!({})).unwrap(); s.execute("layer.layerMask.revealAll", json!({})).unwrap(); @@ -192,8 +204,8 @@ fn pressure_sized_live_dabs_commit_only_the_requested_mask_or_channel() { }) .unwrap(); let before = s.active().unwrap().doc.clone(); - for target in [json!("mask"), json!({"channel":0}), json!("quickMask")] { - for cmd in ["paint.smudge", "paint.blur", "paint.sharpen", "paint.dodge", "paint.burn", "paint.sponge"] { + for (i, target) in [json!("mask"), json!({"channel":0}), json!("quickMask")].into_iter().enumerate() { + for cmd in cmds_at(i, d) { let points = [[40.0, 40.0, 0.1], [65.0, 50.0, 0.4], [100.0, 60.0, 1.0], [140.0, 70.0, 0.7], [60.0, 40.0, 0.2]]; let params = json!({"target":target,"points":points,"size":40,"hardness":70,"strength":80,"opacity":55,"spacing":25}); s.execute(cmd, params.clone()).unwrap(); diff --git a/crates/engine/tests/it/multi_channel_editing.rs b/crates/engine/tests/it/multi_channel_editing.rs index fbb3de72a6..3290897f28 100644 --- a/crates/engine/tests/it/multi_channel_editing.rs +++ b/crates/engine/tests/it/multi_channel_editing.rs @@ -93,29 +93,35 @@ fn adjustments_filters_and_drawing_preserve_other_encoded_components() { ("paint.artHistoryBrush", json!({"points":[[8,8],[22,12]],"size":9,"tolerance":0})), ("paint.mixerBrush", json!({"points":[[8,8],[22,12]],"size":9,"color":"#ffffff"})), ]; - for mode in ["rgb", "cmyk", "lab"] { - for depth in [8, 16, 32] { - for (cmd, p) in &commands { - let mut s = setup(mode, depth); - subset(&mut s); - let before = surface(&s); - // Color Replacement refuses 32-bit RGB (#11923), the Art History Brush every depth - // but 8 bits (#12637), as the reference application does. - if (*cmd == "paint.colorReplacement" && mode == "rgb" && depth == 32) || (*cmd == "paint.artHistoryBrush" && depth != 8) { - assert!(s.execute(cmd, p.clone()).is_err(), "{mode} {depth} {cmd} is refused"); - assert_eq!(surface(&s), before, "{mode} {depth} {cmd}: nothing changed"); - continue; - } - s.execute(cmd, p.clone()).unwrap_or_else(|e| panic!("{mode} {depth} {cmd}: {e}")); - let after = surface(&s); - unchanged(&before, &after); - assert_ne!(before, after, "{mode} {depth} {cmd} must change selected samples"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(surface(&s), before, "undo {cmd}"); - s.execute("edit.redo", json!({})).unwrap(); - assert_eq!(surface(&s), after, "redo {cmd}"); - } + // Command c runs once, at mode c % 3 and depth (c + c / 3) % 3: the 22 commands cover all nine + // mode and depth pairs, and the four tone adjustments cover every mode and every depth. The two + // extra cases run the other side of each refusal: Color Replacement at RGB 32 bits (refused) and + // the Art History Brush at CMYK 8 bits (allowed). + let modes = ["rgb", "cmyk", "lab"]; + let depths = [8, 16, 32]; + let mut cases: Vec<_> = commands.iter().enumerate().map(|(c, (cmd, p))| (modes[c % 3], depths[(c + c / 3) % 3], *cmd, p.clone())).collect(); + cases.push(("rgb", 32, "paint.colorReplacement", commands[17].1.clone())); + cases.push(("cmyk", 8, "paint.artHistoryBrush", commands[20].1.clone())); + for (mode, depth, cmd, p) in &cases { + let (mode, depth) = (*mode, *depth); + let mut s = setup(mode, depth); + subset(&mut s); + let before = surface(&s); + // Color Replacement refuses 32-bit RGB (#11923), the Art History Brush every depth + // but 8 bits (#12637), as the reference application does. + if (*cmd == "paint.colorReplacement" && mode == "rgb" && depth == 32) || (*cmd == "paint.artHistoryBrush" && depth != 8) { + assert!(s.execute(cmd, p.clone()).is_err(), "{mode} {depth} {cmd} is refused"); + assert_eq!(surface(&s), before, "{mode} {depth} {cmd}: nothing changed"); + continue; } + s.execute(cmd, p.clone()).unwrap_or_else(|e| panic!("{mode} {depth} {cmd}: {e}")); + let after = surface(&s); + unchanged(&before, &after); + assert_ne!(before, after, "{mode} {depth} {cmd} must change selected samples"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(surface(&s), before, "undo {cmd}"); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(surface(&s), after, "redo {cmd}"); } } @@ -150,28 +156,28 @@ fn explicit_target_wins_and_invalid_sets_are_transactional() { #[test] fn live_brush_and_eraser_match_commit_at_all_native_depths() { - for mode in ["rgb", "cmyk", "lab"] { - for depth in [8, 16, 32] { - for erase in [false, true] { - let mut s = setup(mode, depth); - subset(&mut s); - let before = surface(&s); - let mut p = json!({"points":[[6,7,1],[23,15,0.7]],"size":9,"color":"#ffffff","erase":erase,"seed":42}); - let live = LiveStroke::begin(&s, &p).unwrap(); - p["seed"] = json!(live.seed); - let st = s.active().unwrap(); - let shown = live.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone(); - unchanged(&before, &shown); - s.offer_live_stroke(live).unwrap(); - let result = s.execute("paint.stroke", p).unwrap(); - assert_eq!(result["fromLive"], true, "reuse {mode} {depth} {erase}"); - assert!( - surface(&s) == shown, - "live pixels differ: {mode} {depth} {erase}; shown tiles {}, committed {}", - shown.tile_count(), - surface(&s).tile_count() - ); - } + // Depth (mode + erase) % 3: each mode and each depth appears with both erase values. + for (mi, mode) in ["rgb", "cmyk", "lab"].into_iter().enumerate() { + for (ei, erase) in [false, true].into_iter().enumerate() { + let depth = [8, 16, 32][(mi + ei) % 3]; + let mut s = setup(mode, depth); + subset(&mut s); + let before = surface(&s); + let mut p = json!({"points":[[6,7,1],[23,15,0.7]],"size":9,"color":"#ffffff","erase":erase,"seed":42}); + let live = LiveStroke::begin(&s, &p).unwrap(); + p["seed"] = json!(live.seed); + let st = s.active().unwrap(); + let shown = live.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone(); + unchanged(&before, &shown); + s.offer_live_stroke(live).unwrap(); + let result = s.execute("paint.stroke", p).unwrap(); + assert_eq!(result["fromLive"], true, "reuse {mode} {depth} {erase}"); + assert!( + surface(&s) == shown, + "live pixels differ: {mode} {depth} {erase}; shown tiles {}, committed {}", + shown.tile_count(), + surface(&s).tile_count() + ); } } } @@ -181,34 +187,33 @@ fn live_mixer_captures_selected_components_and_matches_commit_and_replay() { use photocraft_engine::brush_cmds::mixer_live::LiveMixer; use photocraft_engine::paint::StrokePoint; - for mode in ["rgb", "cmyk", "lab"] { - for depth in [8, 16, 32] { - let mut s = setup(mode, depth); - subset(&mut s); - let before = surface(&s); - let params = json!({"points":[[6,7,1]],"size":9,"color":"#ffffff","seed":42,"sampleAllLayers":true}); - let mut live = LiveMixer::begin(&s, ¶ms).unwrap(); - let id = s.active().unwrap().active_layer.unwrap(); - let first = live.doc.layer(id).unwrap().surface().unwrap(); - unchanged(&before, first); - assert_ne!(&before, first, "the initial dab paints {mode} {depth}"); - live.push(&[StrokePoint::new(23.0, 15.0, 0.7)]).unwrap(); - let shown = live.doc.layer(id).unwrap().surface().unwrap().clone(); - unchanged(&before, &shown); - // The in-flight stroke keeps its original target even if the panel changes. - s.execute("channel.target", json!({"channel":"composite"})).unwrap(); - let params = live.prepare_commit(&mut s).unwrap(); - assert_eq!(params["target"], json!({"colors":[0,2]})); - assert_eq!(s.execute("paint.mixerBrush", params.clone()).unwrap()["fromLive"], true); - assert_eq!(surface(&s), shown, "displayed pixels are committed {mode} {depth}"); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(surface(&s), before); - s.execute("edit.redo", json!({})).unwrap(); - assert_eq!(surface(&s), shown); - let mut replay = setup(mode, depth); - replay.execute("paint.mixerBrush", params).unwrap(); - assert_eq!(surface(&replay), shown, "replay matches {mode} {depth}"); - } + // The mixer is generic over mode and depth: one case per mode, each at a different depth. + for (mode, depth) in [("rgb", 8), ("cmyk", 16), ("lab", 32)] { + let mut s = setup(mode, depth); + subset(&mut s); + let before = surface(&s); + let params = json!({"points":[[6,7,1]],"size":9,"color":"#ffffff","seed":42,"sampleAllLayers":true}); + let mut live = LiveMixer::begin(&s, ¶ms).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let first = live.doc.layer(id).unwrap().surface().unwrap(); + unchanged(&before, first); + assert_ne!(&before, first, "the initial dab paints {mode} {depth}"); + live.push(&[StrokePoint::new(23.0, 15.0, 0.7)]).unwrap(); + let shown = live.doc.layer(id).unwrap().surface().unwrap().clone(); + unchanged(&before, &shown); + // The in-flight stroke keeps its original target even if the panel changes. + s.execute("channel.target", json!({"channel":"composite"})).unwrap(); + let params = live.prepare_commit(&mut s).unwrap(); + assert_eq!(params["target"], json!({"colors":[0,2]})); + assert_eq!(s.execute("paint.mixerBrush", params.clone()).unwrap()["fromLive"], true); + assert_eq!(surface(&s), shown, "displayed pixels are committed {mode} {depth}"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(surface(&s), before); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(surface(&s), shown); + let mut replay = setup(mode, depth); + replay.execute("paint.mixerBrush", params).unwrap(); + assert_eq!(surface(&replay), shown, "replay matches {mode} {depth}"); } } @@ -251,36 +256,44 @@ fn native_float_payloads_survive_unselected_component_restoration() { #[test] fn live_retouching_matches_direct_replay_and_preserves_unselected_bytes() { - for mode in ["rgb", "cmyk", "lab"] { - for depth in [8, 16, 32] { - for cmd in ["paint.dodge", "paint.burn", "paint.blur", "paint.sharpen", "paint.smudge", "paint.cloneStamp", "paint.historyBrush"] { - let mut s = setup(mode, depth); - subset(&mut s); - let original = surface(&s); - let p = json!({"points":[[6,7,1],[23,15,0.7]],"size":9,"source":[2,2]}); - let shown = if matches!(cmd, "paint.cloneStamp" | "paint.historyBrush") { - let live = photocraft_engine::retouch_cmds::LiveRetouch::begin(&s, cmd, &p).unwrap(); - let st = s.active().unwrap(); - let shown = live.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone(); - s.offer_live_retouch(live).unwrap(); - shown - } else { - let live = photocraft_engine::retouch_cmds::LiveDab::begin(&s, cmd, &p).unwrap(); - let st = s.active().unwrap(); - let shown = live.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone(); - s.offer_live_dab(live).unwrap(); - shown - }; - unchanged(&original, &shown); - s.execute(cmd, p.clone()).unwrap(); - let committed = surface(&s); - unchanged(&original, &committed); - let mut replay = setup(mode, depth); - subset(&mut replay); - replay.execute(cmd, p).unwrap(); - assert!(committed == surface(&replay), "{mode} {depth} {cmd}: live reuse differs from replay"); - } - } + // The five dab commands (LiveDab) cover every mode and depth, and so do the two retouch commands + // (LiveRetouch). + let cases = [ + ("rgb", 8, "paint.dodge"), + ("cmyk", 16, "paint.burn"), + ("lab", 32, "paint.blur"), + ("cmyk", 8, "paint.sharpen"), + ("rgb", 16, "paint.smudge"), + ("cmyk", 32, "paint.cloneStamp"), + ("lab", 16, "paint.historyBrush"), + ("rgb", 8, "paint.cloneStamp"), + ]; + for (mode, depth, cmd) in cases { + let mut s = setup(mode, depth); + subset(&mut s); + let original = surface(&s); + let p = json!({"points":[[6,7,1],[23,15,0.7]],"size":9,"source":[2,2]}); + let shown = if matches!(cmd, "paint.cloneStamp" | "paint.historyBrush") { + let live = photocraft_engine::retouch_cmds::LiveRetouch::begin(&s, cmd, &p).unwrap(); + let st = s.active().unwrap(); + let shown = live.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone(); + s.offer_live_retouch(live).unwrap(); + shown + } else { + let live = photocraft_engine::retouch_cmds::LiveDab::begin(&s, cmd, &p).unwrap(); + let st = s.active().unwrap(); + let shown = live.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone(); + s.offer_live_dab(live).unwrap(); + shown + }; + unchanged(&original, &shown); + s.execute(cmd, p.clone()).unwrap(); + let committed = surface(&s); + unchanged(&original, &committed); + let mut replay = setup(mode, depth); + subset(&mut replay); + replay.execute(cmd, p).unwrap(); + assert!(committed == surface(&replay), "{mode} {depth} {cmd}: live reuse differs from replay"); } } @@ -627,31 +640,31 @@ fn legacy_cmyk_channel_clips_keep_their_tone_when_pasted_into_a_set_or_single_ch #[test] fn cmyk_grayscale_clips_roundtrip_explicit_and_limited_paste_at_every_depth() { - for depth in [8, 16, 32] { - for explicit_copy in [false, true] { - for command in ["edit.paste", "edit.pasteSpecial.pasteInto", "edit.pasteSpecial.pasteOutside"] { - let mut s = setup("cmyk", depth); - s.execute("channel.target", json!({"channel":{"color":0}})).unwrap(); - let before = surface(&s); - s.execute("edit.copy", if explicit_copy { json!({"target":{"color":0}}) } else { json!({}) }).unwrap(); - s.edit("clear cyan", |doc, id| { - let surf = doc.layer_mut(id.unwrap()).unwrap().surface_mut().unwrap(); - let mut raw = surf.read_region(Rect::new(0, 0, 32, 24)); - for p in raw.as_chunks_mut::<5>().0 { - p[0] = 0.93; - } - surf.write_region(Rect::new(0, 0, 32, 24), &raw); - Ok(()) - }) - .unwrap(); - if command != "edit.paste" { - s.execute("select.rect", json!({"x":0,"y":0,"width":16,"height":24})).unwrap(); + // Depth (command + explicit copy) % 3: each depth, command and copy kind pairs with the others. + for (ci, command) in ["edit.paste", "edit.pasteSpecial.pasteInto", "edit.pasteSpecial.pasteOutside"].into_iter().enumerate() { + for (ei, explicit_copy) in [false, true].into_iter().enumerate() { + let depth = [8, 16, 32][(ci + ei) % 3]; + let mut s = setup("cmyk", depth); + s.execute("channel.target", json!({"channel":{"color":0}})).unwrap(); + let before = surface(&s); + s.execute("edit.copy", if explicit_copy { json!({"target":{"color":0}}) } else { json!({}) }).unwrap(); + s.edit("clear cyan", |doc, id| { + let surf = doc.layer_mut(id.unwrap()).unwrap().surface_mut().unwrap(); + let mut raw = surf.read_region(Rect::new(0, 0, 32, 24)); + for p in raw.as_chunks_mut::<5>().0 { + p[0] = 0.93; } - s.execute(command, json!({"target":{"color":0},"center":[16,12]})).unwrap(); - let after = surface(&s); - let x = if command.ends_with("pasteOutside") { 20 } else { 4 }; - assert!((before.pixel(x, 8)[0] - after.pixel(x, 8)[0]).abs() < 2.0 / 255.0, "{depth} {explicit_copy} {command}"); + surf.write_region(Rect::new(0, 0, 32, 24), &raw); + Ok(()) + }) + .unwrap(); + if command != "edit.paste" { + s.execute("select.rect", json!({"x":0,"y":0,"width":16,"height":24})).unwrap(); } + s.execute(command, json!({"target":{"color":0},"center":[16,12]})).unwrap(); + let after = surface(&s); + let x = if command.ends_with("pasteOutside") { 20 } else { 4 }; + assert!((before.pixel(x, 8)[0] - after.pixel(x, 8)[0]).abs() < 2.0 / 255.0, "{depth} {explicit_copy} {command}"); } } } @@ -1232,29 +1245,29 @@ fn geometric_filters_on_colour_sets_preserve_background_identity_and_linked_mask #[test] fn colour_adjustments_keep_the_original_cross_component_inputs() { - for mode in ["rgb", "cmyk", "lab"] { - for depth in [8, 16, 32] { - for (cmd, params) in [ - ("image.adjustments.channelMixer", json!({"red":[0,100,0,0]})), - ("image.adjustments.hueSaturation", json!({"saturation":-30})), - ("image.adjustments.vibrance", json!({"vibrance":40})), - ("image.adjustments.colorBalance", json!({"midtones":[20,-10,30]})), - ("image.adjustments.photoFilter", json!({"color":"#ff0000","density":70})), - ] { - let mut control = setup(mode, depth); - let before = surface(&control); - control.execute(cmd, params.clone()).unwrap(); - let composite = surface(&control); - for indices in [vec![0], vec![0, 2]] { - let mut s = setup(mode, depth); - s.execute("channel.target", json!({"colors":indices})).unwrap(); - s.execute(cmd, params.clone()).unwrap(); - let mut expected = composite.clone(); - let colors = color_channels::ColorChannels::from_indices(indices, before.format().mode.color_channels()).unwrap(); - color_channels::restrict_surface(&before, &mut expected, colors).unwrap(); - assert!(surface(&s) == expected, "{mode} {depth} {cmd}"); - } - } + // One mode and depth per command; Color Balance runs twice so RGB also sees a second depth. Both + // index sets run in every case. + let cases = [ + ("rgb", 8, "image.adjustments.channelMixer", json!({"red":[0,100,0,0]})), + ("cmyk", 16, "image.adjustments.hueSaturation", json!({"saturation":-30})), + ("lab", 32, "image.adjustments.vibrance", json!({"vibrance":40})), + ("cmyk", 32, "image.adjustments.colorBalance", json!({"midtones":[20,-10,30]})), + ("lab", 8, "image.adjustments.photoFilter", json!({"color":"#ff0000","density":70})), + ("rgb", 16, "image.adjustments.colorBalance", json!({"midtones":[20,-10,30]})), + ]; + for (mode, depth, cmd, params) in cases { + let mut control = setup(mode, depth); + let before = surface(&control); + control.execute(cmd, params.clone()).unwrap(); + let composite = surface(&control); + for indices in [vec![0], vec![0, 2]] { + let mut s = setup(mode, depth); + s.execute("channel.target", json!({"colors":indices})).unwrap(); + s.execute(cmd, params.clone()).unwrap(); + let mut expected = composite.clone(); + let colors = color_channels::ColorChannels::from_indices(indices, before.format().mode.color_channels()).unwrap(); + color_channels::restrict_surface(&before, &mut expected, colors).unwrap(); + assert!(surface(&s) == expected, "{mode} {depth} {cmd}"); } } } @@ -1400,31 +1413,27 @@ fn refused_mask_cut_and_clear_leave_the_pixels_mask_and_clipboard_unchanged() { #[test] fn desaturate_honours_explicit_native_targets_over_the_panel_selection() { - for mode in ["rgb", "cmyk", "lab"] { - for depth in [8, 16, 32] { - for target in [json!({"color":1}), json!({"colors":[1]}), json!("pixels")] { - let mut s = setup(mode, depth); - let before = surface(&s); - let mut control = Session::new(); - let st = s.active().unwrap(); - control.add_document((*st.doc).clone(), None); - control.select_layer(st.active_layer.unwrap()).unwrap(); - control.execute("image.adjustments.desaturate", json!({})).unwrap(); - let expected = surface(&control); - subset(&mut s); - s.execute("image.adjustments.desaturate", json!({"target":target})).unwrap(); - let actual = surface(&s); - assert_ne!(actual, before, "{mode}@{depth} {target}"); - for y in 0..24 { - for x in 0..32 { - for k in 0..actual.channels() { - let want = if target == "pixels" || k == 1 { &expected } else { &before }; - assert_eq!( - actual.sample_channel(x, y, k).to_bits(), - want.sample_channel(x, y, k).to_bits(), - "{mode}@{depth} {target} component {k}" - ); - } + // Depth (mode + target) % 3: each mode and each target appears at every depth. + for (mi, mode) in ["rgb", "cmyk", "lab"].into_iter().enumerate() { + for (ti, target) in [json!({"color":1}), json!({"colors":[1]}), json!("pixels")].into_iter().enumerate() { + let depth = [8, 16, 32][(mi + ti) % 3]; + let mut s = setup(mode, depth); + let before = surface(&s); + let mut control = Session::new(); + let st = s.active().unwrap(); + control.add_document((*st.doc).clone(), None); + control.select_layer(st.active_layer.unwrap()).unwrap(); + control.execute("image.adjustments.desaturate", json!({})).unwrap(); + let expected = surface(&control); + subset(&mut s); + s.execute("image.adjustments.desaturate", json!({"target":target})).unwrap(); + let actual = surface(&s); + assert_ne!(actual, before, "{mode}@{depth} {target}"); + for y in 0..24 { + for x in 0..32 { + for k in 0..actual.channels() { + let want = if target == "pixels" || k == 1 { &expected } else { &before }; + assert_eq!(actual.sample_channel(x, y, k).to_bits(), want.sample_channel(x, y, k).to_bits(), "{mode}@{depth} {target} component {k}"); } } } @@ -1434,41 +1443,41 @@ fn desaturate_honours_explicit_native_targets_over_the_panel_selection() { #[test] fn mask_view_routes_implicit_edits_and_tone_editors_to_the_mask_before_colour_sets() { - for mode in ["rgb", "cmyk", "lab"] { - for depth in [8, 16, 32] { - for view in ["gray", "overlay"] { - for colors in [vec![0], vec![0, 2]] { - let mut s = setup(mode, depth); - s.execute("layer.layerMask.revealAll", json!({})).unwrap(); - s.execute("channel.target", json!({"colors":colors})).unwrap(); - s.execute("view.layerMask", json!({"mode":view})).unwrap(); - let before = surface(&s); - let st = s.active().unwrap(); - let layer = st.active_layer.unwrap(); - let descriptor = photocraft_engine::channel_cmds::isolated_curve_channel(st).unwrap(); - assert_eq!(descriptor.gray, Some(photocraft_engine::channel_cmds::GraySurface::LayerMask)); - assert!(descriptor.components.is_none()); - s.execute("image.adjustments.invert", json!({})).unwrap(); - assert_eq!(surface(&s), before); - let mask = |s: &Session| s.active().unwrap().doc.layer(layer).unwrap().mask.as_ref().unwrap().surface.clone(); - assert_eq!(mask(&s).sample_channel(8, 8, 0), 0.0); - s.execute("paint.stroke", json!({"points":[[8,8]],"size":6,"hardness":1.0,"color":"#ffffff"})).unwrap(); - assert!(mask(&s).sample_channel(8, 8, 0) > 0.9); - s.execute("filter.blur.gaussianBlur", json!({"radius":2})).unwrap(); - s.execute("image.adjustments.desaturate", json!({})).unwrap(); - assert_eq!(surface(&s), before); - let mask_before = mask(&s); - // An explicit native target can still override the viewed mask. - s.execute("image.adjustments.invert", json!({"target":{"colors":colors}})).unwrap(); - assert_ne!(surface(&s), before); - assert_eq!(mask(&s), mask_before); - s.execute("channel.target", json!({"colors":colors})).unwrap(); - assert!(photocraft_engine::mask_view_cmds::current(s.active().unwrap()).is_none(), "selecting colours leaves mask view"); - s.execute("view.layerMask", json!({"mode":view})).unwrap(); - s.execute("channel.target", json!({"channel":"composite"})).unwrap(); - assert!(photocraft_engine::mask_view_cmds::current(s.active().unwrap()).is_none(), "selecting the composite leaves mask view"); - } - } + // Depth and colour set rotate with (mode + view): each mode and view meets every depth and both + // colour sets across the cases. + for (mi, mode) in ["rgb", "cmyk", "lab"].into_iter().enumerate() { + for (vi, view) in ["gray", "overlay"].into_iter().enumerate() { + let depth = [8, 16, 32][(mi + vi) % 3]; + let colors = [vec![0], vec![0, 2]][(mi + vi) % 2].clone(); + let mut s = setup(mode, depth); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("channel.target", json!({"colors":colors})).unwrap(); + s.execute("view.layerMask", json!({"mode":view})).unwrap(); + let before = surface(&s); + let st = s.active().unwrap(); + let layer = st.active_layer.unwrap(); + let descriptor = photocraft_engine::channel_cmds::isolated_curve_channel(st).unwrap(); + assert_eq!(descriptor.gray, Some(photocraft_engine::channel_cmds::GraySurface::LayerMask)); + assert!(descriptor.components.is_none()); + s.execute("image.adjustments.invert", json!({})).unwrap(); + assert_eq!(surface(&s), before); + let mask = |s: &Session| s.active().unwrap().doc.layer(layer).unwrap().mask.as_ref().unwrap().surface.clone(); + assert_eq!(mask(&s).sample_channel(8, 8, 0), 0.0); + s.execute("paint.stroke", json!({"points":[[8,8]],"size":6,"hardness":1.0,"color":"#ffffff"})).unwrap(); + assert!(mask(&s).sample_channel(8, 8, 0) > 0.9); + s.execute("filter.blur.gaussianBlur", json!({"radius":2})).unwrap(); + s.execute("image.adjustments.desaturate", json!({})).unwrap(); + assert_eq!(surface(&s), before); + let mask_before = mask(&s); + // An explicit native target can still override the viewed mask. + s.execute("image.adjustments.invert", json!({"target":{"colors":colors}})).unwrap(); + assert_ne!(surface(&s), before); + assert_eq!(mask(&s), mask_before); + s.execute("channel.target", json!({"colors":colors})).unwrap(); + assert!(photocraft_engine::mask_view_cmds::current(s.active().unwrap()).is_none(), "selecting colours leaves mask view"); + s.execute("view.layerMask", json!({"mode":view})).unwrap(); + s.execute("channel.target", json!({"channel":"composite"})).unwrap(); + assert!(photocraft_engine::mask_view_cmds::current(s.active().unwrap()).is_none(), "selecting the composite leaves mask view"); } } } diff --git a/crates/engine/tests/it/tone_target_picker.rs b/crates/engine/tests/it/tone_target_picker.rs index 9f34868798..09e98e3501 100644 --- a/crates/engine/tests/it/tone_target_picker.rs +++ b/crates/engine/tests/it/tone_target_picker.rs @@ -42,38 +42,38 @@ fn plane<'a>(doc: &'a Document, target: &Value) -> &'a Surface { /// Black/white pickers edit only their gray target across colour modes and native depths, including undo/redo. #[test] fn native_gray_pickers_ignore_document_colour_and_preserve_other_data() { - for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Lab, ColorMode::Cmyk] { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - for target in [json!("mask"), json!("quickMask"), json!({"channel":0})] { - for kind in ["levels", "curves"] { - for point in ["black", "white"] { - let mut s = session(mode, depth); - let before = s.active().unwrap().doc.clone(); - let history = s.active().unwrap().history.past_len(); - let p = json!({"target":target,"eyedropper":{"point":point,"at":[8,8],"size":3}}); - s.execute(&format!("image.adjustments.{kind}"), p).unwrap(); - let after = s.active().unwrap().doc.clone(); - let expected = if point == "white" { 1.0 } else { 0.0 }; - let actual = plane(&after, &target).sample_channel(8, 8, 0); - assert!((actual - expected).abs() < 0.01, "{mode:?} {depth:?} {target} {kind} {point}: {actual}"); - assert_eq!(before.layers[0].content, after.layers[0].content, "colour pixels and transparency"); - if target != json!("mask") { - assert_eq!(before.layers[0].mask, after.layers[0].mask); - } - if target != json!("quickMask") { - assert_eq!(before.quick_mask, after.quick_mask); - } - if target != json!({"channel":0}) { - assert_eq!(before.channels, after.channels); - } - assert_eq!(before.channels[0].spot, after.channels[0].spot); - assert_eq!(s.active().unwrap().history.past_len(), history + 1); - s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(plane(&s.active().unwrap().doc, &target), plane(&before, &target)); - s.execute("edit.redo", json!({})).unwrap(); - assert_eq!(plane(&s.active().unwrap().doc, &target), plane(&after, &target)); - } + // Depth (mode + target) % 3 and, per kind, a point that alternates: each mode and each target meets every depth, + // and each kind runs with both points. + for (mi, mode) in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Lab, ColorMode::Cmyk].into_iter().enumerate() { + for (ti, target) in [json!("mask"), json!("quickMask"), json!({"channel":0})].into_iter().enumerate() { + let depth = [SampleType::U8, SampleType::U16, SampleType::F32][(mi + ti) % 3]; + for (ki, kind) in ["levels", "curves"].into_iter().enumerate() { + let point = ["black", "white"][(mi + ti + ki) % 2]; + let mut s = session(mode, depth); + let before = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.past_len(); + let p = json!({"target":target,"eyedropper":{"point":point,"at":[8,8],"size":3}}); + s.execute(&format!("image.adjustments.{kind}"), p).unwrap(); + let after = s.active().unwrap().doc.clone(); + let expected = if point == "white" { 1.0 } else { 0.0 }; + let actual = plane(&after, &target).sample_channel(8, 8, 0); + assert!((actual - expected).abs() < 0.01, "{mode:?} {depth:?} {target} {kind} {point}: {actual}"); + assert_eq!(before.layers[0].content, after.layers[0].content, "colour pixels and transparency"); + if target != json!("mask") { + assert_eq!(before.layers[0].mask, after.layers[0].mask); } + if target != json!("quickMask") { + assert_eq!(before.quick_mask, after.quick_mask); + } + if target != json!({"channel":0}) { + assert_eq!(before.channels, after.channels); + } + assert_eq!(before.channels[0].spot, after.channels[0].spot); + assert_eq!(s.active().unwrap().history.past_len(), history + 1); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(plane(&s.active().unwrap().doc, &target), plane(&before, &target)); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(plane(&s.active().unwrap().doc, &target), plane(&after, &target)); } } } @@ -232,82 +232,76 @@ fn bad_scalar_picker_params_fail_without_changing_pixels() { /// Hidden RGB settings must never affect a gray plane, including pencil curves and sampled edits. #[test] fn gray_tone_records_do_not_leak_from_rgb_channels() { - for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Lab, ColorMode::Cmyk] { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - for (target, panel) in - [(json!("mask"), ChannelTarget::LayerMask), (json!({"channel":0}), ChannelTarget::Alpha(0)), (json!("quickMask"), ChannelTarget::Composite)] - { - // Each style sees both flags; all four flag pairs occur across the styles. - for (si, style) in ["levels", "points", "pencil"].into_iter().enumerate() { - for (ai, sampled) in [false, true].into_iter().enumerate() { - for (ei, explicit) in [false, true].into_iter().enumerate() { - if (si + ai) % 2 != ei { - continue; - } - let mut clean = session(mode, depth); - clean.active_mut().unwrap().channel_view.target = panel; - clean - .edit("Vary gray samples", |doc, _| { - let patch = Rect::from_xywh(4, 4, 1, 1); - doc.layers[0].mask.as_mut().unwrap().surface.fill_rect(patch, &[0.125]); - doc.channels[0].surface.fill_rect(patch, &[0.125]); - doc.quick_mask.as_mut().unwrap().surface.fill_rect(patch, &[0.125]); - Ok(()) - }) - .unwrap(); - let before = clean.active().unwrap().doc.clone(); - let layer = clean.active().unwrap().active_layer.unwrap(); - let mut dirty = Session::new(); - dirty.add_document((*before).clone(), None); - dirty.select_layer(layer).unwrap(); - dirty.active_mut().unwrap().channel_view.target = panel; - let kind = if style == "levels" { "levels" } else { "curves" }; - let mut params = if kind == "levels" { json!({"gamma":2}) } else { json!({"points":[[0,255],[255,0]],"pencil":style == "pencil"}) }; - if explicit { - params["target"] = target.clone(); - } - if sampled { - params["eyedropper"] = json!({"point":"white","at":[8,8]}); - } - let mut contaminated = params.clone(); - for key in ["red", "green", "blue"] { - contaminated[key] = if kind == "levels" { - json!({"gamma":4}) - } else if style == "pencil" { - json!(vec![255; 256]) - } else { - json!([[0, 255], [255, 255]]) - }; - } - let command = format!("image.adjustments.{kind}"); - clean.execute(&command, params).unwrap(); - dirty.execute(&command, contaminated).unwrap(); - let expected = &clean.active().unwrap().doc; - let actual = &dirty.active().unwrap().doc; - assert!(plane(expected, &target) != plane(&before, &target), "the scalar adjustment really edits the plane"); - assert_eq!( - plane(actual, &target).sample_channel(4, 4, 0), - plane(expected, &target).sample_channel(4, 4, 0), - "{mode:?} {depth:?} {target} {style} sampled={sampled} explicit={explicit}" - ); - assert!( - plane(actual, &target) == plane(expected, &target), - "{mode:?} {depth:?} {target} {style} sampled={sampled} explicit={explicit}" - ); - assert_eq!(actual.layers[0].content, before.layers[0].content); - if target != json!("mask") { - assert_eq!(actual.layers[0].mask, before.layers[0].mask); - } - if target != json!("quickMask") { - assert_eq!(actual.quick_mask, before.quick_mask); - } - if target != json!({"channel":0}) { - assert_eq!(actual.channels, before.channels); - } - assert_eq!(actual.channels[0].spot, before.channels[0].spot); - } - } + // Depth (mode + target) % 3: each mode and each target meets every depth. + for (mi, mode) in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Lab, ColorMode::Cmyk].into_iter().enumerate() { + for (ti, (target, panel)) in + [(json!("mask"), ChannelTarget::LayerMask), (json!({"channel":0}), ChannelTarget::Alpha(0)), (json!("quickMask"), ChannelTarget::Composite)] + .into_iter() + .enumerate() + { + let depth = [SampleType::U8, SampleType::U16, SampleType::F32][(mi + ti) % 3]; + // Each style runs one (sampled, explicit) pair, rotating with (2 * mode + target + style): every style sees + // all four flag pairs across the cases, and at every depth it sees both sampled and both explicit values. + for (si, style) in ["levels", "points", "pencil"].into_iter().enumerate() { + let (sampled, explicit) = [(false, false), (false, true), (true, false), (true, true)][(2 * mi + ti + si) % 4]; + let mut clean = session(mode, depth); + clean.active_mut().unwrap().channel_view.target = panel; + clean + .edit("Vary gray samples", |doc, _| { + let patch = Rect::from_xywh(4, 4, 1, 1); + doc.layers[0].mask.as_mut().unwrap().surface.fill_rect(patch, &[0.125]); + doc.channels[0].surface.fill_rect(patch, &[0.125]); + doc.quick_mask.as_mut().unwrap().surface.fill_rect(patch, &[0.125]); + Ok(()) + }) + .unwrap(); + let before = clean.active().unwrap().doc.clone(); + let layer = clean.active().unwrap().active_layer.unwrap(); + let mut dirty = Session::new(); + dirty.add_document((*before).clone(), None); + dirty.select_layer(layer).unwrap(); + dirty.active_mut().unwrap().channel_view.target = panel; + let kind = if style == "levels" { "levels" } else { "curves" }; + let mut params = if kind == "levels" { json!({"gamma":2}) } else { json!({"points":[[0,255],[255,0]],"pencil":style == "pencil"}) }; + if explicit { + params["target"] = target.clone(); } + if sampled { + params["eyedropper"] = json!({"point":"white","at":[8,8]}); + } + let mut contaminated = params.clone(); + for key in ["red", "green", "blue"] { + contaminated[key] = if kind == "levels" { + json!({"gamma":4}) + } else if style == "pencil" { + json!(vec![255; 256]) + } else { + json!([[0, 255], [255, 255]]) + }; + } + let command = format!("image.adjustments.{kind}"); + clean.execute(&command, params).unwrap(); + dirty.execute(&command, contaminated).unwrap(); + let expected = &clean.active().unwrap().doc; + let actual = &dirty.active().unwrap().doc; + assert!(plane(expected, &target) != plane(&before, &target), "the scalar adjustment really edits the plane"); + assert_eq!( + plane(actual, &target).sample_channel(4, 4, 0), + plane(expected, &target).sample_channel(4, 4, 0), + "{mode:?} {depth:?} {target} {style} sampled={sampled} explicit={explicit}" + ); + assert!(plane(actual, &target) == plane(expected, &target), "{mode:?} {depth:?} {target} {style} sampled={sampled} explicit={explicit}"); + assert_eq!(actual.layers[0].content, before.layers[0].content); + if target != json!("mask") { + assert_eq!(actual.layers[0].mask, before.layers[0].mask); + } + if target != json!("quickMask") { + assert_eq!(actual.quick_mask, before.quick_mask); + } + if target != json!({"channel":0}) { + assert_eq!(actual.channels, before.channels); + } + assert_eq!(actual.channels[0].spot, before.channels[0].spot); } } } @@ -388,52 +382,51 @@ fn review_picker_reads_the_addressed_mask_layer() { /// A Smart Filter mask is a gray target like a layer mask: the picker reads the stored mask, or the implicit Reveal /// All before anything is stored, without materializing it, and the commit edits only the filter mask, in every -/// colour mode and native depth. (The UI's tone dialogs test only that their pick reaches this target, #15648.) +/// colour mode and, across the cases, every native depth (rotating with mode, stored and kind). (The UI's tone dialogs test only that their pick reaches this target, #15648.) #[test] fn filter_mask_picker_samples_and_edits_only_the_filter_mask() { - for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] { - for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { - for stored in [false, true] { - for kind in ["levels", "curves"] { - let case = format!("{mode:?} {depth:?} stored={stored} {kind}"); - let mut s = session(mode, depth); - // A Smart Filter needs the composite selected, not one colour channel, and no Quick Mask (the filter - // would edit the Quick Mask instead). - s.edit("No Quick Mask", |doc, _| { - doc.quick_mask = None; - Ok(()) - }) - .unwrap(); - s.active_mut().unwrap().channel_view.target = ChannelTarget::Composite; - s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); - s.execute("filter.blur.gaussianBlur", json!({"radius": 1})).unwrap(); - if stored { - s.execute("edit.fill", json!({"target": "filterMask", "contents": "color", "color": "#404040"})).unwrap(); - } - let id = s.active().unwrap().active_layer.unwrap(); - let before = s.active().unwrap().doc.clone(); - let p = json!({"target": "filterMask", "eyedropper": {"point": "white", "at": [8, 8]}}); - let picked = adjust_params::destructive_eyedropper(&s, kind, &p).unwrap().unwrap(); - assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc), "sampling is read-only: {case}"); - let white = if stored { 64.0 } else { 255.0 }; - let sampled = if kind == "levels" { - adjust_params::to_params(&picked)["inWhite"].as_f64().unwrap() - } else { - adjust_params::to_params(&picked)["points"].as_array().unwrap().last().unwrap()[0].as_f64().unwrap() - }; - assert!((sampled - white).abs() < 1.0, "{case}: sampled {sampled}, want {white}"); - s.execute(&format!("image.adjustments.{kind}"), p).unwrap(); - let doc = &s.active().unwrap().doc; - let (LayerContent::Smart(old), LayerContent::Smart(new)) = (&before.layer(id).unwrap().content, &doc.layer(id).unwrap().content) else { - panic!("{case}: not a smart object") - }; - assert!(new.filter_mask.as_ref().unwrap().surface.sample_channel(8, 8, 0) > 0.99, "{case}"); - assert_eq!(new.smart_filters, old.smart_filters, "{case}: the adjustment edits the mask, adds no filter"); - assert_eq!(new.source, old.source, "{case}"); - assert_eq!(doc.layer(id).unwrap().mask, before.layer(id).unwrap().mask, "{case}: the layer mask"); - assert_eq!(doc.channels, before.channels, "{case}"); - assert_eq!(doc.quick_mask, before.quick_mask, "{case}"); + for (mi, mode) in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().enumerate() { + for (si, stored) in [false, true].into_iter().enumerate() { + for (ki, kind) in ["levels", "curves"].into_iter().enumerate() { + let depth = [SampleType::U8, SampleType::U16, SampleType::F32][(mi + si + ki) % 3]; + let case = format!("{mode:?} {depth:?} stored={stored} {kind}"); + let mut s = session(mode, depth); + // A Smart Filter needs the composite selected, not one colour channel, and no Quick Mask (the filter + // would edit the Quick Mask instead). + s.edit("No Quick Mask", |doc, _| { + doc.quick_mask = None; + Ok(()) + }) + .unwrap(); + s.active_mut().unwrap().channel_view.target = ChannelTarget::Composite; + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + s.execute("filter.blur.gaussianBlur", json!({"radius": 1})).unwrap(); + if stored { + s.execute("edit.fill", json!({"target": "filterMask", "contents": "color", "color": "#404040"})).unwrap(); } + let id = s.active().unwrap().active_layer.unwrap(); + let before = s.active().unwrap().doc.clone(); + let p = json!({"target": "filterMask", "eyedropper": {"point": "white", "at": [8, 8]}}); + let picked = adjust_params::destructive_eyedropper(&s, kind, &p).unwrap().unwrap(); + assert!(std::sync::Arc::ptr_eq(&before, &s.active().unwrap().doc), "sampling is read-only: {case}"); + let white = if stored { 64.0 } else { 255.0 }; + let sampled = if kind == "levels" { + adjust_params::to_params(&picked)["inWhite"].as_f64().unwrap() + } else { + adjust_params::to_params(&picked)["points"].as_array().unwrap().last().unwrap()[0].as_f64().unwrap() + }; + assert!((sampled - white).abs() < 1.0, "{case}: sampled {sampled}, want {white}"); + s.execute(&format!("image.adjustments.{kind}"), p).unwrap(); + let doc = &s.active().unwrap().doc; + let (LayerContent::Smart(old), LayerContent::Smart(new)) = (&before.layer(id).unwrap().content, &doc.layer(id).unwrap().content) else { + panic!("{case}: not a smart object") + }; + assert!(new.filter_mask.as_ref().unwrap().surface.sample_channel(8, 8, 0) > 0.99, "{case}"); + assert_eq!(new.smart_filters, old.smart_filters, "{case}: the adjustment edits the mask, adds no filter"); + assert_eq!(new.source, old.source, "{case}"); + assert_eq!(doc.layer(id).unwrap().mask, before.layer(id).unwrap().mask, "{case}: the layer mask"); + assert_eq!(doc.channels, before.channels, "{case}"); + assert_eq!(doc.quick_mask, before.quick_mask, "{case}"); } } } diff --git a/crates/format/src/read.rs b/crates/format/src/read.rs index e089af6ea3..8dc8314ce9 100644 --- a/crates/format/src/read.rs +++ b/crates/format/src/read.rs @@ -92,8 +92,9 @@ fn read_all_with(reader: &mut impl Read, size_hint: u64, chunk: usize, max: u64) loop { if buf.len() == buf.capacity() { let mut probe = [0; 4096]; + let probe_len = chunk.min(probe.len()); let n = loop { - match reader.read(&mut probe) { + match reader.read(&mut probe[..probe_len]) { Err(e) if e.kind() == io::ErrorKind::Interrupted => {} r => break r?, } @@ -186,6 +187,30 @@ mod tests { } } + #[test] + fn probe_reads_respect_the_configured_chunk_size() { + struct SmallReads<'a> { + data: &'a [u8], + max_request: usize, + } + impl Read for SmallReads<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if buf.len() > self.max_request { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "read request exceeds the configured chunk size")); + } + self.data.read(buf) + } + } + let data = b"ninebytes"; + for chunk in [0, 1, 7, 4096] { + for hint in [0, 3, data.len() as u64] { + let mut reader = SmallReads { data, max_request: chunk.max(1) }; + let result = read_all_with(&mut reader, hint, chunk, 64); + assert_eq!(result.unwrap_or_else(|e| panic!("chunk {chunk}, hint {hint}: {e}")), data); + } + } + } + /// Nothing over the total limit is returned (#8601): a file larger than it, a reader that /// gives more than it whatever its hint says, and one that never ends are `FileTooLarge` /// errors, while a file exactly at the limit is read whole. diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl index a7c804ae53..8f0e10bee9 100644 --- a/crates/gpu/src/compose.wgsl +++ b/crates/gpu/src/compose.wgsl @@ -827,7 +827,7 @@ fn dither_noise(d: vec2) -> f32 { h = h ^ (h >> 15u); h = h * 0x2C1B3C6Du; h = h ^ (h >> 12u); - return f32(h & 0xFFFFu) / 65535.0; + return f32(h & 0xFFFFu) / 65536.0; } fn layer_texel(d: vec2) -> vec4 { diff --git a/crates/gpu/tests/it/camera_raw.rs b/crates/gpu/tests/it/camera_raw.rs index d85a2fac52..7d5904fd29 100644 --- a/crates/gpu/tests/it/camera_raw.rs +++ b/crates/gpu/tests/it/camera_raw.rs @@ -1,8 +1,9 @@ -//! Camera Raw's GPU preview pass against the CPU develop (the oracle), stage by stage, at 8, 16 -//! and 32 bits. Skips, with a message, when there is no adapter or device or it can't render -//! `Rgba32Float`; with `WGPU_BACKEND` set those fail instead, as in `parity.rs`. A pipeline that -//! doesn't build on an adapter that can run it fails. The shader itself is validated without a -//! GPU ([`the_shader_validates_without_a_gpu`]), so a WGSL error fails on every runner. +//! Camera Raw's GPU preview pass against the CPU develop (the oracle), stage by stage, at an +//! integer depth (8 or 16 bits) and at 32 bits (see [`depths`]). Skips, with a message, when +//! there is no adapter or device or it can't render `Rgba32Float`; with `WGPU_BACKEND` set those +//! fail instead, as in `parity.rs`. A pipeline that doesn't build on an adapter that can run it +//! fails. The shader itself is validated without a GPU ([`the_shader_validates_without_a_gpu`]), +//! so a WGSL error fails on every runner. use photocraft_algo::camera_raw::{self as raw, CameraRaw, DevelopInputs, StoredVignetteStyle, Wheel}; use photocraft_gpu::{CameraRawDevelop, DeviceHealth, Fault}; @@ -135,6 +136,15 @@ enum Depth { const DEPTHS: [Depth; 3] = [Depth::Eight, Depth::Sixteen, Depth::Float]; +/// The depths the `i`th case of a set runs at: one integer depth and 32 bits. 8 and 16 bits both +/// develop with `float = false` (the dialog hands the develop only `float`, see +/// `crates/ui-egui/src/dialogs/camera_raw_gpu.rs`), so they share every line of the CPU develop +/// and the pass and differ only in how [`image`] quantizes the input; cases alternate between +/// them so both quantizations still run. +fn depths(i: usize) -> [Depth; 2] { + [DEPTHS[i % 2], Depth::Float] +} + fn hash(i: usize, c: u64) -> f32 { let mut z = (i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ c.wrapping_mul(0xC2B2_AE3D_27D4_EB4F); z = (z ^ (z >> 29)).wrapping_mul(0xBF58_476D_1CE4_E5B9); @@ -208,8 +218,8 @@ fn check(name: &str, sets: &[Case]) { fn check_at(name: &str, sets: &[Case], size: (usize, usize)) { let Some(mut g) = gpu() else { return }; - for p in sets { - for depth in DEPTHS { + for (i, p) in sets.iter().enumerate() { + for depth in depths(i) { let d = compare_at(&mut g, p, depth, size); eprintln!("{name} {depth:?}: max |GPU - CPU| = {d:.2e}"); } @@ -439,15 +449,17 @@ fn shadows_and_highlights_on_tiny_odd_and_flat_frames() { let stages = per_pixel(&p, 3, 3, false, None).unwrap(); assert!(g.dev.develop(&g.device, &g.queue, None, &image(w, h, Depth::Eight), None, [w as u32, h as u32], &stages).is_err()); } - for size in [(3, 3), (5, 3), (37, 23), (300, 7)] { - for depth in DEPTHS { - let d = compare_at(&mut g, &p, depth, size); - eprintln!("shadows/highlights {size:?} {depth:?}: max |GPU - CPU| = {d:.2e}"); - } + // One depth per size, in turn: the size decides the pyramid and the edges, the depth only the + // input's quantization and whether the result clips, which `shadows_and_highlights` checks + // at every depth. + for (i, size) in [(3, 3), (5, 3), (37, 23), (300, 7)].into_iter().enumerate() { + let depth = DEPTHS[i % DEPTHS.len()]; + let d = compare_at(&mut g, &p, depth, size); + eprintln!("shadows/highlights {size:?} {depth:?}: max |GPU - CPU| = {d:.2e}"); } - // A flat frame has no range to filter. + // A flat frame has no range to filter. It isn't quantized, so one integer depth. let flat = vec![[0.4, 0.35, 0.3, 1.0]; 64 * 48]; - for depth in DEPTHS { + for depth in depths(0) { compare_image(&mut g, &p, depth, &flat, (64, 48)); } } @@ -480,7 +492,7 @@ fn shadows_and_highlights_with_per_pixel_stages() { check_at( "shadows/highlights + per pixel", &[ - all.clone(), + all, // Whites and Blacks measured after the filter, both directions. cr! { shadows: 60.0, whites: 70.0, blacks: -45.0}, cr! { highlights: -60.0, whites: -60.0, blacks: 50.0, exposure: -0.4}, @@ -488,13 +500,9 @@ fn shadows_and_highlights_with_per_pixel_stages() { ], (171, 48), ); - // At the dialog's proxy width, at one depth: the depth only changes how the input is - // quantized (8 and 16 bits both develop with `float = false`), and every depth already ran - // above at 171×48. The long side is what matters here (subsampled pyramid levels); the short - // one only needs to keep several levels, so the frame is a strip. - let Some(mut g) = gpu() else { return }; - let d = compare_at(&mut g, &all, Depth::Sixteen, (858, 120)); - eprintln!("shadows/highlights + per pixel 858x120: max |GPU - CPU| = {d:.2e}"); + // The dialog's proxy width (the pyramid levels and range cells at that size) runs in + // `clarity_texture_and_dehaze_with_shadows_highlights_and_per_pixel_stages`, whose first set + // has Shadows and Highlights too. } /// Asserts that each of `sets` moves some pixel of the test image by over 2 %, so a comparison @@ -584,21 +592,22 @@ fn clarity_texture_and_dehaze_on_tiny_and_odd_frames() { let Some(mut g) = gpu() else { return }; let p = cr! { dehaze: 45.0, clarity: 50.0, texture: 60.0, whites: 20.0, blacks: -20.0}; // Without Shadows and Highlights even 1 and 2 pixel frames develop on the GPU. - for size in [(1, 1), (2, 2), (40, 2), (3, 3), (5, 3), (37, 23), (300, 7)] { - for depth in DEPTHS { - let d = compare_at(&mut g, &p, depth, size); - eprintln!("clarity/texture/dehaze {size:?} {depth:?}: max |GPU - CPU| = {d:.2e}"); - } + // One depth per size, in turn, as in `shadows_and_highlights_on_tiny_odd_and_flat_frames`; + // `clarity_texture_and_dehaze` checks the stages at every depth. + for (i, size) in [(1, 1), (2, 2), (40, 2), (3, 3), (5, 3), (37, 23), (300, 7)].into_iter().enumerate() { + let depth = DEPTHS[i % DEPTHS.len()]; + let d = compare_at(&mut g, &p, depth, size); + eprintln!("clarity/texture/dehaze {size:?} {depth:?}: max |GPU - CPU| = {d:.2e}"); } // Texture's blur on a small proxy is too narrow to change anything; the stage still runs. let narrow = cr! { texture: 80.0, contrast: 10.0, pixel_scale: 0.1}; assert!(per_pixel(&narrow, 64, 48, true, None).and_then(|s| s.texture).is_some_and(|t| t.radii.is_empty())); - for depth in DEPTHS { + for depth in depths(1) { compare_at(&mut g, &narrow, depth, (64, 48)); } - // A flat frame: no haze to find, no detail to raise. + // A flat frame: no haze to find, no detail to raise. Not quantized, so one integer depth. let flat = vec![[0.4, 0.35, 0.3, 1.0]; 64 * 48]; - for depth in DEPTHS { + for depth in depths(0) { compare_image(&mut g, &p, depth, &flat, (64, 48)); } } @@ -620,25 +629,28 @@ fn dehaze_opens_the_dark_channel_like_the_cpu() { [c[0], c[1], c[2], 1.0] }) .collect(); - for dehaze in [100.0, 60.0, -40.0] { - for depth in DEPTHS { - let d = compare_image(&mut g, &cr! { dehaze: dehaze }, depth, &src, (w, h)); - eprintln!("dehaze {dehaze} on the tower {depth:?}: max |GPU - CPU| = {d:.2e}"); - } + // The scene isn't quantized, so the depth only picks `float` (whether the result clips); one + // per strength, both in turn. + for (dehaze, depth) in [(100.0, Depth::Float), (60.0, Depth::Eight), (-40.0, Depth::Float)] { + let d = compare_image(&mut g, &cr! { dehaze: dehaze }, depth, &src, (w, h)); + eprintln!("dehaze {dehaze} on the tower {depth:?}: max |GPU - CPU| = {d:.2e}"); } } #[test] fn dehaze_remakes_its_copy_when_the_white_balance_changes() { let Some(mut g) = gpu() else { return }; - let src = image(858, 572, Depth::Eight); + // The dialog's proxy width, so the copy is subsampled as there; the cache key doesn't hold the + // size, so the frame is a strip. + let (w, h) = (858, 120); + let src = image(w, h, Depth::Eight); // Same source key throughout: the copy is cached by it and by the white balance. for temperature in [25.0, -40.0, -40.0, 0.0] { let p = cr! { dehaze: 50.0, temperature}; let mut cpu = src.clone(); - develop(&mut cpu, 858, 572, &p, false); - let stages = per_pixel(&p, 858, 572, false, None).unwrap(); - let out = g.dev.develop(&g.device, &g.queue, None, &src, Some(3), [858, 572], &stages).unwrap(); + develop(&mut cpu, w, h, &p, false); + let stages = per_pixel(&p, w, h, false, None).unwrap(); + let out = g.dev.develop(&g.device, &g.queue, None, &src, Some(3), [w as u32, h as u32], &stages).unwrap(); let d = out.iter().zip(&cpu).flat_map(|(a, b)| (0..3).map(move |c| (a[c] - b[c]).abs())).fold(0.0f32, f32::max); assert!(d <= TOL, "temperature {temperature}: off by {d}"); } diff --git a/crates/gpu/tests/it/parity.rs b/crates/gpu/tests/it/parity.rs index 7dcf5b4ee6..02217478cb 100644 --- a/crates/gpu/tests/it/parity.rs +++ b/crates/gpu/tests/it/parity.rs @@ -214,12 +214,25 @@ fn worst_diff(cpu: &[[f32; 4]], gpu: &[[f32; 4]]) -> (f32, usize) { worst } -/// GPU (whole textures, then pages) vs CPU over `rect`: Err with the worst pixel if over the -/// tolerance, else the stats of the unpaged render. -fn diff_rect(g: &mut Gpu, doc: &Document, rect: Rect, what: &str) -> Result { +/// One `diff_rect` pass, kept: the whole-texture compositor's pixels and stats and the paged +/// pass's stats. The CPU reference is computed once and both GPU renders are compared with it; +/// a test that also wants the whole-texture pixels (a measured ramp) or the paged pass's stats +/// (a cell count) reuses them from here instead of paying for a second render of the same +/// document. +struct Diff { + /// The whole-texture compositor's pixels and stats from the pass that checked them. + whole: Vec<[f32; 4]>, + whole_stats: photocraft_gpu::Stats, + paged_stats: photocraft_gpu::Stats, +} + +/// GPU (whole textures, then pages) vs CPU over `rect`, with what a follow-up assert needs: +/// Err with the worst pixel if over the tolerance. +fn diff_rect_full(g: &mut Gpu, doc: &Document, rect: Rect, what: &str) -> Result { let cpu = timed("CPU reference", || photocraft_compose::render(doc, rect)); - let mut first = None; - for (label, comp) in [("", &mut g.comp), (" (paged)", &mut g.paged)] { + let mut whole = None; + let mut paged = None; + for (label, comp, slot) in [("", &mut g.comp, &mut whole), (" (paged)", &mut g.paged, &mut paged)] { let (out, stats) = timed(&format!("{what}{label} GPU render/readback"), || photocraft_gpu::render_to_vec_stats(comp, &g.device, &g.queue, doc, rect)) .map_err(|e| format!("{what}{label}: {e}"))?; let worst = worst_diff(&cpu.px, &out); @@ -228,15 +241,29 @@ fn diff_rect(g: &mut Gpu, doc: &Document, rect: Rect, what: &str) -> Result TOL { return Err(format!("{what}{label}: max diff {:.2}/255 at ({x},{y}): cpu {:?} gpu {:?}", worst.0 * 255.0, cpu.px[worst.1], out[worst.1])); } - first.get_or_insert(stats); + *slot = Some((out, stats)); } - first.ok_or_else(|| format!("{what}: no render")) + match (whole, paged) { + (Some((whole, whole_stats)), Some((_, paged_stats))) => Ok(Diff { whole, whole_stats, paged_stats }), + _ => Err(format!("{what}: no render")), + } +} + +/// GPU vs CPU over `rect`: Err with the worst pixel if over the tolerance, else the stats of +/// the unpaged render. +fn diff_rect(g: &mut Gpu, doc: &Document, rect: Rect, what: &str) -> Result { + diff_rect_full(g, doc, rect, what).map(|pass| pass.whole_stats) } fn check(g: &mut Gpu, doc: &Document, what: &str) { diff_rect(g, doc, doc.bounds(), what).unwrap_or_else(|e| panic!("{e}")); } +/// [`check`] returning the pass's pixels and stats, for tests that assert more than tolerance. +fn check_full(g: &mut Gpu, doc: &Document, what: &str) -> Diff { + diff_rect_full(g, doc, doc.bounds(), what).unwrap_or_else(|e| panic!("{e}")) +} + /// Growing a layer's tile footprint keeps the old texels in the overlap (`keep_overlap`) /// while the same update rewrites tiles inside that overlap (#6243): whatever submission /// shape the copy takes, the kept overlap must never overwrite tiles the same update @@ -311,12 +338,11 @@ fn stack_prefix_reuse_matches_uncached_gpu_and_cpu_at_every_depth() { top.fill_opacity = fill; top.blend = blend; top.visible = visible; - let stats = diff_rect(&mut g, &doc, doc.bounds(), "top properties").unwrap(); - assert!(stats.prefix_hits > 0, "{depth:?}"); - assert!(stats.prefix_passes_skipped > 0); - let cached = render_to_vec(&mut g.comp, &g.device, &g.queue, &doc, doc.bounds()).unwrap(); + let pass = diff_rect_full(&mut g, &doc, doc.bounds(), "top properties").unwrap(); + assert!(pass.whole_stats.prefix_hits > 0, "{depth:?}"); + assert!(pass.whole_stats.prefix_passes_skipped > 0); let cold = render_to_vec(&mut uncached, &g.device, &g.queue, &doc, doc.bounds()).unwrap(); - assert_eq!(cached, cold, "reuse preserves the GPU accumulator exactly"); + assert_eq!(pass.whole, cold, "reuse preserves the GPU accumulator exactly"); } let old = doc.clone(); doc.layers[1].surface_mut().unwrap().write_pixel(5, 5, &[0.8, 0.2, 0.6, 0.7]); @@ -349,18 +375,17 @@ fn prefix_follows_an_edit_up_the_stack_and_stays_exact() { doc.layers.push(if batched { l } else { alone(l) }); } let mut exact = |g: &mut Gpu, doc: &Document, what: &str| -> photocraft_gpu::Stats { - let stats = diff_rect(g, doc, doc.bounds(), what).unwrap_or_else(|e| panic!("{e}")); - let cached = render_to_vec(&mut g.comp, &g.device, &g.queue, doc, doc.bounds()).unwrap(); + let pass = diff_rect_full(g, doc, doc.bounds(), what).unwrap_or_else(|e| panic!("{e}")); let (cold, cold_stats) = photocraft_gpu::render_to_vec_stats(&mut uncached, &g.device, &g.queue, doc, doc.bounds()).unwrap(); - assert_eq!(cached, cold, "{depth:?} batched {batched} {what}: reuse preserves the GPU accumulator exactly"); + assert_eq!(pass.whole, cold, "{depth:?} batched {batched} {what}: reuse preserves the GPU accumulator exactly"); // Batched and single-layer draws needn't give the same bits on every backend (FXC // on D3D12): a render that captures the prefix groups the layers as an uncached one // does, wherever its checkpoint is. - if stats.prefix_hits == 0 { - assert_eq!(stats.layers_batched, cold_stats.layers_batched, "{depth:?} {what}: capturing changed the batches"); + if pass.whole_stats.prefix_hits == 0 { + assert_eq!(pass.whole_stats.layers_batched, cold_stats.layers_batched, "{depth:?} {what}: capturing changed the batches"); } assert_eq!(cold_stats.layers_batched > 0, batched, "{depth:?} {what}"); - stats + pass.whole_stats }; exact(&mut g, &doc, "populate"); // An edit low in the stack puts the cache there. @@ -473,20 +498,23 @@ fn root_checkpoints_keep_clipping_groups_and_adjustments_whole() { #[test] fn disjoint_partial_damages_admit_whole_chunks_not_damage_rects() { let Some(mut g) = gpu() else { return }; - let mut doc = base_doc(600, 300); + // 300 x 260 (#15927, was 600 x 300): still one 1024 px chunk, so whole-chunk admission is + // what keeps the two stroke series from growing the cache. + let mut doc = base_doc(300, 260); // Each layer in a pass of its own (`alone`): batched into one run, the stack has no // checkpoint below the top layer, so no render would capture and the byte count could not // grow whatever the admission did. doc.layers.push(alone(noise_layer("middle", PixelFormat::RGBA8, doc.bounds(), 2, 0.2))); doc.layers.push(alone(noise_layer("top", PixelFormat::RGBA8, doc.bounds(), 3, 0.2))); check(&mut g, &doc, "warm"); - // Each series paints 8 rectangles. The second series' rectangles are all new (7 px across - // and 65 px down from the first's) but in the same chunk (the 600 x 300 document is one - // chunk at `CHUNK`), so a cache entry per damage rectangle would add 8 entries. (The four - // series of 24 this replaces painted the same 24 rectangles every time.) + // Each series paints 8 rectangles. The second series' damage rectangles are distinct from + // the first's (5 px across and 65 px down), but their pixels land in the same chunk the + // first series already made resident (the 300 x 260 document is one chunk at `CHUNK`), so + // only admission could grow the cache: an entry per damage rectangle would add 8 entries. + // (The four series of 24 this replaces painted the same 24 rectangles every time.) let strokes = |g: &mut Gpu, doc: &Document, pass: i32| { for i in 0..8 { - let (x, y) = (40 + i * 60 + pass * 7, 30 + pass * 65); + let (x, y) = (20 + i * 30 + pass * 5, 20 + pass * 65); diff_rect(g, doc, Rect::new(x, y, x + 40, y + 30), "stroke").unwrap(); } }; @@ -514,7 +542,9 @@ fn disjoint_partial_damages_admit_whole_chunks_not_damage_rects() { #[test] fn prefix_partial_damage_context_occlusion_and_budget_are_conservative() { let Some(mut g) = gpu() else { return }; - let mut doc = base_doc(600, 300); + // 300 x 260 (#15927, was 600 x 300): one 1024 px chunk either way; the damage rectangles + // keep their relation to the covered chunk and to the document edge. + let mut doc = base_doc(300, 260); doc.layers.push(alone(noise_layer("middle", PixelFormat::RGBA8, doc.bounds(), 2, 0.2))); doc.layers.push(alone(noise_layer("top", PixelFormat::RGBA8, doc.bounds(), 3, 0.2))); check(&mut g, &doc, "full prefix"); @@ -524,13 +554,13 @@ fn prefix_partial_damage_context_occlusion_and_budget_are_conservative() { let region = Rect::new(10, 10, 50, 45); doc.layers[2].opacity = 0.4; assert!(diff_rect(&mut g, &doc, region, "partial rectangle in a covered chunk").unwrap().prefix_hits > 0); - let outside = Rect::new(10, 310, 50, 345); + let outside = Rect::new(10, 260, 50, 290); assert_eq!(diff_rect(&mut g, &doc, outside, "outside the document").unwrap().prefix_hits, 0); doc.layers[2].opacity = 0.7; assert!(diff_rect(&mut g, &doc, region, "same partial rectangle").unwrap().prefix_hits > 0); - doc.layers[0].surface_mut().unwrap().write_pixel(550, 270, &[1.0, 0.0, 1.0, 0.9]); + doc.layers[0].surface_mut().unwrap().write_pixel(280, 245, &[1.0, 0.0, 1.0, 0.9]); check(&mut g, &doc, "offscreen lower edit"); - diff_rect(&mut g, &doc, Rect::new(500, 250, 580, 290), "disjoint damage after invalidation").unwrap(); + diff_rect(&mut g, &doc, Rect::new(240, 210, 290, 250), "disjoint damage after invalidation").unwrap(); doc.global_light.angle += 15.0; assert_eq!(diff_rect(&mut g, &doc, doc.bounds(), "global context").unwrap().prefix_hits, 0); doc.layers.push(Layer::new("opaque cover", LayerContent::Fill(Fill::Solid(Color::WHITE)))); @@ -1191,8 +1221,11 @@ fn formats_offsets_and_chunks() { #[test] fn incremental_updates_follow_the_document() { let Some(mut g) = gpu() else { return }; - let mut d = base_doc(600, 300); - d.layers.push(noise_layer("top", PixelFormat::RGBA8, Rect::new(0, 0, 600, 300), 61, 0.0)); + // 300 x 260 (#15927, was 600 x 300): the top layer still spans a 2 x 2 grid of 256 px tiles, + // and the paint below still lands in one tile at the same corner; upload bookkeeping is + // per tile. + let mut d = base_doc(300, 260); + d.layers.push(noise_layer("top", PixelFormat::RGBA8, Rect::new(0, 0, 300, 260), 61, 0.0)); check(&mut g, &d, "initial"); // Paint into one tile of the top layer: only that tile uploads. let top = d.layers[1].surface_mut().unwrap(); @@ -1214,8 +1247,10 @@ fn incremental_updates_follow_the_document() { #[test] fn duplicates_copy_their_source_texture() { let Some(mut g) = gpu() else { return }; - let mut d = base_doc(600, 300); - let mut src = noise_layer("src", PixelFormat::RGBA8, Rect::new(0, 0, 600, 300), 71, 0.0); + // 300 x 260 (#15927, was 600 x 300): four 256 px tiles with one absent from a duplicate — + // the copy and COW paths are per tile, and the two painted tiles stay distinct. + let mut d = base_doc(300, 260); + let mut src = noise_layer("src", PixelFormat::RGBA8, Rect::new(0, 0, 300, 260), 71, 0.0); src.opacity = 0.7; d.layers.push(src); check(&mut g, &d, "source"); @@ -1231,7 +1266,7 @@ fn duplicates_copy_their_source_texture() { dup2.blend = BlendMode::Screen; dup2.surface_mut().unwrap().fill_rect(Rect::new(10, 10, 20, 20), &[1.0, 0.0, 0.0, 1.0]); d.layers.push(dup2); - d.layers[1].surface_mut().unwrap().fill_rect(Rect::new(300, 100, 310, 110), &[0.0, 0.0, 1.0, 1.0]); + d.layers[1].surface_mut().unwrap().fill_rect(Rect::new(260, 100, 270, 110), &[0.0, 0.0, 1.0, 1.0]); check(&mut g, &d, "duplicate and source painted"); // And a tile removed from a duplicate: it reads as transparent again. let mut dup3 = d.layers[1].duplicate(); @@ -1249,15 +1284,19 @@ fn duplicates_copy_their_source_texture() { #[test] fn changed_mask_default_updates_absent_tiles() { let Some(mut g) = gpu() else { return }; - let mut d = base_doc(600, 300); - d.layers.push(noise_layer("top", PixelFormat::RGBA8, Rect::new(0, 0, 600, 300), 61, 0.5)); - // Tiles in opposite corners: the resident texture spans the absent tiles between them. - let corners = [Rect::new(0, 0, 70, 70), Rect::new(530, 230, 600, 300)]; - let data = vec![0.5f32; 70 * 70]; + // 300 x 260 (#15927, was 600 x 300): the two stored tiles still span a 2 x 2 resident + // texture whose other two tiles stay absent. A patch reaching the opposite corner at + // (230,190) would store all four tiles and leave the default with nothing to cover. + let mut d = base_doc(300, 260); + d.layers.push(noise_layer("top", PixelFormat::RGBA8, Rect::new(0, 0, 300, 260), 61, 0.5)); + // Tiles in opposite corners only, the far one starting on the 256 px boundary: the resident + // texture spans the absent tile column and the absent tile row between them. + let corners = [Rect::new(0, 0, 70, 70), Rect::new(256, 256, 300, 260)]; for default in [0.0, 1.0] { let mut m = LayerMask::reveal_all(); m.surface = photocraft_raster::Surface::with_default(PixelFormat::GRAY8, &[default]); for r in corners { + let data = vec![0.5f32; r.width() as usize * r.height() as usize]; m.surface.write_region(r, &data); } d.layers[1].mask = Some(m); @@ -1271,7 +1310,10 @@ fn changed_mask_default_updates_absent_tiles() { #[test] fn shared_tiles_upload_once_and_copy() { let Some(mut g) = gpu() else { return }; - let (w, h) = (1100, 700); + // 540 x 540 (#15927, was 1100 x 700): a 3 x 3 grid of 256 px tiles and pages with full + // interior tiles and partial right/bottom ones — every branch here is per tile and page, + // not per document byte. + let (w, h) = (540, 540); for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat { sample: SampleType::U16, ..PixelFormat::GRAYA8 }] { let mut d = base_doc(w, h); let mut l = Layer::raster("fill", fmt); @@ -1309,32 +1351,35 @@ fn shared_tiles_upload_once_and_copy() { #[test] fn growing_layer_keeps_its_resident_tiles() { let Some(mut g) = gpu() else { return }; - let (w, h) = (1100, 700); + // 540 x 540 (#15927, was 1100 x 700): the layer footprint still grows past 256 px tiles in + // all five directions — right, down, towards the origin, inside, and far out — and stays + // within the same 2-tiles-uploaded bound per dab. + let (w, h) = (540, 540); for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA32F] { let mut d = base_doc(w, h); let mut l = Layer::raster("paint", fmt); - l.surface_mut().unwrap().fill_rect(Rect::new(500, 300, 540, 340), &[0.3, 0.6, 0.2, 0.9][..fmt.channels()]); + l.surface_mut().unwrap().fill_rect(Rect::new(260, 260, 300, 300), &[0.3, 0.6, 0.2, 0.9][..fmt.channels()]); let mut m = LayerMask::reveal_all(); m.surface = photocraft_raster::Surface::with_default(PixelFormat::GRAY8, &[0.75]); - m.surface.fill_rect(Rect::new(510, 310, 520, 320), &[0.25]); + m.surface.fill_rect(Rect::new(265, 265, 275, 275), &[0.25]); l.mask = Some(m); d.layers.push(l); check(&mut g, &d, &format!("{fmt:?} initial")); let small = d.clone(); // Dabs right (over a stored tile too, so it changes as the page grows), down, up-left // (the page grows towards the origin), inside, and far out. - for (i, r) in [(480, 320, 760, 380), (520, 560, 580, 620), (60, 40, 120, 100), (505, 305, 535, 335), (1040, 640, 1100, 700)].into_iter().enumerate() { + for (i, r) in [(280, 270, 540, 330), (300, 340, 360, 530), (40, 40, 100, 100), (265, 265, 295, 295), (516, 516, 540, 540)].into_iter().enumerate() { let dab = Rect::new(r.0, r.1, r.2, r.3); d.layers[1].surface_mut().unwrap().fill_rect(dab, &[0.9, 0.1, 0.3, 0.7][..fmt.channels()]); if i == 2 { d.layers[1].mask.as_mut().unwrap().surface.fill_rect(dab, &[0.5]); } let what = format!("{fmt:?} dab {i}"); - let s = diff_rect(&mut g, &d, d.bounds(), &what).unwrap_or_else(|e| panic!("{e}")); - assert!(s.tiles_uploaded <= 2, "{what}: only the dab's tiles upload: {s:?}"); + let pass = diff_rect_full(&mut g, &d, d.bounds(), &what).unwrap_or_else(|e| panic!("{e}")); + assert!(pass.whole_stats.tiles_uploaded <= 2, "{what}: only the dab's tiles upload: {:?}", pass.whole_stats); let mut fresh = g.comp.sibling(); let want = render_to_vec(&mut fresh, &g.device, &g.queue, &d, d.bounds()).unwrap(); - assert!(render_to_vec(&mut g.comp, &g.device, &g.queue, &d, d.bounds()).unwrap() == want, "{what}: same pixels as a fresh upload"); + assert!(pass.whole == want, "{what}: same pixels as a fresh upload"); } // Undo back to the small layer: the pages shrink and show its pixels again. check(&mut g, &small, &format!("{fmt:?} undone")); @@ -1420,8 +1465,9 @@ fn small_layers_composite_over_their_bounds() { pt.opacity = 0.6; d.layers.push(pt); check(&mut g, &d, "small layers"); - // The same over several compositor chunks. - let mut big = base_doc(1500, 1200); + // The same over several compositor chunks. 1080 x 1080 (#15927, was 1500 x 1200): still a + // 2 x 2 grid of 1024 px chunks, and the small layers still straddle the inner chunk border. + let mut big = base_doc(1080, 1080); for (i, mode) in BlendMode::layer_modes().enumerate() { let i = i as i32; big.layers.push(small(400 + i as u32, 1010 + (i % 4) * 5, 1010 + (i / 4) * 5, mode)); @@ -1467,17 +1513,19 @@ fn runs_of_plain_layers_blend_in_one_pass() { // bounds) and clipping groups. Then an edit in the middle, so the prefix cache resumes // part-way up the stack and runs start at its checkpoint. let Some(mut g) = gpu() else { return }; - let mut d = base_doc(96, 64); + // 48 x 32 (#15927, was 96 x 64): batching is decided per layer and per run, not per pixel + // count, and the layers that end inside the canvas still overhang its left edge. + let mut d = base_doc(48, 32); let modes: Vec = BlendMode::layer_modes().collect(); for (i, mode) in modes.iter().copied().cycle().take(90).enumerate() { let i32_ = i as i32; - let rect = if i % 5 == 2 { Rect::from_xywh(-8, 10, 70, 40) } else { Rect::from_xywh(0, 0, 96, 64) }; + let rect = if i % 5 == 2 { Rect::from_xywh(-4, 5, 35, 20) } else { Rect::from_xywh(0, 0, 48, 32) }; let mut l = noise_layer("l", PixelFormat::RGBA8, rect, 900 + i as u32, 0.0); l.blend = mode; l.opacity = 0.35 + 0.05 * (i % 13) as f32; l.fill_opacity = if i % 4 == 1 { 0.6 } else { 1.0 }; if i % 11 == 7 { - l.mask = Some(mask(Rect::from_xywh(i32_ % 30, 0, 50, 64), 70 + i as u32, 0.0)); + l.mask = Some(mask(Rect::from_xywh(i32_ % 15, 0, 25, 32), 70 + i as u32, 0.0)); } if i % 23 == 9 { l.clipped = true; @@ -1489,7 +1537,7 @@ fn runs_of_plain_layers_blend_in_one_pass() { d.layers.push(f); } if i % 17 == 8 { - d.layers.push(noise_layer("small", PixelFormat::RGBA8, Rect::from_xywh(20, 20, 6, 5), 40 + i as u32, 0.5)); + d.layers.push(noise_layer("small", PixelFormat::RGBA8, Rect::from_xywh(10, 10, 6, 5), 40 + i as u32, 0.5)); } } let stats = diff_rect(&mut g, &d, d.bounds(), "plain layer runs").unwrap_or_else(|e| panic!("{e}")); @@ -1510,16 +1558,18 @@ fn runs_of_normal_layers_blend_with_normal_code_alone() { for (mode, depth) in [(ColorMode::Rgb, SampleType::U8), (ColorMode::Rgb, SampleType::U16), (ColorMode::Rgb, SampleType::F32), (ColorMode::Lab, SampleType::U8)] { - let mut d = Document::new("normal", Size::new(96, 64), mode, depth); + // 48 x 32 (#15927, was 96 x 64): the Normal-run shader is picked per layer and mode, not + // per pixel; the runs that end inside the canvas still overhang the left edge. + let mut d = Document::new("normal", Size::new(48, 32), mode, depth); let fmt = d.pixel_format(); - d.layers.push(noise_layer("bg", fmt, Rect::from_xywh(0, 0, 96, 64), 5, 0.0)); + d.layers.push(noise_layer("bg", fmt, Rect::from_xywh(0, 0, 48, 32), 5, 0.0)); for i in 0..40u32 { - let rect = if i % 5 == 3 { Rect::from_xywh(-6, 9, 70, 44) } else { Rect::from_xywh(0, 0, 96, 64) }; + let rect = if i % 5 == 3 { Rect::from_xywh(-3, 5, 35, 22) } else { Rect::from_xywh(0, 0, 48, 32) }; let mut l = noise_layer("n", fmt, rect, 600 + i, if i % 3 == 0 { 0.0 } else { 0.4 }); l.opacity = 0.2 + 0.07 * (i % 11) as f32; l.fill_opacity = [1.0, 0.55, 0.0, 0.8][i as usize % 4]; if i % 7 == 2 { - l.mask = Some(mask(Rect::from_xywh(i as i32 % 25, 0, 60, 64), 50 + i, 0.0)); + l.mask = Some(mask(Rect::from_xywh(i as i32 % 13, 0, 30, 32), 50 + i, 0.0)); } d.layers.push(l); if i % 6 == 4 { @@ -2165,16 +2215,19 @@ fn layer_effects_on_groups_clipping_and_fills() { fn layer_effects_update_incrementally() { let Some(mut g) = gpu() else { return }; let stack = effect_cases().into_iter().find(|(n, _)| *n == "full stack").unwrap().1; - let mut d = fx_doc(700, 600, SampleType::U8); + // 540 x 500 (#15927, was 700 x 600): the effect layer keeps its size — the partial-rebuild + // half-ratio is set by the map area, not by the document margin — and every edit stays on + // canvas. + let mut d = fx_doc(540, 500, SampleType::U8); let mut l = blob("fx", d.pixel_format(), 300.0, 280.0, 200.0, [0.9, 0.4, 0.2]); l.effects.items = stack; d.layers.push(l); - d.layers.push(noise_layer("plain", PixelFormat::RGBA8, Rect::new(500, 20, 650, 120), 5, 0.0)); + d.layers.push(noise_layer("plain", PixelFormat::RGBA8, Rect::new(460, 20, 530, 120), 5, 0.0)); let first = fx_check(&mut g, &d, "initial"); assert!(first.fx_programs > 0 && first.fx_shapes == 1); // An unrelated edit (another layer's pixels, the effect layer's opacity and an effect colour) // reuses every map. - d.layers[2].surface_mut().unwrap().fill_rect(Rect::new(520, 30, 560, 60), &[0.0, 1.0, 0.0, 1.0]); + d.layers[2].surface_mut().unwrap().fill_rect(Rect::new(470, 30, 510, 60), &[0.0, 1.0, 0.0, 1.0]); d.layers[1].opacity = 0.8; if let Effect::ColorOverlay { color, .. } = &mut d.layers[1].effects.items[6] { *color = Color::rgb(0.1, 0.9, 0.9); @@ -3168,14 +3221,13 @@ fn documents_larger_than_the_texture_limit() { let mut d = small_big_doc(); assert!(g.paged.supports(&d).is_ok()); // Every pass sees page borders, and effect maps and blurs crossing them. - check(&mut g, &d, "big document"); - let s = photocraft_gpu::render_to_vec_stats(&mut g.paged, &g.device, &g.queue, &d, d.bounds()).unwrap().1; + let pass = check_full(&mut g, &d, "big document"); + let s = pass.paged_stats; assert!(s.cells >= 9 && s.chunks == s.cells, "{s:?}"); // A viewport off the page grid covers only its cells (3 x 2). let view = Rect::new(200, 230, 530, 430); - diff_rect(&mut g, &d, view, "viewport").unwrap_or_else(|e| panic!("{e}")); - let s = photocraft_gpu::render_to_vec_stats(&mut g.paged, &g.device, &g.queue, &d, view).unwrap().1; - assert_eq!(s.cells, 6, "{s:?}"); + let pass = diff_rect_full(&mut g, &d, view, "viewport").unwrap_or_else(|e| panic!("{e}")); + assert_eq!(pass.paged_stats.cells, 6, "{:?}", pass.paged_stats); // A dab across a page corner on the effect layer, and an edit elsewhere. d.layers[3].surface_mut().unwrap().fill_rect(Rect::new(240, 240, 270, 270), &[0.1, 0.1, 0.9, 1.0]); d.layers[2].surface_mut().unwrap().fill_rect(Rect::new(500, 250, 520, 270), &[0.0, 0.0, 0.0, 0.0]); @@ -3218,9 +3270,11 @@ fn pages_are_evicted_under_the_budget() { #[test] fn layer_pages_are_admitted_under_a_zero_budget_and_stay_on_the_gpu() { let Some(mut g) = gpu() else { return }; - let mut d = base_doc(600, 500); - d.layers.push(noise_layer("mid", PixelFormat::RGBA8, Rect::new(-20, 10, 590, 480), 61, 0.0)); - let mut top = noise_layer("top", PixelFormat::RGBA8, Rect::new(30, -15, 620, 510), 62, 0.2); + // 540 x 260 (#15927, was 600 x 500): still a 3 x 2 grid of 256 px pages, with the two layers + // overhanging the canvas left, top, right and bottom — the page-admission path is per cell. + let mut d = base_doc(540, 260); + d.layers.push(noise_layer("mid", PixelFormat::RGBA8, Rect::new(-20, 10, 530, 240), 61, 0.0)); + let mut top = noise_layer("top", PixelFormat::RGBA8, Rect::new(30, -15, 560, 275), 62, 0.2); top.blend = BlendMode::Multiply; d.layers.push(top); // Exercise page residency itself: lower-stack checkpoints could skip binding the pages. @@ -3250,9 +3304,10 @@ fn layer_pages_are_admitted_under_a_zero_budget_and_stay_on_the_gpu() { #[test] fn a_layer_page_out_of_memory_retries_then_ends_only_that_refresh_on_the_cpu() { let Some(mut g) = gpu() else { return }; - let mut d = base_doc(600, 500); - d.layers.push(noise_layer("mid", PixelFormat::RGBA8, Rect::new(-20, 10, 590, 480), 71, 0.0)); - let mut top = noise_layer("top", PixelFormat::RGBA8, Rect::new(30, -15, 620, 510), 72, 0.2); + // 540 x 260 (#15927, was 600 x 500): the same 3 x 2 page grid the failure counts are set for. + let mut d = base_doc(540, 260); + d.layers.push(noise_layer("mid", PixelFormat::RGBA8, Rect::new(-20, 10, 530, 240), 71, 0.0)); + let mut top = noise_layer("top", PixelFormat::RGBA8, Rect::new(30, -15, 560, 275), 72, 0.2); top.blend = BlendMode::Multiply; d.layers.push(top); g.paged.set_composite_cache_budget(0); @@ -3673,10 +3728,10 @@ fn anti_aliased_inner_shadow_matches_the_cpu_ramps() { let Some(mut g) = gpu() else { return }; let on = inner_shadow_issue_doc(true); let off = inner_shadow_issue_doc(false); - check(&mut g, &on, "#14934 inner shadow, Anti-aliased"); - check(&mut g, &off, "#14934 inner shadow, Anti-aliased off"); - let gpu_on = render_to_vec(&mut g.comp, &g.device, &g.queue, &on, on.bounds()).expect("gpu render, Anti-aliased"); - let gpu_off = render_to_vec(&mut g.comp, &g.device, &g.queue, &off, off.bounds()).expect("gpu render, Anti-aliased off"); + // `check_full` already rendered both documents on the whole-texture compositor: the ramps + // read those pixels, no second render per document (#15927). + let gpu_on = check_full(&mut g, &on, "#14934 inner shadow, Anti-aliased").whole; + let gpu_off = check_full(&mut g, &off, "#14934 inner shadow, Anti-aliased off").whole; let tl: &[f32] = &[65.0, 89.0, 107.0, 118.0, 124.0, 126.0, 127.0, 127.0, 128.0]; let br: &[f32] = &[49.0, 74.0, 96.0, 112.0, 121.0, 125.0, 126.0, 127.0, 128.0]; for ((side, got), want) in ["top", "left", "bottom", "right"].iter().zip(inner_shadow_ramps(&gpu_on)).zip([tl, tl, br, br]) { @@ -3714,6 +3769,11 @@ fn anti_aliased_inner_shadow_matches_the_cpu_ramps() { #[test] fn anti_aliased_inner_shadow_gated_neighbours_match_the_cpu() { let Some(mut g) = gpu() else { return }; + // #15927: the document stays 400 x 300 (crossing the 256 px page is why it is that size), + // but an Inner Shadow only moves pixels at the shape's edges. The CPU reference and both + // compositors are compared over the shape plus a margin around every measured row — the + // gated shift is inside it for every row below. + let shape = Rect::new(88, 63, 312, 237); for (size, spread, distance, what) in [ (10.0, 0.5, 0.0, "Size 10 Choke 50 %"), (10.0, 0.05, 0.0, "Size 10 Choke 5 %"), @@ -3724,6 +3784,7 @@ fn anti_aliased_inner_shadow_gated_neighbours_match_the_cpu() { (10.0, 0.0, 5.0, "Size 10 Choke 0 at Distance 5 (offset on, whole-pixel light offset)"), (10.0, 0.5, 5.0, "Size 10 Choke 50 % at Distance 5 (still gated)"), ] { - check(&mut g, &inner_shadow_doc(size, spread, distance, true), &format!("#14934 inner shadow, {what}, Anti-aliased")); + diff_rect(&mut g, &inner_shadow_doc(size, spread, distance, true), shape, &format!("#14934 inner shadow, {what}, Anti-aliased")) + .unwrap_or_else(|e| panic!("{e}")); } } diff --git a/crates/gpu/tests/it/pipelines.rs b/crates/gpu/tests/it/pipelines.rs index fa4b684ad9..8313213c4d 100644 --- a/crates/gpu/tests/it/pipelines.rs +++ b/crates/gpu/tests/it/pipelines.rs @@ -32,21 +32,24 @@ fn every_compositor_pipeline_builds() { // One instance per backend: `Backends::all()` only enables the others on one instance, and // `request_adapter` then returns the single default adapter, so the other backends' own // translation went untested. One adapter per backend keeps a second, unrelated adapter of the - // same backend (a dual-GPU laptop's integrated GPU) out of the run. - for (backends, compiler) in [(wgpu::Backends::DX12, wgpu::Dx12Compiler::Fxc), (wgpu::Backends::all(), wgpu::Dx12Compiler::Auto)] { + // same backend (a dual-GPU laptop's integrated GPU) out of the run. The second pass names DXC + // rather than `Auto`: without `dxcompiler.dll`, as on the Windows runners, `Auto` falls back to + // FXC and built every pipeline with FXC a second time (#15929), while a DXC that does not load + // leaves DX12 out of that pass. + for (backends, compiler) in [(wgpu::Backends::DX12, wgpu::Dx12Compiler::Fxc), (wgpu::Backends::all(), wgpu::Dx12Compiler::default_dynamic_dxc())] { + let required = cfg!(windows) && matches!(compiler, wgpu::Dx12Compiler::Fxc); for backend in backends.iter() { let instance = wgpu::Instance::new(describe(backend, compiler.clone())); // The Windows runners always have a WARP adapter on DX12, so a missing one there means // the check this test exists for silently did not run. Any other backend is a plain - // skip: `Backends::all()` also names backends this platform does not provide. + // skip: `Backends::all()` also names backends this platform does not provide, and + // DX12 through DXC needs a `dxcompiler.dll`. let Ok(adapter) = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) else { - #[cfg(windows)] - assert!(backend != wgpu::Backends::DX12, "no adapter on Windows: the DX12/FXC pipeline check did not run"); + assert!(!required, "no adapter on Windows: the DX12/FXC pipeline check did not run"); continue; }; let Ok((device, _queue)) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())) else { - #[cfg(windows)] - assert!(backend != wgpu::Backends::DX12, "no device on Windows: the DX12/FXC pipeline check did not run"); + assert!(!required, "no device on Windows: the DX12/FXC pipeline check did not run"); continue; }; let info = adapter.get_info(); diff --git a/crates/io/src/ora.rs b/crates/io/src/ora.rs index 07c00ff126..cf1f6b810d 100644 --- a/crates/io/src/ora.rs +++ b/crates/io/src/ora.rs @@ -509,6 +509,12 @@ impl Writer<'_> { if layer.clipped { self.warnings.layer(&layer.name, "OpenRaster has no clipping masks; these layers were saved unclipped"); } + if layer.excluded_channels != 0 { + self.warnings.layer(&layer.name, "OpenRaster drops channel blending restrictions from editable layers"); + } + if !layer.blend_if.is_default() { + self.warnings.layer(&layer.name, "OpenRaster drops Blend If settings from editable layers"); + } if !layer.effects.items.is_empty() || layer.effects.psd_raw.is_some() { self.warnings.layer(&layer.name, "layer styles are not saved to OpenRaster"); } diff --git a/crates/io/src/ora/tests.rs b/crates/io/src/ora/tests.rs index e073b01908..42b0a5e848 100644 --- a/crates/io/src/ora/tests.rs +++ b/crates/io/src/ora/tests.rs @@ -1,5 +1,5 @@ use super::*; -use photocraft_doc::{Adjustment, Color, Fill, LayerMask}; +use photocraft_doc::{Adjustment, BlendRange, Color, Fill, LayerMask}; const CANVAS: Size = Size { width: 70, height: 50 }; @@ -540,6 +540,8 @@ fn lossy_documents() -> Vec<(&'static str, Document)> { with(&move |d| d.layers.push(l.clone())) }), ("clipped", with(&|d| d.layers[1].clipped = true)), + ("channel blending", with(&|d| d.layers[0].excluded_channels = 1)), + ("Blend If", with(&|d| d.layers[0].blend_if.set(0, [BlendRange { black: [128, 128], ..BlendRange::FULL }, BlendRange::FULL]))), ("fill opacity", with(&|d| d.layers[0].fill_opacity = 0.5)), ("pixel lock", with(&|d| d.layers[0].locks.pixels = true)), // Not the bottom layer: with its transparency lock, `Base` would become the Background. @@ -567,6 +569,8 @@ fn plain_documents_lose_nothing() { for depth in [SampleType::U8, SampleType::U16] { let mut d = doc(depth); assert_eq!(losses(&d), Vec::::new(), "{depth:?}"); + d.layers[0].blend_if.ranges = vec![[BlendRange::FULL; 2]; 4]; + assert_eq!(losses(&d), Vec::::new(), "{depth:?} full Blend If ranges"); d.icc_profile = Some(craft_cms::Builtin::Srgb.profile().to_bytes()); assert_eq!(losses(&d), Vec::::new(), "{depth:?} tagged sRGB"); assert_eq!(export(&d).unwrap().warnings, Vec::::new()); diff --git a/crates/io/tests/it/adjust_warnings.rs b/crates/io/tests/it/adjust_warnings.rs index 55220bb251..d74ffde1e6 100644 --- a/crates/io/tests/it/adjust_warnings.rs +++ b/crates/io/tests/it/adjust_warnings.rs @@ -177,45 +177,49 @@ fn short_color_lookup_table_warns_on_open() { #[test] fn custom_domain_lookup_warns_and_round_trips_verbatim() { + // The domain spelling only decides whether the LUT reads as default (`read_lookup`); from + // there the block is kept as raw bytes, whose stored lengths are all a multiple of four, so + // no spelling changes the containers' padding. Each container takes the spellings in turn: + // every spelling still crosses PSD and PSB, and `adjust_map`'s unit tests parse each one. let domains = ["DOMAIN_MIN 0 0 0\nDOMAIN_MAX 0.5 0.5 0.5\n", "DOMAIN_MIN 0 0.25 0\nDOMAIN_MAX 1 0.75 1\n", "LUT_3D_INPUT_RANGE 0 0.5\n"]; - for domain in domains { + let containers = [ + (Version::Psd, 8, "psd"), + (Version::Psd, 16, "psd"), + (Version::Psd, 32, "psd"), + (Version::Psb, 8, "psb"), + (Version::Psb, 16, "psb"), + (Version::Psb, 32, "psb"), + ]; + for (i, (version, depth, extension)) in containers.into_iter().enumerate() { + let domain = domains[i % domains.len()]; let cube = identity_cube(domain); - for (version, depth, extension) in [ - (Version::Psd, 8, "psd"), - (Version::Psd, 16, "psd"), - (Version::Psd, 32, "psd"), - (Version::Psb, 8, "psb"), - (Version::Psb, 16, "psb"), - (Version::Psb, 32, "psb"), - ] { - let input = synthetic_lookup_psd(version, depth, &cube); - let (_, source_block) = parsed_lookup_block(&input); - let name = format!("input.{extension}"); - let opened = import(&name, &input).expect("open synthetic PSD/PSB"); - assert_eq!(unsupported_lookup_raw(&opened.document), source_block, "{extension}, {depth}-bit, {domain:?}"); - let warnings: Vec<_> = opened.warnings.iter().filter(|warning| warning.contains("Custom-domain LUT")).collect(); - assert_eq!(warnings.len(), 1, "{extension}, {depth}-bit: {:?}", opened.warnings); - assert!( - warnings[0].contains("Color Lookup") - && warnings[0].contains("DOMAIN_MIN") - && warnings[0].contains("DOMAIN_MAX") - && warnings[0].to_ascii_lowercase().contains("not supported"), - "{}", - warnings[0] - ); + let input = synthetic_lookup_psd(version, depth, &cube); + let (_, source_block) = parsed_lookup_block(&input); + let name = format!("input.{extension}"); + let opened = import(&name, &input).expect("open synthetic PSD/PSB"); + assert_eq!(unsupported_lookup_raw(&opened.document), source_block, "{extension}, {depth}-bit, {domain:?}"); + let warnings: Vec<_> = opened.warnings.iter().filter(|warning| warning.contains("Custom-domain LUT")).collect(); + assert_eq!(warnings.len(), 1, "{extension}, {depth}-bit: {:?}", opened.warnings); + assert!( + warnings[0].contains("Color Lookup") + && warnings[0].contains("DOMAIN_MIN") + && warnings[0].contains("DOMAIN_MAX") + && warnings[0].to_ascii_lowercase().contains("not supported"), + "{}", + warnings[0] + ); - let native = export(&opened.document, "preserved.pcraft", &ExportOptions::default()).expect("save native document"); - let native_open = import("preserved.pcraft", &native.bytes).expect("reopen native document"); - assert_eq!(unsupported_lookup_raw(&native_open.document), source_block, "native preservation, {extension}, {depth}-bit"); + let native = export(&opened.document, "preserved.pcraft", &ExportOptions::default()).expect("save native document"); + let native_open = import("preserved.pcraft", &native.bytes).expect("reopen native document"); + assert_eq!(unsupported_lookup_raw(&native_open.document), source_block, "native preservation, {extension}, {depth}-bit"); - let output_name = format!("roundtrip.{extension}"); - let options = ExportOptions { force_psb: version.is_psb(), ..Default::default() }; - let saved = export(&native_open.document, &output_name, &options).expect("re-export PSD/PSB"); - let (_, output_block) = parsed_lookup_block(&saved.bytes); - assert_eq!(output_block, source_block, "saved block, {extension}, {depth}-bit, {domain:?}"); - let reopened = import(&output_name, &saved.bytes).expect("reopen re-exported PSD/PSB"); - assert_eq!(unsupported_lookup_raw(&reopened.document), source_block, "reopened block, {extension}, {depth}-bit"); - } + let output_name = format!("roundtrip.{extension}"); + let options = ExportOptions { force_psb: version.is_psb(), ..Default::default() }; + let saved = export(&native_open.document, &output_name, &options).expect("re-export PSD/PSB"); + let (_, output_block) = parsed_lookup_block(&saved.bytes); + assert_eq!(output_block, source_block, "saved block, {extension}, {depth}-bit, {domain:?}"); + let reopened = import(&output_name, &saved.bytes).expect("reopen re-exported PSD/PSB"); + assert_eq!(unsupported_lookup_raw(&reopened.document), source_block, "reopened block, {extension}, {depth}-bit"); } } diff --git a/crates/ipp/Cargo.toml b/crates/ipp/Cargo.toml index f9480715c4..be8732e9c0 100644 --- a/crates/ipp/Cargo.toml +++ b/crates/ipp/Cargo.toml @@ -7,7 +7,7 @@ license.workspace = true rust-version.workspace = true [dependencies] -craft-ipp = { git = "https://github.com/storytold/craft-libs", rev = "77c7c62345c1f4213f59a07d9fdc156ecde0b540" } +craft-ipp = { git = "https://github.com/storytold/craft-libs", rev = "e953d47a378776dea207899b10baf969fc8cbe53" } [lints] workspace = true diff --git a/crates/raw/tests/it/hostile.rs b/crates/raw/tests/it/hostile.rs index 7ae2287b69..b04d93ce9f 100644 --- a/crates/raw/tests/it/hostile.rs +++ b/crates/raw/tests/it/hostile.rs @@ -157,10 +157,23 @@ fn a_seed_states_a_maker_note_colour_space() { assert!(samples().iter().any(|b| embedded_preview_color_space(b) == Some(PreviewColorSpace::AdobeRgb))); } +/// Whether the fuzz tests below run every case instead of their fixed sample: `PHOTOCRAFT_FULL_SWEEP=1`, +/// the switch `photocraft_testkit::Sweep` reads (this standalone crate cannot depend on the testkit). +fn full_sweep() -> bool { + std::env::var_os("PHOTOCRAFT_FULL_SWEEP").is_some_and(|v| v == "1") +} + #[test] fn every_truncation_fails_cleanly() { + // The fixed sample: the first and last 16 lengths, which cut the header and the last bytes of + // the sensor data, every 7th length in the first 2 KiB, and about 300 lengths per file past it. + // Only the RW2 seed is much longer: RW2 pads its data to a 16 KiB block, so its cuts past 2 KiB + // all decode the same zeros, and every 7th of them cost more than the rest of the test. + // The full sweep tries every length. + let full = full_sweep(); for b in samples() { - for n in (0..b.len()).step_by(3) { + let step = |n: usize| if n < 2048 { 7 } else { (b.len() / 300).max(7) }; + for n in (0..b.len()).filter(|&n| full || n % step(n) == 0 || n < 16 || n + 16 >= b.len()) { exercise(&b[..n]); } } @@ -168,13 +181,15 @@ fn every_truncation_fails_cleanly() { #[test] fn random_corruption_never_panics() { - let mut s = 0xDEAD_BEEF_u64; - let mut next = || { - s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - s >> 33 - }; - for b in samples() { - for _ in 0..400 { + let cases = if full_sweep() { 400 } else { 40 }; + for (i, b) in samples().iter().enumerate() { + // A stream per file, so the fixed sample is the start of the full sweep's. + let mut s = 0xDEAD_BEEF_u64 ^ (i as u64 + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15); + let mut next = || { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + s >> 33 + }; + for _ in 0..cases { let mut c = b.clone(); for _ in 0..1 + next() % 6 { let at = next() as usize % c.len(); diff --git a/crates/tablet/src/xi.rs b/crates/tablet/src/xi.rs index 2195acd3ce..943dc9cf98 100644 --- a/crates/tablet/src/xi.rs +++ b/crates/tablet/src/xi.rs @@ -133,8 +133,14 @@ pub struct State { impl State { /// Replace the device list (after `XIQueryDevice`, on start and hierarchy changes). pub fn set_devices(&mut self, devices: impl IntoIterator) { - self.devices = devices.into_iter().take(MAX_DEVICES).map(|d| (d.id, d)).collect(); - self.last.retain(|id, _| self.devices.contains_key(id)); + let devices: HashMap<_, _> = devices.into_iter().take(MAX_DEVICES).map(|d| (d.id, d)).collect(); + // Cached values are already mapped: changed ranges or axes make them stale. + // XIQueryDevice may return the same classes in a different order. + self.last.retain(|id, _| match (self.devices.get(id), devices.get(id)) { + (Some(old), Some(new)) => old.eraser == new.eraser && old.axes.len() == new.axes.len() && old.axes.iter().all(|axis| new.axes.contains(axis)), + _ => false, + }); + self.devices = devices; } pub fn device(&self, id: u16) -> Option<&Device> { @@ -252,6 +258,35 @@ mod tests { assert_eq!(st.handle(2, [(2, 3.0)]), Update::Keep); } + #[test] + fn refreshing_devices_resets_changed_mappings_only() { + let original = wacom(9, "Pen stylus"); + let unchanged = wacom(10, "Pen eraser"); + let removed = wacom(11, "Pen stylus"); + let mut st = State::default(); + st.set_devices([original.clone(), unchanged.clone(), removed.clone()]); + let _ = st.handle(9, [(2, 32767.5), (3, -30.0), (4, 45.0)]); + let cached = sample(st.handle(10, [(2, 49151.25), (3, 12.0), (5, 0.0)])); + let _ = st.handle(11, [(2, 65535.0)]); + + let mut changed = original; + changed.axes.retain(|a| a.kind != AxisKind::TiltY); + changed.axes.iter_mut().find(|a| a.kind == AxisKind::Pressure).unwrap().max *= 2.0; + // XIQueryDevice does not promise a stable class order. + let mut reordered = unchanged.clone(); + reordered.axes.reverse(); + st.set_devices([changed.clone(), reordered]); + + let fresh = sample(st.handle(9, [])); + assert_eq!((fresh.pressure, fresh.tilt_x, fresh.tilt_y, fresh.rotation), (0.0, 0.0, 0.0, 0.0)); + assert_eq!(sample(st.handle(9, [(2, 32767.5)])).pressure, 0.25); + assert_eq!(sample(st.handle(10, [])), cached, "unchanged mappings retain their sample"); + assert_eq!(st.handle(11, []), Update::Keep); + + st.set_devices([changed, unchanged, removed]); + assert_eq!(sample(st.handle(11, [])).pressure, 0.0, "removed devices lose their cached sample"); + } + #[test] fn tilt_ranges_that_are_not_degrees_are_scaled() { let d = diff --git a/crates/text/src/served.rs b/crates/text/src/served.rs index 1069e29841..d2e42b2177 100644 --- a/crates/text/src/served.rs +++ b/crates/text/src/served.rs @@ -144,7 +144,8 @@ pub fn language_script(tag: &str) -> Option<&'static str> { let tag = tag.trim().to_ascii_lowercase().replace('_', "-"); let mut parts = tag.split('-'); let lang = parts.next()?; - let rest: Vec<&str> = parts.collect(); + // RFC 5646: a singleton starts extensions/private use; their values do not choose the script. + let rest: Vec<&str> = parts.take_while(|part| part.len() != 1).collect(); Some(match lang { "ar" | "fa" | "ur" | "ps" | "ckb" | "sd" | "ug" => "Arab", "he" | "iw" | "yi" => "Hebr", @@ -156,6 +157,8 @@ pub fn language_script(tag: &str) -> Option<&'static str> { "ka" => "Geor", "ja" => "Jpan", "ko" => "Kore", + // An explicit script takes precedence over regional defaults. + "zh" if rest.contains(&"hans") => "Hans", "zh" if rest.iter().any(|r| matches!(*r, "hant" | "tw" | "hk" | "mo")) => "Hant", "zh" => "Hans", _ => return None, @@ -488,7 +491,19 @@ mod tests { ("ja-JP", Some("Jpan")), ("zh-CN", Some("Hans")), ("zh-TW", Some("Hant")), + ("zh-HK", Some("Hant")), + ("zh-MO", Some("Hant")), + ("zh-Hans-TW", Some("Hans")), + ("zh-Hans-HK", Some("Hans")), + ("zh-Hans-MO", Some("Hans")), + ("zh-Hant-CN", Some("Hant")), ("zh-Hant-HK", Some("Hant")), + ("zh-Hant-TW-u-nu-hans", Some("Hant")), + ("zh-TW-u-nu-hans", Some("Hant")), + ("zh-CN-u-nu-hant", Some("Hans")), + ("zh-cmn-Hans-TW", Some("Hans")), + ("zh-cmn-Hant-CN", Some("Hant")), + ("zh-TW-x-hans", Some("Hant")), ("ko", Some("Kore")), ("en-US", None), ("ru", None), diff --git a/crates/text/src/spell.rs b/crates/text/src/spell.rs index 31ddf7bf03..f8dc616959 100644 --- a/crates/text/src/spell.rs +++ b/crates/text/src/spell.rs @@ -110,9 +110,15 @@ impl Dictionary { } /// Up to `max` suggestions for a misspelled word, nearest first (then most common), with the - /// word's case pattern applied. + /// word's case pattern and possessive ending applied. pub fn suggest(&self, word: &str, max: usize) -> Vec { - let w = normalize(word); + let normalized = normalize(word); + let (w, suffix) = normalized + .strip_suffix("'s") + .filter(|w| !w.is_empty()) + .map(|w| (w, "'s")) + .or_else(|| normalized.strip_suffix("'S").filter(|w| !w.is_empty()).map(|w| (w, "'S"))) + .unwrap_or((&normalized, "")); let lower = w.to_lowercase(); let lc: Vec = lower.chars().collect(); let n = lc.len(); @@ -132,6 +138,10 @@ impl Dictionary { continue; }; for (cand, cc, lvl) in bucket { + // The input's ending is restored below; do not append it to another possessive. + if !suffix.is_empty() && cand.ends_with("'s") { + continue; + } if let Some(d) = distance(&lc, cc, max_d, &mut rows) { found.push((d, !anagram(cand), *lvl, cand)); } @@ -146,14 +156,15 @@ impl Dictionary { let mut forms: Vec<&String> = self.by_lower.get(cand).into_iter().flatten().collect(); forms.sort_by_key(|f| f.chars().any(char::is_uppercase)); for form in forms { - let s = if all_caps { + let mut s = if all_caps { form.to_uppercase() } else if first_cap { capitalize(form) } else { form.clone() }; - if !out.contains(&s) && s != w { + s.push_str(suffix); + if !out.contains(&s) && s != normalized { out.push(s); } } @@ -190,7 +201,7 @@ fn capitalize(w: &str) -> String { /// Byte ranges of the words in `text`: letters/digits with inner apostrophes (hyphens split). pub fn words(text: &str) -> Vec<(usize, usize)> { - let is_apos = |c: char| matches!(c, '\'' | '\u{2019}' | '\u{02BC}'); + let is_apos = |c: char| matches!(c, '\'' | '\u{2019}' | '\u{2018}' | '\u{02BC}'); let mut out = Vec::new(); let mut start: Option = None; let chars: Vec<(usize, char)> = text.char_indices().collect(); @@ -298,6 +309,35 @@ mod tests { assert_eq!(d.suggest("HELO", 5).first().map(|s| s.chars().all(|c| c.is_uppercase())), Some(true)); } + #[test] + fn possessive_suggestions_keep_the_ending_and_case() { + let d = Dictionary::from_list("#10\nworld\nworlds\nMonday\n"); + for (word, want) in [("wrold's", "world's"), ("Wrold's", "World's"), ("WROLD'S", "WORLD'S"), ("WROLD's", "WORLD's"), ("Mnday's", "Monday's")] { + assert_eq!(d.suggest(word, 1), vec![want.to_string()], "{word}"); + } + assert!(d.suggest("wrold's", 0).is_empty()); + assert_eq!(d.suggest("wrold", 1), vec!["world".to_string()]); + } + + #[test] + fn possessive_suggestions_normalize_apostrophes_without_doubling_the_ending() { + let d = Dictionary::from_list("world\nworld's\n"); + for apostrophe in ['\'', '\u{2019}', '\u{2018}', '\u{02BC}'] { + assert_eq!(d.suggest(&format!("wrold{apostrophe}s"), 1), vec!["world's".to_string()]); + } + assert!(d.suggest("world's", 8).is_empty(), "a listed possessive must not gain a second ending"); + } + + #[test] + fn bundled_dictionary_suggests_a_correction_for_a_misspelled_possessive() { + let d = Dictionary::english(); + let text = "The wrold's best photo."; + let found = d.misspellings(text, &none()); + assert_eq!(found, vec![Misspelling { start: 4, end: 11, word: "wrold's".into() }]); + assert_eq!(d.suggest(&found[0].word, 1), vec!["world's".to_string()]); + assert!(d.check("world's", &none())); + } + #[test] fn misspellings_and_user_words() { let d = Dictionary::from_list("#10\nhello\nworld\nParis\n"); @@ -310,6 +350,29 @@ mod tests { assert_eq!(&text[mm.start..mm.end], "wrld"); } + #[test] + fn normalized_apostrophes_stay_inside_words() { + let d = Dictionary::english(); + for word in ["doesn't", "doesn\u{2019}t", "doesn\u{2018}t", "doesn\u{02BC}t"] { + let text = format!("({word})"); + assert!(d.check(word, &none()), "{word}"); + assert_eq!(words(&text), vec![(1, 1 + word.len())], "{word}"); + } + } + + #[test] + fn normalized_contractions_are_not_reported_as_misspellings() { + let d = Dictionary::english(); + for word in ["doesn't", "doesn\u{2019}t", "doesn\u{2018}t", "doesn\u{02BC}t"] { + let text = format!("({word})"); + let found = d.misspellings(&text, &none()); + assert!(found.is_empty(), "{word}: {found:?}"); + } + let typo = "doesn\u{2018}tt"; + let found = d.misspellings(typo, &none()); + assert_eq!(found, vec![Misspelling { start: 0, end: typo.len(), word: typo.into() }]); + } + /// `cargo test --release -p photocraft-text -- --ignored --nocapture spell_timing` #[test] #[ignore] diff --git a/crates/ui-egui/src/adjustment_brush_tool_tests.rs b/crates/ui-egui/src/adjustment_brush_tool_tests.rs new file mode 100644 index 0000000000..5073979060 --- /dev/null +++ b/crates/ui-egui/src/adjustment_brush_tool_tests.rs @@ -0,0 +1,212 @@ +//! #12519: the Adjustment Brush Tool in the shell: its toolbar slot between the Blur and Dodge +//! slots (no letter), its options bar, and strokes through the real pointer path that make an +//! adjustment layer whose mask is the stroke, or paint into it. + +use egui::accesskit::Role; +use egui::{Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::{Adjustment, LayerContent}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::panels::toolbar::TOOL_SECTIONS; +use crate::state::Tool; + +/// A 200 x 200 document with a painted layer active and the Adjustment Brush picked, its brush +/// swapped in as a frame does. +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#808080"})).unwrap(); + pick(&mut app); + app +} + +fn pick(app: &mut PhotocraftApp) { + app.ui.tool = Tool::AdjustmentBrush; + crate::paint_mouse::sync_tool_brush(app); + app.sync_views(); +} + +fn stroke(app: &mut PhotocraftApp, y: f64) { + tool_event(app, ToolEvent::Down { x: 40.0, y, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: 160.0, y, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: 160.0, y }, Modifiers::NONE); + app.sync_views(); +} + +fn active(app: &PhotocraftApp) -> &photocraft_doc::Layer { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap() +} + +fn layers(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.walk().len() +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +fn mask_at(app: &PhotocraftApp, x: i32, y: i32) -> f32 { + active(app).mask.as_ref().expect("a mask").surface.sample_channel(x, y, 0) +} + +/// The messages of the open framework alerts. +fn alerts(app: &PhotocraftApp) -> Vec { + app.framework.dialogs.open_dialogs().iter().filter_map(|d| d.fields.as_ref()?.get("message")?.as_str().map(str::to_string)).collect() +} + +#[test] +fn its_own_slot_sits_between_the_blur_and_dodge_slots() { + let slots: Vec<&[Tool]> = TOOL_SECTIONS.iter().flat_map(|s| s.iter().copied()).collect(); + let i = slots.iter().position(|s| *s == [Tool::AdjustmentBrush]).expect("an own slot"); + assert_eq!(slots[i - 1], [Tool::Blur, Tool::Sharpen, Tool::Smudge]); + assert_eq!(slots[i + 1], [Tool::Dodge, Tool::Burn, Tool::Sponge]); + assert_eq!(Tool::AdjustmentBrush.key(), '\0', "no letter"); + assert_eq!(Tool::from_name("adjustmentBrush"), Some(Tool::AdjustmentBrush)); + let command = crate::panels::tool_commands::command_of(Tool::AdjustmentBrush); + assert_eq!(crate::panels::tool_commands::tool_of(command), Tool::AdjustmentBrush); + assert_eq!(crate::icons::tool_icon(Tool::AdjustmentBrush), craft::behavior::IconId::new("adjustment_layer")); +} + +#[test] +fn it_starts_with_a_100_px_soft_round() { + let app = app(); + let b = &app.session.tools.brush; + assert_eq!((b.size, b.hardness), (100.0, 0.0)); +} + +fn bar(app: Box) -> Harness<'static, Box> { + crate::theme::install_fonts(app.ctx()); + crate::theme::apply(app.ctx(), &crate::theme::AppTheme::pro()); + let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(vec2(1800.0, 200.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut Box| { + crate::panels::options_bar(app, ui); + crate::dialogs::run(app, ui); + }, + app, + ); + h.run_steps(4); + h +} + +/// The centre x of the control named `label` (not a caption's text node). +fn x_of(h: &Harness<'static, Box>, label: &str) -> f32 { + let named = h.query_all_by_label(label).find(|n| n.accesskit_node().role() != Role::Label); + let all = || h.query_all_by_role(Role::Button).filter_map(|n| n.accesskit_node().label()).collect::>(); + named.unwrap_or_else(|| panic!("no {label:?} in {:?}", all())).rect().center().x +} + +#[test] +fn the_options_bar_shows_its_controls_in_order() { + let h = bar(app()); + let xs = [ + x_of(&h, "Adjustment:"), + x_of(&h, "Subtract from mask areas to remove adjustment from areas of the image"), + x_of(&h, "Add to mask areas to apply adjustment to more of the image"), + x_of(&h, "Always use pressure for size"), + x_of(&h, "Choose an object and have the adjustment applied to it"), + x_of(&h, "Overlay"), + x_of(&h, "Opacity:"), + x_of(&h, "Always use pressure for opacity"), + x_of(&h, "Flow:"), + x_of(&h, "Enable airbrush-style build-up effects"), + ]; + assert!(xs.windows(2).all(|w| w[0] < w[1]), "left to right: {xs:?}"); +} + +#[test] +fn subtract_and_add_swap_the_colours_and_the_paint() { + let mut h = bar(app()); + h.get_by_label("Subtract from mask areas to remove adjustment from areas of the image").click(); + h.run_steps(2); + let app = h.state(); + assert!(app.ui.tool_options.adjustment_brush_subtract); + assert_eq!((app.session.tools.foreground, app.session.tools.background), ([0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0])); + h.get_by_label("Add to mask areas to apply adjustment to more of the image").click(); + h.run_steps(2); + let app = h.state(); + assert!(!app.ui.tool_options.adjustment_brush_subtract); + assert_eq!((app.session.tools.foreground, app.session.tools.background), ([1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0])); +} + +#[test] +fn the_first_stroke_makes_the_layer_in_one_history_state() { + let mut app = app(); + let (n, past) = (layers(&app), steps(&app)); + stroke(&mut app, 100.0); + assert_eq!((layers(&app), steps(&app)), (n + 1, past + 1), "{}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("New Adjustment Layer")); + assert_eq!(active(&app).name, "Levels 1"); + assert!(matches!(active(&app).content, LayerContent::Adjustment(Adjustment::Levels { .. }))); + assert!(mask_at(&app, 100, 100) > 0.98 && mask_at(&app, 100, 10) == 0.0); + assert!(app.ui.mask_target, "the new mask is targeted"); + // A second stroke paints the same mask. + stroke(&mut app, 30.0); + assert_eq!((layers(&app), steps(&app)), (n + 1, past + 2)); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Adjustment Brush")); + assert!(mask_at(&app, 100, 30) > 0.98); +} + +#[test] +fn a_hidden_locked_or_group_layer_does_not_refuse_the_stroke() { + for setup in ["hidden", "locked", "group", "type"] { + let mut app = app(); + let id = active(&app).id.0; + match setup { + "hidden" => app.run("layer.setProps", json!({"layer": id, "visible": false})).map(|_| ()), + "locked" => app.run("layer.lockLayers", json!({"all": true})).map(|_| ()), + "group" => app.run("layer.new.group", json!({})).map(|_| ()), + _ => app.run("type.create", json!({"text": "Hi", "x": 20, "y": 40})).map(|_| ()), + } + .unwrap_or_else(|e| panic!("{setup}: {e}")); + pick(&mut app); + let n = layers(&app); + stroke(&mut app, 100.0); + assert!(app.framework.dialogs.open_dialogs().is_empty(), "{setup}: {:?}", alerts(&app)); + assert_eq!(layers(&app), n + 1, "{setup}: {}", app.ui.status); + assert!(matches!(active(&app).content, LayerContent::Adjustment(_)), "{setup}"); + } +} + +#[test] +fn selecting_an_adjustment_layer_sets_the_dropdown() { + let mut app = app(); + app.run("layer.newAdjustmentLayer.curves", json!({})).unwrap(); + crate::adjustment_brush::follow_active_layer(&mut app); + assert_eq!(crate::adjustment_brush::kind(&app), "curves"); + // A pick after that sticks while the layer stays active. + app.ui.tool_options.adjustment_brush_kind = "exposure".into(); + crate::adjustment_brush::follow_active_layer(&mut app); + assert_eq!(crate::adjustment_brush::kind(&app), "exposure"); + // And a stroke with it makes an Exposure layer above the Curves one. + let n = layers(&app); + stroke(&mut app, 100.0); + assert_eq!((layers(&app), active(&app).name.as_str()), (n + 1, "Exposure 1")); +} + +#[test] +fn greyed_entries_fall_back_to_the_first_offered_one() { + let mut app = app(); + app.run("image.mode.bits32", json!({})).unwrap(); + app.ui.tool_options.adjustment_brush_kind = "posterize".into(); + assert_eq!(crate::adjustment_brush::kind(&app), "levels"); + stroke(&mut app, 100.0); + assert_eq!(active(&app).name, "Levels 1", "{}", app.ui.status); +} + +#[test] +fn indexed_color_alerts_at_the_press_and_changes_nothing() { + let mut app = app(); + app.run("layer.flatten", json!({})).ok(); + app.run("image.mode.indexedColor", json!({})).unwrap(); + pick(&mut app); + let (n, past) = (layers(&app), steps(&app)); + stroke(&mut app, 100.0); + assert_eq!(alerts(&app), [photocraft_engine::adjustment_brush_cmds::INDEXED_ALERT]); + assert_eq!((layers(&app), steps(&app)), (n, past)); +} diff --git a/crates/ui-egui/src/app/thumbs.rs b/crates/ui-egui/src/app/thumbs.rs index 0677b17c23..f8b25d555a 100644 --- a/crates/ui-egui/src/app/thumbs.rs +++ b/crates/ui-egui/src/app/thumbs.rs @@ -26,7 +26,8 @@ impl<'a> SnapshotThumbs<'a> { impl ThumbSource for SnapshotThumbs<'_> { fn revision(&self, key: &u64, _request: &ThumbRequest) -> Revision { let shown = self.snapshots.iter().find(|s| s.id == *key).map(|s| std::sync::Arc::as_ptr(&s.doc) as usize); - Revision::of(&(self.doc.0, *key, shown)) + // A snapshot's tiles can fail to read and recover without a new `Arc` (`crate::scratch_reads`). + Revision::of(&(self.doc.0, *key, shown, crate::scratch_reads::generation())) } fn render(&self, key: &u64, request: &ThumbRequest) -> ThumbRender { @@ -36,6 +37,12 @@ impl ThumbSource for SnapshotThumbs<'_> { } } +/// What the bounds cache keys `surface`'s bounds by: its generation and the scratch read-error generation, as a tile +/// that fails to read scans as empty and moves neither (`crate::scratch_reads`). +pub(crate) fn bounds_revision(surface: &photocraft_raster::Surface) -> u64 { + crate::scratch_reads::with(surface.generation()) +} + /// The document area a layer thumbnail frames: the canvas, or with `clip` the layer's pixels on /// it (the canvas again when it has none there, so an empty layer still shows the page shape). pub(crate) fn layer_thumb_frame(layer: &photocraft_doc::Layer, canvas: photocraft_geom::Rect, clip: bool) -> photocraft_geom::Rect { @@ -47,9 +54,10 @@ pub(crate) fn layer_thumb_frame(layer: &photocraft_doc::Layer, canvas: photocraf } impl PhotocraftApp { - /// Cached `Surface::content_bounds` keyed by an id and the surface's generation. + /// Cached `Surface::content_bounds` keyed by an id and the surface's generation with the scratch read-error + /// generation ([`bounds_revision`]). pub fn cached_bounds(&mut self, key: u64, surface: &photocraft_raster::Surface) -> photocraft_geom::Rect { - let rev = surface.generation(); + let rev = bounds_revision(surface); if let Some((r, b)) = self.bounds_cache.get(&key) && *r == rev { @@ -67,7 +75,7 @@ impl PhotocraftApp { /// hasn't changed since, else a scan (not cached). pub fn known_bounds(&self, key: u64, surface: &photocraft_raster::Surface) -> photocraft_geom::Rect { match self.bounds_cache.get(&key) { - Some((r, b)) if *r == surface.generation() => *b, + Some((r, b)) if *r == bounds_revision(surface) => *b, _ => surface.content_bounds(), } } @@ -79,7 +87,7 @@ impl PhotocraftApp { match &layer.content { photocraft_doc::LayerContent::Shape(sh) if sh.has_soft_mask() => { // Cached per rendering, like the pixel bounds: the frame renders strips of the shape. - let (key, rev) = (layer.id.0 | 1 << 63, surface.generation()); + let (key, rev) = (layer.id.0 | 1 << 63, bounds_revision(surface)); if let Some((r, b)) = self.bounds_cache.get(&key) && *r == rev { @@ -176,10 +184,13 @@ impl ThumbSource for ChannelThumbs<'_> { fn revision(&self, key: &Row, _request: &ThumbRequest) -> Revision { let doc = &self.st.doc; let size = (doc.size.width, doc.size.height); + // A tile that fails to read and recovers moves neither the document's revision nor its surface's generation + // (`crate::scratch_reads`). + let scratch = crate::scratch_reads::generation(); match key { - Row::Composite | Row::Color(_) => Revision::of(&(doc.id.0, self.st.pixel_revision, self.show_color, size)), + Row::Composite | Row::Color(_) => Revision::of(&(doc.id.0, self.st.pixel_revision, self.show_color, size, scratch)), // A channel-list change with empty damage still refreshes these: they follow their own surface. - _ => Revision::of(&(doc.id.0, self.st.active_layer, self.surface(key).map(photocraft_raster::Surface::generation), size)), + _ => Revision::of(&(doc.id.0, self.st.active_layer, self.surface(key).map(photocraft_raster::Surface::generation), size, scratch)), } } diff --git a/crates/ui-egui/src/canvas/document_display.rs b/crates/ui-egui/src/canvas/document_display.rs index 052581d13d..fe02adcd58 100644 --- a/crates/ui-egui/src/canvas/document_display.rs +++ b/crates/ui-egui/src/canvas/document_display.rs @@ -392,6 +392,12 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, let r = frame.turned_bounds(); PixelRect::new(r.x0.floor() as i32, r.y0.floor() as i32, r.x1.ceil() as i32, r.y1.ceil() as i32) }); + // What a crop that grows the canvas adds to a Background previews in its fill colour, as on the monitor. + let region_fill = region.and_then(|_| crate::crop_ui::grown_fill(app, doc)).and_then(|c| { + let (display, _) = super::display::canvas_display(app, doc, output); + let one = photocraft_compose::Buffer::filled(DRect::from_xywh(0, 0, 1, 1), [c[0], c[1], c[2], 1.0]); + super::display::display_image(display.as_deref(), &one).pixels.first().copied() + }); let app: &PhotocraftApp = app; let (gpu, composite) = match prepared { Some(Prepared::Gpu(picture)) => (Some(picture), None), @@ -401,7 +407,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, let overlay = overlay.map(|prep| prep.source(app)); let bounds = gpu.as_ref().map(GpuPicture::bounds).or_else(|| composite.as_ref().map(|c| c.bounds())).unwrap_or_else(|| doc.bounds()); let mapping = (bounds != doc.bounds()).then(|| placement(bounds)); - let frame = Frame { checker: checker.as_ref(), edge, mapping, pattern, region }; + let frame = Frame { checker: checker.as_ref(), edge, mapping, pattern, region, region_fill }; if let Some(picture) = &gpu { frame.apply(RasterDisplay::painted(label.clone(), size, picture.clone().into_paint())).picture().show_at(ui, body.rect); } else if let Some(composite) = &composite { @@ -578,6 +584,8 @@ struct Frame<'c> { mapping: Option, pattern: bool, region: Option, + /// The colour of the region past the document (a crop's grown Background), over the checkerboard. + region_fill: Option, } impl Frame<'_> { @@ -595,6 +603,10 @@ impl Frame<'_> { Some(region) => display.extent(Extent::Region(region)), None => display, }; + let display = match self.region_fill { + Some(fill) => display.region_fill(fill), + None => display, + }; if self.pattern { display.extent(Extent::Tiled) } else { display } } } @@ -678,7 +690,10 @@ mod tests { view.rect.top() ); } - let room = |length: f32, document: f64| if overscroll { f64::from(length) - document } else { 0.0 }; + // With Overscroll the track reaches into the pasteboard until 100 screen points of the document (all of a + // shorter one) stay in view at the opposite edge (#16328): the document plus, on each side, the visible + // length less those points. The scroll room is that less the visible length. + let room = |length: f32, document: f64| if overscroll { f64::from(length) + document - 2.0 * document.min(100.0) } else { 0.0 }; let x_room = room(view.rect.width(), 400.0); let y_room = room(view.rect.height(), 300.0); assert_eq!(horizontal.accesskit_node().max_numeric_value(), Some(x_room), "horizontal scroll room with Overscroll {overscroll}"); diff --git a/crates/ui-egui/src/canvas/filter_preview.rs b/crates/ui-egui/src/canvas/filter_preview.rs index 2d81c234e2..648385077d 100644 --- a/crates/ui-egui/src/canvas/filter_preview.rs +++ b/crates/ui-egui/src/canvas/filter_preview.rs @@ -108,6 +108,7 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e params, k, tool_colors: (app.session.tools.foreground, app.session.tools.background), + scratch: crate::scratch_reads::generation(), }; app.filter_live.begin(session_of(&request), PixelRect::new(bounds.x0, bounds.y0, bounds.x1, bounds.y1)); let key = request.doc.0 ^ (1u64 << 61); diff --git a/crates/ui-egui/src/canvas/filter_preview/tests.rs b/crates/ui-egui/src/canvas/filter_preview/tests.rs index ae34f227d0..481fcd8e59 100644 --- a/crates/ui-egui/src/canvas/filter_preview/tests.rs +++ b/crates/ui-egui/src/canvas/filter_preview/tests.rs @@ -37,6 +37,28 @@ fn set_fields(app: &mut PhotocraftApp, ctx: &egui::Context, values: &Value) { } } +/// A tile that fails to read and recovers changes the pixels without a new revision or new dialog values: the +/// preview is computed again, so it does not keep what it read during the error (`crate::scratch_reads`). +#[test] +fn the_preview_is_computed_again_after_a_scratch_read_error_transition() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + open_filter(&mut app, "filter.stylize.solarize"); + let ctx = app.ctx().clone(); + let result = |app: &PhotocraftApp| app.filter_preview.as_ref().and_then(|preview| preview.result.clone()).expect("a preview result"); + ensure_filter_preview(&mut app, 0, &ctx).expect("a preview"); + let before = result(&app); + ensure_filter_preview(&mut app, 0, &ctx).expect("the same preview"); + assert!(std::sync::Arc::ptr_eq(&result(&app), &before), "nothing changed: the same result"); + let (revision, values) = (app.session.active().unwrap().revision, fields(&app)); + crate::scratch_reads::tests::simulate_read_error_transition(); + ensure_filter_preview(&mut app, 0, &ctx).expect("a preview"); + assert_eq!(app.session.active().unwrap().revision, revision); + assert_eq!(fields(&app), values, "the dialog values did not change"); + assert!(!std::sync::Arc::ptr_eq(&result(&app), &before), "the preview is computed again"); +} + /// #7490: the inline (web) preview path composites and uploads each changed preview once, as /// the background worker does. It used to flatten and upload it twice and record it twice, /// so the frame's refresh time counted the preview twice. @@ -123,6 +145,7 @@ fn every_filter_previews_off_the_ui_thread_and_a_newer_value_cancels_the_old() { params: json!({"radius": 999.0}), k: 1, tool_colors: (app.session.tools.foreground, app.session.tools.background), + scratch: crate::scratch_reads::generation(), }; let (told, cancelled) = std::sync::mpsc::channel(); app.filter_preview_worker @@ -179,6 +202,7 @@ fn gated_blur_preview(app: &mut PhotocraftApp, ctx: &egui::Context) -> (std::syn params, k: 1, tool_colors: (app.session.tools.foreground, app.session.tools.background), + scratch: crate::scratch_reads::generation(), }; let doc = app.session.documents()[0].doc.clone(); let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect(); @@ -581,6 +605,7 @@ fn a_mid_drag_empty_result_leaves_the_preview_alone() { params: json!({"radius": moved}), k: 1, tool_colors: (app.session.tools.foreground, app.session.tools.background), + scratch: crate::scratch_reads::generation(), }; let (release_empty, wait) = std::sync::mpsc::channel::<()>(); app.filter_preview_worker diff --git a/crates/ui-egui/src/canvas/navigator.rs b/crates/ui-egui/src/canvas/navigator.rs index 8253334baa..88e53640c7 100644 --- a/crates/ui-egui/src/canvas/navigator.rs +++ b/crates/ui-egui/src/canvas/navigator.rs @@ -74,7 +74,9 @@ pub fn navigator_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usiz app.session.documents().get(idx).map(|st| (std::sync::Arc::downgrade(&st.doc), st.doc.id, st.revision, st.damage_from(), st.last_damage))?; let (doc, preview_key) = display_doc(app, idx); let (display, display_key) = canvas_display(app, &doc, None); - let preview_key = preview_key ^ display_key; + // A tile that fails to read and recovers keeps the snapshot and its revision: the picture and its partial updates + // follow the scratch read-error generation too (`crate::scratch_reads`). + let preview_key = crate::scratch_reads::with(preview_key ^ display_key); let cached = app.navigator_textures.get(&id).cloned(); if let Some((r, p, _, t)) = &cached && r.ptr_eq(&snapshot) diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 8e2e18bac0..cb46af475c 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -24,8 +24,10 @@ impl MaskSource for SurfaceMask<'_> { self.size } + /// The mask's revision with the scratch read-error generation: a selection tile that fails to read traces as + /// empty, and as its pixels once it reads, without a new revision (`crate::scratch_reads`). fn revision(&self) -> u64 { - self.revision + crate::scratch_reads::with(self.revision) } /// The allocated tiles: every pixel that differs from the default lies in one, and the union of their rects is diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index bd836398e4..cd58e26268 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -47,14 +47,22 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) { // first Pattern Stamp stroke multiply (or give Healing a mode its menu doesn't have). // The Pattern Stamp also starts at full opacity and flow (#12616): those fields are its own. // The Background Eraser, the Healing Brush, the Burn, Dodge and Sponge tools, the Clone - // Stamp, the Smudge tool and the Art History Brush start with their own measured tips + // Stamp, the Smudge tool, the Adjustment Brush and the Art History Brush start with their own measured tips // instead, as the whole brush Reset Tool gives them (#11911, #12099, #12671, #12684, // #13029, #12601, #12964, #12631); the Art History Brush's is at full opacity (#10263). // The Art History Brush's Angle and pressure toggles are its own bar controls, so they // start at 0° and off too, whatever the outgoing brush has (#12629). None if matches!( tool, - Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp | Tool::Smudge | Tool::ArtHistoryBrush + Tool::BackgroundEraser + | Tool::Healing + | Tool::Burn + | Tool::Dodge + | Tool::Sponge + | Tool::CloneStamp + | Tool::Smudge + | Tool::AdjustmentBrush + | Tool::ArtHistoryBrush ) => { fresh_brush(tool, ¤t) @@ -124,6 +132,9 @@ const ART_HISTORY_BRUSH_TIP: (f32, f32, f32) = (21.0, 0.0, 0.25); const REMOVE_TOOL_SIZE: f32 = 19.0; /// The Smudge tool's tip after Reset Tool (#12964): a 13 px soft round at 25 % spacing. const SMUDGE_TOOL_TIP: (f32, f32, f32) = (13.0, 0.0, 0.25); +/// The Adjustment Brush's starting tip (#12519): a 100 px soft round (hardness 0 %). Its spacing +/// was not measured, so it stays the default brush's. +const ADJUSTMENT_BRUSH_TIP: (f32, f32) = (100.0, 0.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 @@ -166,6 +177,7 @@ pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings brush.smoothing.amount = 0.0; } Tool::Remove => brush.size = REMOVE_TOOL_SIZE, + Tool::AdjustmentBrush => (brush.size, brush.hardness) = ADJUSTMENT_BRUSH_TIP, _ => {} } session_fields(current, &brush) diff --git a/crates/ui-egui/src/canvas/strokes.rs b/crates/ui-egui/src/canvas/strokes.rs index f3806f044e..7c721293ac 100644 --- a/crates/ui-egui/src/canvas/strokes.rs +++ b/crates/ui-egui/src/canvas/strokes.rs @@ -704,7 +704,8 @@ pub(crate) fn finish(app: &mut PhotocraftApp, stroke: PaintStroke) { if live_retouch_command(d.tool).is_some() || crate::retouch_ui::dab_params(app, d.tool).is_some() || d.tool == Tool::ColorReplacement { app.live_stroke = None; } - let finished = crate::eraser_ui::finish_stroke(app, d.tool, &d.points, d.line) + let finished = crate::adjustment_brush::finish_stroke(app, d.tool, &d.points, d.line) + || crate::eraser_ui::finish_stroke(app, d.tool, &d.points, d.line) || crate::retouch_ui::finish_stroke_with(app, d.tool, &d.points, d.modifiers, d.line, d.history_params.clone()); app.session.clear_live_stroke(); if finished { diff --git a/crates/ui-egui/src/canvas/tool_feedback.rs b/crates/ui-egui/src/canvas/tool_feedback.rs index 38bc614cf0..22821a53a2 100644 --- a/crates/ui-egui/src/canvas/tool_feedback.rs +++ b/crates/ui-egui/src/canvas/tool_feedback.rs @@ -102,7 +102,7 @@ mod tests { assert!(has_selection(&app), "nothing cached: scanned"); assert_eq!(selection_op(Tool::Lasso, 0, ALT, has_selection(&app)), SelectionOperation::Subtract); let st = app.session.active().unwrap(); - let (key, fingerprint) = (u64::MAX - st.doc.id.0, st.doc.selection.as_ref().unwrap().generation()); + let (key, fingerprint) = (u64::MAX - st.doc.id.0, crate::app::thumbs::bounds_revision(st.doc.selection.as_ref().unwrap())); // An empty box cached for this very selection is believed, so nothing is scanned. app.bounds_cache.insert(key, (fingerprint, photocraft_geom::Rect::EMPTY)); assert!(!has_selection(&app), "the cached bounds are used"); diff --git a/crates/ui-egui/src/canvas/tools/mod.rs b/crates/ui-egui/src/canvas/tools/mod.rs index 4d03eb8d17..24d046b38a 100644 --- a/crates/ui-egui/src/canvas/tools/mod.rs +++ b/crates/ui-egui/src/canvas/tools/mod.rs @@ -460,6 +460,11 @@ impl Preflight<'_, '_> { let pressure = pointer.sample.pressure; let mods = pointer.mods; self.scope.with_app(|app| { + // The Adjustment Brush paints a new layer's mask whatever the active layer is (hidden, locked, a group or + // type): only Indexed Color refuses it (#12519). + if tool == Tool::AdjustmentBrush { + return crate::adjustment_brush::press_refused(app); + } // Auto-Select's press picks the layer to move, so the hidden active layer is not its target. let picks = tool == Tool::Move && !crate::move_ui::moves_selected_pixels_with(app, tool) && app.ui.tool_options.move_auto_select != mods.cmd; (!picks && press_refused(app, tool)) diff --git a/crates/ui-egui/src/dialog_title_ellipsis_tests.rs b/crates/ui-egui/src/dialog_title_ellipsis_tests.rs index 014c7dc1c5..6865848d8b 100644 --- a/crates/ui-egui/src/dialog_title_ellipsis_tests.rs +++ b/crates/ui-egui/src/dialog_title_ellipsis_tests.rs @@ -25,7 +25,7 @@ fn harness() -> Harness<'static, Box> { #[test] fn dialog_titles_drop_the_menu_ellipsis() { - let cases: [(&str, Open); 4] = [ + let cases: [(&str, Open); 7] = [ ("Stroke", |app| { crate::stroke_ui::open(app); }), @@ -38,6 +38,19 @@ fn dialog_titles_drop_the_menu_ellipsis() { ("New Brush Preset", |app| { crate::brush_preset_dialog::open(app, None); }), + // Layer › Duplicate Layer… names its window after what is selected (#16349). + ("Duplicate Layer", |app| { + crate::duplicate_layer_ui::open(app).unwrap(); + }), + ("Duplicate Layers", |app| { + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.allLayers", json!({})).unwrap(); + crate::duplicate_layer_ui::open(app).unwrap(); + }), + ("Duplicate Group", |app| { + app.run("layer.groupLayers", json!({})).unwrap(); + crate::duplicate_layer_ui::open(app).unwrap(); + }), ]; for (title, open) in cases { let mut h = harness(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e3cca6c221..46a359792d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -698,6 +698,8 @@ pub(super) mod camera_raw_scope_ui; pub mod camera_raw_ui; pub(crate) mod canvas_input; pub mod channel_options_ui; +#[cfg(test)] +mod color_lookup_no_remember_tests; pub(crate) mod color_picker_preview; pub mod color_picker_ui; pub mod color_range_ui; diff --git a/crates/ui-egui/src/dialogs/color_lookup_no_remember_tests.rs b/crates/ui-egui/src/dialogs/color_lookup_no_remember_tests.rs new file mode 100644 index 0000000000..f5df08c6da --- /dev/null +++ b/crates/ui-egui/src/dialogs/color_lookup_no_remember_tests.rs @@ -0,0 +1,155 @@ +//! #14422: Image › Adjustments › Color Lookup opens at its defaults, not at the last LUT. +//! +//! A hosted parameter dialog remembers its rows: reopening starts from the values of the last OK +//! (`crate::dialogs::params::open_param` remembers under `memory_scope`). Color Lookup's LUT rows +//! are exempt: the picker is a `Param::custom` row and its keys (`lut`, `file`, `data`, `fileName`) +//! are never kept, so an OK with a built-in look or a LUT file leaves the next opening at "no LUT", +//! as the reference application does. Dither and Interpolation are remembered like any schema +//! dialog's rows. A recorded or scripted step still opens on its own values +//! (`panels/actions/runner.rs`, pinned by its own tests). + +use craft::ui::dialog::DialogId; +use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog}; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::dialogs::filter_dialog::open; + +const COLOR_LOOKUP: &str = "image.adjustments.colorLookup"; +const GAUSSIAN_BLUR: &str = "filter.blur.gaussianBlur"; + +fn new_app() -> Box { + PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()) +} + +/// An 8x8 RGB document, so `image.adjustments.colorLookup` has something to adjust. +fn app_with_doc() -> Box { + let mut app = new_app(); + app.run("file.new", json!({"width": 8, "height": 8, "background": "#000000"})).unwrap(); + app +} + +fn fields_of(app: &PhotocraftApp, id: DialogId) -> DialogFields { + app.framework.dialogs.get_by_id::(id).expect("open dialog").fields().clone() +} + +fn field_json(app: &PhotocraftApp, id: DialogId, key: &str) -> Value { + serde_json::to_value(fields_of(app, id)).expect("fields serialize").get(key).cloned().unwrap_or(Value::Null) +} + +fn set(app: &mut PhotocraftApp, id: DialogId, key: &str, value: Value) { + let ctx = app.ctx().clone(); + app.framework.dialogs.set_json_field(&ctx, id, key, value).unwrap_or_else(|e| panic!("{key}: {e}")); +} + +fn passes(app: &mut PhotocraftApp, n: usize) { + let ctx = app.ctx().clone(); + for _ in 0..n { + crate::testing::run_ui(&ctx, Default::default(), |ui| crate::dialogs::run(app, ui)); + } +} + +fn is_open(app: &PhotocraftApp, id: DialogId) -> bool { + app.framework.dialogs.get_by_id::(id).is_some() +} + +/// OK, then the passes in which the family runs. True when the dialog closed. +fn ok(app: &mut PhotocraftApp, id: DialogId) -> bool { + let ctx = app.ctx().clone(); + let _ = crate::dialogs::confirm(app, &ctx, id); + passes(app, 3); + !is_open(app, id) +} + +/// The keys that carry a LUT: each opens at its default (no value, or the spec's empty/`none` +/// default) - never at the look or file of a past OK (#14422). +fn assert_no_lut(app: &PhotocraftApp, id: DialogId, opened: &str) { + for (key, defaults) in [("lut", vec![json!("none")]), ("file", vec![json!("")]), ("data", vec![json!("")]), ("fileName", vec![json!("")])] { + let value = field_json(app, id, key); + assert!(value.is_null() || defaults.contains(&value), "{opened}: {key} holds {value}"); + } +} + +/// The first opening shows no LUT and the schema defaults for the other rows. +#[test] +fn color_lookup_opens_with_no_lut_and_its_defaults() { + let mut app = app_with_doc(); + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + assert_no_lut(&app, id, "the first opening"); + assert_eq!(field_json(&app, id, "dither"), json!(false), "the first opening: dither"); + assert_eq!(field_json(&app, id, "interpolation"), json!("trilinear"), "the first opening: interpolation"); + cancel(&mut app, id); +} + +fn cancel(app: &mut PhotocraftApp, id: DialogId) { + let ctx = app.ctx().clone(); + app.framework.dialogs.cancel_by_id(&ctx, id); + passes(app, 2); +} + +/// The measured case: OK with a built-in look, and the next opening shows no LUT again instead of +/// that look. Dither and Interpolation are not the LUT and keep the remembering behaviour: they +/// come back as they were OK'd. +#[test] +fn color_lookup_ok_with_a_builtin_look_reopens_with_no_lut() { + let mut app = app_with_doc(); + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + set(&mut app, id, "lut", json!("warm")); + set(&mut app, id, "dither", json!(true)); + set(&mut app, id, "interpolation", json!("tetrahedral")); + assert!(ok(&mut app, id), "OK with the built-in look warm closes the dialog"); + + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + assert_no_lut(&app, id, "after OK with the built-in look warm"); + assert_eq!(field_json(&app, id, "dither"), json!(true), "Dither keeps its remembered value"); + assert_eq!(field_json(&app, id, "interpolation"), json!("tetrahedral"), "Interpolation keeps its remembered value"); + assert!(!app.session.prefs().dialogs.contains_key(COLOR_LOOKUP), "the LUT memory no longer lives in the preferences"); +} + +/// The other measured opening: a LUT file picked and OK'd. The next opening shows no file and no +/// built-in look. +#[test] +fn color_lookup_ok_with_a_lut_file_reopens_at_the_defaults() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("film.cube"); + std::fs::write(&path, "LUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n").unwrap(); + let mut app = app_with_doc(); + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + set(&mut app, id, "file", json!(path.to_str().unwrap())); + assert!(ok(&mut app, id), "OK with the LUT file closes the dialog"); + + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + assert_no_lut(&app, id, "after OK with a LUT file"); +} + +/// Preferences written before the framework memory exist (#14422 held a saved LUT choice): the +/// one-time move takes the entry out of `Preferences.dialogs`, and the dialog still opens at its +/// defaults - a legacy saved look never comes back. +#[test] +fn color_lookup_legacy_saved_preferences_never_restore_a_lut() { + let mut app = app_with_doc(); + app.session.edit_prefs(|prefs| { + prefs.dialogs.insert(COLOR_LOOKUP.into(), json!({"lut": "warm", "file": "old.cube", "dither": true, "interpolation": "tetrahedral"})) + }); + app.framework.move_memories(&mut app.session); + assert!(!app.session.prefs().dialogs.contains_key(COLOR_LOOKUP), "the entry was moved out of the preferences"); + + let id = open(&mut app, COLOR_LOOKUP).unwrap(); + assert_no_lut(&app, id, "with a legacy saved look in the preferences"); + // The move routes `image.adjustments.*` entries to the adjustment panel's memory, not the + // dialog's scope, so the other rows start at their defaults as well on this first opening. + assert_eq!(field_json(&app, id, "dither"), json!(false), "a legacy saved Dither does not reach the dialog"); + assert_eq!(field_json(&app, id, "interpolation"), json!("trilinear"), "a legacy saved Interpolation does not reach the dialog"); +} + +/// Only the LUT row stopped being remembered: another schema dialog still reopens with what its OK +/// kept (#14422 must not reach past Color Lookup). +#[test] +fn other_schema_dialogs_still_remember_their_choices() { + let mut app = app_with_doc(); + let id = open(&mut app, GAUSSIAN_BLUR).unwrap(); + set(&mut app, id, "radius", json!(11.0)); + assert!(ok(&mut app, id), "OK on Gaussian Blur closes the dialog"); + let id = open(&mut app, GAUSSIAN_BLUR).unwrap(); + assert_eq!(field_json(&app, id, "radius"), json!(11.0), "the blur dialog still remembers"); +} diff --git a/crates/ui-egui/src/dialogs/conditional_mode_change_dialog.rs b/crates/ui-egui/src/dialogs/conditional_mode_change_dialog.rs index 52d2e840bd..aff07c6d8b 100644 --- a/crates/ui-egui/src/dialogs/conditional_mode_change_dialog.rs +++ b/crates/ui-egui/src/dialogs/conditional_mode_change_dialog.rs @@ -5,9 +5,12 @@ //! The checkboxes are one custom row of the command's form: `from` is the list of ticked source //! ids and `to` the target id, so OK, Reset and `ui.dialog.set` work as for every form. +use craft::behavior::ColumnWidth; use craft::ui::buttons::Button; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Props as _, Show as _}; +use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::layout::GridFit; +use craft::ui::layout_components::{Grid, Row, Stack}; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKind}; use craft::ui::runtime::env::Label; use serde_json::{Value, json}; @@ -66,29 +69,33 @@ fn ticked(from: &Value, id: &str) -> bool { } } -/// The eight checkboxes in two columns, All and None under them. +/// The two columns of checkboxes, each as wide as its widest label. +const COLUMNS: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::Content]; + +/// The eight checkboxes in two columns, All and None under them. Laid out by the framework's grid and row: in an egui +/// `Grid` the framework's checkboxes took the whole height left in the dialog, one row each. fn sources_row(ui: &mut egui::Ui, fields: &mut DialogFields, _: &mut craft::ui::patterns::form_dialogs::CustomContext) -> egui::Response { let from = from_value(fields); let mut on = SOURCES.map(|(id, _)| ticked(&from, id)); let before = on; - let response = egui::Grid::new("conditional-mode-sources") - .num_columns(2) - .spacing([24.0, 6.0]) - .show(ui, |ui| { - for row in 0..4 { - for i in [row, row + 4] { - Checkbox::new(Bind::bound(&mut on[i])).label(tl!(SOURCES[i].1)).show(ui); + let response = Stack::new() + .show(ui, |ui, _| { + Grid::new(COLUMNS).fit(GridFit::Fixed).show(ui, |ui, _| { + for row in 0..4 { + for i in [row, row + 4] { + Checkbox::new(Bind::bound(&mut on[i])).label(tl!(SOURCES[i].1)).show(ui); + } } - ui.end_row(); - } - for (label, all) in [(tl!("All"), true), (tl!("None"), false)] { - if Button::new(label).show(ui).clicked() { - on = [all; 8]; + }); + Row::new().show(ui, |ui, _| { + for (label, all) in [(tl!("All"), true), (tl!("None"), false)] { + if Button::new(label).show(ui).clicked() { + on = [all; 8]; + } } - } - ui.end_row(); + }); }) - .response; + .output; if on != before { let ticked: Vec<&str> = SOURCES.iter().zip(on).filter(|(_, on)| *on).map(|((id, _), _)| *id).collect(); fields.set("from", FieldValue::Json(json!(ticked))); diff --git a/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs b/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs index 59e6ace51c..dd47475180 100644 --- a/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs +++ b/crates/ui-egui/src/dialogs/duplicate_layer_ui.rs @@ -52,13 +52,14 @@ pub fn open(app: &mut PhotocraftApp) -> Result { let selected = st.selected_layers(); let layer = st.active_layer.and_then(|id| st.doc.layer(id)).ok_or("no active layer")?; let captured = json!({"document": st.doc.id.0, "selected": selected.iter().map(|id| id.0).collect::>()}); - // Several selected layers keep their names, as in Photoshop's Duplicate Layers. + // Several selected layers keep their names, as in Photoshop's Duplicate Layers. The window + // title is the menu item's name without its ellipsis (#16349). let (title, name) = if selected.len() > 1 { - (tl!("Duplicate Layers…"), None) + (tl!("Duplicate Layers"), None) } else if layer.is_group() { - (tl!("Duplicate Group…"), Some(st.doc.copy_name(&layer.name))) + (tl!("Duplicate Group"), Some(st.doc.copy_name(&layer.name))) } else { - (tl!("Duplicate Layer…"), Some(st.doc.copy_name(&layer.name))) + (tl!("Duplicate Layer"), Some(st.doc.copy_name(&layer.name))) }; let mut options: Vec<(String, Label)> = destinations(app).into_iter().map(|(key, name)| (key, Label::from(name))).collect(); options.push(("new".to_string(), Label::from(tl!("New")))); diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index 8b695b3525..21b5a651c2 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -203,9 +203,10 @@ pub(crate) struct ExportOpen { picking: bool, /// The newest preview the dialog asked for that is not fully answered yet. work: Option, - /// The newest request made, with the working profile it was made under: a change of the working - /// profile alters the preview of an untagged document without changing the settings. - last: Option<(u64, ExportOptions, Option)>, + /// The newest request made, with the working profile and the scratch read-error generation it was made under: a + /// change of the working profile alters the preview of an untagged document without changing the settings, and a + /// tile that fails to read and recovers alters the pixels without a new revision (`crate::scratch_reads`). + last: Option<(u64, ExportOptions, Option, u64)>, } /// One preview request being answered: the proxy preview first, then the exact size estimate. @@ -881,13 +882,14 @@ fn drive(app: &mut PhotocraftApp, ctx: &egui::Context, open: &mut ExportOpen) -> dialog.cancel_requests(); } } - // The settings did not change but the working profile did: ask again for the same revision. + // The settings did not change but the working profile or the scratch read-error generation did: ask again for the + // same revision. let wanted = wanted.or_else(|| { - let (revision, options, hash) = open.last.as_ref()?; - (working_profile_hash(app) != *hash).then(|| PreviewRequest::new(*revision, options.clone())) + let (revision, options, hash, scratch) = open.last.as_ref()?; + (working_profile_hash(app) != *hash || crate::scratch_reads::generation() != *scratch).then(|| PreviewRequest::new(*revision, options.clone())) }); if let Some(request) = wanted { - open.last = Some((request.revision, request.options.clone(), working_profile_hash(app))); + open.last = Some((request.revision, request.options.clone(), working_profile_hash(app), crate::scratch_reads::generation())); open.work = start_preview(app, open, request); } answer_preview(app, ctx, open); @@ -940,7 +942,7 @@ fn start_preview(app: &PhotocraftApp, open: &ExportOpen, request: PreviewRequest let profile = effective_source_profile(app, &doc); let signature = format!("{}:{}", Value::Object(settings.clone()), profile.content_hash()); let layer = open.layers.first().map(|layer| layer.0); - let key = egui::Id::unique(("export-preview", doc.id.0, st.revision, layer)); + let key = egui::Id::unique(("export-preview", doc.id.0, st.revision, layer, crate::scratch_reads::generation())); Some(PreviewWork { revision: request.revision, settings, signature, key, doc, profile, answered: None }) } diff --git a/crates/ui-egui/src/dialogs/export_dialog/tests.rs b/crates/ui-egui/src/dialogs/export_dialog/tests.rs index 24c1b0f6ab..ccbc1244db 100644 --- a/crates/ui-egui/src/dialogs/export_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/export_dialog/tests.rs @@ -924,6 +924,29 @@ fn preview_cache_tracks_working_profiles_but_prefers_embedded_profiles() { } } +/// A tile that fails to read and recovers alters the pixels without a new revision or other settings: the preview +/// is made again, so it does not keep the zeros it read during the error (`crate::scratch_reads`). +#[test] +fn the_preview_is_made_again_after_a_scratch_read_error_transition() { + let app = export_app(20, 10); + let revision = app.session.active().unwrap().revision; + let mut h = harness(app); + open(h.state_mut()).unwrap(); + settle_preview(&mut h); + let texture = + |h: &AppHarness| h.state().export_open.as_ref().and_then(|open| open.texture.as_ref().map(egui::TextureHandle::id)).expect("a preview was made"); + let before = texture(&h); + let options = dialog_options(&h); + h.run_steps(3); + settle_preview(&mut h); + assert_eq!(texture(&h), before, "nothing changed: the same preview"); + crate::scratch_reads::tests::simulate_read_error_transition(); + settle_preview(&mut h); + assert_eq!(h.state().session.active().unwrap().revision, revision); + assert_eq!(dialog_options(&h), options, "the settings did not change"); + assert_ne!(texture(&h), before, "the preview is made again"); +} + /// The dialog's requests are taken once: a second take in the same frame (a frame can run two /// passes) starts no second preview and files no second save request. #[test] diff --git a/crates/ui-egui/src/dialogs/file_ui/print.rs b/crates/ui-egui/src/dialogs/file_ui/print.rs index 1ba51ac4e8..3da1ad4e52 100644 --- a/crates/ui-egui/src/dialogs/file_ui/print.rs +++ b/crates/ui-egui/src/dialogs/file_ui/print.rs @@ -402,9 +402,9 @@ fn fields_set_position(f: &mut DialogFields, left: f64, top: f64) { /// The document's flattened picture at the preview size, mirrored for Emulsion Down (the sheet /// draws the picture unmirrored in the box). The texture lives in the context's memory under the -/// document's id and revision. +/// document's id and revision, and the scratch read-error generation (`crate::scratch_reads`). fn picture(ctx: &egui::Context, doc: &photocraft_doc::Document, revision: u64, mirror: bool) -> egui::load::SizedTexture { - let key = egui::Id::unique(("print-thumb", doc.id.0, revision, mirror)); + let key = egui::Id::unique(("print-thumb", doc.id.0, revision, mirror, crate::scratch_reads::generation())); let tex: Option> = ctx.data(|d| d.get_temp(key)); let tex = tex.unwrap_or_else(|| { let th = photocraft_compose::thumbnail(doc, 400); @@ -570,3 +570,19 @@ pub(crate) fn print_status(app: &mut PhotocraftApp, r: &Value) { }; app.ui.status_error = false; } + +#[cfg(test)] +mod scratch_tests { + /// A tile that fails to read and recovers keeps the document's revision; the preview picture still draws again, + /// so it does not keep the zeros it read during the error. + #[test] + fn the_preview_picture_draws_again_after_a_scratch_read_error_transition() { + use photocraft_doc::{ColorMode, Document, SampleType}; + let ctx = egui::Context::default(); + let doc = Document::new("Print", photocraft_geom::Size::new(8, 8), ColorMode::Rgb, SampleType::U8); + let first = super::picture(&ctx, &doc, 3, false).id; + assert_eq!(super::picture(&ctx, &doc, 3, false).id, first, "the same revision keeps its picture"); + crate::scratch_reads::tests::simulate_read_error_transition(); + assert_ne!(super::picture(&ctx, &doc, 3, false).id, first, "the picture draws again after the transition"); + } +} diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index f52a73e5de..df82081d16 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -1375,6 +1375,9 @@ pub struct FilterPreviewKey { pub params: Value, pub k: u32, pub tool_colors: ([f32; 4], [f32; 4]), + /// The scratch read-error generation (`crate::scratch_reads`): a tile that fails to read and recovers changes + /// the pixels without a new revision, and a preview computed during the error must not be kept. + pub scratch: u64, } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/filter_dialog/rows.rs b/crates/ui-egui/src/dialogs/filter_dialog/rows.rs index 88cb805530..a9cbad5907 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog/rows.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog/rows.rs @@ -316,6 +316,10 @@ fn set_lut_choice(fields: &mut DialogFields, choice: &LutChoice) { /// Color Lookup's 3D LUT menu lists the LUT folder's files after the built-in looks (#9754), as the adjustment /// layer's Properties do: one picker row over the command's `lut`, `file` and, for a LUT loaded from a file, /// `data` and `fileName`. +/// +/// The picker is a `Param::custom` row and the spec's `lut` choice row is dropped, so none of those keys is ever +/// remembered: an OK with a built-in look or a LUT file leaves the next opening at "no LUT", as the reference +/// application does (#14422). The rows that are remembered, Dither and Interpolation, come back as OK'd. fn color_lookup(app: &PhotocraftApp, params: &mut Vec) { let at = params.iter().position(|p| p.key == "lut").unwrap_or(params.len()); params.retain(|p| !matches!(p.key.as_str(), "lut" | "file")); diff --git a/crates/ui-egui/src/dialogs/filter_preview_ui.rs b/crates/ui-egui/src/dialogs/filter_preview_ui.rs index f0aaeb9f21..8bf8be5577 100644 --- a/crates/ui-egui/src/dialogs/filter_preview_ui.rs +++ b/crates/ui-egui/src/dialogs/filter_preview_ui.rs @@ -94,9 +94,10 @@ fn picture(app: &PhotocraftApp, ctx: &egui::Context, id: DialogId) -> Option(cache_id))); - // Channel visibility and the active mask can change without a document revision. Both the - // original (press-and-hold) and filtered textures must follow the canvas's current view. - let view = (st.channel_view.clone(), app.session.prefs().interface.show_channels_in_color, st.active_layer); + // Channel visibility and the active mask can change without a document revision, and so can a tile that fails + // to read and recovers (`crate::scratch_reads`). Both the original (press-and-hold) and filtered textures must + // follow the canvas's current view. + let view = (st.channel_view.clone(), app.session.prefs().interface.show_channels_in_color, st.active_layer, crate::scratch_reads::generation()); if cache.view.as_ref() != Some(&view) { cache = Cache { view: Some(view), ..Default::default() }; } @@ -221,7 +222,7 @@ struct CachedTex { struct Cache { filtered: Option, original: Option, - view: Option<(photocraft_engine::channel_cmds::ChannelView, bool, Option)>, + view: Option<(photocraft_engine::channel_cmds::ChannelView, bool, Option, u64)>, } #[cfg(test)] @@ -358,6 +359,26 @@ mod tests { assert!(pixels.unwrap().iter().all(|p| *p == Color32::BLACK)); } + /// A tile that fails to read and recovers moves no revision; the unfiltered texture still draws again then, so it + /// does not keep the zeros it read during the error. + #[test] + fn original_texture_refreshes_after_a_scratch_read_error_transition() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + crate::filter_dialog::open(&mut app, "filter.blur.gaussianBlur").unwrap(); + let id = top_dialog(&app); + let ctx = app.ctx().clone(); + let cache_id = egui::Id::unique(("filter-preview-ui", id.value())); + let original = |ctx: &egui::Context| ctx.data(|d| d.get_temp::(cache_id).unwrap().original.unwrap().tex.id()); + ctx.run_ui(Default::default(), |ui| feed(&mut app, ui.ctx())).textures_delta.clear(); + let before = original(&ctx); + ctx.run_ui(Default::default(), |ui| feed(&mut app, ui.ctx())).textures_delta.clear(); + assert_eq!(original(&ctx), before, "an unchanged picture is not uploaded again"); + crate::scratch_reads::tests::simulate_read_error_transition(); + ctx.run_ui(Default::default(), |ui| feed(&mut app, ui.ctx())).textures_delta.clear(); + assert_ne!(original(&ctx), before, "the picture draws again after the transition"); + } + #[test] fn only_filter_dialogs_get_the_preview_pane() { for (command, pane) in [ diff --git a/crates/ui-egui/src/dialogs/filter_preview_worker.rs b/crates/ui-egui/src/dialogs/filter_preview_worker.rs index fd440543b6..b6bafade7b 100644 --- a/crates/ui-egui/src/dialogs/filter_preview_worker.rs +++ b/crates/ui-egui/src/dialogs/filter_preview_worker.rs @@ -131,6 +131,7 @@ mod tests { params: json!({"colors": colors}), k: 1, tool_colors: ([0.0, 0.0, 0.0, 1.0], [1.0; 4]), + scratch: 0, } } diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index de856173ae..5b956a5347 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -641,11 +641,18 @@ fn paint_picture(cx: &ContentPainterCx, rect: Rect, key: impl std::hash::Hash + cx.picture(texture, rect, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), 0.0); } +/// The texture store key of the preview swatch: the draft's render hash and the scratch read-error generation, as the +/// swatch draws over the patterns' pixels, which a tile that fails to read shows as zeros until it reads again +/// (`crate::scratch_reads`). +fn swatch_key(draft: &LayerStyleDraft) -> (&'static str, u64, u64) { + ("layer-style-swatch", draft.render_hash(), crate::scratch_reads::generation()) +} + /// Paints the preview swatch: the draft's style on a sample square, rebuilt when its render hash changes. fn preview_thumb(app: &PhotocraftApp) -> impl Fn(&ContentPainterCx, Rect, &LayerStyleDraft) + Send + Sync + 'static { let patterns = app.session.patterns.clone(); move |cx, rect, draft| { - paint_picture(cx, rect, ("layer-style-swatch", draft.render_hash()), || { + paint_picture(cx, rect, swatch_key(draft), || { let mut scratch = Session::new(); scratch.patterns = patterns.clone(); match pending_style(&patterns, &draft.style) { diff --git a/crates/ui-egui/src/dialogs/layer_style/tests.rs b/crates/ui-egui/src/dialogs/layer_style/tests.rs index 7d83620208..3ee114f20c 100644 --- a/crates/ui-egui/src/dialogs/layer_style/tests.rs +++ b/crates/ui-egui/src/dialogs/layer_style/tests.rs @@ -790,3 +790,16 @@ fn an_existing_outer_glow_is_edited_with_its_own_values() { let FxPaint::Color(c) = &g.paint else { panic!("{:?}", g.paint) }; assert_eq!(hex(c), "#ffffbe", "OK kept the colour"); } + +/// The preview swatch draws over the patterns' pixels: a tile that fails to read and recovers keeps the draft's render +/// hash, and the swatch still keys a new picture, so it does not keep the zeros it read during the error. +#[test] +fn the_preview_swatch_follows_a_scratch_read_error_transition() { + let mut app = app_with_layer(32); + let id = open(&mut app, Some(EffectKind::PatternOverlay.key())).unwrap(); + let key = swatch_key(draft(&app, id)); + assert_eq!(swatch_key(draft(&app, id)), key, "nothing changed: the same picture"); + crate::scratch_reads::tests::simulate_read_error_transition(); + assert_eq!(draft(&app, id).render_hash(), key.1, "the draft is unchanged"); + assert_ne!(swatch_key(draft(&app, id)), key, "the swatch draws again"); +} diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 1631cb54a9..dec11d58b4 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -29,6 +29,7 @@ fn filter_dialog_with_preview(background: bool) -> (Box, DialogId params: serde_json::json!({"radius": 4.0}), k: 1, tool_colors: (app.session.tools.foreground, app.session.tools.background), + scratch: crate::scratch_reads::generation(), }; app.filter_preview = Some(crate::filter_dialog::FilterPreview { key, result: result.map(std::sync::Arc::new), committing: false }); (app, id) diff --git a/crates/ui-egui/src/guide_cursor_tests.rs b/crates/ui-egui/src/guide_cursor_tests.rs index 59ddeed269..c972caa80d 100644 --- a/crates/ui-egui/src/guide_cursor_tests.rs +++ b/crates/ui-egui/src/guide_cursor_tests.rs @@ -47,8 +47,10 @@ fn drag(h: &mut Harness<'static, Box>, from: f32, to: f32, m: Mod h.run_steps(1); h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: m }); h.run_steps(1); - for k in 1..=4 { - let q = screen(h, from + (to - from) * k as f32 / 4.0, 150.0); + // Two moves: the guide follows the pointer, so one intermediate point is enough to drive the drag and the + // fourth one only cost another whole-app frame each row (#15941). + for k in 1..=2 { + let q = screen(h, from + (to - from) * k as f32 / 2.0, 150.0); h.event(egui::Event::PointerMoved(q)); h.run_steps(1); } @@ -57,20 +59,35 @@ fn drag(h: &mut Harness<'static, Box>, from: f32, to: f32, m: Mod h.run_steps(2); } +/// The vertical guides as they stand. +fn guides(h: &Harness<'static, Box>) -> Vec { + h.state().session.active().unwrap().doc.guides.vertical.clone() +} + +/// Put the guide back at 200 after a row dragged it, through the ruler's own command, so the next row starts +/// where the first one did without paying for another app. +fn put_guide_back(h: &mut Harness<'static, Box>) { + h.state_mut().run("view.moveGuide", json!({"orientation": "vertical", "index": 0, "position": 200})).unwrap(); + h.run_steps(2); + assert_eq!(guides(h), vec![200.0], "the guide is back at 200 for the next row"); +} + /// The cursor over the guide with ⌘ held (or latched in Window › Modifier Keys, with no key held), -/// and where a ⌘-drag from 200 to 240 leaves it. -fn command_drag(tool: Tool, locked: bool, latched: bool) -> (egui::CursorIcon, Vec) { - let mut h = harness(tool); +/// and where a ⌘-drag from 200 to 240 leaves it, on the shared harness `h`. +fn command_drag(h: &mut Harness<'static, Box>, tool: Tool, locked: bool, latched: bool) -> (egui::CursorIcon, Vec) { + h.state_mut().ui.tool = tool; h.state_mut().ui.extras.lock_guides = locked; let held = if latched { h.state_mut().ui.shell.latched = craft::keymap::Mods::CMD; Modifiers::NONE } else { + h.state_mut().ui.shell.latched = craft::keymap::Mods::NONE; Modifiers::COMMAND }; - let c = hover(&mut h, 200.0, 150.0, held); - drag(&mut h, 200.0, 240.0, held); - (c, h.state().session.active().unwrap().doc.guides.vertical.clone()) + h.run_steps(1); + let c = hover(h, 200.0, 150.0, held); + drag(h, 200.0, 240.0, held); + (c, guides(h)) } const GUIDE: egui::CursorIcon = egui::CursorIcon::ResizeHorizontal; @@ -114,13 +131,43 @@ fn command_over_a_guide_takes_it_where_command_is_the_move_tool() { (Tool::Rectangle, false, false, false), (Tool::Slice, false, false, false), ]; - for (tool, locked, latched, takes_guide) in rows { - let (cursor, guides) = command_drag(tool, locked, latched); + let check = |h: &mut Harness<'static, Box>, tool: Tool, locked: bool, latched: bool, takes_guide: bool| { + let (cursor, moved) = command_drag(h, tool, locked, latched); if takes_guide { - assert_eq!((cursor, guides), (GUIDE, vec![240.0]), "{tool:?} latched={latched}"); + assert_eq!((cursor, moved), (GUIDE, vec![240.0]), "{tool:?} latched={latched}"); + put_guide_back(h); } else { assert_ne!(cursor, GUIDE, "{tool:?} locked={locked}"); - assert_eq!(guides, vec![200.0], "{tool:?} locked={locked}"); + assert_eq!(moved, vec![200.0], "{tool:?} locked={locked}"); + } + }; + // One app for the rows whose ⌘ press the Move tool takes and for the rows that ask a locked guide to stay: + // `harness` builds the whole app and its settle frames, while the selected tool, the ⌘ latch and the locked + // guides are state the app reads each frame. The split is by what a row expects, not by tool name: a takes-row + // puts the guide back with the ruler's own command (`view.moveGuide`, what a user does to move it again) and a + // locked row moves nothing, so neither leaves state for the rows after it (#15941). + let mut shared = harness(Tool::Brush); + let mut ran = 0; + for (tool, locked, latched, takes_guide) in rows { + if takes_guide || locked { + check(&mut shared, tool, locked, latched, takes_guide); + ran += 1; } } + // The tools that keep ⌘ for themselves share an app too. The Type tool goes last: its ⌘-drag leaves an open + // text edit, and `moves_with_command` refuses the guides while one is open, so a later row would be decided by + // that instead of by its tool. The Crop tool keeps an app of its own for the same reason: its drag leaves a + // pending crop frame holding the canvas. + let mut keeps = harness(Tool::Pen); + for tool in [Tool::Pen, Tool::Hand, Tool::Zoom, Tool::Rectangle, Tool::Slice, Tool::Type] { + // Cheap guard on the reason this app is ordered: no row so far left an open text edit that would decide + // this one instead of its tool. + assert!(keeps.state().ui.text_edit.is_none(), "no text edit open before {tool:?} in the keeps app"); + check(&mut keeps, tool, false, false, false); + ran += 1; + } + let mut crop = harness(Tool::Crop); + check(&mut crop, Tool::Crop, false, false, false); + ran += 1; + assert_eq!(ran, rows.len(), "every row ran once: {} shared, 6 keeps, 1 crop", ran - 7); } diff --git a/crates/ui-egui/src/i18n/live_tests.rs b/crates/ui-egui/src/i18n/live_tests.rs index 45cd0cc03c..d40c580558 100644 --- a/crates/ui-egui/src/i18n/live_tests.rs +++ b/crates/ui-egui/src/i18n/live_tests.rs @@ -205,7 +205,8 @@ fn harness_with_services(services: Services) -> egui_kittest::Harness<'static, B } /// Auto draws the detected system language on first launch while keeping the Auto preference; no or -/// unsupported system languages draw English. +/// unsupported system languages draw English. Which language a tag picks is plain logic, checked for +/// every case; drawing differs only by script, so one app each draws Latin, CJK and Cyrillic. #[test] fn first_launch_renders_the_system_language_without_overwriting_auto() { if !needs_catalogs() { @@ -228,6 +229,10 @@ fn first_launch_renders_the_system_language_without_overwriting_auto() { (&["sw-KE", "is-IS"], "en"), ]; for (tags, code) in cases { + assert_eq!(system::with_system_tags(tags, || Lang::from_pref("auto")), lang(code), "{tags:?}"); + } + let drawn: [(&[&str], &str); 3] = [(&["fr-CA"], "fr"), (&["ja-JP"], "ja"), (&["ru-RU"], "ru")]; + for (tags, code) in drawn { system::with_system_tags(tags, || { with_language(Lang::EN, || { let h = harness(); diff --git a/crates/ui-egui/src/input/hold_keys/tests.rs b/crates/ui-egui/src/input/hold_keys/tests.rs index 867bdf7fd5..8a3aa44764 100644 --- a/crates/ui-egui/src/input/hold_keys/tests.rs +++ b/crates/ui-egui/src/input/hold_keys/tests.rs @@ -176,8 +176,13 @@ fn space_repositions_the_drag_being_drawn() { slack: 1, }, ]; + // One app for the three marquee and lasso cases: the tool is state, and each case starts from no selection. + let mut h = harness(Tool::RectMarquee); for c in cases { - let mut h = harness(c.tool); + h.state_mut().run("select.deselect", json!({})).ok(); + assert_eq!(selection(&h), Rect::EMPTY, "{:?}: the case starts with no selection", c.tool); + h.state_mut().ui.tool = c.tool; + h.run_steps(1); press_at(&mut h, c.start.0, c.start.1); for &(x, y) in c.before { move_to(&mut h, x, y); @@ -368,10 +373,11 @@ fn cmd_gives_the_move_tool_only_where_the_tool_does_not_take_cmd() { } // The Crop and Rotate View tools go last, in an app of their own: they leave a pending crop and // a turned view behind. - let keeps = [ - vec![Tool::Hand, Tool::Zoom, Tool::Pen, Tool::Rectangle, Tool::Type, Tool::VerticalType, Tool::PathSelection, Tool::DirectSelection], - vec![Tool::Crop, Tool::RotateView], - ]; + // One tool per decision the refusal comes from: the Hand, Zoom and Rotate-View families, the vector family's + // shared line (the Pen stands for the shapes and both path tools), and the Type tools' `is_type` line (the + // vertical type tool takes the same branch). Every tool's own decision is asserted in + // `the_command_stand_in_rule_is_the_table`, without a drag. + let keeps = [vec![Tool::Hand, Tool::Zoom, Tool::Pen, Tool::Type], vec![Tool::Crop, Tool::RotateView]]; for group in keeps { let mut h = harness(group[0]); for tool in group { @@ -382,6 +388,62 @@ fn cmd_gives_the_move_tool_only_where_the_tool_does_not_take_cmd() { } } +/// The ⌘-as-Move rule read as data: `takes_command_stand_in` and the selection family decide which tool hands a ⌘ +/// press to the Move tool, for every tool in the app. The drags above press one tool per decision; this pins each +/// tool by name, so a tool that moves into another family or starts refusing the stand-in fails here. +#[test] +fn the_command_stand_in_rule_is_the_table() { + use crate::canvas::tools::Family; + let hands_to_move = |t: Tool| crate::canvas::tools::takes_command_stand_in(t) || crate::canvas::tools::family(t) == Family::Selection; + let got: Vec = Tool::ALL.into_iter().filter(|t| hands_to_move(*t)).collect(); + let want: Vec = vec![ + Tool::Artboard, + Tool::RectMarquee, + Tool::EllipseMarquee, + Tool::SingleRowMarquee, + Tool::SingleColumnMarquee, + Tool::Lasso, + Tool::PolygonLasso, + Tool::MagneticLasso, + Tool::MagicWand, + Tool::Eyedropper, + Tool::ColorSampler, + Tool::Ruler, + Tool::Note, + Tool::Count, + Tool::Brush, + Tool::Pencil, + Tool::ColorReplacement, + Tool::MixerBrush, + Tool::Eraser, + Tool::BackgroundEraser, + Tool::MagicEraser, + Tool::Gradient, + Tool::PaintBucket, + Tool::SpotHealing, + Tool::Remove, + Tool::Healing, + Tool::Patch, + Tool::ContentAwareMove, + Tool::RedEye, + Tool::CloneStamp, + Tool::PatternStamp, + Tool::HistoryBrush, + Tool::ArtHistoryBrush, + Tool::Blur, + Tool::Sharpen, + Tool::Smudge, + Tool::AdjustmentBrush, + Tool::Dodge, + Tool::Burn, + Tool::Sponge, + Tool::QuickSelection, + Tool::ObjectSelection, + Tool::Frame, + ]; + assert_eq!(got, want, "which tools hand a ⌘ press to the Move tool"); +} + /// A ⌘-drag with `tool`, one that keeps ⌘ for itself, leaves a fresh layer where it is. fn keeps_the_layer(h: &mut Harness<'static, Box>, tool: Tool) { let id = with_layer(h); @@ -397,8 +459,11 @@ fn keeps_the_layer(h: &mut Harness<'static, Box>, tool: Tool) { /// brush to resize, such as the Gradient. #[test] fn cmd_alt_drag_duplicates_the_layer_then_moves_the_copy() { + // One app, one fresh layer per case (the `with_layer` each case already calls). + let mut h = harness(Tool::Brush); for (tool, mods) in [(Tool::Brush, MAC_CMD_ALT), (Tool::Gradient, MAC_CMD_ALT), (Tool::Gradient, CTRL_ALT)] { - let mut h = harness(tool); + h.state_mut().ui.tool = tool; + h.run_steps(1); let orig = with_layer(&mut h); let n0 = h.state().session.active().unwrap().doc.layers.len(); let h0 = h.state().session.active().unwrap().history.past_len(); @@ -486,8 +551,11 @@ fn last_stroke_erases(h: &Harness<'static, Box>) -> Option /// holds across frames (a second pass in a frame does not clear it) and goes with the release. #[test] fn tilde_erases_only_with_the_brush_and_pencil() { + // One app, a fresh layer per tool (`with_layer`), so the strokes of one tool never sit under the next one's. + let mut h = harness(Tool::Brush); for (tool, label, erases) in [(Tool::Brush, "Brush Tool", true), (Tool::Pencil, "Pencil", true), (Tool::CloneStamp, "", false)] { - let mut h = harness(tool); + h.state_mut().ui.tool = tool; + h.run_steps(1); with_layer(&mut h); key(&mut h, Key::Backtick, true, Modifiers::NONE); h.run_steps(3); @@ -559,8 +627,18 @@ fn a_held_key_keeps_a_pending_crop_and_another_tools_key_commits_it() { /// Photoshop, not the held-over tool's menu; the tool comes back on release (#11271). #[test] fn space_right_click_opens_the_hand_view_menu() { + // One app for the four tools: `harness` starts the whole app (its document, panels and settle frames), which is + // most of a case, while the selected tool is state the app takes between frames (#15941). The tool is switched + // the way the ⌘-Move test below does it. + let mut h = harness(Tool::Move); for tool in [Tool::Move, Tool::Brush, Tool::RectMarquee, Tool::Pen] { - let mut h = harness(tool); + h.state_mut().ui.tool = tool; + // Every case starts at 100 %, not where the case before it left the shared view: the first + // case ends at 200 %, and a later case whose row applied nothing would still read 200 %. + let view = &mut h.state_mut().ui.views[0]; + view.zoom = 1.0; + view.clear_pending(); + h.run_steps(1); let p = screen(&h, 200.0, 150.0); h.event(Event::PointerMoved(p)); h.run_steps(1); @@ -577,6 +655,7 @@ fn space_right_click_opens_the_hand_view_menu() { assert_eq!(h.state().ui.tool, tool, "{tool:?}: the tool is kept"); // Its rows work as the selected Hand's do. let before = zoom(&h); + assert!(before != 2.0, "{tool:?}: the case starts away from 200 % ({before}), so the row has to move the view"); let ctx = h.ctx.clone(); crate::canvas_tool_menu::choose(h.state_mut(), &ctx, "view.twoHundredPercent"); h.run_steps(2); @@ -611,9 +690,13 @@ fn space_hand_view_menu_closes_when_the_tool_underneath_changes() { /// ⌘/Ctrl+right-click, which lists the layers under the pointer for any tool (#307). #[test] fn command_or_alt_space_right_click_opens_no_view_menu() { + // One app for all four cases, as above; the menu a ⌘+right-click leaves open is closed before the next case. + let mut h = harness(Tool::Move); for mods in [Modifiers::COMMAND, Modifiers::ALT] { for tool in [Tool::Move, Tool::Brush] { - let mut h = harness(tool); + h.state_mut().ui.tool = tool; + h.state_mut().ui.canvas_tool_menu = None; + h.run_steps(1); let p = screen(&h, 200.0, 150.0); h.event(Event::PointerMoved(p)); h.run_steps(1); @@ -720,3 +803,44 @@ fn space_hand_pasteboard_menu_opens_outside_the_image_and_outlives_space() { h.run_steps(2); assert!(h.state().ui.canvas_tool_menu.is_none(), "another tool selected closes it"); } + +/// A lone Alt tap or F10 puts the keyboard on the menu bar. Space then opens no menu (it used to open File, and a held +/// Space ran File > New) and is the Hand in the same press: the drag pans, as it always does in the reference +/// application (#16327). +#[test] +fn space_after_an_alt_tap_or_f10_pans_and_opens_no_menu() { + for (f10, clicked) in [(false, false), (true, false), (false, true), (true, true)] { + let mut h = harness(Tool::Brush); + let p = screen(&h, 200.0, 150.0); + if clicked { + // A dab first, so the canvas holds the keyboard when the bar takes it. + click(&mut h, 100.0, 80.0, Modifiers::NONE); + } + h.event(Event::PointerMoved(p)); + h.run_steps(2); + if f10 { + key(&mut h, Key::F10, true, Modifiers::NONE); + key(&mut h, Key::F10, false, Modifiers::NONE); + } else { + h.event(Event::ModifiersChanged(Modifiers::ALT)); + h.run_steps(1); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + } + assert!(craft::ui::menu::bar::is_focused(&h.ctx), "f10 {f10}, clicked {clicked}: the keyboard is on the bar"); + let before = center(&h); + key(&mut h, Key::Space, true, Modifiers::NONE); + assert!(!craft::ui::menu::bar::is_open(&h.ctx), "f10 {f10}, clicked {clicked}: Space opens no menu"); + assert!(!craft::ui::menu::bar::is_focused(&h.ctx), "f10 {f10}, clicked {clicked}: Space takes the keyboard off the bar"); + button(&mut h, p, true, Modifiers::NONE); + move_to(&mut h, 250.0, 180.0); + let q = screen(&h, 250.0, 180.0); + button(&mut h, q, false, Modifiers::NONE); + key(&mut h, Key::Space, false, Modifiers::NONE); + h.run_steps(2); + assert!(!craft::ui::menu::bar::is_open(&h.ctx), "f10 {f10}, clicked {clicked}: no menu after the drag"); + assert_ne!(center(&h), before, "f10 {f10}, clicked {clicked}: Space and a drag pan the view"); + assert_eq!(h.state().session.documents().len(), 1, "f10 {f10}, clicked {clicked}: no new document"); + assert_eq!(h.state().ui.tool, Tool::Brush, "f10 {f10}, clicked {clicked}: the tool comes back"); + } +} diff --git a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs index 77163189e0..cd720d3002 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch/tests.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch/tests.rs @@ -82,13 +82,11 @@ pub(crate) fn tap(h: &mut Harness<'_, Box>, key: Key, mods: Modif h.run_steps(3); } +/// A press and release queued in one input frame, then the frames that take it and run its command: two, not +/// [`tap`]'s three - the runtime takes the key in the first and the app runs the command it fired in the second +/// (`quick_shift_press` in `tool_shift_cycle_order_tests` measures the same for the tool letters). The third frame +/// only drew the app again (#15941). fn press(h: &mut Harness<'_, Box>, sc: &str) { - let sc = parse(sc).unwrap_or_else(|| panic!("unparsable shortcut {sc}")); - tap(h, sc.logical_key, sc.modifiers); -} - -/// Queue one press/release in one input frame, then let the runtime collect and the app dispatch it. -fn press_in_one_frame(h: &mut Harness<'_, Box>, sc: &str) { let sc = parse(sc).unwrap_or_else(|| panic!("unparsable shortcut {sc}")); let m = platform(sc.modifiers); h.input_mut().events.extend([ @@ -349,6 +347,8 @@ fn every_displayed_shortcut_runs_its_menu_item() { fn every_kind_of_shortcut_dispatches_from_where_focus_usually_is() { let mut failures = Vec::new(); for place in [Place::Canvas, Place::LayersRow, Place::FocusedWidget, Place::OpacityField] { + // One app per place: the presses below include the panel toggles the runtime runs itself, so the next + // place could not count on the Layers panel still being there. let mut h = harness(); set_dry_run(&h.ctx, true); put_focus(&mut h, place); @@ -358,7 +358,7 @@ fn every_kind_of_shortcut_dispatches_from_where_focus_usually_is() { // A press the focused component holds (the Layers rows' stacking and visibility keys) // is the component's and reaches no app command. let held = focus_holds(&h.ctx, chord); - press_in_one_frame(&mut h, &sc); + press(&mut h, &sc); let log = take_log(&h.ctx); if typing && !chord.has_command() && !chord.is_function_key() { // A focused text field keeps its typing / editing keys: nothing may fire. @@ -384,7 +384,7 @@ fn every_kind_of_shortcut_dispatches_from_where_focus_usually_is() { for t in one.into_iter().chain(many) { let start = if t.key() == 'H' { Tool::Move } else { Tool::Hand }; h.state_mut().ui.tool = start; - press_in_one_frame(&mut h, &t.key().to_string()); + press(&mut h, &t.key().to_string()); let want = if typing { start } else { t }; if h.state().ui.tool.key() != want.key() { failures.push(format!("{place:?}: tool key {} left {:?}, expected a {} tool", t.key(), h.state().ui.tool, want.key())); @@ -461,8 +461,8 @@ fn keys_run_their_commands() { set_dry_run(&h.ctx, false); // #352: ⌥[ ⌥] ⌥, ⌥. and ⇧⌥[ walk the Layers panel's rows. Rows, top to bottom: paint, Hello (type), group, - // in-group, Background. - let mut h = harness(); + // in-group, Background. The same app: the dry-run presses above ran no command, so the document is still the + // harness's own (#15941). assert_eq!(active_name(&h), "paint"); for (key, want) in [("Alt+[", "Hello"), ("Alt+[", "group"), ("Alt+[", "in-group"), ("Alt+]", "group"), ("Alt+,", "Background"), ("Alt+.", "paint")] { press(&mut h, key); @@ -512,11 +512,14 @@ fn keys_run_their_commands() { fn delete_key_targets() { // The selected layer, from the canvas or the Layers panel, in one undo step. for place in [Place::Canvas, Place::LayersRow] { + // One app per place: each key's delete is undone by the end of its case, so the next key starts from the + // same document without paying for another whole app (#15941). + let mut h = harness(); + put_focus(&mut h, place); for key in ["Delete", "Backspace"] { - let mut h = harness(); - put_focus(&mut h, place); let s = &mut h.state_mut().session; - s.execute("select.deselect", json!({})).unwrap(); + // The first case of the app deselects the harness's own selection; the ones after it start without one. + s.execute("select.deselect", json!({})).ok(); let adj = photocraft_doc::LayerId(s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap()["layer"].as_u64().unwrap()); h.run_steps(2); let before = names(&h); @@ -526,15 +529,21 @@ fn delete_key_targets() { assert_eq!(names(&h).len(), before.len() - 1, "{place:?} {key}: only it"); press(&mut h, "Cmd+Z"); assert_eq!(names(&h), before, "{place:?} {key}: one undo brings it back"); + // The undo's own log entry goes here: the next key of this app starts with an empty log, as the + // app-per-key version did. + take_log(&h.ctx); } } // The layer mask targeted: a selection fills the mask with the background colour, no selection deletes the mask. + // One app for both keys: the first case leaves the layer without a mask and without a selection, and the case + // puts both back before it starts (#15941). + let mut h = harness(); + put_focus(&mut h, Place::Canvas); for key in ["Delete", "Backspace"] { - let mut h = harness(); - put_focus(&mut h, Place::Canvas); let s = &mut h.state_mut().session; let layer = s.active().unwrap().active_layer.unwrap(); + s.execute("select.rect", json!({"x": 20, "y": 20, "width": 80, "height": 60})).unwrap(); s.execute("layer.layerMask.revealAll", json!({})).unwrap(); let sel = s.active().unwrap().doc.selection.as_ref().expect("the harness keeps a selection").content_bounds(); let (x, y) = ((sel.x0 + sel.x1) / 2, (sel.y0 + sel.y1) / 2); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c1b338620f..0927c80a3a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -56,6 +56,7 @@ pub mod panels; pub mod preset_files_ui; pub mod proxy; pub mod render_path; +pub(crate) mod scratch_reads; pub mod state; pub mod texel_guard; pub mod theme; @@ -246,6 +247,7 @@ pub(crate) use services::{opaque_layer, saves_flat_in_place}; pub use text::cjk_fonts; pub use text::direction; pub use text::served_fonts; +pub use tools::adjustment_brush; use tools::align_bar; pub use tools::analysis; pub use tools::artboard_tool; @@ -972,6 +974,8 @@ mod layer_thumb_bounds_tests; mod mask_thumb_refresh_tests; #[cfg(test)] mod menu_floor_trials; +#[cfg(test)] +mod scratch_read_keys_tests; #[cfg(test)] mod new_doc_remember_tests; diff --git a/crates/ui-egui/src/menus/facts.rs b/crates/ui-egui/src/menus/facts.rs index 4732b7800b..aacc54fdfc 100644 --- a/crates/ui-egui/src/menus/facts.rs +++ b/crates/ui-egui/src/menus/facts.rs @@ -205,7 +205,7 @@ impl<'a> RuleFacts<'a> { active_index: s.active_index(), active: s.active_tracked(), all: all_revisions(s.documents()), - scratch: photocraft_raster::spill::read_error_generation(), + scratch: crate::scratch_reads::generation(), jobs: (s.has_jobs(), s.active_job().map(|job| job.id.0)), smart_child: active.is_some_and(|d| s.smart_links.iter().any(|link| link.child == d.doc.id)), fade: s.edit_state.fade.as_ref().map(|fade| (fade.doc, fade.revision)), diff --git a/crates/ui-egui/src/panels/histogram_panel.rs b/crates/ui-egui/src/panels/histogram_panel.rs index 65cb782240..7a241651c7 100644 --- a/crates/ui-egui/src/panels/histogram_panel.rs +++ b/crates/ui-egui/src/panels/histogram_panel.rs @@ -351,7 +351,9 @@ fn committed_key(app: &PhotocraftApp) -> Option<(HistKey, ToneSpace, HistSource) Some((d, r, k)) if d == doc && r == revision => k, _ => tone::selection_key(&st.doc), }; - let source_tag = tone::tag(source, space, HistScope::Selection, sel); + // A tile that fails to read counts as zeros, and as its pixels again once it reads, without a new revision: the + // key follows the scratch read-error generation too (`crate::scratch_reads`). + let source_tag = crate::scratch_reads::with(tone::tag(source, space, HistScope::Selection, sel)); Some((HistKey { doc, revision, source: source_tag, preview: 0, max_level }, space, source)) } diff --git a/crates/ui-egui/src/panels/histogram_panel/tests.rs b/crates/ui-egui/src/panels/histogram_panel/tests.rs index fe53966526..0a85f3b077 100644 --- a/crates/ui-egui/src/panels/histogram_panel/tests.rs +++ b/crates/ui-egui/src/panels/histogram_panel/tests.rs @@ -447,3 +447,21 @@ fn the_tone_histogram_cache_ignores_selection_changes() { app.run("select.deselect", json!({})).unwrap(); assert!(Arc::ptr_eq(&first, &tone::histograms(&mut app, src, ToneSpace::Rgb)), "deselecting keeps it too"); } + +/// A tile that fails to read counts as zeros, and as its pixels again once it reads, without a new revision or +/// selection: the panel's histogram goes stale and is counted again (`crate::scratch_reads`). +#[test] +fn the_panel_recounts_after_a_scratch_read_error_transition() { + let mut app = app_with(json!({"width": 64, "height": 48})); + settle(&mut app); + let counted = app.doc_hist.clone().expect("landed"); + frame(&mut app); + assert_eq!(inspect(&app)["current"], true, "nothing changed: still current"); + crate::scratch_reads::tests::simulate_read_error_transition(); + assert_eq!(inspect(&app)["current"], false, "stale after the transition"); + settle(&mut app); + let recounted = app.doc_hist.clone().expect("landed"); + assert_eq!(recounted.key.revision, counted.key.revision, "no new revision"); + assert_ne!(recounted.key.source, counted.key.source, "counted again for the new generation"); + assert_eq!(inspect(&app)["current"], true); +} diff --git a/crates/ui-egui/src/panels/layers_tree.rs b/crates/ui-egui/src/panels/layers_tree.rs index 25e10df30d..4a6f0b42af 100644 --- a/crates/ui-egui/src/panels/layers_tree.rs +++ b/crates/ui-egui/src/panels/layers_tree.rs @@ -746,7 +746,7 @@ impl ThumbSource> for PhotoThumbs<'_> { }; // A tile that fails to read shows zeros, and its pixels again once it reads, without moving its surface's // generation: the scratch read-error generation moves with both (#16252). - let scratch = photocraft_raster::spill::read_error_generation(); + let scratch = crate::scratch_reads::generation(); Revision::of(&(shown, clip, self.doc.size.width, self.doc.size.height, scratch)) } diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 5679c97ced..2fdda891bb 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -157,7 +157,9 @@ fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // The bar shows the active tool's brush: switch it in before drawing, so a tool change swaps the brush with it // (Photoshop keeps one per tool). crate::paint_mouse::sync_tool_brush(app); - if (tool.is_brushlike() && !matches!(tool, Tool::Brush | Tool::Pencil | Tool::MixerBrush | Tool::Eraser)) || tool == Tool::QuickSelection { + if (tool.is_brushlike() && !matches!(tool, Tool::Brush | Tool::Pencil | Tool::MixerBrush | Tool::Eraser | Tool::AdjustmentBrush)) + || tool == Tool::QuickSelection + { crate::brush_picker::show_field(ui, app, true); crate::brush_picker::settings_toggle(ui, app); Divider::vertical().show(ui); @@ -166,7 +168,8 @@ fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui) { stamp_members(app, ui, tool); Divider::vertical().show(ui); } - if crate::eraser_ui::options_bar(ui, app, tool) + if crate::adjustment_brush::options_bar(ui, app, tool) + || crate::eraser_ui::options_bar(ui, app, tool) || crate::retouch_ui::bar::options_bar(ui, app, tool) || crate::vector_ui::options_bar(app, ui, tool) || crate::analysis::bars::options(app, ui, tool) diff --git a/crates/ui-egui/src/panels/preset_browser.rs b/crates/ui-egui/src/panels/preset_browser.rs index 242b9a3d23..3b8cc76f2e 100644 --- a/crates/ui-egui/src/panels/preset_browser.rs +++ b/crates/ui-egui/src/panels/preset_browser.rs @@ -160,9 +160,12 @@ type HeldPatterns = Arc<[Arc]>; type StylesStamp = (Revision, u64); /// A number for the library's patterns and their pixels: equal stamps mean the same patterns with the same pixels -/// (`Surface::generation` names a pixel state, and is shared by clones). +/// (`Surface::generation` names a pixel state, and is shared by clones). It also moves with the scratch read-error +/// generation: a pattern tile that fails to read draws zeros and its pixels again once it reads, under the same +/// generation (`crate::scratch_reads`), and the style thumbnails drawn over the patterns follow it through this. fn patterns_stamp(library: &PatternLibrary) -> u64 { let mut hasher = DefaultHasher::new(); + crate::scratch_reads::generation().hash(&mut hasher); for pattern in &library.items { (&pattern.id, &pattern.name, pattern.surface.generation()).hash(&mut hasher); } @@ -302,9 +305,9 @@ fn pattern_image(pattern: &photocraft_doc::Pattern) -> ColorImage { } /// The texture store key of `pattern`'s swatch: its id and its pixels, so a pattern replaced under the same id draws -/// anew. +/// anew, and a swatch drawn while a tile failed to read draws again once it reads (`crate::scratch_reads`). fn pattern_key(pattern: &photocraft_doc::Pattern) -> PictureKey { - ("pattern", pattern.id.clone(), pattern.surface.generation()) + ("pattern", pattern.id.clone(), crate::scratch_reads::with(pattern.surface.generation())) } /// A texture of `pattern`'s swatch that its holder owns: it stays while the handle lives, where a cached texture diff --git a/crates/ui-egui/src/panels/preset_browser/tests.rs b/crates/ui-egui/src/panels/preset_browser/tests.rs index ee3c9c6613..6044d8c57e 100644 --- a/crates/ui-egui/src/panels/preset_browser/tests.rs +++ b/crates/ui-egui/src/panels/preset_browser/tests.rs @@ -172,6 +172,24 @@ fn a_pattern_replaced_under_its_id_keys_a_new_picture() { assert_eq!(pattern_key(&first), pattern_key(&first.clone()), "a clone holds the same pixels"); } +/// A pattern swatch drawn while a pattern tile failed to read shows zeros: once the tile reads again (no new +/// generation), the swatch keys a new picture, and so do the style thumbnails drawn over the patterns. +#[test] +fn pattern_and_style_pictures_follow_a_scratch_read_error_transition() { + let mut app = app(); + let pattern = app.session.patterns.items[0].clone(); + let (swatch, library) = (pattern_key(&pattern), StyleLibrary::held(&mut app)); + assert_eq!(pattern_key(&pattern), swatch); + assert!(Arc::ptr_eq(&library, &StyleLibrary::held(&mut app))); + crate::scratch_reads::tests::simulate_read_error_transition(); + assert_ne!(pattern_key(&pattern), swatch, "the swatch draws again"); + let after = StyleLibrary::held(&mut app); + assert!(!Arc::ptr_eq(&library, &after), "the style library is taken again"); + let stamps = |library: &StyleLibrary| library.styles.iter().map(|(stamp, _)| *stamp).collect::>(); + assert!(!stamps(&library).is_empty()); + assert!(stamps(&library).iter().zip(stamps(&after)).all(|(before, now)| *before != now), "every style thumbnail draws again"); +} + /// The flat list of the app's style presets. fn styles(app: &PhotocraftApp) -> Vec { app.session.presets.styles.iter().flat_map(|group| group.items.iter().cloned()).collect() diff --git a/crates/ui-egui/src/panels/smart_ui/editor_tests.rs b/crates/ui-egui/src/panels/smart_ui/editor_tests.rs index 154bc60520..4c2821be11 100644 --- a/crates/ui-egui/src/panels/smart_ui/editor_tests.rs +++ b/crates/ui-egui/src/panels/smart_ui/editor_tests.rs @@ -305,92 +305,106 @@ fn assert_tone_preview_is_non_neutral(app: &mut PhotocraftApp, ctx: &egui::Conte crate::canvas::ensure_filter_preview(app, idx, ctx).unwrap(); } +/// Each-choice set: every mode x kind and every view appears. View 2 (`Color(1)`) runs with all six +/// mode x kind pairs because its forbidden channel name (Green, Magenta, a) depends on the mode; the +/// other views run once, spread over modes and kinds, since `target_context` returns early for any +/// Smart Filter, so every view reaches the same guard. +const TONE_FILTER_CASES: [(&str, &str, usize); 11] = [ + ("rgb", "levels", 2), + ("rgb", "curves", 2), + ("lab", "levels", 2), + ("lab", "curves", 2), + ("cmyk", "levels", 2), + ("cmyk", "curves", 2), + ("rgb", "curves", 0), + ("lab", "levels", 1), + ("cmyk", "curves", 3), + ("rgb", "levels", 4), + ("lab", "curves", 5), +]; + +/// One case: `view` 0..5 is the alpha channel, layer mask target, colour component `Color(1)`, smart-object mask UI target, Quick Mask, filter mask UI target. +fn tone_filter_case(mode: &str, kind: &str, view: usize) { + use photocraft_engine::{adjust_params, channel_cmds::ChannelTarget}; + let (mut app, layer) = app(8, mode); + let command = format!("image.adjustments.{kind}"); + let color_mode = app.session.active().unwrap().doc.mode; + let mut recorded = adjust_params::to_params(&adjust_params::default_for(kind, color_mode).unwrap()); + let key = if mode == "lab" { + "lightness" + } else if kind == "curves" { + "points" + } else { + "" + }; + if kind == "levels" { + if key.is_empty() { + recorded["gamma"] = json!(1.4); + } else { + recorded[key]["gamma"] = json!(1.4); + } + } else { + recorded[key] = json!([[0, 0], [128, 180], [255, 255]]); + } + app.run(&command, recorded.clone()).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.run("channel.new", json!({"name":"Saved sky", "fill":"white"})).unwrap(); + if view == 4 { + app.run("select.editInQuickMaskMode", json!({})).unwrap(); + } + app.session.active_mut().unwrap().channel_view.target = match view { + 0 => ChannelTarget::Alpha(0), + 1 => ChannelTarget::LayerMask, + 2 => ChannelTarget::Color(1), + _ => ChannelTarget::Composite, + }; + app.ui.mask_target = view == 3; + app.ui.filter_mask_target = (view == 5).then_some(layer.0); + let before = app.session.active().unwrap().doc.clone(); + let filters = smart(&app, layer).clone(); + let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(vec2(1200.0, 900.0)).build_app(|ui, app| crate::dialogs::run(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + let ctx = h.ctx.clone(); + super::open_editor(h.state_mut(), &ctx, layer.0, &filters, 2); + h.run_steps(2); + let values = fields(h.state()); + assert_eq!(values.get("target"), None, "{mode} {kind} view={view}: no channel target is added to a Smart Filter"); + let read = |p: &serde_json::Value| adjust_params::from_params(kind, p, None, color_mode).unwrap(); + assert_eq!(read(&values), read(&recorded), "{mode} {kind} view={view}: recorded colour settings survive reopening"); + h.run_steps(3); + let names: Vec<_> = h.query_all_by_role(egui::accesskit::Role::ComboBox).filter_map(|n| n.value()).collect(); + let expected = match mode { + "lab" => "Lightness", + "cmyk" => "CMYK", + _ => "RGB", + }; + assert!(names.iter().any(|n| n == expected), "{mode} {kind} view={view}: {names:?}"); + assert!( + !names.iter().any(|n| n == "Saved sky" || n == "Quick Mask" || n == "Smart Object Mask" || n == "Green" || n == "Magenta" || n == "a"), + "{names:?}" + ); + let ctx = h.ctx.clone(); + let idx = h.state().session.active_index().unwrap(); + assert!(crate::canvas::ensure_filter_preview(h.state_mut(), idx, &ctx).is_some()); + assert_tone_preview_is_non_neutral(h.state_mut(), &ctx, kind); + assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &before), "preview never writes to the selected plane"); + let shown = photocraft_compose::flatten(h.state().filter_preview.as_ref().unwrap().result.as_ref().unwrap()).px.clone(); + confirm(h.state_mut()); + assert_eq!(shown, photocraft_compose::flatten(&h.state().session.active().unwrap().doc).px, "{mode} {kind} view={view}: preview matches commit"); + assert_eq!(smart(h.state(), layer).smart_filters.len(), 3); + assert_eq!(read(&smart(h.state(), layer).smart_filters[2].params), read(&recorded)); + let after = &h.state().session.active().unwrap().doc; + assert_eq!(after.channels, before.channels); + assert_eq!(after.quick_mask, before.quick_mask); + assert_eq!(after.layer(layer).unwrap().mask, before.layer(layer).unwrap().mask); +} + /// Re-editing a whole-image tone Smart Filter keeps its colour controls and stored records, /// even when a colour component, alpha, Quick Mask or either layer-mask UI target is selected. #[test] fn tone_filter_editor_ignores_current_channel_target() { - use photocraft_engine::{adjust_params, channel_cmds::ChannelTarget}; - for mode in ["rgb", "lab", "cmyk"] { - for kind in ["levels", "curves"] { - for view in 0..6 { - let (mut app, layer) = app(8, mode); - let command = format!("image.adjustments.{kind}"); - let color_mode = app.session.active().unwrap().doc.mode; - let mut recorded = adjust_params::to_params(&adjust_params::default_for(kind, color_mode).unwrap()); - let key = if mode == "lab" { - "lightness" - } else if kind == "curves" { - "points" - } else { - "" - }; - if kind == "levels" { - if key.is_empty() { - recorded["gamma"] = json!(1.4); - } else { - recorded[key]["gamma"] = json!(1.4); - } - } else { - recorded[key] = json!([[0, 0], [128, 180], [255, 255]]); - } - app.run(&command, recorded.clone()).unwrap(); - app.run("layer.layerMask.revealAll", json!({})).unwrap(); - app.run("channel.new", json!({"name":"Saved sky", "fill":"white"})).unwrap(); - if view == 4 { - app.run("select.editInQuickMaskMode", json!({})).unwrap(); - } - app.session.active_mut().unwrap().channel_view.target = match view { - 0 => ChannelTarget::Alpha(0), - 1 => ChannelTarget::LayerMask, - 2 => ChannelTarget::Color(1), - _ => ChannelTarget::Composite, - }; - app.ui.mask_target = view == 3; - app.ui.filter_mask_target = (view == 5).then_some(layer.0); - let before = app.session.active().unwrap().doc.clone(); - let filters = smart(&app, layer).clone(); - let mut h = - Harness::builder().with_context(app.ctx().clone()).with_size(vec2(1200.0, 900.0)).build_app(|ui, app| crate::dialogs::run(app, ui), app); - PhotocraftApp::setup_context(&h.ctx, Default::default()); - let ctx = h.ctx.clone(); - super::open_editor(h.state_mut(), &ctx, layer.0, &filters, 2); - h.run_steps(2); - let values = fields(h.state()); - assert_eq!(values.get("target"), None, "{mode} {kind} view={view}: no channel target is added to a Smart Filter"); - let read = |p: &serde_json::Value| adjust_params::from_params(kind, p, None, color_mode).unwrap(); - assert_eq!(read(&values), read(&recorded), "{mode} {kind} view={view}: recorded colour settings survive reopening"); - h.run_steps(3); - let names: Vec<_> = h.query_all_by_role(egui::accesskit::Role::ComboBox).filter_map(|n| n.value()).collect(); - let expected = match mode { - "lab" => "Lightness", - "cmyk" => "CMYK", - _ => "RGB", - }; - assert!(names.iter().any(|n| n == expected), "{mode} {kind} view={view}: {names:?}"); - assert!( - !names.iter().any(|n| n == "Saved sky" || n == "Quick Mask" || n == "Smart Object Mask" || n == "Green" || n == "Magenta" || n == "a"), - "{names:?}" - ); - let ctx = h.ctx.clone(); - let idx = h.state().session.active_index().unwrap(); - assert!(crate::canvas::ensure_filter_preview(h.state_mut(), idx, &ctx).is_some()); - assert_tone_preview_is_non_neutral(h.state_mut(), &ctx, kind); - assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &before), "preview never writes to the selected plane"); - let shown = photocraft_compose::flatten(h.state().filter_preview.as_ref().unwrap().result.as_ref().unwrap()).px.clone(); - confirm(h.state_mut()); - assert_eq!( - shown, - photocraft_compose::flatten(&h.state().session.active().unwrap().doc).px, - "{mode} {kind} view={view}: preview matches commit" - ); - assert_eq!(smart(h.state(), layer).smart_filters.len(), 3); - assert_eq!(read(&smart(h.state(), layer).smart_filters[2].params), read(&recorded)); - let after = &h.state().session.active().unwrap().doc; - assert_eq!(after.channels, before.channels); - assert_eq!(after.quick_mask, before.quick_mask); - assert_eq!(after.layer(layer).unwrap().mask, before.layer(layer).unwrap().mask); - } - } + for (mode, kind, view) in TONE_FILTER_CASES { + tone_filter_case(mode, kind, view); } } diff --git a/crates/ui-egui/src/panels/tool_commands.rs b/crates/ui-egui/src/panels/tool_commands.rs index c974a05be8..47e4a7085a 100644 --- a/crates/ui-egui/src/panels/tool_commands.rs +++ b/crates/ui-egui/src/panels/tool_commands.rs @@ -114,6 +114,8 @@ pub(crate) enum ToolCommand { Sharpen, #[command(label = "Smudge Tool", icon = "pointer", kind = "tool", group = "tools", alias = "tools.select.smudge")] Smudge, + #[command(label = "Adjustment Brush Tool", icon = "adjustment_layer", kind = "tool", group = "tools", alias = "tools.select.adjustmentBrush")] + AdjustmentBrush, #[command(label = "Dodge Tool", icon = "lollipop", kind = "tool", group = "O", default = "O", alias = "tools.select.dodge")] Dodge, #[command(label = "Burn Tool", icon = "flame", kind = "tool", group = "O", default = "O", alias = "tools.select.burn")] @@ -218,6 +220,7 @@ pub(crate) fn command_of(tool: Tool) -> ToolCommand { Tool::Blur => ToolCommand::Blur, Tool::Sharpen => ToolCommand::Sharpen, Tool::Smudge => ToolCommand::Smudge, + Tool::AdjustmentBrush => ToolCommand::AdjustmentBrush, Tool::Dodge => ToolCommand::Dodge, Tool::Burn => ToolCommand::Burn, Tool::Sponge => ToolCommand::Sponge, @@ -293,6 +296,7 @@ pub(crate) fn tool_of(command: ToolCommand) -> Tool { ToolCommand::Blur => Tool::Blur, ToolCommand::Sharpen => Tool::Sharpen, ToolCommand::Smudge => Tool::Smudge, + ToolCommand::AdjustmentBrush => Tool::AdjustmentBrush, ToolCommand::Dodge => Tool::Dodge, ToolCommand::Burn => Tool::Burn, ToolCommand::Sponge => Tool::Sponge, diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs index b158652132..540966496a 100644 --- a/crates/ui-egui/src/panels/toolbar.rs +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -48,6 +48,7 @@ pub(crate) const TOOL_SECTIONS: &[&[&[Tool]]] = &[ &[Tool::Eraser, Tool::BackgroundEraser, Tool::MagicEraser], &[Tool::Gradient, Tool::PaintBucket], &[Tool::Blur, Tool::Sharpen, Tool::Smudge], + &[Tool::AdjustmentBrush], &[Tool::Dodge, Tool::Burn, Tool::Sponge], ], &[ diff --git a/crates/ui-egui/src/pencil_tests.rs b/crates/ui-egui/src/pencil_tests.rs index 2fbc2c9dba..e7a4d6551a 100644 --- a/crates/ui-egui/src/pencil_tests.rs +++ b/crates/ui-egui/src/pencil_tests.rs @@ -416,6 +416,10 @@ fn history_stroke_pixels(mode: &str, pressed: &serde_json::Value, switched: Opti tool_event(&mut app, ToolEvent::Up { x: pts[4].0, y: pts[4].1 }, Modifiers::NONE); let (id, p) = last(&app); assert_eq!(id, "paint.historyBrush", "{mode}: {p}"); + // The mode's own flags: the pixel comparisons can't see one go, as both strokes would lose it. + for flag in ["pencil", "block"] { + assert_eq!(p.get(flag) == Some(&json!(true)), mode == flag, "{mode}: {flag} in {p}"); + } let st = app.session.active().unwrap(); layer(&app).surface().unwrap().read_region(st.doc.bounds()) } @@ -434,15 +438,15 @@ fn a_tool_key_mid_stroke_paints_what_the_stroke_paints_without_it() { ("no dynamics, then size jitter", round.clone(), json!({"shapeDynamics": {"enabled": true, "size": {"jitter": 1.0}}})), ("no smoothing, then 90 %", round.clone(), json!({"smoothing": {"enabled": true, "amount": 0.9}})), ]; - for mode in ["", "brush", "pencil", "block"] { - for (what, pressed, switched) in &cases { - let plain = history_stroke_pixels(mode, pressed, None); - assert!(history_stroke_pixels(mode, pressed, Some(switched)) == plain, "{mode} {what}: the switch changed the stroke"); - // The switched-to brush paints differently, so the comparison means something; Block - // mode keeps only the brush's smoothing. - if mode != "block" || what.contains("smoothing") { - assert!(history_stroke_pixels(mode, switched, None) != plain, "{mode} {what}: both brushes paint alike"); - } - } + // Each choice, not every mode with every case (#16041): the brush is captured once, at the + // press, whatever the mode, so History Brush takes every case and each Erase to History mode + // one, for its own flags: Brush and Pencil with the sampled tip, Block with smoothing (the only + // brush setting Block keeps). + let runs = cases.iter().map(|c| ("", c)).chain([("brush", &cases[2]), ("pencil", &cases[2]), ("block", &cases[4])]); + for (mode, (what, pressed, switched)) in runs { + let plain = history_stroke_pixels(mode, pressed, None); + assert!(history_stroke_pixels(mode, pressed, Some(switched)) == plain, "{mode} {what}: the switch changed the stroke"); + // The switched-to brush paints differently, so the comparison means something. + assert!(history_stroke_pixels(mode, switched, None) != plain, "{mode} {what}: both brushes paint alike"); } } diff --git a/crates/ui-egui/src/prefs/prefs_ui/tests.rs b/crates/ui-egui/src/prefs/prefs_ui/tests.rs index 15ced4a207..c5d53e245b 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/tests.rs @@ -723,8 +723,34 @@ fn run_cases(cases: Vec) { } /// A case that only seeds a file and checks what the app loads from it. -fn loaded(name: &'static str, seed: Value, check: impl Fn(&PhotocraftApp) + 'static) -> Case { - Case { name, seed: Some(seed), set: Box::new(|_, _| {}), check: Box::new(move |app, _, _| check(app)) } +struct Loaded { + name: &'static str, + seed: Value, + check: Box, +} + +fn loaded(name: &'static str, seed: Value, check: impl Fn(&PhotocraftApp) + 'static) -> Loaded { + Loaded { name, seed, check: Box::new(check) } +} + +/// One app per case: what it loads, then what its first tick leaves in the file. A load that reset values writes the +/// repaired preferences on that tick, so the file must read back cleanly as what the app holds; a repair that drops +/// other keys fails here without a restarted app. +fn run_loaded(cases: Vec) { + for case in cases { + eprintln!("case: {}", case.name); + let files = Arc::new(MemoryFiles::new()); + seed(&files, &case.seed, Some(::SCHEMA_VERSION)); + let mut app = app_on(&files); + (case.check)(&app); + let ctx = app.ctx().clone(); + tick(&mut app, &ctx); + let (reread, report) = services_on(&files).settings.unwrap(); + assert!(report.section_errors.is_empty(), "{}: {:?}", case.name, report.section_errors); + // Compared as written: the file has no nulls, while the preset libraries hold some in memory. + let written = |p: &prefs::SavedPrefs| serde_json::to_value(p).unwrap(); + assert_eq!(written(reread.get()), written(&app.session.saved_prefs()), "{}", case.name); + } } fn restart_cases() -> Vec { @@ -982,7 +1008,8 @@ fn remembered_state_survives_a_restart() { run_cases(restart_cases()); } -fn damaged_cases() -> Vec { +/// The load-only cases, and the cases that set state in a first app and restart. +fn damaged_cases() -> (Vec, Vec) { use crate::state::Tool; let d = crate::state::ToolOptions::default; let mut cases = Vec::new(); @@ -1080,8 +1107,9 @@ fn damaged_cases() -> Vec { assert_eq!(app.session.tools.background, [1.0; 4]); })); // A tool-colour preset with an invalid channel is refused and leaves the remembered colours alone. + let mut restarts = Vec::new(); for bad_channel in [json!(1e100), json!("red"), json!(true), json!({}), json!([])] { - cases.push(Case { + restarts.push(Case { name: "tool colours after an invalid preset", seed: None, set: Box::new(move |app, _| { @@ -1099,12 +1127,14 @@ fn damaged_cases() -> Vec { }), }); } - cases + (cases, restarts) } #[test] fn a_damaged_remembered_value_resets_only_itself() { - run_cases(damaged_cases()); + let (loaded, restarts) = damaged_cases(); + run_loaded(loaded); + run_cases(restarts); } #[test] diff --git a/crates/ui-egui/src/reset_tip_tests.rs b/crates/ui-egui/src/reset_tip_tests.rs index 44236f1083..9b6e739a74 100644 --- a/crates/ui-egui/src/reset_tip_tests.rs +++ b/crates/ui-egui/src/reset_tip_tests.rs @@ -112,9 +112,13 @@ fn starting(app: &PhotocraftApp, tool: Tool) -> Tip { #[test] fn each_tool_resets_and_first_uses_its_own_tip() { + // One app for the two reset commands of all sixteen tools. Each case picks the tool and scrambles the brush + // before it invokes, and `tool.reset` / `tool.resetAll` work through `fresh_brush` for the tool in front of them, + // so a case never needs an app of its own: starting the app (document, panels, views) was the cost of a case + // here, 80 of them (#15941). + let mut a = app(); for (tool, first_use) in ROWS { // Reset Tool. - let mut a = app(); pick(&mut a, tool); scramble(&mut a); assert_ne!(live(&a), starting(&a, tool), "{tool:?}: the scrambled tip is not its starting tip"); @@ -122,12 +126,10 @@ fn each_tool_resets_and_first_uses_its_own_tip() { assert_eq!(live(&a), starting(&a, tool), "{tool:?}: Reset Tool"); // Reset All Tools with the tool active, then with it picked later. - let mut a = app(); pick(&mut a, tool); scramble(&mut a); invoke(&mut a, "tool.resetAll", json!({"confirmed": true})); assert_eq!(live(&a), starting(&a, tool), "{tool:?}: Reset All Tools, active"); - let mut a = app(); pick(&mut a, tool); scramble(&mut a); pick(&mut a, other(tool)); @@ -136,7 +138,6 @@ fn each_tool_resets_and_first_uses_its_own_tip() { assert_eq!(live(&a), starting(&a, tool), "{tool:?}: Reset All Tools, picked later"); // Other tools keep their brushes through Reset Tool. - let mut a = app(); pick(&mut a, other(tool)); scramble(&mut a); let kept = live(&a); @@ -145,7 +146,8 @@ fn each_tool_resets_and_first_uses_its_own_tip() { let theirs = a.ui.tool_brushes.iter().find(|(t, _)| *t == other(tool)).map(|(_, b)| tip(b)); assert_eq!(theirs, Some(kept), "{tool:?}: {:?} keeps its tip", other(tool)); - // First use, after another tool's tip; its own tip is then kept across tool switches. + // First use, after another tool's tip; its own tip is then kept across tool switches. The tool must not have + // been picked before, so this case keeps an app of its own. let Some(rule) = first_use else { continue }; let mut a = app(); pick(&mut a, other(tool)); diff --git a/crates/ui-egui/src/scratch_read_keys_tests.rs b/crates/ui-egui/src/scratch_read_keys_tests.rs new file mode 100644 index 0000000000..186d3a1033 --- /dev/null +++ b/crates/ui-egui/src/scratch_read_keys_tests.rs @@ -0,0 +1,116 @@ +//! The UI's pictures and derived values of document pixels follow the scratch read-error generation: a tile that +//! fails to read shows zeros and its real pixels again once it reads, without moving its surface's generation or its +//! document's revision (`crate::scratch_reads`). Each test simulates one such transition and checks that the key a +//! cache is held by moves with it, and stays put without it. + +use craft::imaging::trace::MaskSource; +use craft::layers::ui::thumbs::{LayerThumb, ThumbContents}; +use craft::ui::primitives::textures::{ThumbRequest, ThumbSource}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::channels_panel::Row; +use crate::scratch_reads::tests::simulate_read_error_transition; + +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.run("layer.new.layer", json!({"name": "Paint"})).unwrap(); + app.run("paint.stroke", json!({"points": [[4, 4], [40, 30]], "size": 8, "color": "#2060c0"})).unwrap(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.run("channel.new", json!({"name": "Alpha", "fill": "white"})).unwrap(); + app.run("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + app +} + +fn request() -> ThumbRequest { + ThumbRequest::for_cell(32.0, 1.0) +} + +/// Calls `revision` before, again without a change, and after one transition: the key must hold, then move. +fn holds_then_moves(what: &str, mut revision: impl FnMut() -> T) { + let before = revision(); + assert_eq!(revision(), before, "{what}: nothing changed, the same key"); + simulate_read_error_transition(); + assert_ne!(revision(), before, "{what}: a read error or its recovery moves the key"); +} + +#[test] +fn layer_thumbnails_follow_a_scratch_read_error_transition() { + let app = app(); + let st = app.session.active().unwrap(); + let layer = st.active_layer.unwrap(); + let keys = [LayerThumb::pixels(layer, ThumbContents::EntireDocument), LayerThumb::mask(layer)]; + holds_then_moves("layer thumbnails", || { + let thumbs = crate::panels::layers_tree::PhotoThumbs::new(&app, &st.doc); + keys.iter().map(|key| thumbs.revision(key, &request()).get()).collect::>() + }); +} + +#[test] +fn the_rule_facts_follow_a_scratch_read_error_transition() { + let app = app(); + holds_then_moves("rule facts", || crate::menus::facts::key(&app)); +} + +#[test] +fn channel_thumbnails_follow_a_scratch_read_error_transition() { + let app = app(); + let st = app.session.active().unwrap(); + holds_then_moves("channel thumbnails", || { + let thumbs = crate::app::thumbs::ChannelThumbs::new(&app, st); + [Row::Composite, Row::Color(0), Row::Alpha(0), Row::LayerMask].iter().map(|row| thumbs.revision(row, &request()).get()).collect::>() + }); +} + +#[test] +fn snapshot_thumbnails_follow_a_scratch_read_error_transition() { + let app = app(); + let st = app.session.active().unwrap(); + let snapshot = st.snapshots().first().map(|s| s.id).expect("a new document has its first snapshot"); + holds_then_moves("snapshot thumbnails", || crate::app::thumbs::SnapshotThumbs::new(&app, st.doc.id).revision(&snapshot, &request()).get()); +} + +/// A selection whose tile read as zeros scans as empty: once it reads again, the cached bounds are scanned anew. +#[test] +fn cached_bounds_are_scanned_again_after_a_scratch_read_error_transition() { + let mut app = app(); + let (doc, selection) = { + let st = app.session.active().unwrap(); + (st.doc.id, st.doc.selection.clone().unwrap()) + }; + let key = u64::MAX - doc.0; + let bounds = app.cached_bounds(key, &selection); + assert!(!bounds.is_empty()); + // The box a scan during the read error would have cached. + let fingerprint = crate::app::thumbs::bounds_revision(&selection); + app.bounds_cache.insert(key, (fingerprint, photocraft_geom::Rect::EMPTY)); + assert!(app.known_bounds(key, &selection).is_empty(), "without a transition the cached box is believed"); + simulate_read_error_transition(); + assert_eq!(app.known_bounds(key, &selection), bounds, "after it, the bounds are scanned again"); + assert_eq!(app.cached_bounds(key, &selection), bounds); +} + +#[test] +fn the_selection_outline_follows_a_scratch_read_error_transition() { + let app = app(); + let st = app.session.active().unwrap(); + let selection = st.doc.selection.as_ref().unwrap(); + let size = [st.doc.size.width, st.doc.size.height]; + holds_then_moves("selection outline", || crate::canvas::outline::SurfaceMask::new(selection, selection.generation(), size).revision()); +} + +#[test] +fn the_navigator_picture_draws_again_after_a_scratch_read_error_transition() { + let mut app = app(); + let ctx = app.ctx().clone(); + let doc = app.session.active().unwrap().doc.id; + crate::canvas::navigator_texture(&mut app, &ctx, 0).unwrap(); + let held = |app: &PhotocraftApp| app.navigator_textures.get(&doc).map(|(_, key, _, texture)| (*key, texture.id())).unwrap(); + let before = held(&app); + crate::canvas::navigator_texture(&mut app, &ctx, 0).unwrap(); + assert_eq!(held(&app), before, "nothing changed: the same picture"); + simulate_read_error_transition(); + crate::canvas::navigator_texture(&mut app, &ctx, 0).unwrap(); + assert_ne!(held(&app).0, before.0, "the picture is drawn again for the new generation"); +} diff --git a/crates/ui-egui/src/scratch_reads.rs b/crates/ui-egui/src/scratch_reads.rs new file mode 100644 index 0000000000..014eb823f3 --- /dev/null +++ b/crates/ui-egui/src/scratch_reads.rs @@ -0,0 +1,48 @@ +//! The scratch read-error generation as the UI's caches key on it. +//! +//! A tile whose scratch bytes fail to read shows a zero placeholder through `&self`, and its real pixels again once +//! a reload succeeds, without moving its surface's generation or its document's revision (the `PlainData` comment on +//! `photocraft_raster::Tile`). Both transitions move `spill::read_error_generation`, so every picture or derived +//! value the UI keeps of document or preset pixels keys on [`generation`] too; otherwise a thumbnail drawn during a +//! read error keeps its zeros after the tile recovers. + +/// The scratch read-error generation now: it moves when a tile fails to read and when it reads again. +pub(crate) fn generation() -> u64 { + let real = photocraft_raster::spill::read_error_generation(); + #[cfg(test)] + let real = real.wrapping_add(tests::BUMPS.with(std::cell::Cell::get)); + real +} + +/// [`generation`] folded with `revision`: one number for a cache keyed by a single `u64` that must follow both. +pub(crate) fn with(revision: u64) -> u64 { + use std::hash::{Hash, Hasher}; + let mut hasher = std::hash::DefaultHasher::new(); + (revision, generation()).hash(&mut hasher); + hasher.finish() +} + +#[cfg(test)] +pub(crate) mod tests { + use std::cell::Cell; + + thread_local! { + /// Read-error transitions simulated on this test's thread, so a test sees one without setting up the + /// process-wide scratch file, and tests on other threads never do. + pub(super) static BUMPS: Cell = const { Cell::new(0) }; + } + + /// Simulates one read-error transition (a tile failing, or one recovering) as the caches see it. + pub(crate) fn simulate_read_error_transition() { + BUMPS.with(|bumps| bumps.set(bumps.get().wrapping_add(1))); + } + + #[test] + fn a_simulated_transition_moves_the_generation_and_the_folded_key() { + let (generation, folded) = (super::generation(), super::with(7)); + assert_eq!(super::with(7), folded, "the same state folds to the same key"); + simulate_read_error_transition(); + assert_ne!(super::generation(), generation); + assert_ne!(super::with(7), folded); + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index e494e05cfe..733a453346 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -625,7 +625,7 @@ mod tests { assert!(!Tool::RedEye.is_brushlike()); assert_eq!(Tool::from_name("patternStamp"), Some(Tool::PatternStamp)); assert_eq!(Tool::from_name("Pattern Stamp Tool"), Some(Tool::PatternStamp)); - assert_eq!(Tool::ALL.len(), 69); + assert_eq!(Tool::ALL.len(), 70); } fn vector_tool_names_parse() { diff --git a/crates/ui-egui/src/state/tool.rs b/crates/ui-egui/src/state/tool.rs index 4fee37d9ae..63c8543cc9 100644 --- a/crates/ui-egui/src/state/tool.rs +++ b/crates/ui-egui/src/state/tool.rs @@ -52,6 +52,8 @@ pub enum Tool { Blur, Sharpen, Smudge, + /// Paints an adjustment layer's mask, making the layer on the first stroke (#12519). + AdjustmentBrush, Dodge, Burn, Sponge, @@ -130,6 +132,7 @@ impl Tool { Self::Blur => "blur", Self::Sharpen => "sharpen", Self::Smudge => "smudge", + Self::AdjustmentBrush => "adjustmentBrush", Self::Dodge => "dodge", Self::Burn => "burn", Self::Sponge => "sponge", @@ -164,7 +167,7 @@ impl Tool { .copied() } - pub const ALL: [Tool; 69] = [ + pub const ALL: [Tool; 70] = [ Tool::Move, Tool::Artboard, Tool::RectMarquee, @@ -211,6 +214,7 @@ impl Tool { Tool::Blur, Tool::Sharpen, Tool::Smudge, + Tool::AdjustmentBrush, Tool::Dodge, Tool::Burn, Tool::Sponge, @@ -287,6 +291,7 @@ impl Tool { Tool::Blur => "Blur Tool", Tool::Sharpen => "Sharpen Tool", Tool::Smudge => "Smudge Tool", + Tool::AdjustmentBrush => "Adjustment Brush Tool", Tool::Dodge => "Dodge Tool", Tool::Burn => "Burn Tool", Tool::Sponge => "Sponge Tool", @@ -341,6 +346,7 @@ impl Tool { | Tool::Blur | Tool::Sharpen | Tool::Smudge + | Tool::AdjustmentBrush | Tool::Dodge | Tool::Burn | Tool::Sponge @@ -367,6 +373,8 @@ impl Tool { Tool::CloneStamp | Tool::PatternStamp => 'S', Tool::HistoryBrush | Tool::ArtHistoryBrush => 'Y', Tool::Blur | Tool::Sharpen | Tool::Smudge => '\0', + // Its own slot without a letter: no Shift+letter cycle reaches it. + Tool::AdjustmentBrush => '\0', // In the Marquee flyout, but M cycles only the Rectangular and Elliptical Marquee. Tool::SingleRowMarquee | Tool::SingleColumnMarquee => '\0', Tool::Dodge | Tool::Burn | Tool::Sponge => 'O', diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index d3a211e64a..f218c16b23 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -39,6 +39,16 @@ pub struct ToolOptions { /// Remove tool: each stroke is filled when released (Photoshop's default). Off, the strokes /// collect as a tint on the canvas and ↩ applies them together (Esc drops them). pub remove_after_each_stroke: bool, + /// Adjustment Brush: the Adjustment dropdown's entry (`photocraft_engine::adjustment_brush_cmds::ENTRIES`). + pub adjustment_brush_kind: String, + /// Adjustment Brush: Subtract (paints black into the mask) instead of Add. + pub adjustment_brush_subtract: bool, + /// Adjustment Brush: the Overlay checkbox (its tint over the mask is #12520). + pub adjustment_brush_overlay: bool, + /// Adjustment Brush: the active layer the dropdown last followed, so selecting another + /// adjustment layer sets it once and a pick in the dropdown sticks. + #[serde(skip)] + pub adjustment_brush_followed: Option, pub feather: f32, /// linear | radial | angle | reflected | diamond pub gradient_style: String, @@ -431,6 +441,10 @@ impl Default for ToolOptions { object_hard_edge: true, remove_new_layer: false, remove_after_each_stroke: true, + adjustment_brush_kind: photocraft_engine::adjustment_brush_cmds::DEFAULT_KIND.into(), + adjustment_brush_subtract: false, + adjustment_brush_overlay: false, + adjustment_brush_followed: None, feather: 0.0, gradient_style: "linear".into(), gradient_reverse: false, diff --git a/crates/ui-egui/src/tool_shift_cycle_order_tests.rs b/crates/ui-egui/src/tool_shift_cycle_order_tests.rs index 67760664bc..2435d1ce02 100644 --- a/crates/ui-egui/src/tool_shift_cycle_order_tests.rs +++ b/crates/ui-egui/src/tool_shift_cycle_order_tests.rs @@ -1,6 +1,8 @@ //! Shift+letter steps through a key's tool group in the toolbar flyout's order, wrapping, and the //! anchor point tools have no letter so P never reaches them. +use craft::keymap::Chord; +use craft::ui::runtime::commands::{FirePhase, FireSource, Fired}; use egui::{Key, Modifiers}; use egui_kittest::Harness; use serde_json::json; @@ -63,40 +65,110 @@ fn quick_shift_press(h: &mut Harness<'static, Box>, key: Key) { h.run_steps(2); } +/// The app with the same document as [`app`], but with no harness and no frames: the per-tool assertions below +/// call [`crate::shortcut_dispatch::run_fired`], which is the entry a fired Shift+letter reaches once the runtime +/// has taken the key. One whole-app frame costs more than the pick itself (#15651), and 64 tool members x two frames +/// per press made these three tests the slowest of their file. The keyboard's way to this entry stays pressed for +/// one tool per kind of group in [`a_real_shift_letter_takes_the_next_tool_of_its_group`], and the chord itself is +/// pinned for every group letter by [`every_group_letter_shift_chord_reaches_its_group_step`] below. These sweeps +/// hand the command to [`crate::shortcut_dispatch::run_fired`] directly, and no menu shows a `tools.nextInGroup` +/// row, so `input::shortcut_dispatch::tests::every_displayed_shortcut_runs_its_menu_item` never takes their branch. +fn bare_app() -> (Box, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 20, "height": 10})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + let ctx = app.ctx().clone(); + (app, ctx) +} + +/// Fire `tools.nextInGroup.`, the command Shift+letter is bound to, as a key press fires it. +fn fire_next_in_group(app: &mut PhotocraftApp, ctx: &egui::Context, letter: char) { + let id = crate::shortcut_dispatch::next_in_group_id(letter); + let command = crate::shortcut_dispatch::keymap_command(&id); + crate::shortcut_dispatch::run_fired(app, ctx, &[Fired::new(command, FireSource::Key, FirePhase::Press, 0.0)]); + app.sync_views(); +} + #[test] fn from_every_tool_shift_letter_lands_on_the_next_tool_in_toolbar_order() { - let mut h = app(); + let (mut app, ctx) = bare_app(); for (letter, group) in groups() { for (i, from) in group.iter().enumerate() { - h.state_mut().ui.tool = *from; - quick_shift_press(&mut h, key_for(letter)); + app.ui.tool = *from; + fire_next_in_group(&mut app, &ctx, letter); let want = group[(i + 1) % group.len()]; - assert_eq!(h.state().ui.tool, want, "Shift+{letter} from {from:?}"); + assert_eq!(app.ui.tool, want, "Shift+{letter} from {from:?}"); } } } #[test] fn shift_letter_wraps_from_the_last_tool_to_the_first() { - let mut h = app(); + let (mut app, ctx) = bare_app(); for (letter, group) in groups() { - h.state_mut().ui.tool = *group.last().unwrap(); - shift_press(&mut h, key_for(letter)); - assert_eq!(h.state().ui.tool, group[0], "Shift+{letter} wraps"); + app.ui.tool = *group.last().unwrap(); + fire_next_in_group(&mut app, &ctx, letter); + assert_eq!(app.ui.tool, group[0], "Shift+{letter} wraps"); } } #[test] fn the_first_shift_letter_from_another_tool_lands_on_the_groups_first_tool() { - let mut h = app(); + let (mut app, ctx) = bare_app(); for (letter, group) in groups() { if group.contains(&Tool::Hand) { continue; } - h.state_mut().ui.tool = Tool::Hand; - h.state_mut().ui.group_tools.clear(); - shift_press(&mut h, key_for(letter)); - assert_eq!(h.state().ui.tool, group[0], "Shift+{letter} from the Hand tool"); + app.ui.tool = Tool::Hand; + app.ui.group_tools.clear(); + fire_next_in_group(&mut app, &ctx, letter); + assert_eq!(app.ui.tool, group[0], "Shift+{letter} from the Hand tool"); + } +} + +/// The keyboard route itself, once per kind of group: a shared group's middle tool, the wrap from its last tool, +/// the Pen group (whose flyout holds three anchor tools the letter never reaches), a group entered from a tool +/// outside it, and a single-tool group. Every other member of every group goes through the same `pick_tool` line +/// and is asserted tool by tool in the three tests above. +#[test] +fn a_real_shift_letter_takes_the_next_tool_of_its_group() { + let mut h = app(); + h.state_mut().ui.tool = Tool::PolygonLasso; + quick_shift_press(&mut h, Key::L); + assert_eq!(h.state().ui.tool, Tool::MagneticLasso, "Shift+L from the Polygonal Lasso"); + h.state_mut().ui.tool = Tool::CustomShape; + quick_shift_press(&mut h, Key::U); + assert_eq!(h.state().ui.tool, Tool::Rectangle, "Shift+U wraps to the group's first tool"); + // The Pen group steps its three pens only: the anchor tools are in its flyout but not under its letter. + h.state_mut().ui.tool = Tool::CurvaturePen; + quick_shift_press(&mut h, Key::P); + assert_eq!(h.state().ui.tool, Tool::Pen, "Shift+P wraps the three pens"); + h.state_mut().ui.tool = Tool::Hand; + h.state_mut().ui.group_tools.clear(); + quick_shift_press(&mut h, Key::G); + assert_eq!(h.state().ui.tool, Tool::Gradient, "Shift+G from the Hand picks the group's first tool"); + h.state_mut().ui.tool = Tool::Move; + h.state_mut().ui.group_tools.clear(); + quick_shift_press(&mut h, Key::K); + assert_eq!(h.state().ui.tool, Tool::Frame, "Shift+K picks the only tool of the Frame group"); +} + +/// The chord each group step hangs on: `command_rows` gives every `tools.nextInGroup` row its default +/// `Shift+` binding, and the keymap is what turns the pressed chord into the command the fired sweeps hand to +/// `run_fired` themselves. The sweeps and that entry point pin nothing here, and no menu shows a `tools.nextInGroup` +/// row, so this table - one settled app, one keymap lookup per letter, no frames per letter - is what fails when a +/// row's chord is dropped. The Space group of the Pen flyout's anchor tools (their `key()`, `state::tool`) takes the +/// same loop: its default text is `Shift+ ` with no key name, which `Chord::parse` refuses, so production binds +/// Shift+Space to nothing - pinned too, and this row changes the day a spellable binding for it is added. +#[test] +fn every_group_letter_shift_chord_reaches_its_group_step() { + let h = app(); + for (letter, _) in crate::tool_shortcuts::group_letters() { + let id = crate::shortcut_dispatch::next_in_group_id(letter); + let command = crate::shortcut_dispatch::keymap_command(&id); + let bound = craft::ui::runtime::commands::chord(&h.ctx, &command); + let want = Chord::parse(&format!("Shift+{}", letter.to_ascii_uppercase())).ok(); + assert_eq!(bound, want, "Shift+{letter} reaches {id}"); } } diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index d23b04cd3b..ce933e3f9f 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -1,3 +1,4 @@ +pub mod adjustment_brush; pub(super) mod align_bar; pub mod analysis; pub mod artboard_tool; @@ -82,3 +83,6 @@ mod art_history_reset_tip_tests; #[cfg(test)] mod object_selection_not_found_tests; + +#[cfg(test)] +mod options_bar_field_labels_tests; diff --git a/crates/ui-egui/src/tools/adjustment_brush.rs b/crates/ui-egui/src/tools/adjustment_brush.rs new file mode 100644 index 0000000000..b82f1c9fc0 --- /dev/null +++ b/crates/ui-egui/src/tools/adjustment_brush.rs @@ -0,0 +1,208 @@ +//! The Adjustment Brush Tool (#12519): its options bar and its stroke. Painting runs +//! `paint.adjustmentBrush`, which makes an adjustment layer of the dropdown's kind whose mask is +//! the stroke, or paints into the mask of the active adjustment layer of that kind. The stroke +//! shows as the painting tools' trail while it is drawn and is applied on release. + +use craft::behavior::IconId; +use craft::ui::buttons::{IconButton, ToggleButton}; +use craft::ui::choice::{Checkbox, Segmented}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _}; +use craft::ui::display::Divider; +use craft::ui::pickers::Select; +use photocraft_engine::adjustment_brush_cmds::{self as ab, ENTRIES, INDEXED_ALERT}; +use serde_json::json; + +use super::option_cells; +use crate::PhotocraftApp; +use crate::state::Tool; + +/// The kind a stroke paints: the dropdown's entry, or the first offered one when the document's +/// colour mode or bit depth greys it. +pub fn kind(app: &PhotocraftApp) -> &'static str { + let stored = ab::entry_of(&app.ui.tool_options.adjustment_brush_kind).map_or(ab::DEFAULT_KIND, |e| e.kind); + match app.session.active() { + Some(st) => ab::offered_kind(stored, st.doc.mode, st.doc.depth), + None => stored, + } +} + +/// Selecting an adjustment layer sets the dropdown to its kind, once per selection, so a later +/// pick in the dropdown sticks. +pub fn follow_active_layer(app: &mut PhotocraftApp) { + let active = app.session.active().and_then(|st| st.active_layer).map(|l| l.0); + if app.ui.tool_options.adjustment_brush_followed == active { + return; + } + app.ui.tool_options.adjustment_brush_followed = active; + if let Some(k) = ab::active_kind(&app.session) { + app.ui.tool_options.adjustment_brush_kind = k.into(); + } +} + +/// Subtract (black over white) or Add (white over black): the mode and the colours the stroke +/// paints the mask with. +pub fn set_subtract(app: &mut PhotocraftApp, subtract: bool) { + app.ui.tool_options.adjustment_brush_subtract = subtract; + let (fg, bg) = if subtract { ("#000000", "#ffffff") } else { ("#ffffff", "#000000") }; + if let Err(e) = app.run("tools.setColors", json!({"foreground": fg, "background": bg})) { + app.ui.status = e; + app.ui.status_error = true; + } +} + +/// The reference application's alert for a press in an Indexed Color document, in the UI language. +fn indexed_alert() -> &'static str { + tl!( + "Could not complete your request because the tool does not work with Indexed Color images. Please convert the image to RGB or another supported mode before using." + ) +} + +/// A press in an Indexed Color document: the reference application's alert, and no stroke. +pub fn press_refused(app: &mut PhotocraftApp) -> bool { + let indexed = app.session.active().is_some_and(|st| st.doc.mode == photocraft_doc::ColorMode::Indexed); + if indexed { + let _ = crate::dialogs::alerts::alert(app, indexed_alert()); + } + indexed +} + +/// Applies a finished drag. Returns false for another tool. +pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]], line: bool) -> bool { + if tool != Tool::AdjustmentBrush { + return false; + } + follow_active_layer(app); + let mut p = json!({ + "kind": kind(app), + "subtract": app.ui.tool_options.adjustment_brush_subtract, + "points": points, + "zoom": app.point_zoom(), + }); + crate::canvas::unsmoothed_line(&mut p, line); + match app.run("paint.adjustmentBrush", p) { + Ok(_) => { + // The layer painted is active with its mask targeted, as after a New Adjustment Layer. + app.ui.mask_target = true; + app.ui.vector_mask_target = false; + app.ui.tool_options.adjustment_brush_followed = app.session.active().and_then(|st| st.active_layer).map(|l| l.0); + } + Err(e) if e.contains(INDEXED_ALERT) => { + let _ = crate::dialogs::alerts::alert(app, indexed_alert()); + } + Err(e) => { + app.ui.status = e; + app.ui.status_error = true; + } + } + true +} + +/// The Adjustment dropdown's rows: the entries in their groups, those the document can't take greyed. +fn kind_entries(mode: photocraft_doc::ColorMode, depth: photocraft_doc::SampleType) -> Vec> { + let mut rows = Vec::new(); + for e in ENTRIES.iter() { + rows.push(Entry::new(e.kind, tl!(e.label).to_owned()).enabled(ab::enabled_in(e.kind, mode, depth))); + if e.separator_after { + rows.push(Entry::separator()); + } + } + rows +} + +/// The options bar, left to right as in the reference application: (the tool preset picker) · +/// Adjustment · Subtract / Add · Brush Preset · Pressure for Size · Choose an object · Overlay · +/// Opacity · Pressure for Opacity · Flow · Airbrush. Returns false for another tool. +pub fn options_bar(ui: &mut egui::Ui, app: &mut PhotocraftApp, tool: Tool) -> bool { + if tool != Tool::AdjustmentBrush { + return false; + } + follow_active_layer(app); + let (mode, depth) = app.session.active().map_or((photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8), |st| (st.doc.mode, st.doc.depth)); + let entries = kind_entries(mode, depth); + // Choosing an entry is no history state; a greyed entry can't be picked. + let picked = Select::new(tl!("Adjustment:").to_owned(), Bind::given(kind(app)), &entries).show(ui).events.committed().copied(); + if let Some(k) = picked.filter(|k| ab::enabled_in(k, mode, depth)) { + app.ui.tool_options.adjustment_brush_kind = k.into(); + } + let modes = [ + Entry::new(true, tl!("Subtract from mask areas to remove adjustment from areas of the image").to_owned()).icon(IconId::new("minus")), + Entry::new(false, tl!("Add to mask areas to apply adjustment to more of the image").to_owned()).icon(IconId::new("plus")), + ]; + let subtract = app.ui.tool_options.adjustment_brush_subtract; + if let Some(next) = Segmented::new(tl!("Mask mode").to_owned(), Bind::given(subtract), &modes).show(ui).value().copied() + && next != subtract + { + set_subtract(app, next); + } + Divider::vertical().show(ui); + crate::brush_picker::show_field(ui, app, true); + crate::brush_picker::settings_toggle(ui, app); + + let before = app.session.tools.brush.clone(); + let mut brush = before.clone(); + let mut key = None; + let pressure = + ToggleButton::new(tl!("Always use pressure for size").to_owned(), Bind::given(brush.pressure_size)).icon(IconId::new("target")).icon_only().show(ui); + if let Some(on) = pressure.value().copied() { + brush.pressure_size = on; + key = pressure.events.iter().find_map(|e| crate::history_keys::coalesce("brush", e)); + } + Divider::vertical().show(ui); + // Present but inert: what it does was not measured. + let choose = tl!("Choose an object and have the adjustment applied to it"); + IconButton::new(IconId::new("square-dashed-mouse-pointer")).label(choose).tooltip(choose).enabled(false).show(ui); + // Its tint over the painted mask is its own item (#12520). + Checkbox::new(Bind::bound(&mut app.ui.tool_options.adjustment_brush_overlay)).label(tl!("Overlay").to_owned()).show(ui); + Divider::vertical().show(ui); + + let mut alerts = Vec::new(); + let mut opacity = (brush.opacity * 100.0).round(); + let out = option_cells::number(tl!("Opacity:"), &mut opacity, 1.0..=100.0).whole().unit("%").show(ui); + key = out.events.iter().find_map(|e| crate::history_keys::coalesce("brush", e)).or(key); + brush.opacity = opacity / 100.0; + alerts.extend(out.out_of_range); + let pressure = ToggleButton::new(tl!("Always use pressure for opacity").to_owned(), Bind::given(brush.pressure_opacity)) + .icon(IconId::new("target")) + .icon_only() + .show(ui); + if let Some(on) = pressure.value().copied() { + brush.pressure_opacity = on; + key = pressure.events.iter().find_map(|e| crate::history_keys::coalesce("brush", e)).or(key); + } + let mut flow = brush.flow * 100.0; + let out = option_cells::number(tl!("Flow:"), &mut flow, 1.0..=100.0).unit("%").show(ui); + key = out.events.iter().find_map(|e| crate::history_keys::coalesce("brush", e)).or(key); + brush.flow = flow / 100.0; + alerts.extend(out.out_of_range); + let airbrush = ToggleButton::new(tl!("Enable airbrush-style build-up effects").to_owned(), Bind::given(brush.build_up)) + .icon(IconId::new("sparkles")) + .icon_only() + .show(ui); + if let Some(on) = airbrush.value().copied() { + brush.build_up = on; + key = airbrush.events.iter().find_map(|e| crate::history_keys::coalesce("brush", e)).or(key); + } + // A field shown without an edit keeps the brush's exact value (no rounding by showing the bar). + if out_unchanged(&before, &brush) { + return true; + } + crate::brush_panel::commit_keyed(app, &before, &brush, key); + for alert in &alerts { + option_cells::range_alert(app, ui, alert); + } + true +} + +/// Whether showing the bar left the brush as it was, up to the rounding of the percent fields. +fn out_unchanged(before: &photocraft_engine::BrushSettings, after: &photocraft_engine::BrushSettings) -> bool { + let near = |a: f32, b: f32| (a - b).abs() < 0.005; + near(before.opacity, after.opacity) + && near(before.flow, after.flow) + && before.pressure_size == after.pressure_size + && before.pressure_opacity == after.pressure_opacity + && before.build_up == after.build_up +} + +#[cfg(test)] +#[path = "../adjustment_brush_tool_tests.rs"] +mod adjustment_brush_tool_tests; diff --git a/crates/ui-egui/src/tools/analysis/bars.rs b/crates/ui-egui/src/tools/analysis/bars.rs index baca8837ae..15d34f36e8 100644 --- a/crates/ui-egui/src/tools/analysis/bars.rs +++ b/crates/ui-egui/src/tools/analysis/bars.rs @@ -7,8 +7,9 @@ use craft::draw::ui::measure::{RulerBar, RulerLine}; use craft::theme::Srgba; use craft::ui::buttons::{Button, IconButton, ToggleButton}; use craft::ui::choice::Swatch; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; use craft::ui::display::{Divider, Text}; +use craft::ui::form::Field; use craft::ui::pickers::Select; use craft::ui::runtime::env::Label; use craft::ui::text::TextField; @@ -180,9 +181,11 @@ fn count(app: &mut PhotocraftApp, ui: &mut egui::Ui, doc: &photocraft_doc::Docum } fn note(app: &mut PhotocraftApp, ui: &mut egui::Ui, doc: &photocraft_doc::Document) { - TextField::new(Label::from(tl!("Author")), Bind::bound(&mut app.ui.analysis.note_author)).show(ui); + // In `Field`s: a bare control's label only names it, it is not drawn (#16338). + Field::new(Label::from(tl!("Author"))).show(ui, |ui, _| TextField::new(Label::from(tl!("Author")), Bind::bound(&mut app.ui.analysis.note_author)).show(ui)); let rgb = app.ui.analysis.note_color; - if Swatch::new(Label::from(tl!("Color")), Srgba::from_rgb_array(rgb)).show(ui).clicked + let swatch = Field::new(Label::from(tl!("Color"))).show(ui, |ui, _| Swatch::new(Label::from(tl!("Color")), Srgba::from_rgb_array(rgb)).show(ui).clicked); + if swatch.inner == Some(true) && let Err(message) = crate::color_picker_ui::open_for_target(app, "noteColor", &crate::color_picker_ui::title_for(tl!("Color")), rgb) { crate::notices::error(app, message); diff --git a/crates/ui-egui/src/tools/analysis/data_points_labels_tests.rs b/crates/ui-egui/src/tools/analysis/data_points_labels_tests.rs new file mode 100644 index 0000000000..236a071a3a --- /dev/null +++ b/crates/ui-egui/src/tools/analysis/data_points_labels_tests.rs @@ -0,0 +1,97 @@ +//! #16345: Image › Analysis › Select Data Points draws every check box with its data point's name, and each column's +//! title above its boxes. + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_engine::analysis_cmds; +use serde_json::json; + +use super::sources; +use crate::PhotocraftApp; + +type H = Harness<'static, Box>; + +fn open_dialog() -> H { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 64})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_max_steps(64).with_context(app.ctx().clone()).build_ui_state( + |ui, app: &mut Box| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::dialogs::run(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "image.analysis.selectDataPoints", json!({})).unwrap(); + h.run_steps(6); + h +} + +/// The shown name of data point `column`, as the engine lists it. +fn name(column: &str) -> &str { + analysis_cmds::COLUMNS.iter().find(|c| c.0 == column).map_or(column, |c| c.1) +} + +/// A check box of the dialog: where it is, its name, and where the text that names it is drawn. +struct Shown { + rect: egui::Rect, + name: String, + text: Option, +} + +fn rect(r: egui::accesskit::Rect) -> egui::Rect { + egui::Rect::from_min_max(egui::pos2(r.x0 as f32, r.y0 as f32), egui::pos2(r.x1 as f32, r.y1 as f32)) +} + +#[test] +fn every_check_box_draws_its_data_point_name_and_each_column_its_title_above() { + let h = open_dialog(); + let mut boxes: Vec = h + .query_all_by_role(Role::CheckBox) + .map(|b| { + let node = b.accesskit_node(); + let name = node.label().unwrap_or_default(); + let text = + node.labelled_by().find(|l| l.role() == Role::Label && l.value().as_deref() == Some(name.as_str())).and_then(|l| l.bounding_box()).map(rect); + Shown { rect: b.rect(), name, text } + }) + .collect(); + // In columns by their left edge, each column top to bottom. + boxes.sort_by(|a, b| a.rect.left().total_cmp(&b.rect.left()).then(a.rect.top().total_cmp(&b.rect.top()))); + let mut columns: Vec> = Vec::new(); + for shown in boxes { + match columns.last_mut() { + Some(column) if (column[0].rect.left() - shown.rect.left()).abs() < 0.5 => column.push(shown), + _ => columns.push(vec![shown]), + } + } + let names: Vec> = columns.iter().map(|c| c.iter().map(|s| s.name.as_str()).collect()).collect(); + assert_eq!(columns.len(), sources().len(), "one column of boxes per source: {names:?}"); + for (((source, title), column), shown) in sources().into_iter().zip(&columns).zip(&names) { + let want: Vec<&str> = analysis_cmds::available(source).into_iter().map(name).collect(); + assert_eq!(shown, &want, "{source}: each box is named after its data point, in order"); + // Each box draws its name: the text that names it stands after the box, on its line. + for b in column { + let text = b.text.unwrap_or_else(|| panic!("{source}: {:?} draws no name", b.name)); + assert!( + text.left() >= b.rect.right() - 0.5 && text.top() < b.rect.bottom() && text.bottom() > b.rect.top(), + "{source}: {:?} is named beside its box", + b.name + ); + } + // The title sits over its column's first box, under the dialog's "Data Points:" rather than on its line. + let heading = h.query_by_label("Data Points:").expect("\"Data Points:\" is drawn").rect(); + let first = column[0].rect; + let title = h + .query_all_by_label(title) + .find(|n| n.accesskit_node().role() != Role::CheckBox && n.rect().left() <= first.center().x && n.rect().right() >= first.center().x) + .unwrap_or_else(|| panic!("{title} heads its column")) + .rect(); + assert!(title.bottom() <= first.top() + 0.5, "{source}: the title {title:?} is above the first box {first:?}"); + assert!(heading.bottom() <= title.top() + 0.5, "{source}: \"Data Points:\" {heading:?} is above the title {title:?}"); + } +} diff --git a/crates/ui-egui/src/tools/analysis/dialogs.rs b/crates/ui-egui/src/tools/analysis/dialogs.rs index 9285426605..8247e31ac5 100644 --- a/crates/ui-egui/src/tools/analysis/dialogs.rs +++ b/crates/ui-egui/src/tools/analysis/dialogs.rs @@ -170,26 +170,32 @@ fn form(kind: Kind, fields: &mut DialogFields) -> ParamDialog<'_> { }) } Kind::DataPoints => { + // Full width, with the title over the columns: in a labelled row every check box is named by the row and + // draws no name of its own. let row = Param::custom("columns", tl!("Data Points"), |ui, fields, _| { - Row::new() + Stack::new() .show(ui, |ui, _| { - for (source, title) in sources() { - Stack::new().show(ui, |ui, _| { - Text::new(Label::from(title)).show(ui); - for column in analysis_cmds::available(source) { - let name = analysis_cmds::COLUMNS.iter().find(|c| c.0 == column).map_or(column, |c| c.1); - let field = point_key(source, column); - let mut on = fields.bool(&field).unwrap_or(false); - Checkbox::new(Bind::bound(&mut on)).label(name.to_owned()).show(ui); - if fields.bool(&field) != Some(on) { - fields.set(field, on); + Text::new(Label::from(tl!("Data Points:"))).show(ui); + Row::new().show(ui, |ui, _| { + for (source, title) in sources() { + Stack::new().show(ui, |ui, _| { + Text::new(Label::from(title)).show(ui); + for column in analysis_cmds::available(source) { + let name = analysis_cmds::COLUMNS.iter().find(|c| c.0 == column).map_or(column, |c| c.1); + let field = point_key(source, column); + let mut on = fields.bool(&field).unwrap_or(false); + Checkbox::new(Bind::bound(&mut on)).label(name.to_owned()).show(ui); + if fields.bool(&field) != Some(on) { + fields.set(field, on); + } } - } - }); - } + }); + } + }); }) .output - }); + }) + .full_width(); ParamDialog::command(key, tl!("Select Data Points"), vec![row]) } Kind::ScaleMarker => { @@ -211,3 +217,7 @@ fn form(kind: Kind, fields: &mut DialogFields) -> ParamDialog<'_> { }; dialog.values(Bind::bound(fields)) } + +#[cfg(test)] +#[path = "data_points_labels_tests.rs"] +mod data_points_labels_tests; diff --git a/crates/ui-egui/src/tools/crop_ui.rs b/crates/ui-egui/src/tools/crop_ui.rs index 1235377484..cda684c4de 100644 --- a/crates/ui-egui/src/tools/crop_ui.rs +++ b/crates/ui-egui/src/tools/crop_ui.rs @@ -230,9 +230,19 @@ pub fn frame(app: &PhotocraftApp) -> Option { app.canvas_tools.crop.tool.frame() } -/// The canvas shows the pixels past its edges under the shield. +/// The canvas shows the pixels past its edges under the shield. Default mode only: in Classic Mode the frame lies over +/// the pasteboard and the layers stop at the canvas edge, as in Photoshop. pub(crate) fn shows_beyond_canvas(app: &PhotocraftApp) -> bool { - app.ui.tool == Tool::Crop && app.canvas_tools.crop.tool.shows_beyond_canvas() + app.ui.tool == Tool::Crop && app.ui.tool_options.crop.image_mode() && app.canvas_tools.crop.tool.shows_beyond_canvas() +} + +/// The colour the area a crop adds past the canvas previews in (`shows_beyond_canvas`), as the commit fills it: the +/// background colour on a visible Background with Delete Cropped Pixels on and Fill: Background. `None` previews +/// transparency (Delete off turns the Background into a layer; Content-Aware Fill makes its own pixels). +pub(crate) fn grown_fill(app: &PhotocraftApp, doc: &photocraft_doc::Document) -> Option<[f32; 4]> { + let crop = &app.ui.tool_options.crop; + let fills = crop.delete_pixels && crop.fill == CropFill::Background && doc.background().is_some_and(|layer| layer.visible); + fills.then_some(app.session.tools.background) } /// Show Cropped Area is off with the Crop tool showing a frame: nothing outside it shows. diff --git a/crates/ui-egui/src/tools/crop_ui/tests.rs b/crates/ui-egui/src/tools/crop_ui/tests.rs index 95a1ea379f..11d8883160 100644 --- a/crates/ui-egui/src/tools/crop_ui/tests.rs +++ b/crates/ui-egui/src/tools/crop_ui/tests.rs @@ -417,3 +417,44 @@ fn drawing_a_new_crop_snaps_its_corner_not_the_default_frame() { assert!((frame.rect.x1 - 300.0).abs() < 1e-6, "classic {classic}: {frame:?}"); } } + +/// #16185: as in Photoshop, the pixels past the canvas show while a frame is edited in the default mode only; in Classic +/// Mode the frame lies over the pasteboard and the layers stop at the canvas edge. +#[test] +fn classic_mode_shows_nothing_past_the_canvas() { + let mut app = app(SampleType::U8); + drag(&mut app, &[[10.0, 10.0], [50.0, 40.0]], NONE); + assert!(tool(&mut app).shows_beyond_canvas(), "the drawn frame is being edited"); + assert!(!crop_ui::shows_beyond_canvas(&app), "Classic Mode: no preview past the canvas"); + app.ui.tool_options.crop.shield.classic_mode = false; + assert!(crop_ui::shows_beyond_canvas(&app), "default mode: the canvas shows past its edges"); +} + +/// #16185: the area a crop adds past the canvas previews in the colour the commit fills a Background's new area with, +/// and as transparency where the commit leaves it transparent. +#[test] +fn the_grown_area_previews_in_the_background_colour_the_crop_fills_it_with() { + let mut app = app(SampleType::U8); + app.ui.tool_options.crop.shield.classic_mode = false; + let red = [1.0, 0.0, 0.0, 1.0]; + app.session.tools.background = red; + let doc = (*app.session.active().unwrap().doc).clone(); + assert_eq!(crop_ui::grown_fill(&app, &doc), Some(red), "Delete Cropped Pixels on, Fill: Background"); + + app.ui.tool_options.crop.delete_pixels = false; + assert_eq!(crop_ui::grown_fill(&app, &doc), None, "Delete off turns the Background into a layer: transparency"); + app.ui.tool_options.crop.delete_pixels = true; + + app.ui.tool_options.crop.fill = CropFill::ContentAware; + assert_eq!(crop_ui::grown_fill(&app, &doc), None, "Content-Aware Fill makes its own pixels"); + app.ui.tool_options.crop.fill = CropFill::Background; + + let mut hidden = doc.clone(); + hidden.layers[0].visible = false; + assert_eq!(crop_ui::grown_fill(&app, &hidden), None, "a hidden Background shows nothing"); + + app.session.execute("layer.new.layerFromBackground", json!({})).unwrap(); + let layered = (*app.session.active().unwrap().doc).clone(); + assert!(layered.background().is_none()); + assert_eq!(crop_ui::grown_fill(&app, &layered), None, "no Background: the other layers stay transparent there"); +} diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index 2ebed238af..12fd03a433 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -7,8 +7,9 @@ use craft::behavior::IconId; use craft::ui::buttons::ToggleButton; use craft::ui::choice::{Checkbox, Segmented}; -use craft::ui::contract::{Bind, Entry, Props as _, Show as _}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; use craft::ui::display::Divider; +use craft::ui::form::Field; use craft::ui::pickers::Select; use craft::ui::primitives::IconSpec; use photocraft_engine::eraser_cmds::{MAGIC_ERASER_BITMAP_ERROR, MAGIC_ERASER_INDEXED_ERROR}; @@ -197,12 +198,18 @@ fn background_eraser_members(ui: &mut egui::Ui, app: &mut PhotocraftApp) { Entry::new("contiguous".to_string(), tl!("Contiguous")), Entry::new("findEdges".to_string(), tl!("Find Edges")), ]; - let picked = Select::new(tl!("Limits:"), Bind::given(o.bg_limits.clone()), &limits) - .tooltip(tl!("How far to let the erasing spread").to_owned()) - .show(ui) - .events - .committed() - .cloned(); + // In a `Field`, as Color Replacement's Limits: a bare control's label only names it (#16338). + let picked = Field::new(tl!("Limits:")) + .show(ui, |ui, _| { + Select::new(tl!("Limits:"), Bind::given(o.bg_limits.clone()), &limits) + .tooltip(tl!("How far to let the erasing spread").to_owned()) + .show(ui) + .events + .committed() + .cloned() + }) + .inner + .flatten(); if let Some(limits) = picked { o.bg_limits = limits; } diff --git a/crates/ui-egui/src/tools/options_bar_field_labels_tests.rs b/crates/ui-egui/src/tools/options_bar_field_labels_tests.rs new file mode 100644 index 0000000000..0f5c8c4195 --- /dev/null +++ b/crates/ui-egui/src/tools/options_bar_field_labels_tests.rs @@ -0,0 +1,37 @@ +//! #16338: Background Eraser's "Limits:", Freeform Pen's "Curve Fit:" and the Note tool's "Author:" and "Color:" +//! are drawn in front of their controls, not only given to them as accessible names. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +/// The options bar of `tool` on a new document, rendered through the real host. +fn bar(tool: Tool) -> Harness<'static, Box> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 80, "height": 80})).unwrap(); + app.ui.tool = tool; + let mut h = + Harness::builder().with_size(vec2(1600.0, 200.0)).with_context(app.ctx().clone()).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + h.run_steps(4); + h +} + +#[test] +fn bare_bar_controls_show_their_labels() { + let cases: [(Tool, &[&str]); 3] = [(Tool::BackgroundEraser, &["Limits:"]), (Tool::FreeformPen, &["Curve Fit:"]), (Tool::Note, &["Author", "Color"])]; + for (tool, labels) in cases { + let h = bar(tool); + let shown: Vec = h.query_all_by_role(Role::Label).filter_map(|n| n.accesskit_node().label()).collect(); + for label in labels { + let node = h.query_all_by_role(Role::Label).find(|n| n.accesskit_node().label().as_deref() == Some(label)); + let node = node.unwrap_or_else(|| panic!("{tool:?}: label {label:?} is drawn; labels shown: {shown:?}")); + let r = node.rect(); + assert!(r.width() > 0.0 && r.height() > 0.0 && r.top() >= 0.0, "{tool:?}: {label:?} has a visible rect: {r:?}"); + } + } +} diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index 1084b17e60..266c66dec8 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -213,6 +213,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { Tool::Pencil => reset!(pencil_auto_erase, pencil_clear), Tool::Eraser => reset!(eraser_mode, erase_to_history), Tool::Remove => reset!(remove_new_layer, remove_after_each_stroke), + Tool::AdjustmentBrush => reset!(adjustment_brush_kind, adjustment_brush_subtract, adjustment_brush_overlay), Tool::BackgroundEraser => reset!(bg_sampling, bg_limits, bg_tolerance, bg_protect_fg, bg_tolerance_control), Tool::ColorReplacement => reset!(cr_mode, cr_sampling, cr_limits, cr_tolerance, cr_anti_alias), Tool::MagicEraser => reset!(tolerance, anti_alias, contiguous, magic_eraser_opacity), diff --git a/crates/ui-egui/src/tools/type_tool.rs b/crates/ui-egui/src/tools/type_tool.rs index 13837c6117..9ad4ea23d2 100644 --- a/crates/ui-egui/src/tools/type_tool.rs +++ b/crates/ui-egui/src/tools/type_tool.rs @@ -36,8 +36,8 @@ use defaults::apply; use defaults::{default_style_params, default_styles, shown_scale}; pub use defaults::{foreground_changed, open_color_picker}; pub(crate) use defaults::{formatting_params, target, target_text}; -pub(crate) use editing::commit_before_selecting; pub use editing::{cancel, commit, commit_with, edit_active, edit_at, end_if_left}; +pub(crate) use editing::{commit_before_selecting, focus_editor}; #[cfg(test)] pub(crate) use editing::{step_char_metric, toggle_char_style, toggle_hyphenate}; #[cfg(test)] diff --git a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs index 1e66bef7a2..0b7d4d6438 100644 --- a/crates/ui-egui/src/tools/type_tool/canvas_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/canvas_tests.rs @@ -506,11 +506,16 @@ fn double_click(h: &mut Harness<'static, Box>, p: Pos2) { } fn drag(h: &mut Harness<'static, Box>, a: Pos2, b: Pos2) { + drag_in(h, a, b, 6); +} + +/// [`drag`] in `moves` pointer moves, one frame each. +fn drag_in(h: &mut Harness<'static, Box>, a: Pos2, b: Pos2, moves: u8) { h.hover_at(a); h.run_steps(1); press(h, a, true); - for k in 1..=6 { - h.hover_at(a + (b - a) * (k as f32 / 6.0)); + for k in 1..=moves { + h.hover_at(a + (b - a) * (f32::from(k) / f32::from(moves))); h.run_steps(1); } press(h, b, false); @@ -530,52 +535,57 @@ fn selection(h: &Harness<'static, Box>) -> (usize, usize) { #[test] fn clicks_and_drags_land_on_the_glyph_under_the_pointer() { let rotated = Affine { m: [1.4 * 0.94, 1.4 * 0.342, -1.4 * 0.342, 1.4 * 0.94, 500.0, 420.0] }; - for ppp in [1.0, 2.0] { - for zoom in [0.25f32, 0.5, 1.0, 2.0] { - for (flip, pan) in [(false, [0.0, 0.0]), (true, [37.0, -21.0])] { - for (shape, tf) in [("point", None), ("box", None), ("point", Some(rotated)), ("box", Some(rotated))] { - let mut app = new_app(); - let size = 60.0 / zoom; - let mut p = json!({"text": "HOHOHO HOHO", "size": size, "x": 300, "y": 420}); - if shape == "box" { - p["box"] = json!([250.0, 250.0, size * 6.0, size * 4.0]); - } - let id = LayerId(app.run("type.create", p).unwrap()["layer"].as_u64().unwrap()); - if let Some(a) = tf { - app.run("type.edit", json!({"layer": id.0, "transform": a.m})).unwrap(); - } - app.ui.view.flip_horizontal = flip; - let mut h = harness(ppp, app); - // Centre the view on the text's middle, then pan. - let (l, aff, _) = layout(h.state_mut(), id).unwrap(); - let b = l.bounds().unwrap(); - let m = aff.apply(Point::new(f64::from(b[0] + b[2]) / 2.0, f64::from(b[1] + b[3]) / 2.0)); - set_view(&mut h, zoom, [m.x as f32 + pan[0], m.y as f32 + pan[1]]); - h.run_steps(2); - let ctx = format!("ppp {ppp} zoom {zoom} flip {flip} {shape} transformed {}", tf.is_some()); - let rect = canvas_rect(h.state()); - for (i, f) in [(0, 0.2), (2, 0.8), (4, 0.3), (8, 0.7)] { - let p = glyph(&mut h, id, i, f); - assert!(rect.contains(p), "{ctx}: glyph {i} off screen at {p:?}"); - } - // Click into the layer: caret before glyph 2 (left part), then after glyph 4. - let p = glyph(&mut h, id, 2, 0.2); - click(&mut h, p); - assert_eq!(selection(&h), (2, 2), "{ctx}: click on the left of glyph 2"); - let p = glyph(&mut h, id, 4, 0.8); - click(&mut h, p); - assert_eq!(selection(&h), (5, 5), "{ctx}: click on the right of glyph 4"); - // Drag from glyph 1 (left part) to glyph 8 (right part): characters 1..9. - let (a, b) = (glyph(&mut h, id, 1, 0.25), glyph(&mut h, id, 8, 0.75)); - drag(&mut h, a, b); - assert_eq!(selection(&h), (1, 9), "{ctx}: drag selection"); - // And backwards, starting inside the egui drag threshold of a glyph edge. - let (a, b) = (glyph(&mut h, id, 5, 0.85), glyph(&mut h, id, 3, 0.15)); - drag(&mut h, a, b); - assert_eq!(selection(&h), (6, 3), "{ctx}: backwards drag selection"); - } - } + // One case per zoom, pairwise over the other axes: every ppp, flip and pan, and shape and transform + // appears, ppp meets both flips, and the two ends of the range in points (25 % at 2x is 12.5 %, 200 % + // at 1x is 200 %) are kept. The view maps the pointer to the document (the shown view's `to_doc`) + // the same way for any layer, and the layer's transform maps the document to text space the same way + // at any view, so the two halves need not be crossed. + let pan = [37.0, -21.0]; + for (ppp, zoom, flip, pan, shape, tf) in [ + (2.0, 0.25f32, false, [0.0, 0.0], "point", None), + (1.0, 0.5, true, pan, "box", None), + (2.0, 1.0, true, pan, "point", Some(rotated)), + (1.0, 2.0, false, [0.0, 0.0], "box", Some(rotated)), + ] { + let mut app = new_app(); + let size = 60.0 / zoom; + let mut p = json!({"text": "HOHOHO HOHO", "size": size, "x": 300, "y": 420}); + if shape == "box" { + p["box"] = json!([250.0, 250.0, size * 6.0, size * 4.0]); } + let id = LayerId(app.run("type.create", p).unwrap()["layer"].as_u64().unwrap()); + if let Some(a) = tf { + app.run("type.edit", json!({"layer": id.0, "transform": a.m})).unwrap(); + } + app.ui.view.flip_horizontal = flip; + let mut h = harness(ppp, app); + // Centre the view on the text's middle, then pan. + let (l, aff, _) = layout(h.state_mut(), id).unwrap(); + let b = l.bounds().unwrap(); + let m = aff.apply(Point::new(f64::from(b[0] + b[2]) / 2.0, f64::from(b[1] + b[3]) / 2.0)); + set_view(&mut h, zoom, [m.x as f32 + pan[0], m.y as f32 + pan[1]]); + h.run_steps(2); + let ctx = format!("ppp {ppp} zoom {zoom} flip {flip} {shape} transformed {}", tf.is_some()); + let rect = canvas_rect(h.state()); + for (i, f) in [(0, 0.2), (2, 0.8), (4, 0.3), (8, 0.7)] { + let p = glyph(&mut h, id, i, f); + assert!(rect.contains(p), "{ctx}: glyph {i} off screen at {p:?}"); + } + // Click into the layer: caret before glyph 2 (left part), then after glyph 4. + let p = glyph(&mut h, id, 2, 0.2); + click(&mut h, p); + assert_eq!(selection(&h), (2, 2), "{ctx}: click on the left of glyph 2"); + let p = glyph(&mut h, id, 4, 0.8); + click(&mut h, p); + assert_eq!(selection(&h), (5, 5), "{ctx}: click on the right of glyph 4"); + // Drag from glyph 1 (left part) to glyph 8 (right part): characters 1..9. + let (a, b) = (glyph(&mut h, id, 1, 0.25), glyph(&mut h, id, 8, 0.75)); + drag(&mut h, a, b); + assert_eq!(selection(&h), (1, 9), "{ctx}: drag selection"); + // And backwards, starting inside the egui drag threshold of a glyph edge. + let (a, b) = (glyph(&mut h, id, 5, 0.85), glyph(&mut h, id, 3, 0.15)); + drag(&mut h, a, b); + assert_eq!(selection(&h), (6, 3), "{ctx}: backwards drag selection"); } } @@ -1082,54 +1092,56 @@ fn temporary_type_transform_visibility_and_cursors() { /// Real canvas input: layer-local scaling stays correct across orientation, zoom, HiDPI and flip. #[test] fn temporary_type_transform_scales_without_reflow_or_leaving_type() { - for ppp in [1.0, 2.0] { - for zoom in [0.25, 1.0, 2.0, 8.0] { - for (paragraph, vertical, flip) in [(false, false, false), (true, false, true), (false, true, true)] { - let transform = Affine { m: [1.2, 0.25, 0.18, 0.9, 500.0, 360.0] }; - let (app, id) = transform_app(paragraph, vertical, transform); - let mut h = harness(ppp, app); - let f = frame_of(h.state_mut()).unwrap(); - let center = f.pivot; - h.state_mut().ui.view.flip_horizontal = flip; - // At high zoom, show the dragged corner; a release beyond the canvas is valid. - let at = if zoom >= 2.0 { [f.quad[2][0] as f32, f.quad[2][1] as f32] } else { [center[0] as f32 + 17.0, center[1] as f32 - 9.0] }; - set_view(&mut h, zoom, at); - h.run_steps(2); - let before = text(h.state(), id); - let count = history_len(&h); - let (a, b) = (f.quad[2], [f.quad[0][0] + 1.25 * (f.quad[2][0] - f.quad[0][0]), f.quad[0][1] + 1.25 * (f.quad[2][1] - f.quad[0][1])]); - let (a, b) = (frame_point(h.state(), a), frame_point(h.state(), b)); - assert!(canvas_rect(h.state()).contains(a)); - transform_drag(&mut h, a, b, type_command() | Modifiers::SHIFT, true); - let after = text(h.state(), id); - assert_affine( - after.transform, - transform.mul(&Affine::translate(f.rect[0], f.rect[1])).mul(&Affine::scale(1.25)).mul(&Affine::translate(-f.rect[0], -f.rect[1])), - ); - assert_eq!( - (after.text.as_str(), &after.runs, &after.paragraphs, after.orientation, after.shape), - (before.text.as_str(), &before.runs, &before.paragraphs, before.orientation, before.shape) - ); - assert_eq!(selection(&h), (3, 3)); - assert_eq!(h.state().ui.text_edit.as_ref().unwrap().layer, id.0); - assert!(h.state().ui.tool.is_type()); - assert!(h.state().ui.transform.is_none()); - assert!(h.state().ui.type_transform.is_none()); - assert_eq!(history_len(&h), count + 1); - // Typing goes through the window host, as the platform's reaches the focused editor. - super::commit_tests::type_keys(h.state_mut(), "!"); - assert!(text(h.state(), id).text.starts_with("Hel!lo")); - h.key_press(if vertical { egui::Key::ArrowUp } else { egui::Key::ArrowLeft }); - h.run_steps(1); - assert_eq!(selection(&h), (3, 3)); - assert_eq!(history_len(&h), count + 1, "one edit session"); - h.state_mut().run("edit.undo", json!({})).unwrap(); - assert_affine(text(h.state(), id).transform, before.transform); - assert_eq!(text(h.state(), id).text, before.text); - h.state_mut().run("edit.redo", json!({})).unwrap(); - assert_eq!(text(h.state(), id).transform, after.transform); - } - } + // One case per zoom, pairwise over the other axes: both ppp values meet both flips, point, paragraph + // and vertical type each appear, both sides of the 200 % view choice below run twice, and the ends of + // the range in points (25 % at 2x, 800 % at 1x) are kept. The frame and the drag map through the view + // the same way for any kind of type, and the kind decides the layer's frame the same way at any view. + for (ppp, zoom, (paragraph, vertical, flip)) in + [(2.0, 0.25, (false, false, false)), (1.0, 1.0, (true, false, true)), (2.0, 2.0, (false, true, true)), (1.0, 8.0, (false, false, false))] + { + let transform = Affine { m: [1.2, 0.25, 0.18, 0.9, 500.0, 360.0] }; + let (app, id) = transform_app(paragraph, vertical, transform); + let mut h = harness(ppp, app); + let f = frame_of(h.state_mut()).unwrap(); + let center = f.pivot; + h.state_mut().ui.view.flip_horizontal = flip; + // At high zoom, show the dragged corner; a release beyond the canvas is valid. + let at = if zoom >= 2.0 { [f.quad[2][0] as f32, f.quad[2][1] as f32] } else { [center[0] as f32 + 17.0, center[1] as f32 - 9.0] }; + set_view(&mut h, zoom, at); + h.run_steps(2); + let before = text(h.state(), id); + let count = history_len(&h); + let (a, b) = (f.quad[2], [f.quad[0][0] + 1.25 * (f.quad[2][0] - f.quad[0][0]), f.quad[0][1] + 1.25 * (f.quad[2][1] - f.quad[0][1])]); + let (a, b) = (frame_point(h.state(), a), frame_point(h.state(), b)); + assert!(canvas_rect(h.state()).contains(a)); + transform_drag(&mut h, a, b, type_command() | Modifiers::SHIFT, true); + let after = text(h.state(), id); + assert_affine( + after.transform, + transform.mul(&Affine::translate(f.rect[0], f.rect[1])).mul(&Affine::scale(1.25)).mul(&Affine::translate(-f.rect[0], -f.rect[1])), + ); + assert_eq!( + (after.text.as_str(), &after.runs, &after.paragraphs, after.orientation, after.shape), + (before.text.as_str(), &before.runs, &before.paragraphs, before.orientation, before.shape) + ); + assert_eq!(selection(&h), (3, 3)); + assert_eq!(h.state().ui.text_edit.as_ref().unwrap().layer, id.0); + assert!(h.state().ui.tool.is_type()); + assert!(h.state().ui.transform.is_none()); + assert!(h.state().ui.type_transform.is_none()); + assert_eq!(history_len(&h), count + 1); + // Typing goes through the window host, as the platform's reaches the focused editor. + super::commit_tests::type_keys(h.state_mut(), "!"); + assert!(text(h.state(), id).text.starts_with("Hel!lo")); + h.key_press(if vertical { egui::Key::ArrowUp } else { egui::Key::ArrowLeft }); + h.run_steps(1); + assert_eq!(selection(&h), (3, 3)); + assert_eq!(history_len(&h), count + 1, "one edit session"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_affine(text(h.state(), id).transform, before.transform); + assert_eq!(text(h.state(), id).text, before.text); + h.state_mut().run("edit.redo", json!({})).unwrap(); + assert_eq!(text(h.state(), id).transform, after.transform); } } @@ -2027,67 +2039,68 @@ const HANDLE_SIDES: [(bool, bool, bool, bool); 8] = [ fn every_paragraph_box_handle_resizes_the_box_with_snapping_on() { let scaled = Affine { m: [1.5, 0.0, 0.0, 0.75, 300.0, 300.0] }; let rotated = Affine { m: [1.2 * 0.94, 1.2 * 0.342, -1.2 * 0.342, 1.2 * 0.94, 300.0, 300.0] }; - for ppp in [1.0, 2.0] { - // The ends of the range only: the frame's handles and their grab area are screen-space parts of the - // framework's `TransformBox::text_frame` (`controls.rs`, `frame_box`) and the snap reach is a screen distance, - // so the zoom only scales the view, with no step in between. 25 % and 200 % at 1x and 2x span 12.5 % to - // 200 % in points, which holds 50 % and 100 %. - for zoom in [0.25f32, 2.0] { - for (name, tf) in [("plain", None), ("scaled", Some(scaled)), ("rotated", Some(rotated))] { - let mut app = new_app(); - assert!(app.ui.extras.snap, "snapping is on by default"); - let size = 24.0 / zoom; - let p = json!({"text": "HOHOHO HOHO HOHOHO HOHO HOHOHO", "size": size, "x": 300, "y": 300, "box": [300.0, 300.0, size * 8.0, size * 4.0]}); - let id = LayerId(app.run("type.create", p).unwrap()["layer"].as_u64().unwrap()); - if let Some(a) = tf { - app.run("type.edit", json!({"layer": id.0, "transform": a.m})).unwrap(); - } - let mut h = harness(ppp, app); - let (bx, by, w, bh) = super::box_shape(h.state(), id).unwrap(); - let aff = layout(h.state_mut(), id).unwrap().1; - let m = aff.apply(Point::new(f64::from(bx + w / 2.0), f64::from(by + bh / 2.0))); - set_view(&mut h, zoom, [m.x as f32, m.y as f32]); - h.run_steps(2); - let ctx = format!("ppp {ppp} zoom {zoom} {name}"); - let p = glyph(&mut h, id, 2, 0.2); - click(&mut h, p); - assert_eq!(selection(&h), (2, 2), "{ctx}: editing"); - for (i, (l, r, t, b)) in HANDLE_SIDES.into_iter().enumerate() { - // Press at the handle and inside its grab area, towards the text. - for off in [0.0f32, 4.0] { - let (bx, by, w, bh) = super::box_shape(h.state(), id).unwrap(); - let hx = if l { - bx - } else if r { - bx + w - } else { - bx + w / 2.0 - }; - let hy = if t { - by - } else if b { - by + bh - } else { - by + bh / 2.0 - }; - let dir = vec2(f32::from(u8::from(r)) - f32::from(u8::from(l)), f32::from(u8::from(b)) - f32::from(u8::from(t))); - let at = screen(&mut h, id, hx, hy); - let out = (screen(&mut h, id, hx + dir.x * 10.0, hy + dir.y * 10.0) - at).normalized(); - let a = at - out * off; - drag(&mut h, a, a + out * 30.0); - let ctx = format!("{ctx} handle {i} offset {off}"); - assert_eq!(selection(&h), (2, 2), "{ctx}: the caret stays put"); - let (_, _, w2, h2) = super::box_shape(h.state(), id).unwrap(); - // 30 points outward (a corner's diagonal: about 21 per side) is that over - // zoom × layer scale in text units; snapping may shift the release by up to - // its 8 point reach. - let min = 6.0 / (zoom / h.state().canvas_ppp()) / 1.5; - let grew = |was: f32, now: f32, moved: bool| if moved { now - was >= min } else { (now - was).abs() < 1e-3 }; - assert!(grew(w, w2, l || r), "{ctx}: width {w} -> {w2}"); - assert!(grew(bh, h2, t || b), "{ctx}: height {bh} -> {h2}"); - } - } - } + // Pairwise over (ppp, zoom, transform): each value of each axis appears once or more, and the two + // cases at the ends of the range in points are kept. The frame's handles and their grab area are + // screen-space parts of the framework's `TransformBox::text_frame` (`controls.rs`, `frame_box`) and + // the snap reach is a screen distance, so the zoom and ppp only scale the view: 25 % at 2x is 12.5 % + // in points and 200 % at 1x is 200 %, which hold 50 % and 100 % between them. The layer transform + // goes through the same frame mapping at any view scale, so each one runs at one view. + let cases = [(2.0, 0.25f32, "plain", None), (1.0, 2.0, "scaled", Some(scaled)), (2.0, 2.0, "rotated", Some(rotated))]; + for (case, (ppp, zoom, name, tf)) in cases.into_iter().enumerate() { + let mut app = new_app(); + assert!(app.ui.extras.snap, "snapping is on by default"); + let size = 24.0 / zoom; + let p = json!({"text": "HOHOHO HOHO HOHOHO HOHO HOHOHO", "size": size, "x": 300, "y": 300, "box": [300.0, 300.0, size * 8.0, size * 4.0]}); + let id = LayerId(app.run("type.create", p).unwrap()["layer"].as_u64().unwrap()); + if let Some(a) = tf { + app.run("type.edit", json!({"layer": id.0, "transform": a.m})).unwrap(); + } + let mut h = harness(ppp, app); + let (bx, by, w, bh) = super::box_shape(h.state(), id).unwrap(); + let aff = layout(h.state_mut(), id).unwrap().1; + let m = aff.apply(Point::new(f64::from(bx + w / 2.0), f64::from(by + bh / 2.0))); + set_view(&mut h, zoom, [m.x as f32, m.y as f32]); + h.run_steps(2); + let ctx = format!("ppp {ppp} zoom {zoom} {name}"); + let p = glyph(&mut h, id, 2, 0.2); + click(&mut h, p); + assert_eq!(selection(&h), (2, 2), "{ctx}: editing"); + for (i, (l, r, t, b)) in HANDLE_SIDES.into_iter().enumerate() { + // Press at the handle or inside its grab area, towards the text: corners (even `i`) and sides + // take turns, and the next case swaps them, so every handle is pressed both ways and every case + // presses both ways. The press picks the handle (`TransformBox::text_frame`) and the pass that + // commits carries the final box (`box_of`), so the drag needs the move that starts it and the end. + let off = if (i + case) % 2 == 0 { 0.0f32 } else { 4.0 }; + let (bx, by, w, bh) = super::box_shape(h.state(), id).unwrap(); + let hx = if l { + bx + } else if r { + bx + w + } else { + bx + w / 2.0 + }; + let hy = if t { + by + } else if b { + by + bh + } else { + by + bh / 2.0 + }; + let dir = vec2(f32::from(u8::from(r)) - f32::from(u8::from(l)), f32::from(u8::from(b)) - f32::from(u8::from(t))); + let at = screen(&mut h, id, hx, hy); + let out = (screen(&mut h, id, hx + dir.x * 10.0, hy + dir.y * 10.0) - at).normalized(); + let a = at - out * off; + drag_in(&mut h, a, a + out * 30.0, 2); + let ctx = format!("{ctx} handle {i} offset {off}"); + assert_eq!(selection(&h), (2, 2), "{ctx}: the caret stays put"); + let (_, _, w2, h2) = super::box_shape(h.state(), id).unwrap(); + // 30 points outward (a corner's diagonal: about 21 per side) is that over + // zoom × layer scale in text units; snapping may shift the release by up to + // its 8 point reach. + let min = 6.0 / (zoom / h.state().canvas_ppp()) / 1.5; + let grew = |was: f32, now: f32, moved: bool| if moved { now - was >= min } else { (now - was).abs() < 1e-3 }; + assert!(grew(w, w2, l || r), "{ctx}: width {w} -> {w2}"); + assert!(grew(bh, h2, t || b), "{ctx}: height {bh} -> {h2}"); } } } diff --git a/crates/ui-egui/src/tools/type_tool/editing.rs b/crates/ui-egui/src/tools/type_tool/editing.rs index 936d9fc497..13178879ea 100644 --- a/crates/ui-egui/src/tools/type_tool/editing.rs +++ b/crates/ui-egui/src/tools/type_tool/editing.rs @@ -6,7 +6,7 @@ use super::{LayerId, PhotocraftApp, TextEdit, TextLayer, active_doc_id, byte_ran /// Marks the session's editor to take the keyboard in the pass that first shows it: the framework knows an editor's /// doc key only once it has been shown, so a request made before that finds nothing. -pub(super) fn focus_editor(ctx: &egui::Context) { +pub(crate) fn focus_editor(ctx: &egui::Context) { ctx.data_mut(|d| d.insert_temp(egui::Id::unique(FOCUS_WANTED), true)); } diff --git a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs index 8b47bc69d3..9d1c96e054 100644 --- a/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs +++ b/crates/ui-egui/src/tools/type_tool/font_commit_tests.rs @@ -147,63 +147,59 @@ fn caret_font_choices_style_only_subsequent_typing_including_ime() { // One app: each case's text layer goes with Undo before the next case makes its own. // Every acceptance, as each reaches the caret's pending style by its own route through the // family field (ArrowDown applies its row once per step). One original font, as it only decides - // which font is chosen, and the carets at both ends. + // which font is chosen. The caret at the start of the text, where any text inserts at byte 0 the same way, + // and at the end of each text, where the inserted text and its pending font land after its last character + // boundary (a plain letter, a joined emoji, a letter after a paragraph break). The acceptance only sets the + // pending font (`type_insertion_style`, checked before anything is typed), wherever the caret is, so each + // acceptance runs once or more and need not meet every caret or text. let mut h = document(); let base = past_len(&h); let original = 0; - for accept in ["enter", "click", "arrow-enter"] { - for text in ["abcdef", "AéB👩‍💻", "ab\ncdé"] { - for caret in [0, text.chars().count()] { - let label = (accept, text, caret); - undo_to(&mut h, base); - let id = text_layer(&mut h, original, text); - select(&mut h, [caret, caret]); - h.run(); - let before = saved(&h, id); - let steps = h.state().session.active().unwrap().history.entries().len(); - let requested = FONTS[1 - original]; - choose(&mut h, requested, accept); - // ArrowDown steps to the row below the typed match, which depends on the installed fonts - // ("JetBrains Mono NL" where it is installed), so the pending font is the row it accepted. - let font = h - .state() - .ui - .type_insertion_style - .as_ref() - .map(|s| s.style.font_family.clone()) - .unwrap_or_else(|| panic!("a pending font at the caret: {label:?}")); - let font = font.as_str(); - assert!(font.starts_with(requested) && font != FONTS[original], "the accepted row matches the typed name: {font} {label:?}"); - if accept != "arrow-enter" { - assert_eq!(font, requested, "{label:?}"); - } - assert_eq!(saved(&h, id), before, "a font choice at a caret never restyles existing characters: {label:?}"); - assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps, "{label:?}"); - crate::type_font_preview::set(h.state_mut(), font.into()); - assert!(crate::type_font_preview::display_doc(h.state_mut(), 0).is_none()); - // Two preedit replacements and the final commit keep the pending font. - surrender_focus(&mut h); - ime(h.state_mut(), egui::ImeEvent::Preedit { text: "é".into(), active_range_chars: None }); - h.run(); - ime(h.state_mut(), egui::ImeEvent::Preedit { text: "éX".into(), active_range_chars: None }); - h.run(); - ime(h.state_mut(), egui::ImeEvent::Commit("éX".into())); - h.run(); - super::host::type_text(h.state_mut(), "Z"); - h.run(); - let mut expected = families(&before); - expected.splice(caret..caret, std::iter::repeat_n(font.to_string(), 3)); - assert_eq!(families(&saved(&h, id)), expected, "{label:?}"); - let mut expected_text: Vec = text.chars().collect(); - expected_text.splice(caret..caret, "éXZ".chars()); - let typed = saved(&h, id); - assert_eq!(typed["text"], expected_text.into_iter().collect::(), "the IME and typed text land at the caret: {label:?}"); - assert!(h.state().ui.type_insertion_style.is_some(), "the pending font is still set before the commit: {label:?}"); - checkmark(&mut h); - assert_eq!(saved(&h, id), typed, "{label:?}"); - assert!(h.state().ui.type_insertion_style.is_none(), "the commit clears the pending font: {label:?}"); - } + for (accept, text, end) in [("enter", "abcdef", false), ("click", "abcdef", true), ("arrow-enter", "AéB👩‍💻", true), ("enter", "ab\ncdé", true)] { + let caret = if end { text.chars().count() } else { 0 }; + let label = (accept, text, caret); + undo_to(&mut h, base); + let id = text_layer(&mut h, original, text); + select(&mut h, [caret, caret]); + h.run(); + let before = saved(&h, id); + let steps = h.state().session.active().unwrap().history.entries().len(); + let requested = FONTS[1 - original]; + choose(&mut h, requested, accept); + // ArrowDown steps to the row below the typed match, which depends on the installed fonts + // ("JetBrains Mono NL" where it is installed), so the pending font is the row it accepted. + let font = + h.state().ui.type_insertion_style.as_ref().map(|s| s.style.font_family.clone()).unwrap_or_else(|| panic!("a pending font at the caret: {label:?}")); + let font = font.as_str(); + assert!(font.starts_with(requested) && font != FONTS[original], "the accepted row matches the typed name: {font} {label:?}"); + if accept != "arrow-enter" { + assert_eq!(font, requested, "{label:?}"); } + assert_eq!(saved(&h, id), before, "a font choice at a caret never restyles existing characters: {label:?}"); + assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps, "{label:?}"); + crate::type_font_preview::set(h.state_mut(), font.into()); + assert!(crate::type_font_preview::display_doc(h.state_mut(), 0).is_none()); + // Two preedit replacements and the final commit keep the pending font. + surrender_focus(&mut h); + ime(h.state_mut(), egui::ImeEvent::Preedit { text: "é".into(), active_range_chars: None }); + h.run(); + ime(h.state_mut(), egui::ImeEvent::Preedit { text: "éX".into(), active_range_chars: None }); + h.run(); + ime(h.state_mut(), egui::ImeEvent::Commit("éX".into())); + h.run(); + super::host::type_text(h.state_mut(), "Z"); + h.run(); + let mut expected = families(&before); + expected.splice(caret..caret, std::iter::repeat_n(font.to_string(), 3)); + assert_eq!(families(&saved(&h, id)), expected, "{label:?}"); + let mut expected_text: Vec = text.chars().collect(); + expected_text.splice(caret..caret, "éXZ".chars()); + let typed = saved(&h, id); + assert_eq!(typed["text"], expected_text.into_iter().collect::(), "the IME and typed text land at the caret: {label:?}"); + assert!(h.state().ui.type_insertion_style.is_some(), "the pending font is still set before the commit: {label:?}"); + checkmark(&mut h); + assert_eq!(saved(&h, id), typed, "{label:?}"); + assert!(h.state().ui.type_insertion_style.is_none(), "the commit clears the pending font: {label:?}"); } } diff --git a/crates/ui-egui/src/tools/type_transform.rs b/crates/ui-egui/src/tools/type_transform.rs index 60cf615bfe..b89345cedc 100644 --- a/crates/ui-egui/src/tools/type_transform.rs +++ b/crates/ui-egui/src/tools/type_transform.rs @@ -340,6 +340,11 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, canvas: egui::Rec // The press ended without a drag (a click), or a key moved the box: the capture ends with it. finish(app); } + // The editor is not shown while the box holds the pointer, so its focus scope gives the keyboard back to the + // canvas. The type session goes on after the box, and so does typing: the editor takes the keyboard again. + if app.ui.type_transform.is_none() && app.ui.text_edit.is_some() { + crate::tools::type_tool::focus_editor(&ctx); + } } /// The `typeTransform` of the control protocol: the open transform's document, revision, frame and reference point, diff --git a/crates/ui-egui/src/tools/vector_ui/options.rs b/crates/ui-egui/src/tools/vector_ui/options.rs index 5668bd24ac..face470c71 100644 --- a/crates/ui-egui/src/tools/vector_ui/options.rs +++ b/crates/ui-egui/src/tools/vector_ui/options.rs @@ -7,6 +7,7 @@ use craft::ui::buttons::Button; use craft::ui::choice::Checkbox; use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, clicked}; use craft::ui::display::{Divider, Text}; +use craft::ui::form::Field; use craft::ui::layout_components::Row; use craft::ui::runtime::env::{Label, UnitKind}; use craft::ui::text::NumberField; @@ -205,9 +206,15 @@ fn pen_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool, open: &mut Ba match tool { Tool::FreeformPen => { Divider::vertical().show(ui); - let field = - NumberField::new(label(tl!("Curve Fit:")), Bind::given(Some(f64::from(o.curve_fit)))).range(0.5..=10.0).unit_kind(UnitKind::Pixels).show(ui); - if let Some(Some(v)) = field.value().copied() { + // In a `Field`: a bare control's label only names it, it is not drawn (#16338). + let picked = Field::new(label(tl!("Curve Fit:"))) + .show(ui, |ui, _| { + let field = NumberField::new(label(tl!("Curve Fit:")), Bind::given(Some(f64::from(o.curve_fit)))); + field.range(0.5..=10.0).unit_kind(UnitKind::Pixels).show(ui).value().copied() + }) + .inner + .flatten(); + if let Some(Some(v)) = picked { o.curve_fit = v as f32; } let alt = crate::shortcuts::pretty("Alt"); diff --git a/docs/atn.md b/docs/atn.md index 7570d8a0e8..7609096314 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -486,6 +486,9 @@ This is another implemented subset of #10723, not support for its remaining even - Close without `Svng` preserves the unanswered save choice. Headless playback refuses to discard a changed document. Native `file.close` still defaults to discard; `save: "ask"` opts into this policy. - Photo Filter converts recorded Lab colours through `craft-cms`. +- Black & White exports store coefficients as signed 32-bit integers. Strict export refuses + fractional coefficients; `skipUnsupported:true` reports the omitted step. Native commands + retain fractional coefficients. - Direct Vibrance and Gradient Map save as the string events `vibrance` and `gradientMapEvent`. Stroke Outside uses `StrL.Otsd`, group Pass Through uses `BlnM.passThrough`, Canvas Size extension colours use `FrgC` and `Clr `, and Absolute Colorimetric intent uses `Inte.AClr`. @@ -514,7 +517,9 @@ The Vibrance event and adjustment-opacity handling incorporate [@bommerts' contr - Image Size preserves `scaleStyles`. Native calls default to true; an absent ATN flag means false (the reference application plays both alike), so Save writes the key only when it is true. - Crop and resolution-only resizing retain their existing behavior. + Explicit pixel dimensions take precedence over `percent`; a side without an explicit size + keeps its percentage. Strict export refuses an invalid supplied percentage even when explicit + dimensions would override it. Crop and resolution-only resizing retain their existing behavior. - Convert to Profile preserves `Dthr`, `Fltt` and `rasterizePlaced`, defaulting to false. `sdwM` is written as the reference application records it (-1); other values and malformed flags remain kept steps. Absolute intent writes `AClr`, with `AbsC` still accepted on import. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 2af6f0fe67..844ed16253 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -160,7 +160,7 @@ The transport is the framework's control server (`craft::automation::server` in - `ui.inspect` `rects` maps each open document's canvas (`canvas.`), each hosted dialog (its `dialogs` id) and `taskBar` to its last on-screen rect `[x0, y0, x1, y1]` in screen points; an id with no rect (absent, behind a modal dialog) is left out - `ui.pointer` queues its events for the active document's canvas and replies at once; the canvas takes them on its next frame, so a following request sees their effect only after a frame has run. With no open document or no canvas shown it fails with `no canvas to drive` and queues nothing. `modifiers.space` is held as the Space key for the request - `ui.screenshot {path?, focus?, window?}`: capture the main window, or the document window `window` (its id as `ui.window.open` replied it; `main` is the main window) (PNG). With no path the reply contains - base64 PNG data; a path is relative to the automation write root. Raises the window first + base64 PNG data; a supplied path may be relative to the automation write root or absolute beneath its canonical or configured spelling. Raises the window first (default) because occluded macOS windows stop rendering. A request sent before the first frame is queued (within the same limits and deadline) and captures once the window geometry is known, as on 0.15. At most four captures may be outstanding (waiting for geometry, rendered or awaiting @@ -561,7 +561,7 @@ stdio, and a value that is not a port is a usage error naming the variable. Impl | `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported top-level layer, named like `file.export.layersToFiles` names them. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"` or `"adjustment layer has no pixels of its own"`. Visibility takes precedence for hidden adjustments; `visibleOnly:false` exports hidden non-adjustment layers. Groups export merged; their children are not separate exports or skips. Existing filenames/numbering are unchanged. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips | | `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command | | `doc.importDataSets` | `{path, delimiter? (,), index?}` → `{imported}`: the capability-scoped `file.import.variableDataSets`; the CSV is read beneath the read root | -| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tiffCompression?, tiffTransparency?, tiffPyramid?, tgaBits?, ddsCompression?, ddsMipmaps?, pdfSpotPlates?, pcraftFullComposite?, maximizeCompatibility?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tiffCompression` (`none`, `lzw`, `zip`), `tiffTransparency` (bool: Save Transparency; unset, kept unless the document has alpha or spot channels) and `tiffPyramid` (bool) are TIFF Options; `tgaBits` 24 or 32 sets a TGA's bits per pixel, `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, and `maximizeCompatibility: false` writes a layered PSD/PSB with Photoshop's placeholder instead of the merged image, except for Bitmap, Indexed Color and Duotone documents, as `app.save` does; `pdfSpotPlates: false` leaves a PDF's spot plates out, which are written by default, and refuses a Multichannel document, which has no image to write without them; `pcraftFullComposite: true` also writes the flattened document at its canvas size into a `.pcraft` file as `composite/full.png`; the save may leave it out in the cases listed in [the format guide](../book/src/formats/pcraft.md), and the manifest's `full_composite` member names it when written). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | +| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tiffCompression?, tiffTransparency?, tiffPyramid?, tgaBits?, dpxBits?, ddsCompression?, ddsMipmaps?, pdfSpotPlates?, pcraftFullComposite?, maximizeCompatibility?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tiffCompression` (`none`, `lzw`, `zip`), `tiffTransparency` (bool: Save Transparency; unset, kept unless the document has alpha or spot channels) and `tiffPyramid` (bool) are TIFF Options; `dpxBits` selects 8, 10, 12 or 16 bits per sample for DPX (unset: 8 for an 8-bit document, otherwise 16); `tgaBits` 24 or 32 sets a TGA's bits per pixel, `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, and `maximizeCompatibility: false` writes a layered PSD/PSB with Photoshop's placeholder instead of the merged image, except for Bitmap, Indexed Color and Duotone documents, as `app.save` does; `pdfSpotPlates: false` leaves a PDF's spot plates out, which are written by default, and refuses a Multichannel document, which has no image to write without them; `pcraftFullComposite: true` also writes the flattened document at its canvas size into a `.pcraft` file as `composite/full.png`; the save may leave it out in the cases listed in [the format guide](../book/src/formats/pcraft.md), and the manifest's `full_composite` member names it when written). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | | `doc.inspect` | `{index?}`: same JSON as `document.inspect` | | `doc.render` | `{index?, maxSide? (1024; 0 = full), path?}`: PNG to `path`, else `{mime, base64}` | | `doc.select` / `doc.close` | `{index}` / `{index?}` | @@ -573,6 +573,10 @@ An `index` targets that one call: `doc.place`, `doc.exportLayers`, `doc.exportDa without making it the active one, so the next call without `index` still runs on the document that was active before (`doc.select` is the method that changes it). +`doc.render` treats omitted `params` and `"params": null` as `{}`. Pass a string `path` +for a file reply. An omitted or null `path` requests an inline PNG. Other parameter +container or path types return an error before rendering. + ```sh printf '%s\n' \ '{"id":1,"method":"doc.open","params":{"path":"in.jpg"}}' \ diff --git a/docs/development.md b/docs/development.md index bf77960039..d9d8fd0adb 100644 --- a/docs/development.md +++ b/docs/development.md @@ -100,7 +100,7 @@ On a native host with a working wgpu adapter, capture the two images into a fres set -eu shortcut_snapshots="$(mktemp -d)" PHOTOCRAFT_SHORTCUT_SNAPSHOTS="$shortcut_snapshots" cargo test -p photocraft-ui-egui --lib \ - prefs_ui::shortcut_capture_tests::captured_shortcut_gpu_snapshots -- --exact + prefs::prefs_ui::shortcut_capture_tests::captured_shortcut_gpu_snapshots -- --exact test -s "$shortcut_snapshots/ctrl-k-1x.png" test -s "$shortcut_snapshots/ctrl-k-2x.png" printf 'Review the shortcut row and conflict message in %s\n' "$shortcut_snapshots" diff --git a/docs/gaps.md b/docs/gaps.md index 4baa2bbb4c..9681bf5aa5 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -129,7 +129,7 @@ what an agent can't finish alone. - **Done 2026-10-31 (#10606):** all twelve Stylize/Pixelate ATN events (Group D) load, play and save with measured defaults, documented clamping and strict export checks. The [event reference](atn.md) now lists 128 supported and 89 unmapped events. Other Actions/scripting gaps remain; no overall readiness percentage or estimate changed. - **2026-10-21 evidence (#8304):** Save Actions expands compound layer-property edits into separate Photoshop Set events, with rename last so named layer references remain valid. - Exported descriptors and native playback at RGB 8/16/32-bit have [regression coverage](../crates/engine/src/atn_cmds/layer_props_tests.rs); + Exported descriptors and native playback at RGB 8/16/32-bit have [regression coverage](../crates/engine/src/cmd/atn_cmds/layer_props_tests.rs); independent Photoshop replay of the fix is still pending. No readiness percentage or estimate changed. - **Done 2026-10-17 (#7101):** `.atn` Apply Layer Comp steps with a named `compsClass` reference import as `layerComp.apply` and export to the same Photoshop event. Names resolve diff --git a/docs/mcp.md b/docs/mcp.md index 64fd88baa5..59859326be 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -171,8 +171,9 @@ flags on `photocraft-cli mcp --bridge` are rejected. Explicit `--control-token` `--control-token-file` flags require `--bridge` (or `PHOTOCRAFT_CONTROL_PORT`) and are mutually exclusive. Bridge credentials can also come from `PHOTOCRAFT_CONTROL_TOKEN` or `PHOTOCRAFT_CONTROL_TOKEN_FILE`. -MCP and `serve` launch options (all but `--help`/`-h`) take one non-empty value each and cannot -be repeated. Missing values, stray positional arguments and options for the wrong mode are +MCP and `serve` switches such as `--headless`, `--gpu`, `--no-gpu` and `--help`/`-h` take no +value. Value options take one non-empty value each; `--automation-read-root` may repeat to +add ordered read directories, while other launch options cannot be repeated. Missing values, stray positional arguments and options for the wrong mode are usage errors (exit 2), reported on stderr before the server starts; stdout stays available for protocol messages. For `serve`, explicit credential flags require `--port` (or `PHOTOCRAFT_CONTROL_PORT`); stdio needs no control token. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2e4dbd309b..dc88e234a5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -526,8 +526,8 @@ one undo step (`strokes`), Esc (or ⊘) drops them (#1750). 2026-10-08: the tools update above is checked against the current toolbar groups in [`panels.rs`](../crates/ui-egui/src/panels.rs), the Pencil and tool-cycle tests in [`pencil_tests.rs`](../crates/ui-egui/src/pencil_tests.rs), Patch's live-preview test in -[`patch_preview.rs`](../crates/ui-egui/src/patch_preview.rs), and Vertical Type's point/paragraph -creation and undo test in [`type_tool_tests.rs`](../crates/ui-egui/src/type_tool_tests.rs). +[`patch_preview.rs`](../crates/ui-egui/src/canvas/patch_preview.rs), and Vertical Type's point/paragraph +creation and undo test in [`type_tool/canvas_tests.rs`](../crates/ui-egui/src/tools/type_tool/canvas_tests.rs). These implementations remove the tools from the missing list; they do not establish Photoshop behavioural parity. The historical estimates and corpus measurements in this assessment are unchanged; current measured floors remain in the scorecard. diff --git a/docs/user/guides/adjust-colors-with-adjustment-layers.md b/docs/user/guides/adjust-colors-with-adjustment-layers.md index 500ff3521c..760a3db7a9 100644 --- a/docs/user/guides/adjust-colors-with-adjustment-layers.md +++ b/docs/user/guides/adjust-colors-with-adjustment-layers.md @@ -2,7 +2,7 @@ title: Adjust colors without changing your pixels description: Add a Curves, Levels or other adjustment layer in PhotoCraft so you can change or switch it off later. order: 20 -verified: 0.8.2 +verified: 0.23.1 --- Use **Layer › New Adjustment Layer** and pick an adjustment. The change sits on its own layer above your image, so your original pixels stay as they were and you can edit or hide the adjustment later. @@ -13,20 +13,19 @@ Use **Layer › New Adjustment Layer** and pick an adjustment. The change sits o 2. Choose **Layer › New Adjustment Layer**, then an adjustment such as **Curves…**, **Levels…**, **Vibrance…** or **Hue/Saturation…**. 3. Change the settings in the **Properties** panel, which shows the settings of the new layer. -The same list is behind the button at the bottom of the **Layers** panel, labelled **Create new fill or adjustment layer** when you hover over it. +The fill and adjustment button at the bottom of **Layers** offers the same choices. The adjustments in the menu are **Brightness/Contrast**, **Levels**, **Curves**, **Exposure**, **Vibrance**, **Hue/Saturation**, **Color Balance**, **Black & White**, **Photo Filter**, **Channel Mixer**, **Color Lookup**, **Invert**, **Posterize**, **Threshold**, **Gradient Map** and **Selective Color**. ## Limit it to one area 1. Select the area first, for example with the **Elliptical Marquee Tool**. See [Select part of an image and mask it](select-and-mask.md). -2. Add the adjustment layer as above. -3. With the adjustment layer active, choose **Layer › Layer Mask › Reveal Selection**. The adjustment now shows only inside the selection. +2. Add the adjustment layer as above. PhotoCraft uses the selection as the new layer’s mask, so the adjustment affects only that area. ## Change it later -Click the adjustment layer in the **Layers** panel and edit its settings in **Properties**. Every step you take is also listed in the **History** panel. +Click the adjustment thumbnail in **Layers**, then edit its settings in **Properties**. Every step you take is also listed in the **History** panel. ## Apply an adjustment straight to the pixels -If you do not need to change it later, use **Image › Adjustments**, for example **Image › Adjustments › Curves…**. These change the pixels of the layer directly and are not kept as a separate layer. +To adjust a pixel layer directly, use **Image › Adjustments**, for example **Image › Adjustments › Curves…**. On a Smart Object, supported adjustments appear as Smart Filters. diff --git a/xtask/src/corpus.rs b/xtask/src/corpus.rs index 3d217c9f78..70297aea85 100644 --- a/xtask/src/corpus.rs +++ b/xtask/src/corpus.rs @@ -32,6 +32,13 @@ fn is_critical(path: &str) -> bool { /// `cargo xtask corpus [--all | --pngsuite | --download | --psd | --psd-tools | --heif | --exr | --pixls | --affinity | --atn | --photoshop [--local] | --gimp [--local]] [--update-manifest]` pub fn cmd(args: &[&str]) -> Result<(), String> { + for arg in args { + match *arg { + "--all" | "--pngsuite" | "--download" | "--psd" | "--psd-tools" | "--heif" | "--pixls" | "--exr" | "--affinity" | "--atn" | "--photoshop" + | "--gimp" | "--local" | "--update-manifest" => {} + other => return Err(format!("corpus: unknown argument `{other}`")), + } + } let update = args.contains(&"--update-manifest"); let mut did = false; if args.contains(&"--all") { diff --git a/xtask/src/corpus/tests.rs b/xtask/src/corpus/tests.rs index 921bdc24e9..9795272627 100644 --- a/xtask/src/corpus/tests.rs +++ b/xtask/src/corpus/tests.rs @@ -1,5 +1,12 @@ use super::*; +#[test] +fn corpus_rejects_unknown_arguments_before_fetching() { + for args in [vec!["--psd-tool"], vec!["--all", "--psd-tool"], vec!["--psd-tool", "--all"]] { + assert_eq!(cmd(&args), Err("corpus: unknown argument `--psd-tool`".into())); + } +} + #[test] fn changed_atn_root_triggers_corpus_tests() { assert!(is_critical("crates/engine/src/cmd/atn_cmds.rs")); diff --git a/xtask/src/i18n_report.rs b/xtask/src/i18n_report.rs index 3f0d7866ad..2cbbbd88ad 100644 --- a/xtask/src/i18n_report.rs +++ b/xtask/src/i18n_report.rs @@ -227,16 +227,20 @@ fn tl_keys(sources: &[(PathBuf, String)]) -> BTreeSet { } let code = without_test_modules(source); let mut rest = code.as_str(); - while let Some(at) = rest.find("tl!(\"") { - rest = rest.get(at + 5..).unwrap_or(""); + while let Some(at) = rest.find("tl!(") { + rest = rest.get(at + 4..).unwrap_or("").trim_start(); + let Some(literal) = rest.strip_prefix('"') else { continue }; + rest = literal; let bytes = rest.as_bytes(); let mut end = 0; - while end < bytes.len() && !(bytes[end] == b'"' && (end == 0 || bytes[end - 1] != b'\\')) { + let mut escaped = false; + while end < bytes.len() && (bytes[end] != b'"' || escaped) { + escaped = bytes[end] == b'\\' && !escaped; end += 1; } if let Some(raw) = rest.get(..end) { let source = unescape_rust_string(raw); - if rest.get(end + 1..end + 2) == Some(")") { + if rest.get(end + 1..).is_some_and(|after| after.trim_start().starts_with(')')) { keys.insert(Key { context: String::new(), source }); } } @@ -488,7 +492,9 @@ fn quoted_strings(source: &str) -> Vec { rest = rest.get(at + 1..).unwrap_or(""); let bytes = rest.as_bytes(); let mut end = 0; - while end < bytes.len() && !(bytes[end] == b'"' && (end == 0 || bytes[end - 1] != b'\\')) { + let mut escaped = false; + while end < bytes.len() && (bytes[end] != b'"' || escaped) { + escaped = bytes[end] == b'\\' && !escaped; end += 1; } if let Some(raw) = rest.get(..end) { @@ -503,11 +509,19 @@ fn unescape_rust_string(raw: &str) -> String { let mut out = String::with_capacity(raw.len()); let mut chars = raw.chars(); while let Some(ch) = chars.next() { + // Rust normalizes physical CRLF pairs before interpreting escapes. + if ch == '\r' && chars.as_str().starts_with('\n') { + continue; + } if ch != '\\' { out.push(ch); continue; } match chars.next() { + // Rust normalizes CRLF source lines before removing string continuations. + Some(ch) if ch == '\n' || (ch == '\r' && chars.as_str().starts_with('\n')) => { + chars = chars.as_str().trim_start_matches(['\t', '\n', '\r', ' ']).chars(); + } Some('n') => out.push('\n'), Some('r') => out.push('\r'), Some('t') => out.push('\t'), @@ -627,6 +641,114 @@ mod tests { } } + #[test] + fn literal_translation_keys_allow_formatting_whitespace() { + for newline in ["\n", "\r\n"] { + let source = format!("tl!({newline} \"multiline key\"{newline}); tl!( \t\"inline key\" \t); tl!(\"compact key\");"); + let sources = vec![(PathBuf::from("ui.rs"), source)]; + let keys = tl_keys(&sources); + assert_eq!( + keys, + ["multiline key", "inline key", "compact key"].into_iter().map(|source| Key { context: String::new(), source: source.into() }).collect() + ); + } + let sources = vec![(PathBuf::from("ui.rs"), r#"tl!(dynamic); tl!("prefix".to_string()); tl!("first", "second"); tl!("key" + suffix);"#.into())]; + assert!(tl_keys(&sources).is_empty()); + } + + #[test] + fn gathers_multiline_tooltips_used_by_the_ui() { + let source = r#" + tl!( + "Drag the pin to move the band, or its ring to change its blur. Drag the solid lines to widen the sharp band, the dashed lines to set the transition, and the dots to turn it." + ); + tl!( + "How the camera's color filter mosaic is filled in. It is applied when the file opens; the preview shows the method it was opened with." + ); + tl!( + "The estimate is above 8 GiB and the available memory is unknown, so this process or browser tab may run out of memory. You can still try to open it." + ); + tl!( + "Drag on the image to add a constraint; Shift for horizontal/vertical; right-click a constraint to change or delete it." + ); + tl!( + "The layers need {needed} of GPU memory and may hold {budget}, so edits that redraw the whole document do it on the CPU. Click to set GPU Memory." + ); + tl!( + "WinTab reads pressure, tilt, rotation and the eraser end from the tablet driver. Turn off Windows Ink in your tablet's software utility (for example Wacom Center) before using it." + ); + tl!( + "AI apps such as Claude can open, edit and save documents in this window while ArtCraft Launcher › Settings › AI agents › Let AI agents use Craft apps is on. Only programs on this computer can connect." + ); + tl!( + "PhotoCraft found your keyboard shortcut set {set} from another image editor on this computer: {n} of its shortcuts differ from PhotoCraft's. Import it?" + ); + "#; + let expected: BTreeSet = quoted_strings(source).into_iter().map(|source| Key { context: String::new(), source }).collect(); + assert_eq!(expected.len(), 8); + let keys = tl_keys(&[(PathBuf::from("ui.rs"), source.into())]); + assert_eq!(keys, expected); + let languages = [Language { code: "en".into() }, Language { code: "fr".into() }]; + let report = format_report(&languages, &keys, &BTreeMap::from([("fr".into(), BTreeSet::new())]), &BTreeMap::new()); + assert_eq!(report.lines().find(|line| line.starts_with("fr ")).and_then(|line| line.split_whitespace().nth(1)), Some("0/8")); + assert!(report.contains("fr: 8 missing\n")); + for key in &expected { + assert!(report.contains(&format!(" {}\n", key.source)), "{}", key.source); + } + } + + #[test] + fn continued_literal_keys_match_rust_string_values() { + let expected = "Open \ + image"; + assert_eq!(expected, "Open image"); + for newline in ["\n", "\r\n"] { + let source = format!("tl!({newline} \"Open \\{newline} \t{newline} image\"{newline});"); + assert_eq!(tl_keys(&[(PathBuf::from("ui.rs"), source)]), BTreeSet::from([Key { context: String::new(), source: expected.into() }])); + } + } + + #[test] + fn continuations_preserve_other_newlines_and_non_ascii_whitespace() { + for (raw, expected) in [ + (r"Open \n image", "Open \n image"), + ("Open \n image", "Open \n image"), + ("Open \\\\\n image", "Open \\\n image"), + ("Open \\\n \u{a0}image", "Open \u{a0}image"), + ] { + let source = format!("tl!(\n \"{raw}\"\n);"); + assert_eq!(tl_keys(&[(PathBuf::from("ui.rs"), source)]), BTreeSet::from([Key { context: String::new(), source: expected.into() }]), "{raw:?}"); + } + } + + #[test] + fn literal_boundaries_distinguish_escaped_quotes_and_trailing_backslashes() { + for (literal, expected) in [(r#""Folder\\""#, "Folder\\"), (r#""Say \"Open\".""#, "Say \"Open\"."), (r#""Folder\\\\""#, "Folder\\\\")] { + assert_eq!(quoted_strings(literal), vec![expected]); + for padding in ["", "\n "] { + let source = format!("tl!({padding}{literal}{padding}); tl!(\"next\");"); + let expected = [expected, "next"].into_iter().map(|source| Key { context: String::new(), source: source.into() }).collect(); + assert_eq!(tl_keys(&[(PathBuf::from("ui.rs"), source)]), expected); + } + } + } + + #[test] + fn physical_crlf_keys_match_rust_string_values() { + let expected = "A\ + B +C"; + assert_eq!(expected, "AB\nC"); + for newline in ["\n", "\r\n"] { + let source = format!("tl!(\n \"A\\{newline} B{newline}C\"\n);"); + assert_eq!(tl_keys(&[(PathBuf::from("ui.rs"), source)]), BTreeSet::from([Key { context: String::new(), source: expected.into() }])); + let source = format!("tl!(\"A{newline}B\");"); + assert_eq!(tl_keys(&[(PathBuf::from("ui.rs"), source)]), BTreeSet::from([Key { context: String::new(), source: "A\nB".into() }])); + } + let source = r#"tl!("A\r\nB");"#; + assert_eq!(tl_keys(&[(PathBuf::from("ui.rs"), source.into())]), BTreeSet::from([Key { context: String::new(), source: "A\r\nB".into() }])); + } + #[test] fn plural_forms_follow_count_expressions_and_dynamic_forms_are_not_literal_keys() { let sources = vec![( diff --git a/xtask/src/ico.rs b/xtask/src/ico.rs index 021572a12f..6646ea3812 100644 --- a/xtask/src/ico.rs +++ b/xtask/src/ico.rs @@ -8,7 +8,8 @@ use std::path::Path; /// Width and height from a PNG's IHDR chunk. pub fn png_size(png: &[u8]) -> Result<(u32, u32), String> { const SIG: &[u8] = b"\x89PNG\r\n\x1a\n"; - if png.len() < 24 || &png[..8] != SIG || &png[12..16] != b"IHDR" { + // Require the complete first chunk: IHDR has 13 payload bytes followed by its CRC. + if png.len() < 33 || &png[..8] != SIG || &png[8..12] != b"\0\0\0\x0d" || &png[12..16] != b"IHDR" { return Err("not a PNG file".into()); } let w = u32::from_be_bytes([png[16], png[17], png[18], png[19]]); @@ -93,6 +94,26 @@ mod tests { assert_eq!(png_size(&fake_png(48)).unwrap(), (48, 48)); } + #[test] + fn rejects_truncated_ihdr_chunks() { + let png = fake_png(48); + for len in 0..png.len() { + assert!(png_size(&png[..len]).is_err(), "accepted a truncated IHDR at {len} bytes"); + } + assert_eq!(png_size(&png), Ok((48, 48))); + assert!(pack(&[png[..24].to_vec()]).is_err()); + } + + #[test] + fn rejects_wrong_ihdr_payload_lengths() { + for length in [0u32, 8, 12, 14, u32::MAX] { + let mut png = fake_png(48); + png[8..12].copy_from_slice(&length.to_be_bytes()); + assert!(png_size(&png).is_err(), "accepted IHDR payload length {length}"); + assert!(pack(&[png]).is_err(), "packed IHDR payload length {length}"); + } + } + #[test] fn committed_icon_is_valid() { let path = crate::root().join("assets/app-icon/photocraft.ico"); diff --git a/xtask/src/perf.rs b/xtask/src/perf.rs index 3ff076f3b1..d4a25f5f72 100644 --- a/xtask/src/perf.rs +++ b/xtask/src/perf.rs @@ -869,7 +869,11 @@ pub fn run(root: &Path, rest: &[&str]) -> Result<(), String> { return Err(format!("perf: unknown bench `{name}` (see {BUDGETS})")); } } - let baseline_value: Option = std::fs::read_to_string(root.join(BASELINE)).ok().and_then(|t| serde_json::from_str(&t).ok()); + let baseline_value: Option = match std::fs::read_to_string(root.join(BASELINE)) { + Ok(text) => Some(serde_json::from_str(&text).map_err(|e| format!("parse {BASELINE}: {e}"))?), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => return Err(format!("read {BASELINE}: {e}")), + }; if !o.from.is_empty() { return baseline_from_files(root, &budgets, baseline_value.as_ref(), &o); } @@ -1576,6 +1580,60 @@ row = "r99" assert_eq!(after, baseline, "an unknown bench must not update the baseline"); } + struct BaselineFixture(PathBuf); + + impl Drop for BaselineFixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn invalid_baseline_stops_before_benchmarks_or_saved_run_updates() { + let root = std::env::temp_dir().join(format!("photocraft-perf-invalid-baseline-{}", std::process::id())); + std::fs::create_dir(&root).unwrap(); + let _cleanup = BaselineFixture(root.clone()); + std::fs::create_dir(root.join("perf")).unwrap(); + std::fs::write(root.join(BUDGETS), "[settings]\nbaseline_min_runs = 1\n").unwrap(); + let saved = root.join("run.json"); + std::fs::write(&saved, r#"{"mode":"quick","machine":{"class":"test"},"scenarios":{}}"#).unwrap(); + let modes = [vec!["--update-baseline", "--from", saved.to_str().unwrap()], vec![], vec!["--update-baseline"]]; + for (bytes, context) in [(b"{malformed".as_slice(), "parse"), (b"\xff".as_slice(), "read")] { + for args in &modes { + std::fs::write(root.join(BASELINE), bytes).unwrap(); + let result = run(&root, args); + let after = std::fs::read(root.join(BASELINE)).unwrap(); + assert!(result.as_ref().is_err_and(|e| e.starts_with(&format!("{context} {BASELINE}:"))), "{args:?}: {result:?}"); + assert_eq!(after, bytes, "a failed load must not replace the baseline"); + } + } + std::fs::remove_file(root.join(BASELINE)).unwrap(); + std::fs::create_dir(root.join(BASELINE)).unwrap(); + for args in &modes { + assert!(run(&root, args).is_err_and(|e| e.starts_with(&format!("read {BASELINE}:"))), "{args:?}"); + } + } + + #[test] + fn saved_run_updates_allow_a_missing_baseline_and_preserve_other_valid_modes() { + let root = std::env::temp_dir().join(format!("photocraft-perf-load-baseline-{}", std::process::id())); + std::fs::create_dir(&root).unwrap(); + let _cleanup = BaselineFixture(root.clone()); + std::fs::create_dir(root.join("perf")).unwrap(); + std::fs::write(root.join(BUDGETS), "[settings]\nbaseline_min_runs = 1\n").unwrap(); + let saved = root.join("run.json"); + std::fs::write(&saved, r#"{"mode":"quick","machine":{"class":"test"},"scenarios":{}}"#).unwrap(); + let args = ["--update-baseline", "--from", saved.to_str().unwrap()]; + run(&root, &args).unwrap(); + let initial: Value = serde_json::from_str(&std::fs::read_to_string(root.join(BASELINE)).unwrap()).unwrap(); + assert!(initial["modes"]["quick"].is_object()); + std::fs::write(root.join(BASELINE), r#"{"machine_class":"test","modes":{"full":{"sentinel":true}}}"#).unwrap(); + run(&root, &args).unwrap(); + let updated: Value = serde_json::from_str(&std::fs::read_to_string(root.join(BASELINE)).unwrap()).unwrap(); + assert_eq!(updated["modes"]["full"]["sentinel"], true); + assert!(updated["modes"]["quick"].is_object()); + } + #[test] fn options() { assert!(parse_opts(&["--bogus"]).is_err()); diff --git a/xtask/src/pinned.rs b/xtask/src/pinned.rs index ddca8a6163..0618cf4838 100644 --- a/xtask/src/pinned.rs +++ b/xtask/src/pinned.rs @@ -370,9 +370,13 @@ fn file_hex(path: &std::path::Path) -> Option { /// per-file download rather than a git upstream; the manifest discipline is the same /// (`--update-manifest` re-pins). Opt-in: not part of `--all` or CI until a maintainer says so. pub fn fetch_pixls(update: bool) -> Result<(), String> { - let dest = crate::root().join("corpus").join("pixls"); + fetch_pixls_at(&crate::root(), update) +} + +fn fetch_pixls_at(root: &Path, update: bool) -> Result<(), String> { + let dest = root.join("corpus").join("pixls"); std::fs::create_dir_all(&dest).map_err(|e| format!("create {}: {e}", dest.display()))?; - let manifest = crate::root().join("xtask").join("pixls.sha256"); + let manifest = root.join("xtask").join("pixls.sha256"); if update { let mut names: Vec<&str> = crate::corpus_pins::PIXLS_FILES.iter().map(|(_, n)| *n).collect(); names.sort_unstable(); @@ -390,6 +394,12 @@ pub fn fetch_pixls(update: bool) -> Result<(), String> { .lines() .filter_map(|l| l.split_once(" ").map(|(s, n)| (n.to_string(), s.to_string()))) .collect(); + // Check every pin before any download: two absent hashes must not count as a cache hit. + for (_, name) in crate::corpus_pins::PIXLS_FILES { + if !want.contains_key(*name) { + return Err(format!("pixls {name}: missing sha256 entry in {}", manifest.display())); + } + } for (path, name) in crate::corpus_pins::PIXLS_FILES { let file = dest.join(name); if file_hex(&file).as_deref() == want.get(*name).map(String::as_str) { @@ -478,4 +488,80 @@ mod tests { let _ = std::fs::remove_dir_all(&tmp); } + + struct PixlsFixture(PathBuf); + + impl PixlsFixture { + fn new(case: &str) -> Self { + let root = std::env::temp_dir().join(format!("photocraft-pixls-{}-{case}", std::process::id())); + std::fs::create_dir(&root).unwrap(); + std::fs::create_dir(root.join("xtask")).unwrap(); + std::fs::create_dir_all(root.join("corpus/pixls")).unwrap(); + Self(root) + } + + fn populate(&self, omitted: Option<&str>, cached: bool) { + let hash = crate::sha256::hex(b"camera fixture"); + let mut manifest = String::new(); + for (_, name) in crate::corpus_pins::PIXLS_FILES { + if Some(*name) != omitted { + manifest.push_str(&format!("{hash} {name}\n")); + } + if cached { + std::fs::write(self.0.join("corpus/pixls").join(name), b"camera fixture").unwrap(); + } + } + std::fs::write(self.0.join("xtask/pixls.sha256"), manifest).unwrap(); + } + + fn missing_pin_error(&self, name: &str) -> String { + format!("pixls {name}: missing sha256 entry in {}", self.0.join("xtask").join("pixls.sha256").display()) + } + } + + impl Drop for PixlsFixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn pixls_rejects_empty_manifest_without_claiming_missing_files_are_verified() { + let fixture = PixlsFixture::new("empty-manifest"); + std::fs::write(fixture.0.join("xtask/pixls.sha256"), "").unwrap(); + let name = crate::corpus_pins::PIXLS_FILES[0].1; + assert_eq!(super::fetch_pixls_at(&fixture.0, false), Err(fixture.missing_pin_error(name))); + } + + #[test] + fn pixls_rejects_missing_pin_even_when_file_is_cached() { + let fixture = PixlsFixture::new("cached-missing-pin"); + let name = crate::corpus_pins::PIXLS_FILES[0].1; + fixture.populate(Some(name), true); + assert_eq!(super::fetch_pixls_at(&fixture.0, false), Err(fixture.missing_pin_error(name))); + } + + #[test] + fn pixls_checks_last_pin_before_downloading_an_earlier_missing_file() { + let fixture = PixlsFixture::new("last-pin"); + let name = crate::corpus_pins::PIXLS_FILES.last().unwrap().1; + fixture.populate(Some(name), false); + assert_eq!(super::fetch_pixls_at(&fixture.0, false), Err(fixture.missing_pin_error(name))); + } + + #[test] + fn pixls_accepts_complete_matching_cached_files() { + let fixture = PixlsFixture::new("complete-cache"); + fixture.populate(None, true); + assert_eq!(super::fetch_pixls_at(&fixture.0, false), Ok(())); + } + + #[test] + fn pixls_update_manifest_still_hashes_cached_files() { + let fixture = PixlsFixture::new("update-manifest"); + fixture.populate(None, true); + std::fs::write(fixture.0.join("xtask/pixls.sha256"), "").unwrap(); + assert_eq!(super::fetch_pixls_at(&fixture.0, true), Ok(())); + assert_eq!(super::fetch_pixls_at(&fixture.0, false), Ok(())); + } } diff --git a/xtask/src/psd_write_oracle.rs b/xtask/src/psd_write_oracle.rs index b1f4cc2b0c..c0cfb4f13e 100644 --- a/xtask/src/psd_write_oracle.rs +++ b/xtask/src/psd_write_oracle.rs @@ -81,7 +81,13 @@ fn read_limited(path: &Path) -> Result, String> { /// Accept a case identifier that can safely name one output subdirectory. fn valid_id(id: &str) -> bool { - !id.is_empty() && id.len() <= 100 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') + if id.is_empty() || id.len() > 100 || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') { + return false; + } + // These names resolve to devices on Windows, so the case cannot hold its output files. + let name = id.to_ascii_uppercase(); + let port = name.strip_prefix("COM").or_else(|| name.strip_prefix("LPT")).is_some_and(|n| matches!(n.as_bytes(), [b'1'..=b'9'])); + !matches!(name.as_str(), "CON" | "PRN" | "AUX" | "NUL") && !port } /// Reject unsupported recipes, unsafe paths, duplicate IDs, and incomplete checks. @@ -649,4 +655,25 @@ exit 1 assert_eq!(verify(&[Check::ChangedTo { path: "/n".into(), value: json!(17) }], &json!({}), &after)[0]["status"], "pass"); assert_eq!(verify(&[Check::Equals { path: "/m".into(), value: json!(1) }], &before, &after)[0]["status"], "fail"); } + + #[test] + fn schema_rejects_windows_device_ids_but_allows_near_matches() { + let recipe = json!({"version":1,"corpus_revision":"pin","cases":[{"id":"case","base":"x.psd","base_sha256":"a".repeat(64), + "target":{"kind":"Text"},"checks":[{"op":"unchanged","path":"/name"}]}]}); + let mut recipes: Recipes = serde_json::from_value(recipe).unwrap(); + let mut reserved = vec!["CON".to_string(), "PRN".to_string(), "AUX".to_string(), "NUL".to_string()]; + for n in 1..=9 { + reserved.extend([format!("COM{n}"), format!("LPT{n}")]); + } + for id in reserved { + for variant in [id.clone(), id.to_ascii_lowercase(), format!("{}{}", &id[..1], id[1..].to_ascii_lowercase())] { + recipes.cases[0].id = variant.clone(); + assert_eq!(validate(&recipes), Err(format!("invalid or duplicate case id: {variant}")), "{variant}"); + } + } + for id in ["console", "PRN-1", "auxiliary", "NUL_", "COM0", "COM10", "LPT0", "LPT10", "case-1"] { + recipes.cases[0].id = id.to_string(); + assert!(validate(&recipes).is_ok(), "{id}"); + } + } } diff --git a/xtask/src/stats.rs b/xtask/src/stats.rs index f40b1300ac..b4e6923617 100644 --- a/xtask/src/stats.rs +++ b/xtask/src/stats.rs @@ -15,15 +15,18 @@ fn walk(dir: &Path, c: &mut Counts) { return; }; for e in rd.flatten() { + // Do not count linked source trees twice or follow a directory link back to an ancestor. + let Ok(kind) = e.file_type() else { continue }; let p = e.path(); let name = e.file_name(); let name = name.to_string_lossy(); - if p.is_dir() { + if kind.is_dir() { // Nested fuzz workspaces and build output are not part of the crate. if name != "target" && name != "fuzz" && !name.starts_with('.') { walk(&p, c); } - } else if name.ends_with(".rs") + } else if kind.is_file() + && name.ends_with(".rs") && let Ok(s) = std::fs::read_to_string(&p) { c.files += 1; @@ -108,7 +111,63 @@ pub fn run(_root: &Path, exact: bool) -> Result<(), String> { #[cfg(test)] mod tests { - use super::count_tests; + use super::{Counts, count_tests, walk}; + use std::path::PathBuf; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct Fixture(PathBuf); + + impl Fixture { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let root = std::env::temp_dir().join(format!("photocraft-stats-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + std::fs::create_dir(&root).unwrap(); + Self(root) + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + // Remove the fixture's known links before recursively removing its own directory. + let _ = std::fs::remove_file(self.0.join("project/linked.rs")); + #[cfg(unix)] + let _ = std::fs::remove_file(self.0.join("project/linked-dir")); + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn walk_counts_sources_and_skips_excluded_directories() { + let fixture = Fixture::new(); + for dir in ["src/nested", "target", "fuzz", ".hidden"] { + std::fs::create_dir_all(fixture.0.join(dir)).unwrap(); + } + std::fs::write(fixture.0.join("src/a.rs"), "#[test]\nfn a() {}\n").unwrap(); + std::fs::write(fixture.0.join("src/nested/b.rs"), "proptest! {}\n").unwrap(); + for path in ["target/a.rs", "fuzz/a.rs", ".hidden/a.rs", "src/not-rust.txt"] { + std::fs::write(fixture.0.join(path), "#[test]\n").unwrap(); + } + + let mut counts = Counts::default(); + walk(&fixture.0, &mut counts); + assert_eq!((counts.files, counts.lines, counts.tests, counts.proptests), (2, 3, 1, 1)); + } + + #[cfg(unix)] + #[test] + fn walk_ignores_linked_sources() { + let fixture = Fixture::new(); + std::fs::create_dir(fixture.0.join("project")).unwrap(); + std::fs::create_dir(fixture.0.join("external")).unwrap(); + std::fs::write(fixture.0.join("project/real.rs"), "#[test]\nfn real() {}\n").unwrap(); + std::fs::write(fixture.0.join("external/extra.rs"), "#[test]\nfn extra() {}\n").unwrap(); + std::os::unix::fs::symlink(fixture.0.join("external"), fixture.0.join("project/linked-dir")).unwrap(); + std::os::unix::fs::symlink(fixture.0.join("external/extra.rs"), fixture.0.join("project/linked.rs")).unwrap(); + + let mut counts = Counts::default(); + walk(&fixture.0.join("project"), &mut counts); + assert_eq!((counts.files, counts.lines, counts.tests, counts.proptests), (1, 2, 1, 0)); + } #[test] fn counts_attributes_and_proptest_blocks() { diff --git a/xtask/src/version.rs b/xtask/src/version.rs index 7dae638077..99b37fa65c 100644 --- a/xtask/src/version.rs +++ b/xtask/src/version.rs @@ -8,17 +8,30 @@ use std::path::Path; /// The `version = "…"` value inside `[workspace.package]`. pub fn read(manifest: &str) -> Result { let (_, line) = find_line(manifest)?; - let v = line.split_once('=').map(|(_, v)| v.trim().trim_matches('"').to_string()).unwrap_or_default(); + let (_, v, _) = version_parts(line)?; if v.is_empty() { return Err("empty [workspace.package] version".into()); } - Ok(v) + Ok(v.to_owned()) +} + +/// The canonical double-quoted SemVer form, not general TOML string syntax. Keep the +/// surrounding text opaque so formatting and comments, including their quotes, survive. +fn version_parts(line: &str) -> Result<(&str, &str, &str), String> { + let bad = || "expected a double-quoted [workspace.package] version".to_string(); + if !line.split_once('=').is_some_and(|(_, value)| value.trim_start().starts_with('"')) { + return Err(bad()); + } + let (prefix, rest) = line.split_once('"').ok_or_else(bad)?; + let (value, suffix) = rest.split_once('"').ok_or_else(bad)?; + Ok((prefix, value, suffix)) } /// `manifest` with the workspace version replaced; everything else is byte-for-byte unchanged. pub fn replace(manifest: &str, new: &str) -> Result { validate(new)?; - let (idx, _) = find_line(manifest)?; + let (idx, line) = find_line(manifest)?; + let (prefix, _, suffix) = version_parts(line)?; let mut out = String::with_capacity(manifest.len() + 8); for (i, line) in manifest.split_inclusive('\n').enumerate() { if i == idx { @@ -29,7 +42,7 @@ pub fn replace(manifest: &str, new: &str) -> Result { } else { "" }; - out.push_str(&format!("version = \"{new}\"{eol}")); + out.push_str(&format!("{prefix}\"{new}\"{suffix}{eol}")); } else { out.push_str(line); } @@ -66,7 +79,10 @@ fn find_line(manifest: &str) -> Result<(usize, &str), String> { for (i, line) in manifest.lines().enumerate() { let t = line.trim(); if t.starts_with('[') { - in_section = t == "[workspace.package]"; + in_section = t.strip_prefix("[workspace.package]").is_some_and(|rest| { + let rest = rest.trim_start(); + rest.is_empty() || rest.starts_with('#') + }); continue; } if in_section @@ -137,6 +153,39 @@ mod tests { assert_eq!(out, crlf.replace("\"0.1.0\"", "\"2.0.0\"")); } + #[test] + fn reads_the_version_before_an_inline_comment() { + let manifest = MANIFEST.replace("version = \"0.1.0\"", "version = \"0.1.0\" # release note with \"quotes\" and #"); + assert_eq!(read(&manifest).unwrap(), "0.1.0"); + } + + #[test] + fn rejects_unsupported_string_syntax_before_comment_quotes() { + let manifest = MANIFEST.replace("version = \"0.1.0\"", "version = '0.1.0' # \"keep\""); + assert!(read(&manifest).is_err()); + assert!(replace(&manifest, "1.2.3").is_err()); + } + + #[test] + fn accepts_a_comment_after_the_workspace_package_header() { + let manifest = MANIFEST.replace("[workspace.package]", "[workspace.package] # shared package metadata"); + assert_eq!(read(&manifest).unwrap(), "0.1.0"); + assert_eq!(replace(&manifest, "1.2.3").unwrap(), manifest.replace("version = \"0.1.0\"", "version = \"1.2.3\"")); + } + + #[test] + fn preserves_version_line_formatting_comments_and_endings() { + for ending in ["\n", "\r\n", ""] { + let newline = if ending.is_empty() { "\n" } else { ending }; + let manifest = + format!("[package]{newline}version = \"9.0.0\"{newline}[workspace.package]{newline}\tversion\t=\t\"0.1.0\"\t # keep \"0.1.0\" and #{ending}"); + let expected = manifest.replacen("\"0.1.0\"", "\"1.2.3-rc.1\"", 1); + let updated = replace(&manifest, "1.2.3-rc.1").unwrap(); + assert_eq!(updated, expected, "ending={ending:?}"); + assert_eq!(read(&updated).unwrap(), "1.2.3-rc.1"); + } + } + #[test] fn validates_versions() { for ok in ["0.1.0", "1.20.300", "1.0.0-rc.1", "1.0.0-alpha", "1.0.0-x-y.2"] {